Merge remote-tracking branch 'upstream/beta' into arena-tag-cleanup

This commit is contained in:
Bertie690 2025-09-16 12:38:01 -04:00
commit 724b8db01d
201 changed files with 2588 additions and 1527 deletions

7
.dockerignore Normal file
View File

@ -0,0 +1,7 @@
# .dockerignore
node_modules
*.log
*.md
.gitignore
Dockerfile
.env

View File

@ -55,15 +55,15 @@ jobs:
- name: Create release branch
run: git checkout -b release
# In order to be able to open a PR into beta, we need the branch to have at least one change.
- name: Overwrite RELEASE file
# In order to be able to open a PR into beta, we need the branch to have at least one commit.
# The first commit is _usually_ just bumping the version number, so we can kill 2 birds with 1 stone here
- name: Bump release version
run: |
git config --local user.name "github-actions[bot]"
git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
echo "Release v${{ github.event.inputs.versionName }}" > RELEASE
git add RELEASE
git commit -m "Stage release v${{ github.event.inputs.versionName }}"
pnpm --no-git-tag-version version ${{ github.events.inputs.versionName }}
git commit -am "Stage release for v${{ github.events.inputs.versionName }}"
- name: Push new branch
run: git push origin release

View File

@ -22,8 +22,6 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:

View File

@ -20,8 +20,6 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- uses: actions/setup-node@v4
with:

View File

@ -30,8 +30,6 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Set up Node
uses: actions/setup-node@v4

View File

@ -32,8 +32,6 @@ jobs:
- name: Install pnpm
uses: pnpm/action-setup@v4
with:
version: 10
- name: Set up Node.js
uses: actions/setup-node@v4

View File

@ -80,7 +80,8 @@ Notable topics include:
- [Commenting your code](./docs/comments.md)
- [Linting & Formatting](./docs/linting.md)
- [Localization](./docs/localization.md)
- [Enemy AI move selection](./docs/enemy-ai.md)
- [Enemy AI move selection](./docs/enemy-ai.md)
- [Running with Podman](./docs/podman.md)
Again, if you have unanswered questions please feel free to ask!

47
Dockerfile Normal file
View File

@ -0,0 +1,47 @@
# syntax=docker/dockerfile:1
ARG NODE_VERSION=22.14
ARG OS=alpine
FROM node:${NODE_VERSION}-${OS}
# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
# Install git (for potential runtime needs)
RUN apk add --no-cache git
# Set working directory
WORKDIR /app
# Enable and prepare pnpm
RUN corepack enable && corepack prepare pnpm@10.14.0 --activate
COPY . .
# Copy package files
COPY package.json pnpm-lock.yaml ./
# Install all dependencies
RUN --mount=type=cache,target=/home/appuser/.pnpm-store \
pnpm install --frozen-lockfile && \
rm -rf /home/appuser/.pnpm-store/*
# Change ownership
RUN chown -R appuser:appgroup /app
# Switch to non-root user
USER appuser
# Set environment variables
ENV VITE_BYPASS_LOGIN=1 \
VITE_BYPASS_TUTORIAL=0 \
NEXT_TELEMETRY_DISABLED=1 \
PNP_HOME=/home/appuser/.shrc \
NODE_ENV=development \
PORT=8000
# Expose port
EXPOSE $PORT
# Start the app in development mode
CMD ["pnpm", "run", "start:podman"]

View File

@ -1 +0,0 @@
Release v1.10.0

View File

@ -1,5 +1,5 @@
{
"$schema": "https://biomejs.dev/schemas/2.2.3/schema.json",
"$schema": "https://biomejs.dev/schemas/2.2.4/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
@ -98,7 +98,9 @@
"useTrimStartEnd": "error",
"useReadonlyClassProperties": {
"level": "info", // TODO: Graduate to error eventually
"options": { "checkAllProperties": true }
// NOTE: "checkAllProperties" has an immature implementation that
// causes many false positives across files. Enable if/when maturity improves
"options": { "checkAllProperties": false }
},
"useConsistentObjectDefinitions": {
"level": "error",
@ -209,11 +211,15 @@
"nursery": {
"noUselessUndefined": "error",
"useMaxParams": {
"level": "warn", // TODO: Change to "error"... eventually...
"options": { "max": 4 } // A lot of stuff has a few params, but
"level": "info", // TODO: Change to "error"... eventually...
"options": { "max": 7 }
},
"noShadow": "warn", // TODO: refactor and make "error"
"noNonNullAssertedOptionalChain": "warn" // TODO: refactor and make "error"
"noNonNullAssertedOptionalChain": "warn", // TODO: refactor and make "error"
"noDuplicateDependencies": "error",
"noImportCycles": "error",
// TODO: Change to error once promises are used properly
"noMisusedPromises": "info"
}
}
},
@ -248,16 +254,9 @@
},
// Overrides to prevent unused import removal inside `overrides.ts`, enums & `.d.ts` files (for TSDoc linkcodes),
// as well as inside script boilerplate files.
// as well as inside script boilerplate files (whose imports will _presumably_ be used in the generated file).
{
// TODO: Rename existing boilerplates in the folder and remove this last alias
"includes": [
"**/src/overrides.ts",
"**/src/enums/**/*",
"**/*.d.ts",
"scripts/**/*.boilerplate.ts",
"**/boilerplates/*.ts"
],
"includes": ["**/src/overrides.ts", "**/src/enums/**/*", "**/*.d.ts", "scripts/**/*.boilerplate.ts"],
"linter": {
"rules": {
"correctness": {

27
docs/podman.md Normal file
View File

@ -0,0 +1,27 @@
# Using Podman
## Requirements
* `podman >=5.x`
## Steps
1. `podman build -t pokerogue -f Dockerfile .`
2. `podman create --name temp-pokerogue localhost/pokerogue`
3. `podman cp temp-pokerogue:/app/node_modules ./`
4. `podman cp temp-pokerogue:/app/public/locales ./public/`
5. `podman rm temp-pokerogue`
6. `podman run --rm -p 8000:8000 -v $(pwd):/app:Z --userns=keep-id -u $(id -u):$(id -g) localhost/pokerogue`
7. Visit `http://localhost:8000/`
Note:
1. Steps 2,3,4 are required because mounting working directory without installed `node_modules/` and assets locally will be empty,
this way we prevent it by copying them from the container itself to local directory
2. `podman run` may take a couple of minutes to mount the working directory
### Running tests inside container
`podman run --rm -p 8000:8000 -v $(pwd):/app:Z --userns=keep-id -u $(id -u):$(id -g) localhost/pokerogue pnpm test:silent
`

View File

@ -7,8 +7,10 @@
"start:prod": "vite --mode production",
"start:beta": "vite --mode beta",
"start:dev": "vite --mode development",
"start:podman": "vite --mode development --host 0.0.0.0 --port $PORT",
"build": "vite build",
"build:beta": "vite build --mode beta",
"build:dev": "vite build --mode development",
"preview": "vite preview",
"test": "vitest run --no-isolate",
"test:cov": "vitest run --coverage --no-isolate",
@ -31,7 +33,7 @@
"update-locales:remote": "git submodule update --progress --init --recursive --force --remote"
},
"devDependencies": {
"@biomejs/biome": "2.2.3",
"@biomejs/biome": "2.2.4",
"@ls-lint/ls-lint": "2.3.1",
"@types/crypto-js": "^4.2.0",
"@types/jsdom": "^21.1.7",
@ -46,12 +48,12 @@
"lefthook": "^1.12.2",
"msw": "^2.10.4",
"phaser3spectorjs": "^0.0.8",
"typedoc": "^0.28.12",
"typedoc": "0.28.7",
"typedoc-github-theme": "^0.3.1",
"typedoc-plugin-coverage": "^4.0.1",
"typedoc-plugin-mdn-links": "^5.0.9",
"typescript": "^5.8.3",
"vite": "^7.0.6",
"typescript": "^5.9.2",
"vite": "^7.0.7",
"vite-tsconfig-paths": "^5.1.4",
"vitest": "^3.2.4",
"vitest-canvas-mock": "^0.3.3"
@ -71,5 +73,6 @@
},
"engines": {
"node": ">=22.0.0"
}
},
"packageManager": "pnpm@10.16.1"
}

File diff suppressed because it is too large Load Diff

@ -1 +1 @@
Subproject commit 090bfefaf7e9d4efcbca61fa78a9cdf5d701830b
Subproject commit 74de730a64272c8e9ca0a4cdcf3426cbf1b0aeda

View File

@ -47,6 +47,6 @@ describe("{{description}}", () => {
await game.toEndOfTurn();
expect(feebas).toHaveUsedMove({ move: MoveId.SPLASH, result: MoveResult.SUCCESS });
expect(game.textInterceptor.logs).toContain(i18next.t("moveTriggers:splash"));
expect(game).toHaveShownMessage(i18next.t("moveTriggers:splash"));
});
});

View File

@ -102,9 +102,9 @@ async function promptFileName(selectedType) {
function getBoilerplatePath(choiceType) {
switch (choiceType) {
// case "Reward":
// return path.join(__dirname, "boilerplates/reward.ts");
// return path.join(__dirname, "boilerplates/reward.boilerplate.ts");
default:
return path.join(__dirname, "boilerplates/default.ts");
return path.join(__dirname, "boilerplates/default.boilerplate.ts");
}
}

View File

@ -1,4 +1,4 @@
import type { ScoreboardCategory } from "#ui/containers/daily-run-scoreboard";
import type { ScoreboardCategory } from "#ui/daily-run-scoreboard";
export interface GetDailyRankingsRequest {
category: ScoreboardCategory;

770
src/ai/ai-moveset-gen.ts Normal file
View File

@ -0,0 +1,770 @@
import { globalScene } from "#app/global-scene";
import { speciesEggMoves } from "#balance/egg-moves";
import {
BASE_LEVEL_WEIGHT_OFFSET,
BASE_WEIGHT_MULTIPLIER,
BOSS_EXTRA_WEIGHT_MULTIPLIER,
COMMON_TIER_TM_LEVEL_REQUIREMENT,
COMMON_TM_MOVESET_WEIGHT,
EGG_MOVE_LEVEL_REQUIREMENT,
EGG_MOVE_TO_LEVEL_WEIGHT,
EGG_MOVE_WEIGHT_MAX,
EVOLUTION_MOVE_WEIGHT,
GREAT_TIER_TM_LEVEL_REQUIREMENT,
GREAT_TM_MOVESET_WEIGHT,
getMaxEggMoveCount,
getMaxTmCount,
RARE_EGG_MOVE_LEVEL_REQUIREMENT,
STAB_BLACKLIST,
ULTRA_TIER_TM_LEVEL_REQUIREMENT,
ULTRA_TM_MOVESET_WEIGHT,
} from "#balance/moveset-generation";
import { EVOLVE_MOVE, RELEARN_MOVE } from "#balance/pokemon-level-moves";
import { speciesTmMoves, tmPoolTiers } from "#balance/tms";
import { allMoves } from "#data/data-lists";
import { ModifierTier } from "#enums/modifier-tier";
import { MoveCategory } from "#enums/move-category";
import type { MoveId } from "#enums/move-id";
import { PokemonType } from "#enums/pokemon-type";
import type { SpeciesId } from "#enums/species-id";
import { Stat } from "#enums/stat";
import type { EnemyPokemon, Pokemon } from "#field/pokemon";
import { PokemonMove } from "#moves/pokemon-move";
import { NumberHolder, randSeedInt } from "#utils/common";
import { isBeta } from "#utils/utility-vars";
/**
* Compute and assign a weight to the level-up moves currently available to the Pokémon
*
* @param pokemon - The Pokémon to generate a level-based move pool for
* @returns A map of move IDs to their computed weights
*
* @remarks
* A move's weight is determined by its level, as follows:
* 1. If the level is an {@linkcode EVOLVE_MOVE} move, weight is 60
* 2. If it is level 1 with 80+ BP, it is considered a "move reminder" move and
* weight is 60
* 3. If the Pokémon has a trainer and the move is a {@linkcode RELEARN_MOVE},
* weight is 60
* 4. Otherwise, weight is the earliest level the move can be learned + 20
*/
function getAndWeightLevelMoves(pokemon: Pokemon): Map<MoveId, number> {
const movePool = new Map<MoveId, number>();
let allLevelMoves: [number, MoveId][];
// TODO: Investigate why there needs to be error handling here
try {
allLevelMoves = pokemon.getLevelMoves(1, true, true, pokemon.hasTrainer());
} catch (e) {
console.warn("Error encountered trying to generate moveset for %s: %s", pokemon.species.name, e);
return movePool;
}
const level = pokemon.level;
const hasTrainer = pokemon.hasTrainer();
for (const levelMove of allLevelMoves) {
const [learnLevel, id] = levelMove;
if (level < learnLevel) {
break;
}
const move = allMoves[id];
// Skip unimplemented moves or moves that are already in the pool
if (move.name.endsWith(" (N)") || movePool.has(id)) {
continue;
}
let weight = learnLevel + BASE_LEVEL_WEIGHT_OFFSET;
switch (learnLevel) {
case EVOLVE_MOVE:
weight = EVOLUTION_MOVE_WEIGHT;
break;
// Assume level 1 moves with 80+ BP are "move reminder" moves and bump their weight. Trainers use actual relearn moves.
case 1:
if (move.power >= 80) {
weight = 60;
}
break;
case RELEARN_MOVE:
if (hasTrainer) {
weight = 60;
}
}
movePool.set(id, weight);
}
return movePool;
}
/**
* Determine which TM tiers a Pokémon can learn based on its level
* @param level - The level of the Pokémon
* @returns A tuple indicating whether the Pokémon can learn common, great, and ultra tier TMs
*/
function getAllowedTmTiers(level: number): [common: boolean, great: boolean, ultra: boolean] {
return [
level >= COMMON_TIER_TM_LEVEL_REQUIREMENT,
level >= GREAT_TIER_TM_LEVEL_REQUIREMENT,
level >= ULTRA_TIER_TM_LEVEL_REQUIREMENT,
];
}
/**
* Get the TMs that a species can learn based on its ID and formKey
* @param speciesId - The species ID of the Pokémon
* @param level - The level of the Pokémon
* @param formKey - The form key of the Pokémon
* @param levelPool - The current level-based move pool, to avoid duplicates
* @param tmPool - The TM move pool to add to, which will be modified in place
* @param allowedTiers - The tiers of TMs the Pokémon is allowed to learn
*
* @privateRemarks
* Split out from `getAndWeightTmMoves` to allow fusion species to add their TMs
* without duplicating code.
*/
function getTmPoolForSpecies(
speciesId: number,
level: number,
formKey: string,
levelPool: ReadonlyMap<MoveId, number>,
eggPool: ReadonlyMap<MoveId, number>,
tmPool: Map<MoveId, number>,
allowedTiers = getAllowedTmTiers(level),
): void {
const [allowCommon, allowGreat, allowUltra] = allowedTiers;
const tms = speciesTmMoves[speciesId];
// Species with no learnable TMs (e.g. Ditto) don't have entries in the `speciesTmMoves` object,
// so this is needed to avoid iterating over `undefined`
if (tms == null) {
return;
}
let moveId: MoveId;
for (const tm of tms) {
if (Array.isArray(tm)) {
if (tm[0] !== formKey) {
continue;
}
moveId = tm[1];
} else {
moveId = tm;
}
if (levelPool.has(moveId) || eggPool.has(moveId) || tmPool.has(moveId)) {
continue;
}
switch (tmPoolTiers[moveId]) {
case ModifierTier.COMMON:
allowCommon && tmPool.set(moveId, COMMON_TM_MOVESET_WEIGHT);
break;
case ModifierTier.GREAT:
allowGreat && tmPool.set(moveId, GREAT_TM_MOVESET_WEIGHT);
break;
case ModifierTier.ULTRA:
allowUltra && tmPool.set(moveId, ULTRA_TM_MOVESET_WEIGHT);
break;
}
}
}
/**
* Compute and assign a weight to the TM moves currently available to the Pokémon
* @param pokemon - The Pokémon to generate a TM-based move pool for
* @param currentSet - The current movepool, to avoid duplicates
* @param tmPool - The TM move pool to add to, which will be modified in place
* @returns A map of move IDs to their computed weights
*
* @remarks
* Only trainer pokemon can learn TM moves, and there are restrictions
* as to how many and which TMs are available based on the level of the Pokémon.
* 1. Before level 25, no TM moves are available
* 2. Between levels 25 and 40, only COMMON tier TMs are available,
*/
function getAndWeightTmMoves(
pokemon: Pokemon,
currentPool: ReadonlyMap<MoveId, number>,
eggPool: ReadonlyMap<MoveId, number>,
tmPool: Map<MoveId, number>,
): void {
const level = pokemon.level;
const allowedTiers = getAllowedTmTiers(level);
if (!allowedTiers.includes(true)) {
return;
}
const form = pokemon.species.forms[pokemon.formIndex]?.formKey ?? "";
getTmPoolForSpecies(pokemon.species.speciesId, level, form, currentPool, eggPool, tmPool, allowedTiers);
const fusionFormKey = pokemon.getFusionFormKey();
const fusionSpecies = pokemon.fusionSpecies?.speciesId;
if (fusionSpecies != null && fusionFormKey != null && fusionFormKey !== "") {
getTmPoolForSpecies(fusionSpecies, level, fusionFormKey, currentPool, eggPool, tmPool, allowedTiers);
}
}
/**
* Get the weight multiplier for an egg move
* @param levelPool - Map of level up moves to their weights
* @param level - The level of the Pokémon
* @param forRare - Whether this is for a rare egg move
* @param isBoss - Whether the Pokémon having the egg move generated is a boss Pokémon
*/
export function getEggMoveWeight(
// biome-ignore-start lint/correctness/noUnusedFunctionParameters: Saved to allow this algorithm to be tweaked easily without adjusting signatures
levelPool: ReadonlyMap<MoveId, number>,
level: number,
forRare: boolean,
isBoss: boolean,
// biome-ignore-end lint/correctness/noUnusedFunctionParameters: Endrange
): number {
const levelUpWeightedEggMoveWeight = Math.round(Math.max(...levelPool.values()) * EGG_MOVE_TO_LEVEL_WEIGHT);
// Rare egg moves are always weighted at 5/6 the weight of normal egg moves
return Math.min(levelUpWeightedEggMoveWeight, EGG_MOVE_WEIGHT_MAX) * (forRare ? 5 / 6 : 1);
}
/**
* Submethod of {@linkcode getAndWeightEggMoves} that adds egg moves for a specific species to the egg move pool
*
* @param rootSpeciesId - The ID of the root species for which to generate the egg move pool.
* @param levelPool - A readonly map of move IDs to their levels, representing moves already learned by leveling up.
* @param eggPool - A map to be populated with egg move IDs and their corresponding weights.
* @param eggMoveWeight - The default weight to assign to regular egg moves.
* @param excludeRare - If true, excludes rare egg moves
* @param rareEggMoveWeight - The weight to assign to rare egg moves; default 0
*
* @privateRemarks
* Split from `getAndWeightEggMoves` to allow fusion species to add their egg moves without duplicating code.
*
* @remarks
* - Moves present in `levelPool` are excluded from the egg pool.
* - If `excludeRare` is true, rare egg moves (at index 3) are skipped.
* - Rare egg moves are assigned `rareEggMoveWeight`, while others receive `eggMoveWeight`.
*/
function getEggPoolForSpecies(
rootSpeciesId: SpeciesId,
levelPool: ReadonlyMap<MoveId, number>,
eggPool: Map<MoveId, number>,
eggMoveWeight: number,
excludeRare: boolean,
rareEggMoveWeight = 0,
): void {
const eggMoves = speciesEggMoves[rootSpeciesId];
if (eggMoves == null) {
return;
}
for (const [idx, moveId] of eggMoves.entries()) {
if (levelPool.has(moveId) || (idx === 3 && excludeRare)) {
continue;
}
eggPool.set(Math.max(moveId, eggPool.get(moveId) ?? 0), idx === 3 ? rareEggMoveWeight : eggMoveWeight);
}
}
/**
* Compute and assign a weight to the egg moves currently available to the Pokémon
* @param pokemon - The Pokémon to generate egg moves for
* @param levelPool - The map of level-based moves to their weights
* @param eggPool - A map of move IDs to their weights for egg moves that will be modified in place
*
* @remarks
* This function checks if the Pokémon meets the requirements to learn egg moves,
* and if allowed, calculates the weights for regular and rare egg moves using the provided pools.
*/
function getAndWeightEggMoves(
pokemon: Pokemon,
levelPool: ReadonlyMap<MoveId, number>,
eggPool: Map<MoveId, number>,
): void {
const level = pokemon.level;
if (level < EGG_MOVE_LEVEL_REQUIREMENT || !globalScene.currentBattle?.trainer?.config.allowEggMoves) {
return;
}
const isBoss = pokemon.isBoss();
const excludeRare = isBoss || level < RARE_EGG_MOVE_LEVEL_REQUIREMENT;
const eggMoveWeight = getEggMoveWeight(levelPool, level, false, isBoss);
let rareEggMoveWeight: number | undefined;
if (!excludeRare) {
rareEggMoveWeight = getEggMoveWeight(levelPool, level, true, isBoss);
}
getEggPoolForSpecies(
pokemon.species.getRootSpeciesId(),
levelPool,
eggPool,
eggMoveWeight,
excludeRare,
rareEggMoveWeight,
);
const fusionSpecies = pokemon.fusionSpecies?.getRootSpeciesId();
if (fusionSpecies != null) {
getEggPoolForSpecies(fusionSpecies, levelPool, eggPool, eggMoveWeight, excludeRare, rareEggMoveWeight);
}
}
/**
* Filter a move pool, removing moves that are not allowed based on conditions
* @param pool - The move pool to filter
* @param isBoss - Whether the Pokémon is a boss
* @param hasTrainer - Whether the Pokémon has a trainer
*/
function filterMovePool(pool: Map<MoveId, number>, isBoss: boolean, hasTrainer: boolean): void {
for (const [moveId, weight] of pool) {
if (weight <= 0) {
pool.delete(moveId);
continue;
}
const move = allMoves[moveId];
// Forbid unimplemented moves
if (move.name.endsWith(" (N)")) {
pool.delete(moveId);
continue;
}
// Bosses never get self ko moves or Pain Split
if (isBoss && (move.hasAttr("SacrificialAttr") || move.hasAttr("HpSplitAttr"))) {
pool.delete(moveId);
}
// No one gets Memento or Final Gambit
if (move.hasAttr("SacrificialAttrOnHit")) {
pool.delete(moveId);
continue;
}
// Trainers never get OHKO moves
if (hasTrainer && move.hasAttr("OneHitKOAttr")) {
pool.delete(moveId);
}
}
}
/**
* Perform Trainer-specific adjustments to move weights in a move pool
* @param pool - The move pool to adjust
*/
function adjustWeightsForTrainer(pool: Map<MoveId, number>): void {
for (const [moveId, weight] of pool.entries()) {
const move = allMoves[moveId];
let adjustedWeight = weight;
// Half the weight of self KO moves on trainers
adjustedWeight *= move.hasAttr("SacrificialAttr") ? 0.5 : 1;
// Trainers get a weight bump to stat buffing moves
adjustedWeight *= move.getAttrs("StatStageChangeAttr").some(a => a.stages > 1 && a.selfTarget) ? 1.25 : 1;
// Trainers get a weight decrease to multiturn moves
adjustedWeight *= !!move.isChargingMove() || !!move.hasAttr("RechargeAttr") ? 0.7 : 1;
if (adjustedWeight !== weight) {
pool.set(moveId, adjustedWeight);
}
}
}
/**
* Adjust weights of damaging moves in a move pool based on their power and category
*
* @param pool - The move pool to adjust
* @param pokemon - The Pokémon for which the moveset is being generated
* @param willTera - Whether the Pokémon is expected to Tera (i.e., has instant Tera on a Trainer Pokémon); default `false`
* @remarks
* Caps max power at 90 to avoid something like hyper beam ruining the stats.
* pokemon is a pretty soft weighting factor, although it is scaled with the weight multiplier.
*/
function adjustDamageMoveWeights(pool: Map<MoveId, number>, pokemon: Pokemon, willTera = false): void {
// begin max power at 40 to avoid inflating weights too much when there are only low power moves
let maxPower = 40;
for (const moveId of pool.keys()) {
const move = allMoves[moveId];
maxPower = Math.max(maxPower, move.calculateEffectivePower());
if (maxPower >= 90) {
maxPower = 90;
break;
}
}
const atk = pokemon.getStat(Stat.ATK);
const spAtk = pokemon.getStat(Stat.SPATK);
const lowerStat = Math.min(atk, spAtk);
const higherStat = Math.max(atk, spAtk);
const worseCategory = atk > spAtk ? MoveCategory.SPECIAL : MoveCategory.PHYSICAL;
const statRatio = lowerStat / higherStat;
const adjustmentRatio = Math.min(Math.pow(statRatio, 3) * 1.3, 1);
for (const [moveId, weight] of pool) {
const move = allMoves[moveId];
let adjustedWeight = weight;
if (move.category === MoveCategory.STATUS) {
continue;
}
// Scale weight based on their ratio to the highest power move, capping at 50% reduction
adjustedWeight *= Math.max(Math.min(move.calculateEffectivePower() / maxPower, 1), 0.5);
// Scale weight based the stat it uses to deal damage, based on the ratio between said stat
// and the higher stat
if (move.hasAttr("DefAtkAttr")) {
const def = pokemon.getStat(Stat.DEF);
const defRatio = def / higherStat;
const defAdjustRatio = Math.min(Math.pow(defRatio, 3) * 1.3, 1.1);
adjustedWeight *= defAdjustRatio;
} else if (
move.category === worseCategory
&& !move.hasAttr("PhotonGeyserCategoryAttr")
&& !move.hasAttr("ShellSideArmCategoryAttr")
&& !(move.hasAttr("TeraMoveCategoryAttr") && willTera)
) {
// Raw multiply each move's category by the stat it uses to deal damage
// moves that always use the higher offensive stat are left unadjusted
adjustedWeight *= adjustmentRatio;
}
if (adjustedWeight !== weight) {
pool.set(moveId, adjustedWeight);
}
}
}
/**
* Calculate the total weight of all moves in a move pool
* @param pool - The move pool to calculate the total weight for
* @returns The total weight of all moves in the pool
*/
function calculateTotalPoolWeight(pool: Map<MoveId, number>): number {
let totalWeight = 0;
for (const weight of pool.values()) {
totalWeight += weight;
}
return totalWeight;
}
/**
* Filter a pool and return a new array of moves that pass the predicate
* @param pool - The move pool to filter
* @param predicate - The predicate function to determine if a move should be included
* @param totalWeight - An output parameter to hold the total weight of the filtered pool. Its value is reset to 0 if provided.
* @returns An array of move ID and weight tuples that pass the predicate
*/
function filterPool(
pool: ReadonlyMap<MoveId, number>,
predicate: (moveId: MoveId) => boolean,
totalWeight?: NumberHolder,
): [id: MoveId, weight: number][] {
let hasTotalWeight = false;
if (totalWeight != null) {
totalWeight.value = 0;
hasTotalWeight = true;
}
const newPool: [id: MoveId, weight: number][] = [];
for (const [moveId, weight] of pool) {
if (predicate(moveId)) {
newPool.push([moveId, weight]);
if (hasTotalWeight) {
// Bang is safe here because we set `hasTotalWeight` in the if check above
totalWeight!.value += weight;
}
}
}
return newPool;
}
/**
* Forcibly add a STAB move to the Pokémon's moveset from the provided pools
*
* @remarks
* If no STAB move is available, add any damaging move.
* If no damaging move is available, no move is added
* @param pool - The master move pool
* @param tmPool - The TM move pool
* @param eggPool - The egg move pool
* @param pokemon - The Pokémon for which the moveset is being generated
* @param tmCount - A holder for the count of TM moves selected
* @param eggMoveCount - A holder for the count of egg moves selected
* @param willTera - Whether the Pokémon is expected to Tera (i.e., has instant Tera on a Trainer Pokémon); default `false`
* @param forceAnyDamageIfNoStab - If true, will force any damaging move if no STAB move is available
*/
// biome-ignore lint/nursery/useMaxParams: This is a complex function that needs all these parameters
function forceStabMove(
pool: Map<MoveId, number>,
tmPool: Map<MoveId, number>,
eggPool: Map<MoveId, number>,
pokemon: Pokemon,
tmCount: NumberHolder,
eggMoveCount: NumberHolder,
willTera = false,
forceAnyDamageIfNoStab = false,
): void {
// All Pokemon force a STAB move first
const totalWeight = new NumberHolder(0);
const stabMovePool = filterPool(
pool,
moveId => {
const move = allMoves[moveId];
return (
move.category !== MoveCategory.STATUS
&& (pokemon.isOfType(move.type)
|| (willTera && move.hasAttr("TeraBlastTypeAttr") && pokemon.getTeraType() !== PokemonType.STELLAR))
&& !STAB_BLACKLIST.has(moveId)
);
},
totalWeight,
);
const chosenPool =
stabMovePool.length > 0 || !forceAnyDamageIfNoStab
? stabMovePool
: filterPool(
pool,
m => allMoves[m[0]].category !== MoveCategory.STATUS && !STAB_BLACKLIST.has(m[0]),
totalWeight,
);
if (chosenPool.length > 0) {
let rand = randSeedInt(totalWeight.value);
let index = 0;
while (rand > chosenPool[index][1]) {
rand -= chosenPool[index++][1];
}
const selectedId = chosenPool[index][0];
pool.delete(selectedId);
if (tmPool.has(selectedId)) {
tmPool.delete(selectedId);
tmCount.value++;
} else if (eggPool.has(selectedId)) {
eggPool.delete(selectedId);
eggMoveCount.value++;
}
pokemon.moveset.push(new PokemonMove(selectedId));
}
}
/**
* Adjust weights in the remaining move pool based on existing moves in the Pokémon's moveset
*
* @remarks
* Submethod for step 5 of moveset generation
* @param pool - The move pool to filter
* @param pokemon - The Pokémon for which the moveset is being generated
*/
function filterRemainingTrainerMovePool(pool: [id: MoveId, weight: number][], pokemon: Pokemon) {
// Sqrt the weight of any damaging moves with overlapping types. pokemon is about a 0.05 - 0.1 multiplier.
// Other damaging moves 2x weight if 0-1 damaging moves, 0.5x if 2, 0.125x if 3. These weights get 20x if STAB.
// Status moves remain unchanged on weight, pokemon encourages 1-2
for (const [idx, [moveId, weight]] of pool.entries()) {
let ret: number;
if (
pokemon.moveset.some(
mo => mo.getMove().category !== MoveCategory.STATUS && mo.getMove().type === allMoves[moveId].type,
)
) {
ret = Math.ceil(Math.sqrt(weight));
} else if (allMoves[moveId].category !== MoveCategory.STATUS) {
ret = Math.ceil(
(weight / Math.max(Math.pow(4, pokemon.moveset.filter(mo => (mo.getMove().power ?? 0) > 1).length) / 8, 0.5))
* (pokemon.isOfType(allMoves[moveId].type) && !STAB_BLACKLIST.has(moveId) ? 20 : 1),
);
} else {
ret = weight;
}
pool[idx] = [moveId, ret];
}
}
/**
* Fill in the remaining slots in the Pokémon's moveset from the provided pools
* @param pokemon - The Pokémon for which the moveset is being generated
* @param tmPool - The TM move pool
* @param eggMovePool - The egg move pool
* @param tmCount - A holder for the count of moves that have been added to the moveset from TMs
* @param eggMoveCount - A holder for the count of moves that have been added to the moveset from egg moves
* @param baseWeights - The base weights of all moves in the master pool
* @param remainingPool - The remaining move pool to select from
*/
function fillInRemainingMovesetSlots(
pokemon: Pokemon,
tmPool: Map<MoveId, number>,
eggMovePool: Map<MoveId, number>,
tmCount: NumberHolder,
eggMoveCount: NumberHolder,
baseWeights: Map<MoveId, number>,
remainingPool: [id: MoveId, weight: number][],
): void {
const tmCap = getMaxTmCount(pokemon.level);
const eggCap = getMaxEggMoveCount(pokemon.level);
const remainingPoolWeight = new NumberHolder(0);
while (remainingPool.length > pokemon.moveset.length && pokemon.moveset.length < 4) {
const nonLevelMoveCount = tmCount.value + eggMoveCount.value;
remainingPool = filterPool(
baseWeights,
(m: MoveId) =>
!pokemon.moveset.some(
mo =>
m === mo.moveId || (allMoves[m]?.hasAttr("SacrificialAttr") && mo.getMove()?.hasAttr("SacrificialAttr")), // Only one self-KO move allowed
)
&& (nonLevelMoveCount < tmCap || !tmPool.has(m))
&& (nonLevelMoveCount < eggCap || !eggMovePool.has(m)),
remainingPoolWeight,
);
if (pokemon.hasTrainer()) {
filterRemainingTrainerMovePool(remainingPool, pokemon);
}
const totalWeight = remainingPool.reduce((v, m) => v + m[1], 0);
let rand = randSeedInt(totalWeight);
let index = 0;
while (rand > remainingPool[index][1]) {
rand -= remainingPool[index++][1];
}
const selectedMoveId = remainingPool[index][0];
baseWeights.delete(selectedMoveId);
if (tmPool.has(selectedMoveId)) {
tmCount.value++;
tmPool.delete(selectedMoveId);
} else if (eggMovePool.has(selectedMoveId)) {
eggMoveCount.value++;
eggMovePool.delete(selectedMoveId);
}
pokemon.moveset.push(new PokemonMove(selectedMoveId));
}
}
/**
* Debugging function to log computed move weights for a Pokémon
* @param pokemon - The Pokémon for which the move weights were computed
* @param pool - The move pool containing move IDs and their weights
* @param note - Short note to include in the log for context
*/
function debugMoveWeights(pokemon: Pokemon, pool: Map<MoveId, number>, note: string): void {
if ((isBeta || import.meta.env.DEV) && import.meta.env.NODE_ENV !== "test") {
const moveNameToWeightMap = new Map<string, number>();
const sortedByValue = Array.from(pool.entries()).sort((a, b) => b[1] - a[1]);
for (const [moveId, weight] of sortedByValue) {
moveNameToWeightMap.set(allMoves[moveId].name, weight);
}
console.log("%cComputed move weights [%s] for %s", "color: blue", note, pokemon.name, moveNameToWeightMap);
}
}
/**
* Generate a moveset for a given Pokémon based on its level, types, stats, and whether it is wild or a trainer's Pokémon.
* @param pokemon - The Pokémon to generate a moveset for
* @returns A reference to the Pokémon's moveset array
*/
export function generateMoveset(pokemon: Pokemon): void {
pokemon.moveset = [];
// Step 1: Generate the pools from various sources: level up, egg moves, and TMs
const learnPool = getAndWeightLevelMoves(pokemon);
debugMoveWeights(pokemon, learnPool, "Initial Level Moves");
const hasTrainer = pokemon.hasTrainer();
const tmPool = new Map<MoveId, number>();
const eggMovePool = new Map<MoveId, number>();
if (hasTrainer) {
getAndWeightEggMoves(pokemon, learnPool, eggMovePool);
eggMovePool.size > 0 && debugMoveWeights(pokemon, eggMovePool, "Initial Egg Moves");
getAndWeightTmMoves(pokemon, learnPool, eggMovePool, tmPool);
tmPool.size > 0 && debugMoveWeights(pokemon, tmPool, "Initial Tm Moves");
}
// Now, combine pools into one master pool.
// The pools are kept around so we know where the move was sourced from
const movePool = new Map<MoveId, number>([...tmPool.entries(), ...eggMovePool.entries(), ...learnPool.entries()]);
// Step 2: Filter out forbidden moves
const isBoss = pokemon.isBoss();
filterMovePool(movePool, isBoss, hasTrainer);
// Step 3: Adjust weights for trainers
if (hasTrainer) {
adjustWeightsForTrainer(movePool);
}
/** Determine whether this pokemon will instantly tera */
const willTera =
hasTrainer
&& globalScene.currentBattle?.trainer?.config.trainerAI.instantTeras.includes(
// The cast to EnemyPokemon is safe; includes will just return false if the property doesn't exist
(pokemon as EnemyPokemon).initialTeamIndex,
);
adjustDamageMoveWeights(movePool, pokemon, willTera);
/** The higher this is, the greater the impact of weight. At `0` all moves are equal weight. */
let weightMultiplier = BASE_WEIGHT_MULTIPLIER;
if (isBoss) {
weightMultiplier += BOSS_EXTRA_WEIGHT_MULTIPLIER;
}
const baseWeights = new Map<MoveId, number>(movePool);
for (const [moveId, weight] of baseWeights) {
if (weight <= 0) {
baseWeights.delete(moveId);
continue;
}
baseWeights.set(moveId, Math.ceil(Math.pow(weight, weightMultiplier) * 100));
}
const tmCount = new NumberHolder(0);
const eggMoveCount = new NumberHolder(0);
debugMoveWeights(pokemon, baseWeights, "Pre STAB Move");
// Step 4: Force a STAB move if possible
forceStabMove(movePool, tmPool, eggMovePool, pokemon, tmCount, eggMoveCount, willTera);
// Note: To force a secondary stab, call this a second time, and pass `false` for the last parameter
// Would also tweak the function to not consider moves already in the moveset
// e.g. forceStabMove(..., false);
// Step 5: Fill in remaining slots
fillInRemainingMovesetSlots(
pokemon,
tmPool,
eggMovePool,
tmCount,
eggMoveCount,
baseWeights,
filterPool(baseWeights, (m: MoveId) => !pokemon.moveset.some(mo => m[0] === mo.moveId)),
);
}
/**
* Exports for internal testing purposes.
* These *must not* be used outside of tests, as they will not be defined.
* @internal
*/
export const __INTERNAL_TEST_EXPORTS: {
getAndWeightLevelMoves: typeof getAndWeightLevelMoves;
getAllowedTmTiers: typeof getAllowedTmTiers;
getTmPoolForSpecies: typeof getTmPoolForSpecies;
getAndWeightTmMoves: typeof getAndWeightTmMoves;
getEggMoveWeight: typeof getEggMoveWeight;
getEggPoolForSpecies: typeof getEggPoolForSpecies;
getAndWeightEggMoves: typeof getAndWeightEggMoves;
filterMovePool: typeof filterMovePool;
adjustWeightsForTrainer: typeof adjustWeightsForTrainer;
adjustDamageMoveWeights: typeof adjustDamageMoveWeights;
calculateTotalPoolWeight: typeof calculateTotalPoolWeight;
filterPool: typeof filterPool;
forceStabMove: typeof forceStabMove;
filterRemainingTrainerMovePool: typeof filterRemainingTrainerMovePool;
fillInRemainingMovesetSlots: typeof fillInRemainingMovesetSlots;
} = {} as any;
// We can't use `import.meta.vitest` here, because this would not be set
// until the tests themselves begin to run, which is after imports
// So we rely on NODE_ENV being test instead
if (import.meta.env.NODE_ENV === "test") {
Object.assign(__INTERNAL_TEST_EXPORTS, {
getAndWeightLevelMoves,
getAllowedTmTiers,
getTmPoolForSpecies,
getAndWeightTmMoves,
getEggMoveWeight,
getEggPoolForSpecies,
getAndWeightEggMoves,
filterMovePool,
adjustWeightsForTrainer,
adjustDamageMoveWeights,
calculateTotalPoolWeight,
filterPool,
forceStabMove,
filterRemainingTrainerMovePool,
fillInRemainingMovesetSlots,
});
}

View File

@ -121,13 +121,13 @@ import { vouchers } from "#system/voucher";
import { trainerConfigs } from "#trainers/trainer-config";
import type { HeldModifierConfig } from "#types/held-modifier-config";
import type { Localizable } from "#types/locales";
import { AbilityBar } from "#ui/containers/ability-bar";
import { ArenaFlyout } from "#ui/containers/arena-flyout";
import { CandyBar } from "#ui/containers/candy-bar";
import { CharSprite } from "#ui/containers/char-sprite";
import { PartyExpBar } from "#ui/containers/party-exp-bar";
import { PokeballTray } from "#ui/containers/pokeball-tray";
import { PokemonInfoContainer } from "#ui/containers/pokemon-info-container";
import { AbilityBar } from "#ui/ability-bar";
import { ArenaFlyout } from "#ui/arena-flyout";
import { CandyBar } from "#ui/candy-bar";
import { CharSprite } from "#ui/char-sprite";
import { PartyExpBar } from "#ui/party-exp-bar";
import { PokeballTray } from "#ui/pokeball-tray";
import { PokemonInfoContainer } from "#ui/pokemon-info-container";
import { addTextObject, getTextColor } from "#ui/text";
import { UI } from "#ui/ui";
import { addUiThemeOverrides } from "#ui/ui-theme";
@ -138,7 +138,6 @@ import {
formatMoney,
getIvsFromId,
isBetween,
isNullOrUndefined,
NumberHolder,
randomString,
randSeedInt,
@ -859,20 +858,21 @@ export class BattleScene extends SceneBase {
}
/**
* Return the {@linkcode Pokemon} associated with a given ID.
* @param pokemonId - The ID whose Pokemon will be retrieved.
* @returns The {@linkcode Pokemon} associated with the given id.
* Returns `null` if the ID is `undefined` or not present in either party.
* @todo Change the `null` to `undefined` and update callers' signatures -
* this is weird and causes a lot of random jank
* Return the {@linkcode Pokemon} associated with the given ID.
* @param pokemonId - The PID whose Pokemon will be retrieved
* @returns The `Pokemon` associated with the given ID,
* or `undefined` if none is found in either team's party.
* @see {@linkcode Pokemon.id}
* @todo `pokemonId` should not allow `undefined`
*/
getPokemonById(pokemonId: number | undefined): Pokemon | null {
if (isNullOrUndefined(pokemonId)) {
return null;
public getPokemonById(pokemonId: number | undefined): Pokemon | undefined {
if (pokemonId == null) {
// biome-ignore lint/nursery/noUselessUndefined: More explicit
return undefined;
}
const party = (this.getPlayerParty() as Pokemon[]).concat(this.getEnemyParty());
return party.find(p => p.id === pokemonId) ?? null;
return party.find(p => p.id === pokemonId);
}
addPlayerPokemon(
@ -1319,7 +1319,7 @@ export class BattleScene extends SceneBase {
if (
!this.gameMode.hasTrainers
|| Overrides.BATTLE_TYPE_OVERRIDE === BattleType.WILD
|| (Overrides.DISABLE_STANDARD_TRAINERS_OVERRIDE && isNullOrUndefined(trainerData))
|| (Overrides.DISABLE_STANDARD_TRAINERS_OVERRIDE && trainerData == null)
) {
newBattleType = BattleType.WILD;
} else {
@ -1332,13 +1332,12 @@ export class BattleScene extends SceneBase {
if (newBattleType === BattleType.TRAINER) {
const trainerType =
Overrides.RANDOM_TRAINER_OVERRIDE?.trainerType ?? this.arena.randomTrainerType(newWaveIndex);
const hasDouble = trainerConfigs[trainerType].hasDouble;
let doubleTrainer = false;
if (trainerConfigs[trainerType].doubleOnly) {
doubleTrainer = true;
} else if (trainerConfigs[trainerType].hasDouble) {
doubleTrainer =
Overrides.RANDOM_TRAINER_OVERRIDE?.alwaysDouble
|| !randSeedInt(this.getDoubleBattleChance(newWaveIndex, playerField));
} else if (hasDouble) {
doubleTrainer = !randSeedInt(this.getDoubleBattleChance(newWaveIndex, playerField));
// Add a check that special trainers can't be double except for tate and liza - they should use the normal double chance
if (
trainerConfigs[trainerType].trainerTypeDouble
@ -1347,11 +1346,19 @@ export class BattleScene extends SceneBase {
doubleTrainer = false;
}
}
const variant = doubleTrainer
? TrainerVariant.DOUBLE
: randSeedInt(2)
? TrainerVariant.FEMALE
: TrainerVariant.DEFAULT;
// Forcing a double battle on wave 1 causes a bug where only one enemy is sent out,
// making it impossible to complete the fight without a reload
const overrideVariant =
Overrides.RANDOM_TRAINER_OVERRIDE?.trainerVariant === TrainerVariant.DOUBLE
&& (!hasDouble || newWaveIndex <= 1)
? TrainerVariant.DEFAULT
: Overrides.RANDOM_TRAINER_OVERRIDE?.trainerVariant;
const variant =
overrideVariant
?? (doubleTrainer ? TrainerVariant.DOUBLE : randSeedInt(2) ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT);
newTrainer = trainerData !== undefined ? trainerData.toTrainer() : new Trainer(trainerType, variant);
this.field.add(newTrainer);
}
@ -1383,7 +1390,7 @@ export class BattleScene extends SceneBase {
newDouble = false;
}
if (!isNullOrUndefined(Overrides.BATTLE_STYLE_OVERRIDE)) {
if (Overrides.BATTLE_STYLE_OVERRIDE != null) {
let doubleOverrideForWave: "single" | "double" | null = null;
switch (Overrides.BATTLE_STYLE_OVERRIDE) {
@ -1572,7 +1579,7 @@ export class BattleScene extends SceneBase {
// Give trainers with specialty types an appropriately-typed form for Wormadam, Rotom, Arceus, Oricorio, Silvally, or Paldean Tauros.
!isEggPhase
&& this.currentBattle?.battleType === BattleType.TRAINER
&& !isNullOrUndefined(this.currentBattle.trainer)
&& this.currentBattle.trainer != null
&& this.currentBattle.trainer.config.hasSpecialtyType()
) {
if (species.speciesId === SpeciesId.WORMADAM) {
@ -2692,7 +2699,7 @@ export class BattleScene extends SceneBase {
}
} else if (modifier instanceof FusePokemonModifier) {
args.push(this.getPokemonById(modifier.fusePokemonId) as PlayerPokemon);
} else if (modifier instanceof RememberMoveModifier && !isNullOrUndefined(cost)) {
} else if (modifier instanceof RememberMoveModifier && cost != null) {
args.push(cost);
}
@ -3007,7 +3014,7 @@ export class BattleScene extends SceneBase {
}
if (
modifier instanceof PokemonHeldItemModifier
&& !isNullOrUndefined(modifier.getSpecies())
&& modifier.getSpecies() != null
&& !this.getPokemonById(modifier.pokemonId)?.hasSpecies(modifier.getSpecies()!)
) {
modifiers.splice(m--, 1);
@ -3573,7 +3580,7 @@ export class BattleScene extends SceneBase {
// Loading override or session encounter
let encounter: MysteryEncounter | null;
if (
!isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_OVERRIDE)
Overrides.MYSTERY_ENCOUNTER_OVERRIDE != null
&& allMysteryEncounters.hasOwnProperty(Overrides.MYSTERY_ENCOUNTER_OVERRIDE)
) {
encounter = allMysteryEncounters[Overrides.MYSTERY_ENCOUNTER_OVERRIDE];
@ -3584,7 +3591,7 @@ export class BattleScene extends SceneBase {
encounter = allMysteryEncounters[encounterType ?? -1];
return encounter;
} else {
encounter = !isNullOrUndefined(encounterType) ? allMysteryEncounters[encounterType] : null;
encounter = encounterType != null ? allMysteryEncounters[encounterType] : null;
}
// Check for queued encounters first
@ -3643,7 +3650,7 @@ export class BattleScene extends SceneBase {
? MysteryEncounterTier.ULTRA
: MysteryEncounterTier.ROGUE;
if (!isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_TIER_OVERRIDE)) {
if (Overrides.MYSTERY_ENCOUNTER_TIER_OVERRIDE != null) {
tier = Overrides.MYSTERY_ENCOUNTER_TIER_OVERRIDE;
}

View File

@ -1,7 +1,8 @@
/**
* @module
*
* A big file storing colors used in logging.
* Minified by Terser during production builds, so has no overhead.
* @module
*/
// Colors used in prod

View File

@ -67,7 +67,6 @@ import type { Constructor } from "#utils/common";
import {
BooleanHolder,
coerceArray,
isNullOrUndefined,
NumberHolder,
randSeedFloat,
randSeedInt,
@ -1040,7 +1039,7 @@ export class PostDefendStatStageChangeAbAttr extends PostDefendAbAttr {
if (this.allOthers) {
const ally = pokemon.getAlly();
const otherPokemon = !isNullOrUndefined(ally) ? pokemon.getOpponents().concat([ally]) : pokemon.getOpponents();
const otherPokemon = ally != null ? pokemon.getOpponents().concat([ally]) : pokemon.getOpponents();
for (const other of otherPokemon) {
globalScene.phaseManager.unshiftNew(
"StatStageChangePhase",
@ -1470,7 +1469,7 @@ export class PostDefendMoveDisableAbAttr extends PostDefendAbAttr {
override canApply({ move, opponent: attacker, pokemon }: PostMoveInteractionAbAttrParams): boolean {
return (
isNullOrUndefined(attacker.getTag(BattlerTagType.DISABLED))
attacker.getTag(BattlerTagType.DISABLED) == null
&& move.doesFlagEffectApply({ flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon })
&& (this.chance === -1 || pokemon.randBattleSeedInt(100) < this.chance)
);
@ -2807,7 +2806,7 @@ export class PostSummonAllyHealAbAttr extends PostSummonAbAttr {
override apply({ pokemon, simulated }: AbAttrBaseParams): void {
const target = pokemon.getAlly();
if (!simulated && !isNullOrUndefined(target)) {
if (!simulated && target != null) {
globalScene.phaseManager.unshiftNew(
"PokemonHealPhase",
target.getBattlerIndex(),
@ -2838,7 +2837,7 @@ export class PostSummonClearAllyStatStagesAbAttr extends PostSummonAbAttr {
override apply({ pokemon, simulated }: AbAttrBaseParams): void {
const target = pokemon.getAlly();
if (!simulated && !isNullOrUndefined(target)) {
if (!simulated && target != null) {
for (const s of BATTLE_STATS) {
target.setStatStage(s, 0);
}
@ -2957,13 +2956,13 @@ export class PostSummonHealStatusAbAttr extends PostSummonRemoveEffectAbAttr {
public override canApply({ pokemon }: AbAttrBaseParams): boolean {
const status = pokemon.status?.effect;
return !isNullOrUndefined(status) && (this.immuneEffects.length === 0 || this.immuneEffects.includes(status));
return status != null && (this.immuneEffects.length === 0 || this.immuneEffects.includes(status));
}
public override apply({ pokemon }: AbAttrBaseParams): void {
// TODO: should probably check against simulated...
const status = pokemon.status?.effect;
if (!isNullOrUndefined(status)) {
if (status != null) {
this.statusHealed = status;
pokemon.resetStatus(false);
pokemon.updateInfo();
@ -3099,7 +3098,7 @@ export class PostSummonCopyAllyStatsAbAttr extends PostSummonAbAttr {
}
const ally = pokemon.getAlly();
return !(isNullOrUndefined(ally) || ally.getStatStages().every(s => s === 0));
return !(ally == null || ally.getStatStages().every(s => s === 0));
}
override apply({ pokemon, simulated }: AbAttrBaseParams): void {
@ -3107,7 +3106,7 @@ export class PostSummonCopyAllyStatsAbAttr extends PostSummonAbAttr {
return;
}
const ally = pokemon.getAlly();
if (!isNullOrUndefined(ally)) {
if (ally != null) {
for (const s of BATTLE_STATS) {
pokemon.setStatStage(s, ally.getStatStage(s));
}
@ -3237,7 +3236,7 @@ export class CommanderAbAttr extends AbAttr {
const ally = pokemon.getAlly();
return (
globalScene.currentBattle?.double
&& !isNullOrUndefined(ally)
&& ally != null
&& ally.species.speciesId === SpeciesId.DONDOZO
&& !(ally.isFainted() || ally.getTag(BattlerTagType.COMMANDED))
);
@ -3281,7 +3280,7 @@ export class PreSwitchOutResetStatusAbAttr extends PreSwitchOutAbAttr {
}
override canApply({ pokemon }: AbAttrBaseParams): boolean {
return !isNullOrUndefined(pokemon.status);
return pokemon.status != null;
}
override apply({ pokemon, simulated }: AbAttrBaseParams): void {
@ -3561,7 +3560,7 @@ export class ProtectStatAbAttr extends PreStatStageChangeAbAttr {
}
override canApply({ stat, cancelled }: PreStatStageChangeAbAttrParams): boolean {
return !cancelled.value && (isNullOrUndefined(this.protectedStat) || stat === this.protectedStat);
return !cancelled.value && (this.protectedStat == null || stat === this.protectedStat);
}
/**
@ -3797,11 +3796,7 @@ export class ConditionalUserFieldProtectStatAbAttr extends PreStatStageChangeAbA
if (!target) {
return false;
}
return (
!cancelled.value
&& (isNullOrUndefined(this.protectedStat) || stat === this.protectedStat)
&& this.condition(target)
);
return !cancelled.value && (this.protectedStat == null || stat === this.protectedStat) && this.condition(target);
}
/**
@ -4558,7 +4553,7 @@ export class PostTurnStatusHealAbAttr extends PostTurnAbAttr {
}
override canApply({ pokemon }: AbAttrBaseParams): boolean {
return !isNullOrUndefined(pokemon.status) && this.effects.includes(pokemon.status.effect) && !pokemon.isFullHp();
return pokemon.status != null && this.effects.includes(pokemon.status.effect) && !pokemon.isFullHp();
}
override apply({ simulated, passive, pokemon }: AbAttrBaseParams): void {
@ -4893,7 +4888,7 @@ export class PostTurnHurtIfSleepingAbAttr extends PostTurnAbAttr {
*/
export class FetchBallAbAttr extends PostTurnAbAttr {
override canApply({ simulated, pokemon }: AbAttrBaseParams): boolean {
return !simulated && !isNullOrUndefined(globalScene.currentBattle.lastUsedPokeball) && !!pokemon.isPlayer;
return !simulated && globalScene.currentBattle.lastUsedPokeball != null && !!pokemon.isPlayer;
}
/**
@ -6258,7 +6253,7 @@ class ForceSwitchOutHelper {
true,
500,
);
if (globalScene.currentBattle.double && !isNullOrUndefined(allyPokemon)) {
if (globalScene.currentBattle.double && allyPokemon != null) {
globalScene.redirectPokemonMoves(switchOutTarget, allyPokemon);
}
}
@ -7110,7 +7105,7 @@ export function initAbilities() {
.attr(PostDefendMoveDisableAbAttr, 30)
.bypassFaint(),
new Ability(AbilityId.HEALER, 5)
.conditionalAttr(pokemon => !isNullOrUndefined(pokemon.getAlly()) && randSeedInt(10) < 3, PostTurnResetStatusAbAttr, true),
.conditionalAttr(pokemon => pokemon.getAlly() != null && randSeedInt(10) < 3, PostTurnResetStatusAbAttr, true),
new Ability(AbilityId.FRIEND_GUARD, 5)
.attr(AlliedFieldDamageReductionAbAttr, 0.75)
.ignorable(),

View File

@ -1,40 +1,4 @@
/** 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";
import { CommonBattleAnim } from "#data/battle-anims";
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 { 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 { 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 { isSpreadMove } from "#moves/move-utils";
import type {
ArenaScreenTagType,
ArenaTagData,
EntryHazardTagType,
RoomArenaTagType,
SerializableArenaTagType,
} from "#types/arena-tags";
import type { Mutable } from "#types/type-helpers";
import { BooleanHolder, type NumberHolder, toDmgValue } from "#utils/common";
import i18next from "i18next";
/**
* @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
@ -77,8 +41,44 @@ import i18next from "i18next";
* ```
* Notes
* - If the class has any subclasses, then the second form of `loadTag` *must* be used.
* @module
*/
/** 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";
import { CommonBattleAnim } from "#data/battle-anims";
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 { 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 { 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 { isSpreadMove } from "#moves/move-utils";
import type {
ArenaScreenTagType,
ArenaTagData,
EntryHazardTagType,
RoomArenaTagType,
SerializableArenaTagType,
} from "#types/arena-tags";
import type { Mutable } from "#types/type-helpers";
import { BooleanHolder, type NumberHolder, toDmgValue } from "#utils/common";
import i18next from "i18next";
/** Interface containing the serializable fields of ArenaTagData. */
interface BaseArenaTag {
/**
@ -197,9 +197,10 @@ export abstract class ArenaTag implements BaseArenaTag {
/**
* Apply effects when this Tag overlaps by creating a new instance while one is already present.
* @param _source - The {@linkcode Pokemon} having added the tag, or `null` if no pokemon did
* @param _source - The {@linkcode Pokemon} having added the tag, or `undefined` if no pokemon did
* @todo Rather than passing this `undefined`, maybe just... don't pass the tags?
*/
public onOverlap(_source: Pokemon | null): void {}
public onOverlap(_source: Pokemon | undefined): void {}
/**
* Reduce this {@linkcode ArenaTag}'s duration and apply any end-of-turn effects
@ -229,17 +230,17 @@ export abstract class ArenaTag implements BaseArenaTag {
}
/**
* Helper function that retrieves the source Pokemon
* Helper function that retrieves the source Pokemon.
* @returns - The source {@linkcode Pokemon} for this tag.
* Returns `undefined` if `this.sourceId` is `undefined`
*/
protected getSourcePokemon(): Pokemon | undefined {
return globalScene.getPokemonById(this.sourceId) ?? undefined;
return globalScene.getPokemonById(this.sourceId);
}
/**
* Helper function that retrieves the Pokemon affected
* @returns list of PlayerPokemon or EnemyPokemon on the field
* Helper function that retrieves the Pokemon affected.
* @returns An array containing all {@linkcode Pokemon} affected by this Tag.
*/
protected getAffectedPokemon(): Pokemon[] {
switch (this.side) {
@ -1467,7 +1468,7 @@ export class SuppressAbilitiesTag extends SerializableArenaTag {
return "arenaTag:neutralizingGasOnRemove";
}
private playActivationMessage(pokemon: Pokemon | null) {
private playActivationMessage(pokemon: Pokemon | undefined): void {
if (pokemon) {
globalScene.phaseManager.queueMessage(
i18next.t("arenaTag:neutralizingGasOnAdd", {
@ -1499,7 +1500,7 @@ export class SuppressAbilitiesTag extends SerializableArenaTag {
}
}
public override onOverlap(source: Pokemon | null): void {
public override onOverlap(source: Pokemon | undefined): void {
(this as Mutable<this>).sourceCount++;
this.playActivationMessage(source);
}

View File

@ -0,0 +1,235 @@
/*
* SPDX-Copyright-Text: 2025 Pagefault Games
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
/**
* # Balance: Moveset Generation Configuration
*
* This module contains configuration constants and functions that control
* the limitations and rules around moveset generation for generated Pokémon.
*
*
* ### Move Weights
*
* The various move weight constants in this module control how likely
* certain categories of moves are to appear in a generated Pokémon's
* moveset. Higher weights make a move more likely to be chosen.
* The constants here specify the *base* weight for a move when first computed.
* These weights are post-processed (and then scaled up such that weights have a larger impact,
* for instance, on boss Pokémon) before being used in the actual moveset generation.
*
* Post Processing of weights includes, but is not limited to:
* - Adjusting weights of status moves
* - Adjusting weights based on the move's power relative to the highest power available
* - Adjusting weights based on the stat the move uses to calculate damage relative to the higher stat
*
*
* All weights go through additional post-processing based on
* their expected power (accuracy * damage * expected number of hits)
*
* @module
*/
import { MoveId } from "#enums/move-id";
//#region Constants
/**
* The minimum level for a Pokémon to generate with a move it can only learn
* from a common tier TM
*/
export const COMMON_TIER_TM_LEVEL_REQUIREMENT = 25;
/**
* The minimum level for a Pokémon to generate with a move it can only learn
* from a great tier TM
*/
export const GREAT_TIER_TM_LEVEL_REQUIREMENT = 40;
/**
* The minimum level for a Pokémon to generate with a move it can only learn
* from an ultra tier TM
*/
export const ULTRA_TIER_TM_LEVEL_REQUIREMENT = 55;
/** Below this level, Pokémon will be unable to generate with any egg moves */
export const EGG_MOVE_LEVEL_REQUIREMENT = 60;
/** Below this level, Pokémon will be unable to generate with rare egg moves */
export const RARE_EGG_MOVE_LEVEL_REQUIREMENT = 170;
// Note: Not exported, only for use with `getMaxTmCount
/** Below this level, Pokémon will be unable to generate with any TMs */
const ONE_TM_THRESHOLD = 25;
/** Below this level, Pokémon will generate with at most 1 TM */
const TWO_TM_THRESHOLD = 41;
/** Below this level, Pokémon will generate with at most two TMs */
const THREE_TM_THRESHOLD = 71;
/** Below this level, Pokémon will generate with at most three TMs */
const FOUR_TM_THRESHOLD = 101;
/** Below this level, Pokémon will be unable to generate any egg moves */
const ONE_EGG_MOVE_THRESHOLD = 80;
/** Below this level, Pokémon will generate with at most 1 egg moves */
const TWO_EGG_MOVE_THRESHOLD = 121;
/** Below this level, Pokémon will generate with at most 2 egg moves */
const THREE_EGG_MOVE_THRESHOLD = 161;
/** Above this level, Pokémon will generate with at most 3 egg moves */
const FOUR_EGG_MOVE_THRESHOLD = 201;
/** The weight given to TMs in the common tier during moveset generation */
export const COMMON_TM_MOVESET_WEIGHT = 12;
/** The weight given to TMs in the great tier during moveset generation */
export const GREAT_TM_MOVESET_WEIGHT = 14;
/** The weight given to TMs in the ultra tier during moveset generation */
export const ULTRA_TM_MOVESET_WEIGHT = 18;
/**
* The base weight offset for level moves
*
* @remarks
* The relative likelihood of moves learned at different levels is determined by
* the ratio of their weights,
* or, the formula:
* `(levelB + BASE_LEVEL_WEIGHT_OFFSET) / (levelA + BASE_LEVEL_WEIGHT_OFFSET)`
*
* For example, consider move A and B that are learned at levels 1 and 60, respectively,
* but have no other differences (same power, accuracy, category, etc).
* The following table demonstrates the likelihood of move B being chosen over move A.
*
* | Offset | Likelihood |
* |--------|------------|
* | 0 | 60x |
* | 1 | 30x |
* | 5 | 10.8x |
* | 20 | 3.8x |
* | 60 | 2x |
*
* Note that increasing this without adjusting the other weights will decrease the likelihood of non-level moves
*
* For a complete picture, see {@link https://www.desmos.com/calculator/wgln4dxigl}
*/
export const BASE_LEVEL_WEIGHT_OFFSET = 20;
/**
* The maximum weight an egg move can ever have
* @remarks
* Egg moves have their weights adjusted based on the maximum weight of the Pokémon's
* level-up moves. Rare Egg moves are always 5/6th of the computed egg move weight.
* Boss pokemon are not allowed to spawn with rare egg moves.
* @see {@linkcode EGG_MOVE_TO_LEVEL_WEIGHT}
*/
export const EGG_MOVE_WEIGHT_MAX = 60;
/**
* The percentage of the Pokémon's highest weighted level move to the weight an
* egg move can generate with
*/
export const EGG_MOVE_TO_LEVEL_WEIGHT = 0.85;
/** The weight given to evolution moves */
export const EVOLUTION_MOVE_WEIGHT = 70;
/** The weight given to relearn moves */
export const RELEARN_MOVE_WEIGHT = 60;
/** The base weight multiplier to use
*
* The higher the number, the more impact weights have on the final move selection.
* i.e. if set to 0, all moves have equal chance of being selected regardless of their weight.
*/
export const BASE_WEIGHT_MULTIPLIER = 1.6;
/** The additional weight added onto {@linkcode BASE_WEIGHT_MULTIPLIER} for boss Pokémon */
export const BOSS_EXTRA_WEIGHT_MULTIPLIER = 0.4;
/**
* Set of moves that should be blacklisted from the forced STAB during moveset generation
*
* @remarks
* During moveset generation, trainer pokemon attempt to force their pokemon to generate with STAB
* moves in their movesets. Moves in this list not be considered to be "STAB" moves for this purpose.
* This does *not* prevent them from appearing in the moveset, but they will never
* be selected as a forced STAB move.
*/
export const STAB_BLACKLIST: ReadonlySet<MoveId> = new Set([
MoveId.BEAT_UP,
MoveId.BELCH,
MoveId.BIDE,
MoveId.COMEUPPANCE,
MoveId.COUNTER,
MoveId.DOOM_DESIRE,
MoveId.DRAGON_RAGE,
MoveId.DREAM_EATER,
MoveId.ENDEAVOR,
MoveId.EXPLOSION,
MoveId.FAKE_OUT,
MoveId.FIRST_IMPRESSION,
MoveId.FISSURE,
MoveId.FLING,
MoveId.FOCUS_PUNCH,
MoveId.FUTURE_SIGHT,
MoveId.GUILLOTINE,
MoveId.HOLD_BACK,
MoveId.HORN_DRILL,
MoveId.LAST_RESORT,
MoveId.METAL_BURST,
MoveId.MIRROR_COAT,
MoveId.MISTY_EXPLOSION,
MoveId.NATURAL_GIFT,
MoveId.NATURES_MADNESS,
MoveId.NIGHT_SHADE,
MoveId.PSYWAVE,
MoveId.RUINATION,
MoveId.SELF_DESTRUCT,
MoveId.SHEER_COLD,
MoveId.SHELL_TRAP,
MoveId.SKY_DROP,
MoveId.SNORE,
MoveId.SONIC_BOOM,
MoveId.SPIT_UP,
MoveId.STEEL_BEAM,
MoveId.STEEL_ROLLER,
MoveId.SUPER_FANG,
MoveId.SYNCHRONOISE,
MoveId.UPPER_HAND,
]);
//#endregion Constants
/**
* Get the maximum number of TMs a Pokémon is allowed to learn based on
* its level
* @param level - The level of the Pokémon
* @returns The number of TMs the Pokémon can learn at this level
*/
export function getMaxTmCount(level: number) {
if (level < ONE_TM_THRESHOLD) {
return 0;
}
if (level < TWO_TM_THRESHOLD) {
return 1;
}
if (level < THREE_TM_THRESHOLD) {
return 2;
}
if (level < FOUR_TM_THRESHOLD) {
return 3;
}
return 4;
}
export function getMaxEggMoveCount(level: number): number {
if (level < ONE_EGG_MOVE_THRESHOLD) {
return 0;
}
if (level < TWO_EGG_MOVE_THRESHOLD) {
return 1;
}
if (level < THREE_EGG_MOVE_THRESHOLD) {
return 2;
}
if (level < FOUR_EGG_MOVE_THRESHOLD) {
return 3;
}
return 4;
}

View File

@ -14,7 +14,7 @@ import { TimeOfDay } from "#enums/time-of-day";
import { WeatherType } from "#enums/weather-type";
import type { Pokemon } from "#field/pokemon";
import type { SpeciesStatBoosterItem, SpeciesStatBoosterModifierType } from "#modifiers/modifier-type";
import { coerceArray, isNullOrUndefined, randSeedInt } from "#utils/common";
import { coerceArray, randSeedInt } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import { toCamelCase } from "#utils/strings";
import i18next from "i18next";
@ -53,6 +53,7 @@ export enum EvolutionItem {
PRISM_SCALE,
RAZOR_CLAW,
RAZOR_FANG,
OVAL_STONE,
REAPER_CLOTH,
ELECTIRIZER,
MAGMARIZER,
@ -128,7 +129,7 @@ export class SpeciesEvolutionCondition {
}
public get description(): string[] {
if (!isNullOrUndefined(this.desc)) {
if (this.desc != null) {
return this.desc;
}
this.desc = this.data.map(cond => {
@ -161,11 +162,11 @@ export class SpeciesEvolutionCondition {
case EvoCondKey.HELD_ITEM:
return i18next.t(`pokemonEvolutions:heldItem.${toCamelCase(cond.itemKey)}`);
}
}).filter(s => !isNullOrUndefined(s)); // Filter out stringless conditions
}).filter(s => s != null); // Filter out stringless conditions
return this.desc;
}
public conditionsFulfilled(pokemon: Pokemon): boolean {
public conditionsFulfilled(pokemon: Pokemon, forFusion = false): boolean {
console.log(this.data);
return this.data.every(cond => {
switch (cond.key) {
@ -185,7 +186,7 @@ export class SpeciesEvolutionCondition {
m.getStackCount() + pokemon.getPersistentTreasureCount() >= cond.value
);
case EvoCondKey.GENDER:
return pokemon.gender === cond.gender;
return cond.gender === (forFusion ? pokemon.fusionGender : pokemon.gender);
case EvoCondKey.SHEDINJA: // Shedinja cannot be evolved into directly
return false;
case EvoCondKey.BIOME:
@ -233,7 +234,7 @@ export class SpeciesFormEvolution {
this.evoFormKey = evoFormKey;
this.level = level;
this.item = item || EvolutionItem.NONE;
if (!isNullOrUndefined(condition)) {
if (condition != null) {
this.condition = new SpeciesEvolutionCondition(...coerceArray(condition));
}
this.wildDelay = wildDelay ?? SpeciesWildEvolutionDelay.NONE;
@ -291,8 +292,8 @@ export class SpeciesFormEvolution {
return (
pokemon.level >= this.level &&
// Check form key, using the fusion's form key if we're checking the fusion
(isNullOrUndefined(this.preFormKey) || (forFusion ? pokemon.getFusionFormKey() : pokemon.getFormKey()) === this.preFormKey) &&
(isNullOrUndefined(this.condition) || this.condition.conditionsFulfilled(pokemon)) &&
(this.preFormKey == null || (forFusion ? pokemon.getFusionFormKey() : pokemon.getFormKey()) === this.preFormKey) &&
(this.condition == null || this.condition.conditionsFulfilled(pokemon, forFusion)) &&
((item ?? EvolutionItem.NONE) === (this.item ?? EvolutionItem.NONE))
);
}
@ -305,11 +306,11 @@ export class SpeciesFormEvolution {
*/
public isValidItemEvolution(pokemon: Pokemon, forFusion = false): boolean {
return (
!isNullOrUndefined(this.item) &&
this.item != null &&
pokemon.level >= this.level &&
// Check form key, using the fusion's form key if we're checking the fusion
(isNullOrUndefined(this.preFormKey) || (forFusion ? pokemon.getFusionFormKey() : pokemon.getFormKey()) === this.preFormKey) &&
(isNullOrUndefined(this.condition) || this.condition.conditionsFulfilled(pokemon))
(this.preFormKey == null || (forFusion ? pokemon.getFusionFormKey() : pokemon.getFormKey()) === this.preFormKey) &&
(this.condition == null || this.condition.conditionsFulfilled(pokemon))
);
}
@ -1496,10 +1497,13 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesFormEvolution(SpeciesId.DUDUNSPARCE, "", "two-segment", 32, null, {key: EvoCondKey.MOVE, move: MoveId.HYPER_DRILL}, SpeciesWildEvolutionDelay.LONG)
],
[SpeciesId.GLIGAR]: [
new SpeciesEvolution(SpeciesId.GLISCOR, 1, EvolutionItem.RAZOR_FANG, {key: EvoCondKey.TIME, time: [TimeOfDay.DUSK, TimeOfDay.NIGHT]} /* Razor fang at night*/, SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(SpeciesId.GLISCOR, 1, EvolutionItem.RAZOR_FANG, {key: EvoCondKey.TIME, time: [TimeOfDay.DUSK, TimeOfDay.NIGHT]}, SpeciesWildEvolutionDelay.VERY_LONG)
],
[SpeciesId.SNEASEL]: [
new SpeciesEvolution(SpeciesId.WEAVILE, 1, EvolutionItem.RAZOR_CLAW, {key: EvoCondKey.TIME, time: [TimeOfDay.DUSK, TimeOfDay.NIGHT]} /* Razor claw at night*/, SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(SpeciesId.WEAVILE, 1, EvolutionItem.RAZOR_CLAW, {key: EvoCondKey.TIME, time: [TimeOfDay.DUSK, TimeOfDay.NIGHT]}, SpeciesWildEvolutionDelay.VERY_LONG)
],
[SpeciesId.HAPPINY]: [
new SpeciesEvolution(SpeciesId.CHANSEY, 1, EvolutionItem.OVAL_STONE, {key: EvoCondKey.TIME, time: [TimeOfDay.DAWN, TimeOfDay.DAY]}, SpeciesWildEvolutionDelay.SHORT)
],
[SpeciesId.URSARING]: [
new SpeciesEvolution(SpeciesId.URSALUNA, 1, EvolutionItem.PEAT_BLOCK, null, SpeciesWildEvolutionDelay.VERY_LONG) //Ursaring does not evolve into Bloodmoon Ursaluna
@ -1760,7 +1764,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(SpeciesId.CROBAT, 1, null, {key: EvoCondKey.FRIENDSHIP, value: 120}, SpeciesWildEvolutionDelay.VERY_LONG)
],
[SpeciesId.CHANSEY]: [
new SpeciesEvolution(SpeciesId.BLISSEY, 1, null, {key: EvoCondKey.FRIENDSHIP, value: 200}, SpeciesWildEvolutionDelay.LONG)
new SpeciesEvolution(SpeciesId.BLISSEY, 1, null, {key: EvoCondKey.FRIENDSHIP, value: 180}, SpeciesWildEvolutionDelay.LONG)
],
[SpeciesId.PICHU]: [
new SpeciesFormEvolution(SpeciesId.PIKACHU, "spiky", "partner", 1, null, {key: EvoCondKey.FRIENDSHIP, value: 90}, SpeciesWildEvolutionDelay.SHORT),
@ -1787,9 +1791,6 @@ export const pokemonEvolutions: PokemonEvolutions = {
[SpeciesId.CHINGLING]: [
new SpeciesEvolution(SpeciesId.CHIMECHO, 1, null, [{key: EvoCondKey.FRIENDSHIP, value: 90}, {key: EvoCondKey.TIME, time: [TimeOfDay.DUSK, TimeOfDay.NIGHT]}], SpeciesWildEvolutionDelay.MEDIUM)
],
[SpeciesId.HAPPINY]: [
new SpeciesEvolution(SpeciesId.CHANSEY, 1, null, {key: EvoCondKey.FRIENDSHIP, value: 160}, SpeciesWildEvolutionDelay.SHORT)
],
[SpeciesId.MUNCHLAX]: [
new SpeciesEvolution(SpeciesId.SNORLAX, 1, null, {key: EvoCondKey.FRIENDSHIP, value: 120}, SpeciesWildEvolutionDelay.LONG)
],

View File

@ -7,7 +7,7 @@ import { AnimBlendType, AnimFocus, AnimFrameTarget, ChargeAnim, CommonAnim } fro
import { MoveFlags } from "#enums/move-flags";
import { MoveId } from "#enums/move-id";
import type { Pokemon } from "#field/pokemon";
import { coerceArray, getFrameMs, isNullOrUndefined, type nil } from "#utils/common";
import { coerceArray, getFrameMs, type nil } from "#utils/common";
import { getEnumKeys, getEnumValues } from "#utils/enums";
import { toKebabCase } from "#utils/strings";
import Phaser from "phaser";
@ -388,7 +388,7 @@ class AnimTimedAddBgEvent extends AnimTimedBgEvent {
moveAnim.bgSprite.setAlpha(this.opacity / 255);
globalScene.field.add(moveAnim.bgSprite);
const fieldPokemon = globalScene.getEnemyPokemon(false) ?? globalScene.getPlayerPokemon(false);
if (!isNullOrUndefined(priority)) {
if (priority != null) {
globalScene.field.moveTo(moveAnim.bgSprite as Phaser.GameObjects.GameObject, priority);
} else if (fieldPokemon?.isOnField()) {
globalScene.field.moveBelow(moveAnim.bgSprite as Phaser.GameObjects.GameObject, fieldPokemon);
@ -524,7 +524,7 @@ export async function initEncounterAnims(encounterAnim: EncounterAnim | Encounte
const encounterAnimNames = getEnumKeys(EncounterAnim);
const encounterAnimFetches: Promise<Map<EncounterAnim, AnimConfig>>[] = [];
for (const anim of anims) {
if (encounterAnims.has(anim) && !isNullOrUndefined(encounterAnims.get(anim))) {
if (encounterAnims.has(anim) && encounterAnims.get(anim) != null) {
continue;
}
encounterAnimFetches.push(
@ -1240,7 +1240,7 @@ export abstract class BattleAnim {
const graphicIndex = graphicFrameCount++;
const moveSprite = sprites[graphicIndex];
if (!isNullOrUndefined(frame.priority)) {
if (frame.priority != null) {
const setSpritePriority = (priority: number) => {
if (existingFieldSprites.length > priority) {
// Move to specified priority index

View File

@ -1,3 +1,42 @@
/**
* 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<this>).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<ExampleTag, "tagType" | "a" | "b"): void;
* public override loadTag<const T extends this>(source: BaseBattlerTag & Pick<T, "tagType" | "a" | "b">): void;
* }
* ```
* Notes
* - If the class has any subclasses, then the second form of `loadTag` *must* be used.
* @module
*/
import { applyAbAttrs } from "#abilities/apply-ab-attrs";
import { globalScene } from "#app/global-scene";
import { getPokemonNameWithAffix } from "#app/messages";
@ -49,48 +88,9 @@ import type {
TypeBoostTagType,
} from "#types/battler-tags";
import type { Mutable } from "#types/type-helpers";
import { BooleanHolder, coerceArray, getFrameMs, isNullOrUndefined, NumberHolder, toDmgValue } from "#utils/common";
import { BooleanHolder, coerceArray, getFrameMs, NumberHolder, toDmgValue } from "#utils/common";
import { toCamelCase } from "#utils/strings";
/**
* @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<this>).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<ExampleTag, "tagType" | "a" | "b"): void;
* public override loadTag<const T extends this>(source: BaseBattlerTag & Pick<T, "tagType" | "a" | "b">): void;
* }
* ```
* Notes
* - If the class has any subclasses, then the second form of `loadTag` *must* be used.
*/
/** Interface containing the serializable fields of BattlerTag */
interface BaseBattlerTag {
/** The tag's remaining duration */
@ -198,7 +198,7 @@ export class BattlerTag implements BaseBattlerTag {
* Helper function that retrieves the source Pokemon object
* @returns The source {@linkcode Pokemon}, or `null` if none is found
*/
public getSourcePokemon(): Pokemon | null {
public getSourcePokemon(): Pokemon | undefined {
return globalScene.getPokemonById(this.sourceId);
}
}
@ -378,7 +378,7 @@ export class DisabledTag extends MoveRestrictionBattlerTag {
// Disable fails against struggle or an empty move history
// TODO: Confirm if this is redundant given Disable/Cursed Body's disable conditions
const move = pokemon.getLastNonVirtualMove();
if (isNullOrUndefined(move) || move.move === MoveId.STRUGGLE) {
if (move == null || move.move === MoveId.STRUGGLE) {
return;
}
@ -451,7 +451,7 @@ export class GorillaTacticsTag extends MoveRestrictionBattlerTag {
override canAdd(pokemon: Pokemon): boolean {
// Choice items ignore struggle, so Gorilla Tactics should too
const lastSelectedMove = pokemon.getLastNonVirtualMove();
return !isNullOrUndefined(lastSelectedMove) && lastSelectedMove.move !== MoveId.STRUGGLE;
return lastSelectedMove != null && lastSelectedMove.move !== MoveId.STRUGGLE;
}
/**
@ -968,7 +968,7 @@ export class InfatuatedTag extends SerializableBattlerTag {
phaseManager.queueMessage(
i18next.t("battlerTags:infatuatedLapse", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
sourcePokemonName: getPokemonNameWithAffix(this.getSourcePokemon()),
}),
);
phaseManager.unshiftNew("CommonAnimPhase", pokemon.getBattlerIndex(), undefined, CommonAnim.ATTRACT);
@ -1305,7 +1305,7 @@ export class EncoreTag extends MoveRestrictionBattlerTag {
override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.CUSTOM) {
const encoredMove = pokemon.getMoveset().find(m => m.moveId === this.moveId);
return !isNullOrUndefined(encoredMove) && encoredMove.getPpRatio() > 0;
return encoredMove != null && encoredMove.getPpRatio() > 0;
}
return super.lapse(pokemon, lapseType);
}

View File

@ -1,5 +1,6 @@
import type { FixedBattleConfig } from "#app/battle";
import { getRandomTrainerFunc } from "#app/battle";
import { globalScene } from "#app/global-scene";
import { defaultStarterSpeciesAndEvolutions } from "#balance/pokemon-evolutions";
import { speciesStarterCosts } from "#balance/starters";
import type { PokemonSpecies } from "#data/pokemon-species";
@ -12,6 +13,7 @@ import { ClassicFixedBossWaves } from "#enums/fixed-boss-waves";
import { ModifierTier } from "#enums/modifier-tier";
import { MoveId } from "#enums/move-id";
import type { MoveSourceType } from "#enums/move-source-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Nature } from "#enums/nature";
import { PokemonType } from "#enums/pokemon-type";
import { SpeciesId } from "#enums/species-id";
@ -1076,7 +1078,12 @@ export class LimitedCatchChallenge extends Challenge {
override applyPokemonAddToParty(pokemon: EnemyPokemon, status: BooleanHolder): boolean {
if (status.value) {
status.value = pokemon.metWave % 10 === 1;
const isTeleporter =
globalScene.currentBattle.mysteryEncounter?.encounterType === MysteryEncounterType.TELEPORTING_HIJINKS
&& globalScene.currentBattle.mysteryEncounter.selectedOption
!== globalScene.currentBattle.mysteryEncounter.options[2]; // don't allow catch when not choosing biome change option
const isFirstWave = pokemon.metWave % 10 === 1;
status.value = isTeleporter || isFirstWave;
return true;
}
return false;

View File

@ -6,8 +6,8 @@ import { PokemonSpecies } from "#data/pokemon-species";
import { BiomeId } from "#enums/biome-id";
import { PartyMemberStrength } from "#enums/party-member-strength";
import { SpeciesId } from "#enums/species-id";
import type { Starter } from "#ui/handlers/starter-select-ui-handler";
import { isNullOrUndefined, randSeedGauss, randSeedInt, randSeedItem } from "#utils/common";
import type { Starter } from "#ui/starter-select-ui-handler";
import { randSeedGauss, randSeedInt, randSeedItem } from "#utils/common";
import { getEnumValues } from "#utils/enums";
import { getPokemonSpecies, getPokemonSpeciesForm } from "#utils/pokemon-utils";
@ -32,7 +32,7 @@ export function getDailyRunStarters(seed: string): Starter[] {
const startingLevel = globalScene.gameMode.getStartingLevel();
const eventStarters = getDailyEventSeedStarters(seed);
if (!isNullOrUndefined(eventStarters)) {
if (eventStarters != null) {
starters.push(...eventStarters);
return;
}
@ -127,7 +127,7 @@ const dailyBiomeWeights: BiomeWeights = {
export function getDailyStartingBiome(): BiomeId {
const eventBiome = getDailyEventSeedBiome(globalScene.seed);
if (!isNullOrUndefined(eventBiome)) {
if (eventBiome != null) {
return eventBiome;
}

View File

@ -7,7 +7,7 @@ import { PokemonType } from "#enums/pokemon-type";
import type { Pokemon } from "#field/pokemon";
import { applyMoveAttrs } from "#moves/apply-attrs";
import type { Move, MoveTargetSet, UserMoveConditionFunc } from "#moves/move";
import { isNullOrUndefined, NumberHolder } from "#utils/common";
import { NumberHolder } from "#utils/common";
/**
* Return whether the move targets the field
@ -78,7 +78,7 @@ export function getMoveTargets(user: Pokemon, move: MoveId, replaceTarget?: Move
case MoveTarget.OTHER:
case MoveTarget.ALL_NEAR_OTHERS:
case MoveTarget.ALL_OTHERS:
set = !isNullOrUndefined(ally) ? opponents.concat([ally]) : opponents;
set = ally != null ? opponents.concat([ally]) : opponents;
multiple = moveTarget === MoveTarget.ALL_NEAR_OTHERS || moveTarget === MoveTarget.ALL_OTHERS;
break;
case MoveTarget.NEAR_ENEMY:
@ -95,22 +95,22 @@ export function getMoveTargets(user: Pokemon, move: MoveId, replaceTarget?: Move
return { targets: [-1 as BattlerIndex], multiple: false };
case MoveTarget.NEAR_ALLY:
case MoveTarget.ALLY:
set = !isNullOrUndefined(ally) ? [ally] : [];
set = ally != null ? [ally] : [];
break;
case MoveTarget.USER_OR_NEAR_ALLY:
case MoveTarget.USER_AND_ALLIES:
case MoveTarget.USER_SIDE:
set = !isNullOrUndefined(ally) ? [user, ally] : [user];
set = ally != null ? [user, ally] : [user];
multiple = moveTarget !== MoveTarget.USER_OR_NEAR_ALLY;
break;
case MoveTarget.ALL:
case MoveTarget.BOTH_SIDES:
set = (!isNullOrUndefined(ally) ? [user, ally] : [user]).concat(opponents);
set = (ally != null ? [user, ally] : [user]).concat(opponents);
multiple = true;
break;
case MoveTarget.CURSE:
{
const extraTargets = !isNullOrUndefined(ally) ? [ally] : [];
const extraTargets = ally != null ? [ally] : [];
set = user.getTypes(true).includes(PokemonType.GHOST) ? opponents.concat(extraTargets) : [user];
}
break;

View File

@ -88,7 +88,7 @@ import type { AttackMoveResult } from "#types/attack-move-result";
import type { Localizable } from "#types/locales";
import type { ChargingMove, MoveAttrMap, MoveAttrString, MoveClassMap, MoveKindString, MoveMessageFunc } from "#types/move-types";
import type { TurnMove } from "#types/turn-move";
import { BooleanHolder, coerceArray, type Constructor, isNullOrUndefined, NumberHolder, randSeedFloat, randSeedInt, randSeedItem, toDmgValue } from "#utils/common";
import { BooleanHolder, coerceArray, type Constructor, NumberHolder, randSeedFloat, randSeedInt, randSeedItem, toDmgValue } from "#utils/common";
import { getEnumValues } from "#utils/enums";
import { toCamelCase, toTitleCase } from "#utils/strings";
import i18next from "i18next";
@ -835,7 +835,7 @@ export abstract class Move implements Localizable {
applyAbAttrs("VariableMovePowerAbAttr", abAttrParams);
const ally = source.getAlly();
if (!isNullOrUndefined(ally)) {
if (ally != null) {
applyAbAttrs("AllyMoveCategoryPowerBoostAbAttr", {...abAttrParams, pokemon: ally});
}
@ -965,7 +965,7 @@ export abstract class Move implements Localizable {
// ...and cannot enhance Pollen Puff when targeting an ally.
const ally = user.getAlly();
const exceptPollenPuffAlly: boolean = this.id === MoveId.POLLEN_PUFF && !isNullOrUndefined(ally) && targets.includes(ally.getBattlerIndex())
const exceptPollenPuffAlly: boolean = this.id === MoveId.POLLEN_PUFF && ally != null && targets.includes(ally.getBattlerIndex())
return (!restrictSpread || !isMultiTarget)
&& !this.isChargingMove()
@ -2114,7 +2114,7 @@ export class FlameBurstAttr extends MoveEffectAttr {
const targetAlly = target.getAlly();
const cancelled = new BooleanHolder(false);
if (!isNullOrUndefined(targetAlly)) {
if (targetAlly != null) {
applyAbAttrs("BlockNonDirectDamageAbAttr", {pokemon: targetAlly, cancelled});
}
@ -2127,7 +2127,7 @@ export class FlameBurstAttr extends MoveEffectAttr {
}
getTargetBenefitScore(user: Pokemon, target: Pokemon, move: Move): number {
return !isNullOrUndefined(target.getAlly()) ? -5 : 0;
return target.getAlly() != null ? -5 : 0;
}
}
@ -3156,7 +3156,7 @@ export class WeatherInstantChargeAttr extends InstantChargeAttr {
super((user, move) => {
const currentWeather = globalScene.arena.weather;
if (isNullOrUndefined(currentWeather?.weatherType)) {
if (currentWeather?.weatherType == null) {
return false;
} else {
return !currentWeather?.isEffectSuppressed()
@ -6293,7 +6293,7 @@ export class RevivalBlessingAttr extends MoveEffectAttr {
pokemon.heal(Math.min(toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp()));
globalScene.phaseManager.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: getPokemonNameWithAffix(pokemon) }), 0, true);
const allyPokemon = user.getAlly();
if (globalScene.currentBattle.double && globalScene.getEnemyParty().length > 1 && !isNullOrUndefined(allyPokemon)) {
if (globalScene.currentBattle.double && globalScene.getEnemyParty().length > 1 && allyPokemon != null) {
// Handle cases where revived pokemon needs to get switched in on same turn
if (allyPokemon.isFainted() || allyPokemon === pokemon) {
// Enemy switch phase should be removed and replaced with the revived pkmn switching in
@ -6462,7 +6462,7 @@ export class ForceSwitchOutAttr extends MoveEffectAttr {
globalScene.phaseManager.queueMessage(i18next.t("moveTriggers:fled", { pokemonName: getPokemonNameWithAffix(switchOutTarget) }), null, true, 500);
// in double battles redirect potential moves off fled pokemon
if (globalScene.currentBattle.double && !isNullOrUndefined(allyPokemon)) {
if (globalScene.currentBattle.double && allyPokemon != null) {
globalScene.redirectPokemonMoves(switchOutTarget, allyPokemon);
}
}
@ -7122,7 +7122,7 @@ export class CopyMoveAttr extends CallMoveAttr {
getCondition(): MoveConditionFunc {
return (_user, target, _move) => {
const lastMove = this.mirrorMove ? target.getLastNonVirtualMove(false, false)?.move : globalScene.currentBattle.lastMove;
return !isNullOrUndefined(lastMove) && !this.invalidMoves.has(lastMove);
return lastMove != null && !this.invalidMoves.has(lastMove);
};
}
}
@ -7169,7 +7169,7 @@ export class RepeatMoveAttr extends MoveEffectAttr {
&& firstTarget !== target.getAlly()
) {
const ally = firstTarget.getAlly();
if (!isNullOrUndefined(ally) && ally.isActive()) {
if (ally != null && ally.isActive()) {
moveTargets = [ ally.getBattlerIndex() ];
}
}
@ -7476,7 +7476,7 @@ export class SketchAttr extends MoveEffectAttr {
}
const targetMove = target.getLastNonVirtualMove();
return !isNullOrUndefined(targetMove)
return targetMove != null
&& !invalidSketchMoves.has(targetMove.move)
&& user.getMoveset().every(m => m.moveId !== targetMove.move)
};
@ -7533,7 +7533,7 @@ export class AbilityCopyAttr extends MoveEffectAttr {
user.setTempAbility(target.getAbility());
const ally = user.getAlly();
if (this.copyToPartner && globalScene.currentBattle?.double && !isNullOrUndefined(ally) && ally.hp) { // TODO is this the best way to check that the ally is active?
if (this.copyToPartner && globalScene.currentBattle?.double && ally != null && ally.hp) { // TODO is this the best way to check that the ally is active?
globalScene.phaseManager.queueMessage(i18next.t("moveTriggers:copiedTargetAbility", { pokemonName: getPokemonNameWithAffix(ally), targetName: getPokemonNameWithAffix(target), abilityName: allAbilities[target.getAbility().id].name }));
ally.setTempAbility(target.getAbility());
}
@ -8054,7 +8054,7 @@ const failIfGhostTypeCondition: MoveConditionFunc = (user: Pokemon, target: Poke
const failIfNoTargetHeldItemsCondition: MoveConditionFunc = (user: Pokemon, target: Pokemon, move: Move) => target.getHeldItems().filter(i => i.isTransferable)?.length > 0;
const attackedByItemMessageFunc = (user: Pokemon, target: Pokemon, move: Move) => {
if (isNullOrUndefined(target)) { // Fix bug when used against targets that have both fainted
if (target == null) { // Fix bug when used against targets that have both fainted
return "";
}
const heldItems = target.getHeldItems().filter(i => i.isTransferable);
@ -8611,7 +8611,7 @@ export function initMoves() {
.attr(AddBattlerTagAttr, BattlerTagType.DISABLED, false, true)
.condition((_user, target, _move) => {
const lastNonVirtualMove = target.getLastNonVirtualMove();
return !isNullOrUndefined(lastNonVirtualMove) && lastNonVirtualMove.move !== MoveId.STRUGGLE;
return lastNonVirtualMove != null && lastNonVirtualMove.move !== MoveId.STRUGGLE;
})
.ignoresSubstitute()
.reflectable(),
@ -9955,7 +9955,7 @@ export function initMoves() {
.condition(failOnGravityCondition)
.condition((_user, target, _move) => ![ SpeciesId.DIGLETT, SpeciesId.DUGTRIO, SpeciesId.ALOLA_DIGLETT, SpeciesId.ALOLA_DUGTRIO, SpeciesId.SANDYGAST, SpeciesId.PALOSSAND, SpeciesId.WIGLETT, SpeciesId.WUGTRIO ].includes(target.species.speciesId))
.condition((_user, target, _move) => !(target.species.speciesId === SpeciesId.GENGAR && target.getFormKey() === "mega"))
.condition((_user, target, _move) => isNullOrUndefined(target.getTag(BattlerTagType.INGRAIN)) && isNullOrUndefined(target.getTag(BattlerTagType.IGNORE_FLYING)))
.condition((_user, target, _move) => target.getTag(BattlerTagType.INGRAIN) == null && target.getTag(BattlerTagType.IGNORE_FLYING) == null)
.attr(AddBattlerTagAttr, BattlerTagType.TELEKINESIS, false, true, 3)
.attr(AddBattlerTagAttr, BattlerTagType.FLOATING, false, true, 3)
.reflectable(),

View File

@ -46,9 +46,9 @@ import {
} from "#mystery-encounters/mystery-encounter-requirements";
import { getRandomPartyMemberFunc, trainerConfigs } from "#trainers/trainer-config";
import { TrainerPartyCompoundTemplate, TrainerPartyTemplate } from "#trainers/trainer-party-template";
import { MoveInfoOverlay } from "#ui/containers/move-info-overlay";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import { isNullOrUndefined, randSeedInt, randSeedShuffle } from "#utils/common";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { MoveInfoOverlay } from "#ui/move-info-overlay";
import { randSeedInt, randSeedShuffle } from "#utils/common";
import i18next from "i18next";
/** the i18n namespace for the encounter */
@ -571,7 +571,7 @@ function getTrainerConfigForWave(waveIndex: number) {
.setPartyMemberFunc(
4,
getRandomPartyMemberFunc([pool3Mon.species], TrainerSlot.TRAINER, true, p => {
if (!isNullOrUndefined(pool3Mon.formIndex)) {
if (pool3Mon.formIndex != null) {
p.formIndex = pool3Mon.formIndex;
p.generateAndPopulateMoveset();
p.generateName();
@ -603,7 +603,7 @@ function getTrainerConfigForWave(waveIndex: number) {
.setPartyMemberFunc(
3,
getRandomPartyMemberFunc([pool3Mon.species], TrainerSlot.TRAINER, true, p => {
if (!isNullOrUndefined(pool3Mon.formIndex)) {
if (pool3Mon.formIndex != null) {
p.formIndex = pool3Mon.formIndex;
p.generateAndPopulateMoveset();
p.generateName();
@ -613,7 +613,7 @@ function getTrainerConfigForWave(waveIndex: number) {
.setPartyMemberFunc(
4,
getRandomPartyMemberFunc([pool3Mon2.species], TrainerSlot.TRAINER, true, p => {
if (!isNullOrUndefined(pool3Mon2.formIndex)) {
if (pool3Mon2.formIndex != null) {
p.formIndex = pool3Mon2.formIndex;
p.generateAndPopulateMoveset();
p.generateName();
@ -648,7 +648,7 @@ function getTrainerConfigForWave(waveIndex: number) {
.setPartyMemberFunc(
3,
getRandomPartyMemberFunc([pool3Mon.species], TrainerSlot.TRAINER, true, p => {
if (!isNullOrUndefined(pool3Mon.formIndex)) {
if (pool3Mon.formIndex != null) {
p.formIndex = pool3Mon.formIndex;
p.generateAndPopulateMoveset();
p.generateName();
@ -687,7 +687,7 @@ function getTrainerConfigForWave(waveIndex: number) {
.setPartyMemberFunc(
2,
getRandomPartyMemberFunc([pool3Mon.species], TrainerSlot.TRAINER, true, p => {
if (!isNullOrUndefined(pool3Mon.formIndex)) {
if (pool3Mon.formIndex != null) {
p.formIndex = pool3Mon.formIndex;
p.generateAndPopulateMoveset();
p.generateName();
@ -697,7 +697,7 @@ function getTrainerConfigForWave(waveIndex: number) {
.setPartyMemberFunc(
3,
getRandomPartyMemberFunc([pool3Mon2.species], TrainerSlot.TRAINER, true, p => {
if (!isNullOrUndefined(pool3Mon2.formIndex)) {
if (pool3Mon2.formIndex != null) {
p.formIndex = pool3Mon2.formIndex;
p.generateAndPopulateMoveset();
p.generateName();

View File

@ -45,7 +45,7 @@ import { MysteryEncounterBuilder } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encounter-option";
import { trainerConfigs } from "#trainers/trainer-config";
import { TrainerPartyCompoundTemplate, TrainerPartyTemplate } from "#trainers/trainer-party-template";
import type { OptionSelectConfig } from "#ui/handlers/abstract-option-select-ui-handler";
import type { OptionSelectConfig } from "#ui/abstract-option-select-ui-handler";
import { randSeedInt, randSeedShuffle } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import i18next from "i18next";

View File

@ -37,7 +37,7 @@ import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encou
import { MoveRequirement } from "#mystery-encounters/mystery-encounter-requirements";
import { DANCING_MOVES } from "#mystery-encounters/requirement-groups";
import { PokemonData } from "#system/pokemon-data";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import i18next from "i18next";

View File

@ -15,7 +15,7 @@ import { getRandomPlayerPokemon, getRandomSpeciesByStarterCost } from "#mystery-
import type { MysteryEncounter } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterBuilder } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encounter-option";
import { isNullOrUndefined, randSeedInt } from "#utils/common";
import { randSeedInt } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
/** i18n namespace for encounter */
@ -192,7 +192,7 @@ export const DarkDealEncounter: MysteryEncounter = MysteryEncounterBuilder.withE
};
}),
};
if (!isNullOrUndefined(bossSpecies.forms) && bossSpecies.forms.length > 0) {
if (bossSpecies.forms != null && bossSpecies.forms.length > 0) {
pokemonConfig.formIndex = 0;
}
const config: EnemyPartyConfig = {

View File

@ -33,7 +33,7 @@ import {
MoneyRequirement,
} from "#mystery-encounters/mystery-encounter-requirements";
import i18next from "#plugins/i18n";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { randSeedItem } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";

View File

@ -18,7 +18,7 @@ import {
import type { MysteryEncounter } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterBuilder } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encounter-option";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import i18next from "i18next";
/** i18n namespace for the encounter */

View File

@ -45,7 +45,7 @@ import {
TypeRequirement,
} from "#mystery-encounters/mystery-encounter-requirements";
import { FIRE_RESISTANT_ABILITIES } from "#mystery-encounters/requirement-groups";
import { isNullOrUndefined, randSeedInt } from "#utils/common";
import { randSeedInt } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
/** the i18n namespace for the encounter */
@ -238,7 +238,7 @@ export const FieryFalloutEncounter: MysteryEncounter = MysteryEncounterBuilder.w
// Burn random member
const burnable = nonFireTypes.filter(
p => isNullOrUndefined(p.status) || isNullOrUndefined(p.status.effect) || p.status.effect === StatusEffect.NONE,
p => p.status == null || p.status.effect == null || p.status.effect === StatusEffect.NONE,
);
if (burnable?.length > 0) {
const roll = randSeedInt(burnable.length);

View File

@ -42,8 +42,8 @@ import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encou
import { PartySizeRequirement } from "#mystery-encounters/mystery-encounter-requirements";
import { PokemonData } from "#system/pokemon-data";
import { MusicPreference } from "#system/settings";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import { isNullOrUndefined, NumberHolder, randInt, randSeedInt, randSeedItem, randSeedShuffle } from "#utils/common";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { NumberHolder, randInt, randSeedInt, randSeedItem, randSeedShuffle } from "#utils/common";
import { getEnumKeys } from "#utils/enums";
import { getRandomLocaleEntry } from "#utils/i18n";
import { getPokemonSpecies } from "#utils/pokemon-utils";
@ -537,7 +537,7 @@ function generateTradeOption(alreadyUsedSpecies: PokemonSpecies[], originalBst?:
bstCap = originalBst + 100;
bstMin = originalBst - 100;
}
while (isNullOrUndefined(newSpecies)) {
while (newSpecies == null) {
// Get all non-legendary species that fall within the Bst range requirements
let validSpecies = allSpecies.filter(s => {
const isLegendaryOrMythical = s.legendary || s.subLegendary || s.mythical;
@ -550,7 +550,7 @@ function generateTradeOption(alreadyUsedSpecies: PokemonSpecies[], originalBst?:
if (validSpecies?.length > 20) {
validSpecies = randSeedShuffle(validSpecies);
newSpecies = validSpecies.pop();
while (isNullOrUndefined(newSpecies) || alreadyUsedSpecies.includes(newSpecies)) {
while (newSpecies == null || alreadyUsedSpecies.includes(newSpecies)) {
newSpecies = validSpecies.pop();
}
} else {

View File

@ -28,7 +28,7 @@ import { MysteryEncounterBuilder } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encounter-option";
import { MoneyRequirement } from "#mystery-encounters/mystery-encounter-requirements";
import { PokemonData } from "#system/pokemon-data";
import { isNullOrUndefined, randSeedInt, randSeedItem } from "#utils/common";
import { randSeedInt, randSeedItem } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
/** the i18n namespace for this encounter */
@ -81,7 +81,7 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter = MysteryEncounterBui
let tries = 0;
// Reroll any species that don't have HAs
while ((isNullOrUndefined(species.abilityHidden) || species.abilityHidden === AbilityId.NONE) && tries < 5) {
while ((species.abilityHidden == null || species.abilityHidden === AbilityId.NONE) && tries < 5) {
species = getSalesmanSpeciesOffer();
tries++;
}
@ -110,7 +110,7 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter = MysteryEncounterBui
*/
if (
r === 0
|| ((isNullOrUndefined(species.abilityHidden) || species.abilityHidden === AbilityId.NONE)
|| ((species.abilityHidden == null || species.abilityHidden === AbilityId.NONE)
&& validEventEncounters.length === 0)
) {
// If you roll 1%, give shiny Magikarp with random variant
@ -118,7 +118,7 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter = MysteryEncounterBui
pokemon = new PlayerPokemon(species, 5, 2, undefined, undefined, true);
} else if (
validEventEncounters.length > 0
&& (r <= EVENT_THRESHOLD || isNullOrUndefined(species.abilityHidden) || species.abilityHidden === AbilityId.NONE)
&& (r <= EVENT_THRESHOLD || species.abilityHidden == null || species.abilityHidden === AbilityId.NONE)
) {
tries = 0;
do {

View File

@ -27,8 +27,8 @@ import { MysteryEncounterBuilder } from "#mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encounter-option";
import { PokemonData } from "#system/pokemon-data";
import type { HeldModifierConfig } from "#types/held-modifier-config";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import { isNullOrUndefined, randSeedShuffle } from "#utils/common";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { randSeedShuffle } from "#utils/common";
import { getEnumValues } from "#utils/enums";
import i18next from "i18next";
@ -324,7 +324,7 @@ export const TrainingSessionEncounter: MysteryEncounter = MysteryEncounterBuilde
// Only update the fusion's dex data if the Pokemon is already caught in dex (ignore rentals)
const rootFusionSpecies = playerPokemon.fusionSpecies?.getRootSpeciesId();
if (
!isNullOrUndefined(rootFusionSpecies)
rootFusionSpecies != null
&& speciesStarterCosts.hasOwnProperty(rootFusionSpecies)
&& !!globalScene.gameData.dexData[rootFusionSpecies].caughtAttr
) {

View File

@ -32,7 +32,7 @@ import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encou
import { MoveRequirement, PersistentModifierRequirement } from "#mystery-encounters/mystery-encounter-requirements";
import { CHARMING_MOVES } from "#mystery-encounters/requirement-groups";
import { PokemonData } from "#system/pokemon-data";
import { isNullOrUndefined, randSeedInt } from "#utils/common";
import { randSeedInt } from "#utils/common";
/** the i18n namespace for the encounter */
const namespace = "mysteryEncounters/uncommonBreed";
@ -167,7 +167,7 @@ export const UncommonBreedEncounter: MysteryEncounter = MysteryEncounterBuilder.
const encounter = globalScene.currentBattle.mysteryEncounter!;
const eggMove = encounter.misc.eggMove;
if (!isNullOrUndefined(eggMove)) {
if (eggMove != null) {
// Check what type of move the egg move is to determine target
const pokemonMove = new PokemonMove(eggMove);
const move = pokemonMove.getMove();

View File

@ -41,7 +41,7 @@ import { PokemonData } from "#system/pokemon-data";
import { trainerConfigs } from "#trainers/trainer-config";
import { TrainerPartyTemplate } from "#trainers/trainer-party-template";
import type { HeldModifierConfig } from "#types/held-modifier-config";
import { isNullOrUndefined, NumberHolder, randSeedInt, randSeedShuffle } from "#utils/common";
import { NumberHolder, randSeedInt, randSeedShuffle } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
/** i18n namespace for encounter */
@ -634,7 +634,7 @@ function getTransformedSpecies(
alreadyUsedSpecies: PokemonSpecies[],
): PokemonSpecies {
let newSpecies: PokemonSpecies | undefined;
while (isNullOrUndefined(newSpecies)) {
while (newSpecies == null) {
const bstCap = originalBst + bstSearchRange[1];
const bstMin = Math.max(originalBst + bstSearchRange[0], 0);
@ -655,7 +655,7 @@ function getTransformedSpecies(
if (validSpecies?.length > 20) {
validSpecies = randSeedShuffle(validSpecies);
newSpecies = validSpecies.pop();
while (isNullOrUndefined(newSpecies) || alreadyUsedSpecies.includes(newSpecies)) {
while (newSpecies == null || alreadyUsedSpecies.includes(newSpecies)) {
newSpecies = validSpecies.pop();
}
} else {
@ -771,12 +771,12 @@ async function addEggMoveToNewPokemonMoveset(
if (eggMoves) {
const eggMoveIndices = randSeedShuffle([0, 1, 2, 3]);
let randomEggMoveIndex = eggMoveIndices.pop();
let randomEggMove = !isNullOrUndefined(randomEggMoveIndex) ? eggMoves[randomEggMoveIndex] : null;
let randomEggMove = randomEggMoveIndex != null ? eggMoves[randomEggMoveIndex] : null;
let retries = 0;
while (retries < 3 && (!randomEggMove || newPokemon.moveset.some(m => m.moveId === randomEggMove))) {
// If Pokemon already knows this move, roll for another egg move
randomEggMoveIndex = eggMoveIndices.pop();
randomEggMove = !isNullOrUndefined(randomEggMoveIndex) ? eggMoves[randomEggMoveIndex] : null;
randomEggMove = randomEggMoveIndex != null ? eggMoves[randomEggMoveIndex] : null;
retries++;
}
@ -791,11 +791,7 @@ async function addEggMoveToNewPokemonMoveset(
}
// For pokemon that the player owns (including ones just caught), unlock the egg move
if (
!forBattle
&& !isNullOrUndefined(randomEggMoveIndex)
&& !!globalScene.gameData.dexData[speciesRootForm].caughtAttr
) {
if (!forBattle && randomEggMoveIndex != null && !!globalScene.gameData.dexData[speciesRootForm].caughtAttr) {
await globalScene.gameData.setEggMoveUnlocked(getPokemonSpecies(speciesRootForm), randomEggMoveIndex, true);
}
}

View File

@ -12,7 +12,7 @@ import {
MoneyRequirement,
TypeRequirement,
} from "#mystery-encounters/mystery-encounter-requirements";
import { isNullOrUndefined, randSeedInt } from "#utils/common";
import { randSeedInt } from "#utils/common";
// biome-ignore lint/suspicious/noConfusingVoidType: void unions in callbacks are OK
export type OptionPhaseCallback = () => Promise<void | boolean>;
@ -62,7 +62,7 @@ export class MysteryEncounterOption implements IMysteryEncounterOption {
onPostOptionPhase?: OptionPhaseCallback;
constructor(option: IMysteryEncounterOption | null) {
if (!isNullOrUndefined(option)) {
if (option != null) {
Object.assign(this, option);
}
this.hasDexProgress = this.hasDexProgress ?? false;

View File

@ -15,7 +15,7 @@ import { WeatherType } from "#enums/weather-type";
import type { PlayerPokemon } from "#field/pokemon";
import { AttackTypeBoosterModifier } from "#modifiers/modifier";
import type { AttackTypeBoosterModifierType } from "#modifiers/modifier-type";
import { coerceArray, isNullOrUndefined } from "#utils/common";
import { coerceArray } from "#utils/common";
export interface EncounterRequirement {
meetsRequirement(): boolean; // Boolean to see if a requirement is met
@ -219,7 +219,7 @@ export class WaveRangeRequirement extends EncounterSceneRequirement {
}
override meetsRequirement(): boolean {
if (!isNullOrUndefined(this.waveRange) && this.waveRange[0] <= this.waveRange[1]) {
if (this.waveRange != null && this.waveRange[0] <= this.waveRange[1]) {
const waveIndex = globalScene.currentBattle.waveIndex;
if (
(waveIndex >= 0 && this.waveRange[0] >= 0 && this.waveRange[0] > waveIndex)
@ -275,11 +275,7 @@ export class TimeOfDayRequirement extends EncounterSceneRequirement {
override meetsRequirement(): boolean {
const timeOfDay = globalScene.arena?.getTimeOfDay();
return !(
!isNullOrUndefined(timeOfDay)
&& this.requiredTimeOfDay?.length > 0
&& !this.requiredTimeOfDay.includes(timeOfDay)
);
return !(timeOfDay != null && this.requiredTimeOfDay?.length > 0 && !this.requiredTimeOfDay.includes(timeOfDay));
}
override getDialogueToken(_pokemon?: PlayerPokemon): [string, string] {
@ -298,7 +294,7 @@ export class WeatherRequirement extends EncounterSceneRequirement {
override meetsRequirement(): boolean {
const currentWeather = globalScene.arena.weather?.weatherType;
return !(
!isNullOrUndefined(currentWeather)
currentWeather != null
&& this.requiredWeather?.length > 0
&& !this.requiredWeather.includes(currentWeather!)
);
@ -307,7 +303,7 @@ export class WeatherRequirement extends EncounterSceneRequirement {
override getDialogueToken(_pokemon?: PlayerPokemon): [string, string] {
const currentWeather = globalScene.arena.weather?.weatherType;
let token = "";
if (!isNullOrUndefined(currentWeather)) {
if (currentWeather != null) {
token = WeatherType[currentWeather].replace("_", " ").toLocaleLowerCase();
}
return ["weather", token];
@ -331,7 +327,7 @@ export class PartySizeRequirement extends EncounterSceneRequirement {
}
override meetsRequirement(): boolean {
if (!isNullOrUndefined(this.partySizeRange) && this.partySizeRange[0] <= this.partySizeRange[1]) {
if (this.partySizeRange != null && this.partySizeRange[0] <= this.partySizeRange[1]) {
const partySize = this.excludeDisallowedPokemon
? globalScene.getPokemonAllowedInBattle().length
: globalScene.getPlayerParty().length;
@ -363,7 +359,7 @@ export class PersistentModifierRequirement extends EncounterSceneRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredHeldItemModifiers?.length < 0) {
if (partyPokemon == null || this.requiredHeldItemModifiers?.length < 0) {
return false;
}
let modifierCount = 0;
@ -396,7 +392,7 @@ export class MoneyRequirement extends EncounterSceneRequirement {
override meetsRequirement(): boolean {
const money = globalScene.money;
if (isNullOrUndefined(money)) {
if (money == null) {
return false;
}
@ -429,7 +425,7 @@ export class SpeciesRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredSpecies?.length < 0) {
if (partyPokemon == null || this.requiredSpecies?.length < 0) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -469,7 +465,7 @@ export class NatureRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredNature?.length < 0) {
if (partyPokemon == null || this.requiredNature?.length < 0) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -484,7 +480,7 @@ export class NatureRequirement extends EncounterPokemonRequirement {
}
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
if (!isNullOrUndefined(pokemon?.nature) && this.requiredNature.includes(pokemon.nature)) {
if (pokemon?.nature != null && this.requiredNature.includes(pokemon.nature)) {
return ["nature", Nature[pokemon.nature]];
}
return ["nature", ""];
@ -508,7 +504,7 @@ export class TypeRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
let partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon)) {
if (partyPokemon == null) {
return false;
}
@ -561,7 +557,7 @@ export class MoveRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) {
if (partyPokemon == null || this.requiredMoves?.length < 0) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -612,7 +608,7 @@ export class CompatibleMoveRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) {
if (partyPokemon == null || this.requiredMoves?.length < 0) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -668,7 +664,7 @@ export class AbilityRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredAbilities?.length < 0) {
if (partyPokemon == null || this.requiredAbilities?.length < 0) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -692,7 +688,7 @@ export class AbilityRequirement extends EncounterPokemonRequirement {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const matchingAbility = this.requiredAbilities.find(a => pokemon?.hasAbility(a, false));
if (!isNullOrUndefined(matchingAbility)) {
if (matchingAbility != null) {
return ["ability", allAbilities[matchingAbility].name];
}
return ["ability", ""];
@ -713,7 +709,7 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredStatusEffect?.length < 0) {
if (partyPokemon == null || this.requiredStatusEffect?.length < 0) {
return false;
}
const x = this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -727,11 +723,7 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement {
return this.requiredStatusEffect.some(statusEffect => {
if (statusEffect === StatusEffect.NONE) {
// StatusEffect.NONE also checks for null or undefined status
return (
isNullOrUndefined(pokemon.status)
|| isNullOrUndefined(pokemon.status.effect)
|| pokemon.status.effect === statusEffect
);
return pokemon.status == null || pokemon.status.effect == null || pokemon.status.effect === statusEffect;
}
return pokemon.status?.effect === statusEffect;
});
@ -742,11 +734,7 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement {
return !this.requiredStatusEffect.some(statusEffect => {
if (statusEffect === StatusEffect.NONE) {
// StatusEffect.NONE also checks for null or undefined status
return (
isNullOrUndefined(pokemon.status)
|| isNullOrUndefined(pokemon.status.effect)
|| pokemon.status.effect === statusEffect
);
return pokemon.status == null || pokemon.status.effect == null || pokemon.status.effect === statusEffect;
}
return pokemon.status?.effect === statusEffect;
});
@ -756,9 +744,7 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const reqStatus = this.requiredStatusEffect.filter(a => {
if (a === StatusEffect.NONE) {
return (
isNullOrUndefined(pokemon?.status) || isNullOrUndefined(pokemon.status.effect) || pokemon.status.effect === a
);
return pokemon?.status == null || pokemon.status.effect == null || pokemon.status.effect === a;
}
return pokemon!.status?.effect === a;
});
@ -788,7 +774,7 @@ export class CanFormChangeWithItemRequirement extends EncounterPokemonRequiremen
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon) || this.requiredFormChangeItem?.length < 0) {
if (partyPokemon == null || this.requiredFormChangeItem?.length < 0) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -847,7 +833,7 @@ export class HeldItemRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon)) {
if (partyPokemon == null) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -911,7 +897,7 @@ export class AttackTypeBoosterHeldItemTypeRequirement extends EncounterPokemonRe
override meetsRequirement(): boolean {
const partyPokemon = globalScene.getPlayerParty();
if (isNullOrUndefined(partyPokemon)) {
if (partyPokemon == null) {
return false;
}
return this.queryParty(partyPokemon).length >= this.minNumberOfPokemon;
@ -978,7 +964,7 @@ export class LevelRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
// Party Pokemon inside required level range
if (!isNullOrUndefined(this.requiredLevelRange) && this.requiredLevelRange[0] <= this.requiredLevelRange[1]) {
if (this.requiredLevelRange != null && this.requiredLevelRange[0] <= this.requiredLevelRange[1]) {
const partyPokemon = globalScene.getPlayerParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
@ -1019,10 +1005,7 @@ export class FriendshipRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
// Party Pokemon inside required friendship range
if (
!isNullOrUndefined(this.requiredFriendshipRange)
&& this.requiredFriendshipRange[0] <= this.requiredFriendshipRange[1]
) {
if (this.requiredFriendshipRange != null && this.requiredFriendshipRange[0] <= this.requiredFriendshipRange[1]) {
const partyPokemon = globalScene.getPlayerParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
@ -1071,7 +1054,7 @@ export class HealthRatioRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
// Party Pokemon's health inside required health range
if (!isNullOrUndefined(this.requiredHealthRange) && this.requiredHealthRange[0] <= this.requiredHealthRange[1]) {
if (this.requiredHealthRange != null && this.requiredHealthRange[0] <= this.requiredHealthRange[1]) {
const partyPokemon = globalScene.getPlayerParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
@ -1098,7 +1081,7 @@ export class HealthRatioRequirement extends EncounterPokemonRequirement {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const hpRatio = pokemon?.getHpRatio();
if (!isNullOrUndefined(hpRatio)) {
if (hpRatio != null) {
return ["healthRatio", Math.floor(hpRatio * 100).toString() + "%"];
}
return ["healthRatio", ""];
@ -1119,7 +1102,7 @@ export class WeightRequirement extends EncounterPokemonRequirement {
override meetsRequirement(): boolean {
// Party Pokemon's weight inside required weight range
if (!isNullOrUndefined(this.requiredWeightRange) && this.requiredWeightRange[0] <= this.requiredWeightRange[1]) {
if (this.requiredWeightRange != null && this.requiredWeightRange[0] <= this.requiredWeightRange[1]) {
const partyPokemon = globalScene.getPlayerParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {

View File

@ -1,7 +1,6 @@
import { BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT } from "#app/constants";
import type { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
import type { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { isNullOrUndefined } from "#utils/common";
export class SeenEncounterData {
type: MysteryEncounterType;
@ -28,7 +27,7 @@ export class MysteryEncounterSaveData {
queuedEncounters: QueuedEncounter[] = [];
constructor(data?: MysteryEncounterSaveData) {
if (!isNullOrUndefined(data)) {
if (data != null) {
Object.assign(this, data);
}

View File

@ -25,7 +25,7 @@ import {
StatusEffectRequirement,
WaveRangeRequirement,
} from "#mystery-encounters/mystery-encounter-requirements";
import { coerceArray, isNullOrUndefined, randSeedInt } from "#utils/common";
import { coerceArray, randSeedInt } from "#utils/common";
import { capitalizeFirstLetter } from "#utils/strings";
export interface EncounterStartOfBattleEffect {
@ -275,7 +275,7 @@ export class MysteryEncounter implements IMysteryEncounter {
private seedOffset?: any;
constructor(encounter: IMysteryEncounter | null) {
if (!isNullOrUndefined(encounter)) {
if (encounter != null) {
Object.assign(this, encounter);
}
this.encounterTier = this.encounterTier ?? MysteryEncounterTier.COMMON;

View File

@ -3,7 +3,7 @@ import type { MoveId } from "#enums/move-id";
import type { PlayerPokemon } from "#field/pokemon";
import { PokemonMove } from "#moves/pokemon-move";
import { EncounterPokemonRequirement } from "#mystery-encounters/mystery-encounter-requirements";
import { coerceArray, isNullOrUndefined } from "#utils/common";
import { coerceArray } from "#utils/common";
/**
* {@linkcode CanLearnMoveRequirement} options
@ -44,7 +44,7 @@ export class CanLearnMoveRequirement extends EncounterPokemonRequirement {
.getPlayerParty()
.filter(pkm => (this.includeFainted ? pkm.isAllowedInChallenge() : pkm.isAllowedInBattle()));
if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) {
if (partyPokemon == null || this.requiredMoves?.length < 0) {
return false;
}

View File

@ -1,7 +1,6 @@
import { globalScene } from "#app/global-scene";
import type { TextStyle } from "#enums/text-style";
import { getTextWithColors } from "#ui/text";
import { isNullOrUndefined } from "#utils/common";
import i18next from "i18next";
/**
@ -11,7 +10,7 @@ import i18next from "i18next";
* @param primaryStyle Can define a text style to be applied to the entire string. Must be defined for BBCodeText styles to be applied correctly
*/
export function getEncounterText(keyOrString?: string, primaryStyle?: TextStyle): string | null {
if (isNullOrUndefined(keyOrString)) {
if (keyOrString == null) {
return null;
}

View File

@ -46,10 +46,10 @@ import type { PokemonData } from "#system/pokemon-data";
import type { TrainerConfig } from "#trainers/trainer-config";
import { trainerConfigs } from "#trainers/trainer-config";
import type { HeldModifierConfig } from "#types/held-modifier-config";
import type { OptionSelectConfig, OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import type { PartyOption, PokemonSelectFilter } from "#ui/handlers/party-ui-handler";
import { PartyUiMode } from "#ui/handlers/party-ui-handler";
import { coerceArray, isNullOrUndefined, randomString, randSeedInt, randSeedItem } from "#utils/common";
import type { OptionSelectConfig, OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import type { PartyOption, PokemonSelectFilter } from "#ui/party-ui-handler";
import { PartyUiMode } from "#ui/party-ui-handler";
import { coerceArray, randomString, randSeedInt, randSeedItem } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import i18next from "i18next";
@ -143,7 +143,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
const trainerType = partyConfig?.trainerType;
const partyTrainerConfig = partyConfig?.trainerConfig;
let trainerConfig: TrainerConfig;
if (!isNullOrUndefined(trainerType) || partyTrainerConfig) {
if (trainerType != null || partyTrainerConfig) {
globalScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.TRAINER_BATTLE;
if (globalScene.currentBattle.trainer) {
globalScene.currentBattle.trainer.setVisible(false);
@ -154,7 +154,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
const doubleTrainer = trainerConfig.doubleOnly || (trainerConfig.hasDouble && !!partyConfig.doubleBattle);
doubleBattle = doubleTrainer;
const trainerFemale = isNullOrUndefined(partyConfig.female) ? !!randSeedInt(2) : partyConfig.female;
const trainerFemale = partyConfig.female == null ? !!randSeedInt(2) : partyConfig.female;
const newTrainer = new Trainer(
trainerConfig.trainerType,
doubleTrainer ? TrainerVariant.DOUBLE : trainerFemale ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT,
@ -202,7 +202,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
let dataSource: PokemonData | undefined;
let isBoss = false;
if (!loaded) {
if ((!isNullOrUndefined(trainerType) || trainerConfig) && battle.trainer) {
if ((trainerType != null || trainerConfig) && battle.trainer) {
// Allows overriding a trainer's pokemon to use specific species/data
if (partyConfig?.pokemonConfigs && e < partyConfig.pokemonConfigs.length) {
const config = partyConfig.pokemonConfigs[e];
@ -258,7 +258,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
enemyPokemon.resetSummonData();
}
if ((!loaded && isNullOrUndefined(partyConfig.countAsSeen)) || partyConfig.countAsSeen) {
if ((!loaded && partyConfig.countAsSeen == null) || partyConfig.countAsSeen) {
globalScene.gameData.setPokemonSeen(enemyPokemon, true, !!(trainerType || trainerConfig));
}
@ -266,7 +266,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
const config = partyConfig.pokemonConfigs[e];
// Set form
if (!isNullOrUndefined(config.nickname)) {
if (config.nickname != null) {
enemyPokemon.nickname = btoa(unescape(encodeURIComponent(config.nickname)));
}
@ -276,22 +276,22 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
}
// Set form
if (!isNullOrUndefined(config.formIndex)) {
if (config.formIndex != null) {
enemyPokemon.formIndex = config.formIndex;
}
// Set shiny
if (!isNullOrUndefined(config.shiny)) {
if (config.shiny != null) {
enemyPokemon.shiny = config.shiny;
}
// Set Variant
if (enemyPokemon.shiny && !isNullOrUndefined(config.variant)) {
if (enemyPokemon.shiny && config.variant != null) {
enemyPokemon.variant = config.variant;
}
// Set custom mystery encounter data fields (such as sprite scale, custom abilities, types, etc.)
if (!isNullOrUndefined(config.customPokemonData)) {
if (config.customPokemonData != null) {
enemyPokemon.customPokemonData = config.customPokemonData;
}
@ -300,7 +300,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
let segments =
config.bossSegments
?? globalScene.getEncounterBossSegments(globalScene.currentBattle.waveIndex, level, enemySpecies, true);
if (!isNullOrUndefined(config.bossSegmentModifier)) {
if (config.bossSegmentModifier != null) {
segments += config.bossSegmentModifier;
}
enemyPokemon.setBoss(true, segments);
@ -335,18 +335,18 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig):
}
// Set ability
if (!isNullOrUndefined(config.abilityIndex)) {
if (config.abilityIndex != null) {
enemyPokemon.abilityIndex = config.abilityIndex;
}
// Set gender
if (!isNullOrUndefined(config.gender)) {
if (config.gender != null) {
enemyPokemon.gender = config.gender!;
enemyPokemon.summonData.gender = config.gender;
}
// Set AI type
if (!isNullOrUndefined(config.aiType)) {
if (config.aiType != null) {
enemyPokemon.aiType = config.aiType;
}

View File

@ -31,11 +31,11 @@ import {
showEncounterText,
} from "#mystery-encounters/encounter-dialogue-utils";
import { achvs } from "#system/achv";
import type { PartyOption } from "#ui/handlers/party-ui-handler";
import { PartyUiMode } from "#ui/handlers/party-ui-handler";
import { SummaryUiMode } from "#ui/handlers/summary-ui-handler";
import type { PartyOption } from "#ui/party-ui-handler";
import { PartyUiMode } from "#ui/party-ui-handler";
import { SummaryUiMode } from "#ui/summary-ui-handler";
import { applyChallenges } from "#utils/challenge-utils";
import { BooleanHolder, isNullOrUndefined, randSeedInt } from "#utils/common";
import { BooleanHolder, randSeedInt } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import i18next from "i18next";
@ -276,7 +276,7 @@ export function getRandomSpeciesByStarterCost(
if (types && types.length > 0) {
filteredSpecies = filteredSpecies.filter(
s => types.includes(s[0].type1) || (!isNullOrUndefined(s[0].type2) && types.includes(s[0].type2)),
s => types.includes(s[0].type1) || (s[0].type2 != null && types.includes(s[0].type2)),
);
}

View File

@ -28,7 +28,7 @@ import type { Variant, VariantSet } from "#sprites/variant";
import { populateVariantColorCache, variantColorCache, variantData } from "#sprites/variant";
import type { Localizable } from "#types/locales";
import type { StarterMoveset } from "#types/save-data";
import { isNullOrUndefined, randSeedFloat, randSeedGauss, randSeedInt } from "#utils/common";
import { randSeedFloat, randSeedGauss, randSeedInt } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import { toCamelCase, toPascalCase } from "#utils/strings";
import { argbFromRgba, QuantizerCelebi, rgbaFromArgb } from "@material/material-color-utilities";
@ -197,7 +197,7 @@ export abstract class PokemonSpeciesForm {
* @returns The id of the ability
*/
getPassiveAbility(formIndex?: number): AbilityId {
if (isNullOrUndefined(formIndex)) {
if (formIndex == null) {
formIndex = this.formIndex;
}
let starterSpeciesId = this.speciesId;
@ -551,7 +551,7 @@ export abstract class PokemonSpeciesForm {
const spriteKey = this.getSpriteKey(female, formIndex, shiny, variant, back);
globalScene.loadPokemonAtlas(spriteKey, this.getSpriteAtlasPath(female, formIndex, shiny, variant, back));
globalScene.load.audio(this.getCryKey(formIndex), `audio/${this.getCryKey(formIndex)}.m4a`);
if (!isNullOrUndefined(variant)) {
if (variant != null) {
await this.loadVariantColors(spriteKey, female, variant, back, formIndex);
}
return new Promise<void>(resolve => {
@ -579,7 +579,7 @@ export abstract class PokemonSpeciesForm {
const spritePath = this.getSpriteAtlasPath(female, formIndex, shiny, variant, back)
.replace("variant/", "")
.replace(/_[1-3]$/, "");
if (!isNullOrUndefined(variant)) {
if (variant != null) {
loadPokemonVariantAssets(spriteKey, spritePath, variant).then(() => resolve());
}
});
@ -791,7 +791,7 @@ export class PokemonSpecies extends PokemonSpeciesForm implements Localizable {
* @returns A randomly rolled gender based on this Species' {@linkcode malePercent}.
*/
generateGender(): Gender {
if (isNullOrUndefined(this.malePercent)) {
if (this.malePercent == null) {
return Gender.GENDERLESS;
}

View File

@ -16,7 +16,6 @@ import type { AttackMoveResult } from "#types/attack-move-result";
import type { IllusionData } from "#types/illusion-data";
import type { TurnMove } from "#types/turn-move";
import type { CoerceNullPropertiesToUndefined } from "#types/type-helpers";
import { isNullOrUndefined } from "#utils/common";
import { getPokemonSpeciesForm } from "#utils/pokemon-utils";
/**
@ -64,14 +63,14 @@ function deserializePokemonSpeciesForm(value: SerializedSpeciesForm | PokemonSpe
// @ts-expect-error: We may be deserializing a PokemonSpeciesForm, but we catch later on
let { id, formIdx } = value;
if (isNullOrUndefined(id) || isNullOrUndefined(formIdx)) {
if (id == null || formIdx == null) {
// @ts-expect-error: Typescript doesn't know that in block, `value` must be a PokemonSpeciesForm
id = value.speciesId;
// @ts-expect-error: Same as above (plus we are accessing a protected property)
formIdx = value._formIndex;
}
// If for some reason either of these fields are null/undefined, we cannot reconstruct the species form
if (isNullOrUndefined(id) || isNullOrUndefined(formIdx)) {
if (id == null || formIdx == null) {
return null;
}
return getPokemonSpeciesForm(id, formIdx);
@ -151,13 +150,13 @@ export class PokemonSummonData {
public moveHistory: TurnMove[] = [];
constructor(source?: PokemonSummonData | SerializedPokemonSummonData) {
if (isNullOrUndefined(source)) {
if (source == null) {
return;
}
// TODO: Rework this into an actual generic function for use elsewhere
for (const [key, value] of Object.entries(source)) {
if (isNullOrUndefined(value) && this.hasOwnProperty(key)) {
if (value == null && this.hasOwnProperty(key)) {
continue;
}
@ -171,7 +170,7 @@ export class PokemonSummonData {
const illusionData = {
...value,
};
if (!isNullOrUndefined(illusionData.fusionSpecies)) {
if (illusionData.fusionSpecies != null) {
switch (typeof illusionData.fusionSpecies) {
case "object":
illusionData.fusionSpecies = allSpecies[illusionData.fusionSpecies.speciesId];
@ -224,18 +223,18 @@ export class PokemonSummonData {
CoerceNullPropertiesToUndefined<PokemonSummonData>,
"speciesForm" | "fusionSpeciesForm" | "illusion"
>),
speciesForm: isNullOrUndefined(speciesForm)
? undefined
: { id: speciesForm.speciesId, formIdx: speciesForm.formIndex },
fusionSpeciesForm: isNullOrUndefined(fusionSpeciesForm)
? undefined
: { id: fusionSpeciesForm.speciesId, formIdx: fusionSpeciesForm.formIndex },
illusion: isNullOrUndefined(illusion)
? undefined
: {
...(this.illusion as Omit<typeof illusion, "fusionSpecies">),
fusionSpecies: illusionSpeciesForm?.speciesId,
},
speciesForm: speciesForm == null ? undefined : { id: speciesForm.speciesId, formIdx: speciesForm.formIndex },
fusionSpeciesForm:
fusionSpeciesForm == null
? undefined
: { id: fusionSpeciesForm.speciesId, formIdx: fusionSpeciesForm.formIndex },
illusion:
illusion == null
? undefined
: {
...(this.illusion as Omit<typeof illusion, "fusionSpecies">),
fusionSpecies: illusionSpeciesForm?.speciesId,
},
};
// Replace `null` with `undefined`, as `undefined` never gets serialized
for (const [key, value] of Object.entries(t)) {
@ -278,7 +277,7 @@ export class PokemonBattleData {
public berriesEaten: BerryType[] = [];
constructor(source?: PokemonBattleData | Partial<PokemonBattleData>) {
if (!isNullOrUndefined(source)) {
if (source != null) {
this.hitCount = source.hitCount ?? 0;
this.hasEatenBerry = source.hasEatenBerry ?? false;
this.berriesEaten = source.berriesEaten ?? [];

View File

@ -234,7 +234,7 @@ const seasonalSplashMessages: Season[] = [
"valentines.happyValentines",
"valentines.fullOfLove",
"valentines.applinForYou",
"valentines.thePowerOfLoveIsThreeThirtyBST",
"valentines.thePowerOfLoveIsThreeThirtyBst",
"valentines.haveAHeartScale",
"valentines.i<3You",
],
@ -265,7 +265,7 @@ const seasonalSplashMessages: Season[] = [
"aprilFools.whoIsFinn",
"aprilFools.watchOutForShadowPokemon",
"aprilFools.nowWithDarkTypeLuxray",
"aprilFools.onlyOnPokerogueNetAGAIN",
"aprilFools.onlyOnPokerogueNetAgain",
"aprilFools.noFreeVouchers",
"aprilFools.altffourAchievementPoints",
"aprilFools.rokePogue",

View File

@ -3,6 +3,8 @@ import { globalScene } from "#app/global-scene";
import { pokemonEvolutions, pokemonPrevolutions } from "#balance/pokemon-evolutions";
import { signatureSpecies } from "#balance/signature-species";
import { tmSpecies } from "#balance/tms";
// biome-ignore lint/correctness/noUnusedImports: Used in a tsdoc comment
import type { RARE_EGG_MOVE_LEVEL_REQUIREMENT } from "#data/balance/moveset-generation";
import { modifierTypes } from "#data/data-lists";
import { doubleBattleDialogue } from "#data/double-battle-dialogue";
import { Gender } from "#data/gender";
@ -41,7 +43,8 @@ import type {
TrainerConfigs,
TrainerTierPools,
} from "#types/trainer-funcs";
import { coerceArray, isNullOrUndefined, randSeedInt, randSeedIntRange, randSeedItem } from "#utils/common";
import type { Mutable } from "#types/type-helpers";
import { coerceArray, randSeedInt, randSeedIntRange, randSeedItem } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import { toCamelCase, toTitleCase } from "#utils/strings";
import i18next from "i18next";
@ -119,6 +122,15 @@ export class TrainerConfig {
public hasVoucher = false;
public trainerAI: TrainerAI;
/**
* Whether this trainer's Pokémon are allowed to generate with egg moves
* @defaultValue `false`
*
* @see {@linkcode setEggMovesAllowed}
* @see {@linkcode RARE_EGG_MOVE_LEVEL_THRESHOLD}
*/
public readonly allowEggMoves: boolean = false;
public encounterMessages: string[] = [];
public victoryMessages: string[] = [];
public defeatMessages: string[] = [];
@ -387,8 +399,27 @@ export class TrainerConfig {
return this;
}
setBoss(): TrainerConfig {
/**
* Allow this trainer's Pokémon to have egg moves when generating their movesets.
*
* @remarks
* It is redundant to call this if {@linkcode setBoss} is also called on the configuration.
* @returns `this` for method chaining
* @see {@linkcode allowEggMoves}
*/
public setEggMovesAllowed(): this {
(this as Mutable<this>).allowEggMoves = true;
return this;
}
/**
* Set this trainer as a boss trainer
* @returns `this` for method chaining
* @see {@linkcode isBoss}
*/
public setBoss(): TrainerConfig {
this.isBoss = true;
(this as Mutable<this>).allowEggMoves = true;
return this;
}
@ -474,7 +505,7 @@ export class TrainerConfig {
.fill(null)
.map((_, i) => i)
.filter(i => shedinjaCanTera || party[i].species.speciesId !== SpeciesId.SHEDINJA); // Shedinja can only Tera on Bug specialty type (or no specialty type)
const setPartySlot = !isNullOrUndefined(slot) ? Phaser.Math.Wrap(slot, 0, party.length) : -1; // If we have a tera slot defined, wrap it to party size.
const setPartySlot = slot != null ? Phaser.Math.Wrap(slot, 0, party.length) : -1; // If we have a tera slot defined, wrap it to party size.
for (let t = 0; t < Math.min(count(), party.length); t++) {
const randomIndex =
partyMemberIndexes.indexOf(setPartySlot) > -1 ? setPartySlot : randSeedItem(partyMemberIndexes);
@ -537,7 +568,7 @@ export class TrainerConfig {
initI18n();
}
if (!isNullOrUndefined(specialtyType)) {
if (specialtyType != null) {
this.setSpecialtyType(specialtyType);
}
@ -612,7 +643,7 @@ export class TrainerConfig {
signatureSpecies.forEach((speciesPool, s) => {
this.setPartyMemberFunc(-(s + 1), getRandomPartyMemberFunc(coerceArray(speciesPool)));
});
if (!isNullOrUndefined(specialtyType)) {
if (specialtyType != null) {
this.setSpeciesFilter(p => p.isOfType(specialtyType));
this.setSpecialtyType(specialtyType);
}
@ -717,7 +748,7 @@ export class TrainerConfig {
});
// Set species filter and specialty type if provided, otherwise filter by base total.
if (!isNullOrUndefined(specialtyType)) {
if (specialtyType != null) {
this.setSpeciesFilter(p => p.isOfType(specialtyType) && p.baseTotal >= ELITE_FOUR_MINIMUM_BST);
this.setSpecialtyType(specialtyType);
} else {
@ -895,7 +926,7 @@ export class TrainerConfig {
* @returns `true` if `specialtyType` is defined and not {@link PokemonType.UNKNOWN}
*/
hasSpecialtyType(): boolean {
return !isNullOrUndefined(this.specialtyType) && this.specialtyType !== PokemonType.UNKNOWN;
return this.specialtyType != null && this.specialtyType !== PokemonType.UNKNOWN;
}
/**
@ -2942,7 +2973,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.SLOWBRO, SpeciesId.GALAR_SLOWBRO], TrainerSlot.TRAINER, true, p => {
// Tera Ice Slowbro/G-Slowbro
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.ICE_BEAM)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.ICE_BEAM)) {
// Check if Ice Beam is in the moveset, if not, replace the third move with Ice Beam.
p.moveset[2] = new PokemonMove(MoveId.ICE_BEAM);
}
@ -2967,7 +2998,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.STEELIX], TrainerSlot.TRAINER, true, p => {
// Tera Fighting Steelix
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.BODY_PRESS)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.BODY_PRESS)) {
// Check if Body Press is in the moveset, if not, replace the third move with Body Press.
p.moveset[2] = new PokemonMove(MoveId.BODY_PRESS);
}
@ -2992,7 +3023,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.ARBOK, SpeciesId.WEEZING], TrainerSlot.TRAINER, true, p => {
// Tera Ghost Arbok/Weezing
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3018,7 +3049,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.GYARADOS, SpeciesId.AERODACTYL], TrainerSlot.TRAINER, true, p => {
// Tera Dragon Gyarados/Aerodactyl
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3079,7 +3110,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.GENGAR], TrainerSlot.TRAINER, true, p => {
// Tera Dark Gengar
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.DARK_PULSE)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.DARK_PULSE)) {
// Check if Dark Pulse is in the moveset, if not, replace the third move with Dark Pulse.
p.moveset[2] = new PokemonMove(MoveId.DARK_PULSE);
}
@ -3163,7 +3194,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.DHELMISE], TrainerSlot.TRAINER, true, p => {
// Tera Dragon Dhelmise
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3193,7 +3224,7 @@ export const trainerConfigs: TrainerConfigs = {
p.setBoss(true, 2);
p.abilityIndex = 1; // Sniper
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.X_SCISSOR)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.X_SCISSOR)) {
// Check if X-Scissor is in the moveset, if not, replace the third move with X-Scissor.
p.moveset[2] = new PokemonMove(MoveId.X_SCISSOR);
}
@ -3232,7 +3263,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.STEELIX, SpeciesId.LOPUNNY], TrainerSlot.TRAINER, true, p => {
// Tera Fire Steelix/Lopunny
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3375,7 +3406,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.CERULEDGE], TrainerSlot.TRAINER, true, p => {
// Tera Steel Ceruledge
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.IRON_HEAD)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.IRON_HEAD)) {
// Check if Iron Head is in the moveset, if not, replace the third move with Iron Head.
p.moveset[2] = new PokemonMove(MoveId.IRON_HEAD);
}
@ -3413,7 +3444,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.INCINEROAR], TrainerSlot.TRAINER, true, p => {
// Tera Fighting Incineroar
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.CROSS_CHOP)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.CROSS_CHOP)) {
// Check if Cross Chop is in the moveset, if not, replace the third move with Cross Chop.
p.moveset[2] = new PokemonMove(MoveId.CROSS_CHOP);
}
@ -3486,7 +3517,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.DECIDUEYE], TrainerSlot.TRAINER, true, p => {
// Tera Flying Decidueye
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.BRAVE_BIRD)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.BRAVE_BIRD)) {
// Check if Brave Bird is in the moveset, if not, replace the third move with Brave Bird.
p.moveset[2] = new PokemonMove(MoveId.BRAVE_BIRD);
}
@ -3511,7 +3542,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.TOXICROAK], TrainerSlot.TRAINER, true, p => {
// Tera Dark Toxicroak
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.SUCKER_PUNCH)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.SUCKER_PUNCH)) {
// Check if Sucker Punch is in the moveset, if not, replace the third move with Sucker Punch.
p.moveset[2] = new PokemonMove(MoveId.SUCKER_PUNCH);
}
@ -3536,7 +3567,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.EISCUE], TrainerSlot.TRAINER, true, p => {
// Tera Water Eiscue
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.LIQUIDATION)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.LIQUIDATION)) {
// Check if Liquidation is in the moveset, if not, replace the third move with Liquidation.
p.moveset[2] = new PokemonMove(MoveId.LIQUIDATION);
}
@ -3598,7 +3629,7 @@ export const trainerConfigs: TrainerConfigs = {
// Tera Dragon Torkoal
p.abilityIndex = 1; // Drought
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3695,7 +3726,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.EXEGGUTOR], TrainerSlot.TRAINER, true, p => {
// Tera Fire Exeggutor
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3705,7 +3736,7 @@ export const trainerConfigs: TrainerConfigs = {
3,
getRandomPartyMemberFunc([SpeciesId.TALONFLAME], TrainerSlot.TRAINER, true, p => {
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.SUNNY_DAY)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.SUNNY_DAY)) {
// Check if Sunny Day is in the moveset, if not, replace the third move with Sunny Day.
p.moveset[2] = new PokemonMove(MoveId.SUNNY_DAY);
}
@ -3728,7 +3759,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.REUNICLUS], TrainerSlot.TRAINER, true, p => {
// Tera Steel Reuniclus
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.FLASH_CANNON)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.FLASH_CANNON)) {
// Check if Flash Cannon is in the moveset, if not, replace the third move with Flash Cannon.
p.moveset[2] = new PokemonMove(MoveId.FLASH_CANNON);
}
@ -3756,7 +3787,7 @@ export const trainerConfigs: TrainerConfigs = {
// Tera Fairy Excadrill
p.setBoss(true, 2);
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -3771,7 +3802,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.SCEPTILE], TrainerSlot.TRAINER, true, p => {
// Tera Dragon Sceptile
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.DUAL_CHOP)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.DUAL_CHOP)) {
// Check if Dual Chop is in the moveset, if not, replace the third move with Dual Chop.
p.moveset[2] = new PokemonMove(MoveId.DUAL_CHOP);
}
@ -3841,7 +3872,7 @@ export const trainerConfigs: TrainerConfigs = {
p.formIndex = 1; // Partner Pikachu
p.gender = Gender.MALE;
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.VOLT_TACKLE)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.VOLT_TACKLE)) {
// Check if Volt Tackle is in the moveset, if not, replace the first move with Volt Tackle.
p.moveset[0] = new PokemonMove(MoveId.VOLT_TACKLE);
}
@ -4072,7 +4103,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.KELDEO], TrainerSlot.TRAINER, true, p => {
p.pokeball = PokeballType.ROGUE_BALL;
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.SECRET_SWORD)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.SECRET_SWORD)) {
// Check if Secret Sword is in the moveset, if not, replace the third move with Secret Sword.
p.moveset[2] = new PokemonMove(MoveId.SECRET_SWORD);
}
@ -4401,7 +4432,7 @@ export const trainerConfigs: TrainerConfigs = {
5,
getRandomPartyMemberFunc([SpeciesId.KINGAMBIT], TrainerSlot.TRAINER, true, p => {
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -4480,7 +4511,7 @@ export const trainerConfigs: TrainerConfigs = {
4,
getRandomPartyMemberFunc([SpeciesId.TERAPAGOS], TrainerSlot.TRAINER, true, p => {
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_STARSTORM)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_STARSTORM)) {
// Check if Tera Starstorm is in the moveset, if not, replace the first move with Tera Starstorm.
p.moveset[0] = new PokemonMove(MoveId.TERA_STARSTORM);
}
@ -4494,7 +4525,7 @@ export const trainerConfigs: TrainerConfigs = {
p.setBoss(true, 2);
p.teraType = PokemonType.FIGHTING;
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TERA_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TERA_BLAST)) {
// Check if Tera Blast is in the moveset, if not, replace the third move with Tera Blast.
p.moveset[2] = new PokemonMove(MoveId.TERA_BLAST);
}
@ -5054,7 +5085,7 @@ export const trainerConfigs: TrainerConfigs = {
2,
getRandomPartyMemberFunc([SpeciesId.HONCHKROW], TrainerSlot.TRAINER, true, p => {
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.SUCKER_PUNCH)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.SUCKER_PUNCH)) {
// Check if Sucker Punch is in the moveset, if not, replace the third move with Sucker Punch.
p.moveset[2] = new PokemonMove(MoveId.SUCKER_PUNCH);
}
@ -5517,7 +5548,7 @@ export const trainerConfigs: TrainerConfigs = {
p.formIndex = randSeedInt(18); // Random Silvally Form
p.generateAndPopulateMoveset();
p.pokeball = PokeballType.ROGUE_BALL;
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.MULTI_ATTACK)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.MULTI_ATTACK)) {
// Check if Multi Attack is in the moveset, if not, replace the first move with Multi Attack.
p.moveset[0] = new PokemonMove(MoveId.MULTI_ATTACK);
}
@ -5590,7 +5621,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.GOLISOPOD], TrainerSlot.TRAINER, true, p => {
p.setBoss(true, 2);
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.FIRST_IMPRESSION)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.FIRST_IMPRESSION)) {
// Check if First Impression is in the moveset, if not, replace the third move with First Impression.
p.moveset[2] = new PokemonMove(MoveId.FIRST_IMPRESSION);
p.gender = Gender.MALE;
@ -5607,7 +5638,7 @@ export const trainerConfigs: TrainerConfigs = {
getRandomPartyMemberFunc([SpeciesId.GOLISOPOD], TrainerSlot.TRAINER, true, p => {
p.setBoss(true, 2);
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.FIRST_IMPRESSION)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.FIRST_IMPRESSION)) {
// Check if First Impression is in the moveset, if not, replace the third move with First Impression.
p.moveset[2] = new PokemonMove(MoveId.FIRST_IMPRESSION);
p.abilityIndex = 2; // Anticipation
@ -5643,7 +5674,7 @@ export const trainerConfigs: TrainerConfigs = {
p.generateAndPopulateMoveset();
p.pokeball = PokeballType.ROGUE_BALL;
p.formIndex = randSeedInt(4, 1); // Shock, Burn, Chill, or Douse Drive
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.TECHNO_BLAST)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.TECHNO_BLAST)) {
// Check if Techno Blast is in the moveset, if not, replace the third move with Techno Blast.
p.moveset[2] = new PokemonMove(MoveId.TECHNO_BLAST);
}
@ -5778,7 +5809,7 @@ export const trainerConfigs: TrainerConfigs = {
p.setBoss(true, 2);
p.abilityIndex = 2; // Pixilate
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.HYPER_VOICE)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.HYPER_VOICE)) {
// Check if Hyper Voice is in the moveset, if not, replace the second move with Hyper Voice.
p.moveset[1] = new PokemonMove(MoveId.HYPER_VOICE);
p.gender = Gender.FEMALE;
@ -5807,7 +5838,7 @@ export const trainerConfigs: TrainerConfigs = {
p.setBoss(true, 2);
p.abilityIndex = 2; // Pixilate
p.generateAndPopulateMoveset();
if (!p.moveset.some(move => !isNullOrUndefined(move) && move.moveId === MoveId.HYPER_VOICE)) {
if (!p.moveset.some(move => move != null && move.moveId === MoveId.HYPER_VOICE)) {
// Check if Hyper Voice is in the moveset, if not, replace the second move with Hyper Voice.
p.moveset[1] = new PokemonMove(MoveId.HYPER_VOICE);
p.gender = Gender.FEMALE;

View File

@ -36,7 +36,7 @@ import type { Pokemon } from "#field/pokemon";
import { FieldEffectModifier } from "#modifiers/modifier";
import type { Move } from "#moves/move";
import type { AbstractConstructor } from "#types/type-helpers";
import { type Constructor, isNullOrUndefined, NumberHolder, randSeedInt } from "#utils/common";
import { type Constructor, NumberHolder, randSeedInt } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
export class Arena {
@ -339,7 +339,7 @@ export class Arena {
const weatherDuration = new NumberHolder(0);
if (!isNullOrUndefined(user)) {
if (user != null) {
weatherDuration.value = 5;
globalScene.applyModifier(FieldEffectModifier, user.isPlayer(), user, weatherDuration);
}
@ -420,7 +420,7 @@ export class Arena {
const terrainDuration = new NumberHolder(0);
if (!isNullOrUndefined(user)) {
if (user != null) {
terrainDuration.value = 5;
globalScene.applyModifier(FieldEffectModifier, user.isPlayer(), user, terrainDuration);
}

View File

@ -5,7 +5,6 @@ import { getSpriteKeysFromSpecies } from "#mystery-encounters/encounter-pokemon-
import type { MysteryEncounter } from "#mystery-encounters/mystery-encounter";
import { loadPokemonVariantAssets } from "#sprites/pokemon-sprite";
import type { Variant } from "#sprites/variant";
import { isNullOrUndefined } from "#utils/common";
import type { GameObjects } from "phaser";
type PlayAnimationConfig = Phaser.Types.Animations.PlayAnimationConfig;
@ -98,7 +97,7 @@ export class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Container {
...config,
};
if (!isNullOrUndefined(result.species)) {
if (result.species != null) {
const keys = getSpriteKeysFromSpecies(result.species, undefined, undefined, result.isShiny, result.variant);
result.spriteKey = keys.spriteKey;
result.fileRoot = keys.fileRoot;
@ -205,12 +204,12 @@ export class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Container {
n++;
}
if (!isNullOrUndefined(pokemonShinySparkle)) {
if (pokemonShinySparkle != null) {
// Offset the sparkle to match the Pokemon's position
pokemonShinySparkle.setPosition(sprite.x, sprite.y);
}
if (!isNullOrUndefined(alpha)) {
if (alpha != null) {
sprite.setAlpha(alpha);
tintSprite.setAlpha(alpha);
}
@ -234,7 +233,7 @@ export class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Container {
this.spriteConfigs.forEach(config => {
if (config.isPokemon) {
globalScene.loadPokemonAtlas(config.spriteKey, config.fileRoot);
if (config.isShiny && !isNullOrUndefined(config.variant)) {
if (config.isShiny && config.variant != null) {
shinyPromises.push(loadPokemonVariantAssets(config.spriteKey, config.fileRoot, config.variant));
}
} else if (config.isItem) {

View File

@ -1,5 +1,6 @@
import type { Ability, PreAttackModifyDamageAbAttrParams } from "#abilities/ability";
import { applyAbAttrs, applyOnGainAbAttrs, applyOnLoseAbAttrs } from "#abilities/apply-ab-attrs";
import { generateMoveset } from "#app/ai/ai-moveset-gen";
import type { AnySound, BattleScene } from "#app/battle-scene";
import { PLAYER_PARTY_MAX_SIZE, RARE_CANDY_FRIENDSHIP_CAP } from "#app/constants";
import { timedEventManager } from "#app/global-event-manager";
@ -18,7 +19,7 @@ import type { LevelMoves } from "#balance/pokemon-level-moves";
import { EVOLVE_MOVE, RELEARN_MOVE } from "#balance/pokemon-level-moves";
import { BASE_HIDDEN_ABILITY_CHANCE, BASE_SHINY_CHANCE, SHINY_EPIC_CHANCE, SHINY_VARIANT_CHANCE } from "#balance/rates";
import { getStarterValueFriendshipCap, speciesStarterCosts } from "#balance/starters";
import { reverseCompatibleTms, tmPoolTiers, tmSpecies } from "#balance/tms";
import { reverseCompatibleTms, tmSpecies } from "#balance/tms";
import type { SuppressAbilitiesTag } from "#data/arena-tag";
import { NoCritTag, WeakenMoveScreenTag } from "#data/arena-tag";
import {
@ -81,7 +82,6 @@ import { DexAttr } from "#enums/dex-attr";
import { FieldPosition } from "#enums/field-position";
import { HitResult } from "#enums/hit-result";
import { LearnMoveSituation } from "#enums/learn-move-situation";
import { ModifierTier } from "#enums/modifier-tier";
import { MoveCategory } from "#enums/move-category";
import { MoveFlags } from "#enums/move-flags";
import { MoveId } from "#enums/move-id";
@ -147,8 +147,8 @@ import type { StarterDataEntry, StarterMoveset } from "#types/save-data";
import type { TurnMove } from "#types/turn-move";
import { BattleInfo } from "#ui/battle-info";
import { EnemyBattleInfo } from "#ui/enemy-battle-info";
import type { PartyOption } from "#ui/handlers/party-ui-handler";
import { PartyUiHandler, PartyUiMode } from "#ui/handlers/party-ui-handler";
import type { PartyOption } from "#ui/party-ui-handler";
import { PartyUiHandler, PartyUiMode } from "#ui/party-ui-handler";
import { PlayerBattleInfo } from "#ui/player-battle-info";
import { applyChallenges } from "#utils/challenge-utils";
import {
@ -159,7 +159,6 @@ import {
fixedInt,
getIvsFromId,
isBetween,
isNullOrUndefined,
NumberHolder,
randSeedFloat,
randSeedInt,
@ -886,7 +885,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
return this.fallbackVariantColor(cacheKey, spritePath, useExpSprite, battleSpritePath, error);
})
.then(c => {
if (!isNullOrUndefined(c)) {
if (c != null) {
variantColorCache[cacheKey] = c;
}
});
@ -1475,7 +1474,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
}
const ally = this.getAlly();
if (!isNullOrUndefined(ally)) {
if (ally != null) {
applyAbAttrs("AllyStatMultiplierAbAttr", {
pokemon: ally,
stat,
@ -1658,7 +1657,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
if (useIllusion && this.summonData.illusion) {
return this.summonData.illusion.gender;
}
if (!ignoreOverride && !isNullOrUndefined(this.summonData.gender)) {
if (!ignoreOverride && this.summonData.gender != null) {
return this.summonData.gender;
}
return this.gender;
@ -1674,7 +1673,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
if (useIllusion && this.summonData.illusion?.fusionGender) {
return this.summonData.illusion.fusionGender;
}
if (!ignoreOverride && !isNullOrUndefined(this.summonData.fusionGender)) {
if (!ignoreOverride && this.summonData.fusionGender != null) {
return this.summonData.fusionGender;
}
return this.fusionGender;
@ -1793,7 +1792,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
* @returns Whether this Pokemon has this species as either its base or fusion counterpart.
*/
hasSpecies(species: SpeciesId, formKey?: string): boolean {
if (isNullOrUndefined(formKey)) {
if (formKey == null) {
return this.species.speciesId === species || this.fusionSpecies?.speciesId === species;
}
@ -1941,7 +1940,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
secondType = fusionType1;
}
if (secondType === PokemonType.UNKNOWN && isNullOrUndefined(fusionType2)) {
if (secondType === PokemonType.UNKNOWN && fusionType2 == null) {
// If second pokemon was monotype and shared its primary type
secondType =
customTypes
@ -2024,12 +2023,12 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
return allAbilities[Overrides.ENEMY_ABILITY_OVERRIDE];
}
if (this.isFusion()) {
if (!isNullOrUndefined(this.fusionCustomPokemonData?.ability) && this.fusionCustomPokemonData.ability !== -1) {
if (this.fusionCustomPokemonData?.ability != null && this.fusionCustomPokemonData.ability !== -1) {
return allAbilities[this.fusionCustomPokemonData.ability];
}
return allAbilities[this.getFusionSpeciesForm(ignoreOverride).getAbility(this.fusionAbilityIndex)];
}
if (!isNullOrUndefined(this.customPokemonData.ability) && this.customPokemonData.ability !== -1) {
if (this.customPokemonData.ability != null && this.customPokemonData.ability !== -1) {
return allAbilities[this.customPokemonData.ability];
}
let abilityId = this.getSpeciesForm(ignoreOverride).getAbility(this.abilityIndex);
@ -2053,7 +2052,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
if (Overrides.ENEMY_PASSIVE_ABILITY_OVERRIDE && this.isEnemy()) {
return allAbilities[Overrides.ENEMY_PASSIVE_ABILITY_OVERRIDE];
}
if (!isNullOrUndefined(this.customPokemonData.passive) && this.customPokemonData.passive !== -1) {
if (this.customPokemonData.passive != null && this.customPokemonData.passive !== -1) {
return allAbilities[this.customPokemonData.passive];
}
@ -2237,7 +2236,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
public getWeight(): number {
const autotomizedTag = this.getTag(AutotomizedTag);
let weightRemoved = 0;
if (!isNullOrUndefined(autotomizedTag)) {
if (autotomizedTag != null) {
weightRemoved = 100 * autotomizedTag.autotomizeCount;
}
const minWeight = 0.1;
@ -2384,7 +2383,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
cancelled?: BooleanHolder,
useIllusion = false,
): TypeDamageMultiplier {
if (!isNullOrUndefined(this.turnData?.moveEffectiveness)) {
if (this.turnData?.moveEffectiveness != null) {
return this.turnData?.moveEffectiveness;
}
@ -2636,7 +2635,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
e => new FusionSpeciesFormEvolution(this.species.speciesId, e),
);
for (const fe of fusionEvolutions) {
if (fe.validate(this)) {
if (fe.validate(this, true)) {
return fe;
}
}
@ -2775,7 +2774,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
* This causes problems when there are intentional duplicates (i.e. Smeargle with Sketch)
*/
if (levelMoves) {
this.getUniqueMoves(levelMoves, ret);
Pokemon.getUniqueMoves(levelMoves, ret);
}
return ret;
@ -2789,7 +2788,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
* @param levelMoves the input array to search for non-duplicates from
* @param ret the output array to be pushed into.
*/
private getUniqueMoves(levelMoves: LevelMoves, ret: LevelMoves): void {
private static getUniqueMoves(levelMoves: LevelMoves, ret: LevelMoves): void {
const uniqueMoves: MoveId[] = [];
for (const lm of levelMoves) {
if (!uniqueMoves.find(m => m === lm[1])) {
@ -3047,294 +3046,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
/** Generates a semi-random moveset for a Pokemon */
public generateAndPopulateMoveset(): void {
this.moveset = [];
let movePool: [MoveId, number][] = [];
const allLevelMoves = this.getLevelMoves(1, true, true, this.hasTrainer());
if (!allLevelMoves) {
console.warn("Error encountered trying to generate moveset for:", this.species.name);
return;
}
for (const levelMove of allLevelMoves) {
if (this.level < levelMove[0]) {
break;
}
let weight = levelMove[0] + 20;
// Evolution Moves
if (levelMove[0] === EVOLVE_MOVE) {
weight = 70;
}
// Assume level 1 moves with 80+ BP are "move reminder" moves and bump their weight. Trainers use actual relearn moves.
if (
(levelMove[0] === 1 && allMoves[levelMove[1]].power >= 80)
|| (levelMove[0] === RELEARN_MOVE && this.hasTrainer())
) {
weight = 60;
}
if (!movePool.some(m => m[0] === levelMove[1]) && !allMoves[levelMove[1]].name.endsWith(" (N)")) {
movePool.push([levelMove[1], weight]);
}
}
if (this.hasTrainer()) {
const tms = Object.keys(tmSpecies);
for (const tm of tms) {
const moveId = Number.parseInt(tm) as MoveId;
let compatible = false;
for (const p of tmSpecies[tm]) {
if (Array.isArray(p)) {
if (
p[0] === this.species.speciesId
|| (this.fusionSpecies
&& p[0] === this.fusionSpecies.speciesId
&& p.slice(1).indexOf(this.species.forms[this.formIndex]) > -1)
) {
compatible = true;
break;
}
} else if (p === this.species.speciesId || (this.fusionSpecies && p === this.fusionSpecies.speciesId)) {
compatible = true;
break;
}
}
if (compatible && !movePool.some(m => m[0] === moveId) && !allMoves[moveId].name.endsWith(" (N)")) {
if (tmPoolTiers[moveId] === ModifierTier.COMMON && this.level >= 15) {
movePool.push([moveId, 24]);
} else if (tmPoolTiers[moveId] === ModifierTier.GREAT && this.level >= 30) {
movePool.push([moveId, 28]);
} else if (tmPoolTiers[moveId] === ModifierTier.ULTRA && this.level >= 50) {
movePool.push([moveId, 34]);
}
}
}
// No egg moves below level 60
if (this.level >= 60) {
for (let i = 0; i < 3; i++) {
const moveId = speciesEggMoves[this.species.getRootSpeciesId()][i];
if (!movePool.some(m => m[0] === moveId) && !allMoves[moveId].name.endsWith(" (N)")) {
movePool.push([moveId, 60]);
}
}
const moveId = speciesEggMoves[this.species.getRootSpeciesId()][3];
// No rare egg moves before e4
if (
this.level >= 170
&& !movePool.some(m => m[0] === moveId)
&& !allMoves[moveId].name.endsWith(" (N)")
&& !this.isBoss()
) {
movePool.push([moveId, 50]);
}
if (this.fusionSpecies) {
for (let i = 0; i < 3; i++) {
const moveId = speciesEggMoves[this.fusionSpecies.getRootSpeciesId()][i];
if (!movePool.some(m => m[0] === moveId) && !allMoves[moveId].name.endsWith(" (N)")) {
movePool.push([moveId, 60]);
}
}
const moveId = speciesEggMoves[this.fusionSpecies.getRootSpeciesId()][3];
// No rare egg moves before e4
if (
this.level >= 170
&& !movePool.some(m => m[0] === moveId)
&& !allMoves[moveId].name.endsWith(" (N)")
&& !this.isBoss()
) {
movePool.push([moveId, 50]);
}
}
}
}
// Bosses never get self ko moves or Pain Split
if (this.isBoss()) {
movePool = movePool.filter(
m => !allMoves[m[0]].hasAttr("SacrificialAttr") && !allMoves[m[0]].hasAttr("HpSplitAttr"),
);
}
// No one gets Memento or Final Gambit
movePool = movePool.filter(m => !allMoves[m[0]].hasAttr("SacrificialAttrOnHit"));
if (this.hasTrainer()) {
// Trainers never get OHKO moves
movePool = movePool.filter(m => !allMoves[m[0]].hasAttr("OneHitKOAttr"));
// Half the weight of self KO moves
movePool = movePool.map(m => [m[0], m[1] * (allMoves[m[0]].hasAttr("SacrificialAttr") ? 0.5 : 1)]);
// Trainers get a weight bump to stat buffing moves
movePool = movePool.map(m => [
m[0],
m[1] * (allMoves[m[0]].getAttrs("StatStageChangeAttr").some(a => a.stages > 1 && a.selfTarget) ? 1.25 : 1),
]);
// Trainers get a weight decrease to multiturn moves
movePool = movePool.map(m => [
m[0],
m[1] * (!!allMoves[m[0]].isChargingMove() || !!allMoves[m[0]].hasAttr("RechargeAttr") ? 0.7 : 1),
]);
}
// Weight towards higher power moves, by reducing the power of moves below the highest power.
// Caps max power at 90 to avoid something like hyper beam ruining the stats.
// This is a pretty soft weighting factor, although it is scaled with the weight multiplier.
const maxPower = Math.min(
movePool.reduce((v, m) => Math.max(allMoves[m[0]].calculateEffectivePower(), v), 40),
90,
);
movePool = movePool.map(m => [
m[0],
m[1]
* (allMoves[m[0]].category === MoveCategory.STATUS
? 1
: Math.max(Math.min(allMoves[m[0]].calculateEffectivePower() / maxPower, 1), 0.5)),
]);
// Weight damaging moves against the lower stat. This uses a non-linear relationship.
// If the higher stat is 1 - 1.09x higher, no change. At higher stat ~1.38x lower stat, off-stat moves have half weight.
// One third weight at ~1.58x higher, one quarter weight at ~1.73x higher, one fifth at ~1.87x, and one tenth at ~2.35x higher.
const atk = this.getStat(Stat.ATK);
const spAtk = this.getStat(Stat.SPATK);
const worseCategory: MoveCategory = atk > spAtk ? MoveCategory.SPECIAL : MoveCategory.PHYSICAL;
const statRatio = worseCategory === MoveCategory.PHYSICAL ? atk / spAtk : spAtk / atk;
movePool = movePool.map(m => [
m[0],
m[1] * (allMoves[m[0]].category === worseCategory ? Math.min(Math.pow(statRatio, 3) * 1.3, 1) : 1),
]);
/** The higher this is the more the game weights towards higher level moves. At `0` all moves are equal weight. */
let weightMultiplier = 1.6;
if (this.isBoss()) {
weightMultiplier += 0.4;
}
const baseWeights: [MoveId, number][] = movePool.map(m => [
m[0],
Math.ceil(Math.pow(m[1], weightMultiplier) * 100),
]);
const STAB_BLACKLIST: ReadonlySet<MoveId> = new Set([
MoveId.BEAT_UP,
MoveId.BELCH,
MoveId.BIDE,
MoveId.COMEUPPANCE,
MoveId.COUNTER,
MoveId.DOOM_DESIRE,
MoveId.DRAGON_RAGE,
MoveId.DREAM_EATER,
MoveId.ENDEAVOR,
MoveId.EXPLOSION,
MoveId.FAKE_OUT,
MoveId.FIRST_IMPRESSION,
MoveId.FISSURE,
MoveId.FLING,
MoveId.FOCUS_PUNCH,
MoveId.FUTURE_SIGHT,
MoveId.GUILLOTINE,
MoveId.HOLD_BACK,
MoveId.HORN_DRILL,
MoveId.LAST_RESORT,
MoveId.METAL_BURST,
MoveId.MIRROR_COAT,
MoveId.MISTY_EXPLOSION,
MoveId.NATURAL_GIFT,
MoveId.NATURES_MADNESS,
MoveId.NIGHT_SHADE,
MoveId.PSYWAVE,
MoveId.RUINATION,
MoveId.SELF_DESTRUCT,
MoveId.SHEER_COLD,
MoveId.SHELL_TRAP,
MoveId.SKY_DROP,
MoveId.SNORE,
MoveId.SONIC_BOOM,
MoveId.SPIT_UP,
MoveId.STEEL_BEAM,
MoveId.STEEL_ROLLER,
MoveId.SUPER_FANG,
MoveId.SYNCHRONOISE,
MoveId.UPPER_HAND,
]);
// All Pokemon force a STAB move first
const stabMovePool = baseWeights.filter(
m =>
allMoves[m[0]].category !== MoveCategory.STATUS
&& this.isOfType(allMoves[m[0]].type)
&& !STAB_BLACKLIST.has(m[0]),
);
if (stabMovePool.length > 0) {
const totalWeight = stabMovePool.reduce((v, m) => v + m[1], 0);
let rand = randSeedInt(totalWeight);
let index = 0;
while (rand > stabMovePool[index][1]) {
rand -= stabMovePool[index++][1];
}
this.moveset.push(new PokemonMove(stabMovePool[index][0]));
} else {
// If there are no damaging STAB moves, just force a random damaging move
const attackMovePool = baseWeights.filter(
m => allMoves[m[0]].category !== MoveCategory.STATUS && !STAB_BLACKLIST.has(m[0]),
);
if (attackMovePool.length > 0) {
const totalWeight = attackMovePool.reduce((v, m) => v + m[1], 0);
let rand = randSeedInt(totalWeight);
let index = 0;
while (rand > attackMovePool[index][1]) {
rand -= attackMovePool[index++][1];
}
this.moveset.push(new PokemonMove(attackMovePool[index][0], 0, 0));
}
}
while (baseWeights.length > this.moveset.length && this.moveset.length < 4) {
if (this.hasTrainer()) {
// Sqrt the weight of any damaging moves with overlapping types. This is about a 0.05 - 0.1 multiplier.
// Other damaging moves 2x weight if 0-1 damaging moves, 0.5x if 2, 0.125x if 3. These weights get 20x if STAB.
// Status moves remain unchanged on weight, this encourages 1-2
movePool = baseWeights
.filter(
m =>
!this.moveset.some(
mo =>
m[0] === mo.moveId
|| (allMoves[m[0]].hasAttr("SacrificialAttr") && mo.getMove().hasAttr("SacrificialAttr")), // Only one self-KO move allowed
),
)
.map(m => {
let ret: number;
if (
this.moveset.some(
mo => mo.getMove().category !== MoveCategory.STATUS && mo.getMove().type === allMoves[m[0]].type,
)
) {
ret = Math.ceil(Math.sqrt(m[1]));
} else if (allMoves[m[0]].category !== MoveCategory.STATUS) {
ret = Math.ceil(
(m[1] / Math.max(Math.pow(4, this.moveset.filter(mo => (mo.getMove().power ?? 0) > 1).length) / 8, 0.5))
* (this.isOfType(allMoves[m[0]].type) && !STAB_BLACKLIST.has(m[0]) ? 20 : 1),
);
} else {
ret = m[1];
}
return [m[0], ret];
});
} else {
// Non-trainer pokemon just use normal weights
movePool = baseWeights.filter(
m =>
!this.moveset.some(
mo =>
m[0] === mo.moveId
|| (allMoves[m[0]].hasAttr("SacrificialAttr") && mo.getMove().hasAttr("SacrificialAttr")), // Only one self-KO move allowed
),
);
}
const totalWeight = movePool.reduce((v, m) => v + m[1], 0);
let rand = randSeedInt(totalWeight);
let index = 0;
while (rand > movePool[index][1]) {
rand -= movePool[index++][1];
}
this.moveset.push(new PokemonMove(movePool[index][0]));
}
generateMoveset(this);
// Trigger FormChange, except for enemy Pokemon during Mystery Encounters, to avoid crashes
if (
@ -3606,7 +3318,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
});
const ally = this.getAlly();
if (!isNullOrUndefined(ally)) {
if (ally != null) {
const ignore =
this.hasAbilityWithAttr("MoveAbilityBypassAbAttr") || sourceMove.hasFlag(MoveFlags.IGNORE_ABILITIES);
applyAbAttrs("AllyStatMultiplierAbAttr", {
@ -4015,7 +3727,7 @@ export abstract class Pokemon extends Phaser.GameObjects.Container {
const ally = this.getAlly();
/** Additionally apply friend guard damage reduction if ally has it. */
if (globalScene.currentBattle.double && !isNullOrUndefined(ally) && ally.isActive(true)) {
if (globalScene.currentBattle.double && ally != null && ally.isActive(true)) {
applyAbAttrs("AlliedFieldDamageReductionAbAttr", {
...abAttrParams,
// Same parameters as before, except we are applying the ally's ability
@ -6391,13 +6103,13 @@ export class EnemyPokemon extends Pokemon {
if (
speciesId in Overrides.ENEMY_FORM_OVERRIDES
&& !isNullOrUndefined(Overrides.ENEMY_FORM_OVERRIDES[speciesId])
&& Overrides.ENEMY_FORM_OVERRIDES[speciesId] != null
&& this.species.forms[Overrides.ENEMY_FORM_OVERRIDES[speciesId]]
) {
this.formIndex = Overrides.ENEMY_FORM_OVERRIDES[speciesId];
} else if (globalScene.gameMode.isDaily && globalScene.gameMode.isWaveFinal(globalScene.currentBattle.waveIndex)) {
const eventBoss = getDailyEventSeedBoss(globalScene.seed);
if (!isNullOrUndefined(eventBoss)) {
if (eventBoss != null) {
this.formIndex = eventBoss.formIndex;
}
}
@ -6933,12 +6645,20 @@ export class EnemyPokemon extends Pokemon {
* @param segmentIndex index of the segment to get down to (0 = no shield left, 1 = 1 shield left, etc.)
*/
handleBossSegmentCleared(segmentIndex: number): void {
let doStatBoost = !this.hasTrainer();
// TODO: Rewrite this bespoke logic to improve clarity
while (this.bossSegmentIndex > 0 && segmentIndex - 1 < this.bossSegmentIndex) {
this.bossSegmentIndex--;
// Continue, _not_ break here, to ensure that each segment is still broken
if (!doStatBoost) {
continue;
}
let boostedStat: EffectiveStat | undefined;
// Filter out already maxed out stat stages and weigh the rest based on existing stats
const leftoverStats = EFFECTIVE_STATS.filter((s: EffectiveStat) => this.getStatStage(s) < 6);
const statWeights = leftoverStats.map((s: EffectiveStat) => this.getStat(s, false));
let boostedStat: EffectiveStat | undefined;
const statThresholds: number[] = [];
let totalWeight = 0;
@ -6957,18 +6677,18 @@ export class EnemyPokemon extends Pokemon {
}
if (boostedStat === undefined) {
this.bossSegmentIndex--;
return;
doStatBoost = false;
continue;
}
let stages = 1;
// increase the boost if the boss has at least 3 segments and we passed last shield
if (this.bossSegments >= 3 && this.bossSegmentIndex === 1) {
if (this.bossSegments >= 3 && this.bossSegmentIndex === 0) {
stages++;
}
// increase the boost if the boss has at least 5 segments and we passed the second to last shield
if (this.bossSegments >= 5 && this.bossSegmentIndex === 2) {
if (this.bossSegments >= 5 && this.bossSegmentIndex === 1) {
stages++;
}
@ -6981,7 +6701,6 @@ export class EnemyPokemon extends Pokemon {
true,
true,
);
this.bossSegmentIndex--;
}
}

View File

@ -14,7 +14,7 @@ import { SpeciesId } from "#enums/species-id";
import type { Arena } from "#field/arena";
import { classicFixedBattles, type FixedBattleConfigs } from "#trainers/fixed-battle-configs";
import { applyChallenges } from "#utils/challenge-utils";
import { BooleanHolder, isNullOrUndefined, randSeedInt, randSeedItem } from "#utils/common";
import { BooleanHolder, randSeedInt, randSeedItem } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import i18next from "i18next";
@ -146,7 +146,7 @@ export class GameMode implements GameModeConfig {
* - Town
*/
getStartingBiome(): BiomeId {
if (!isNullOrUndefined(Overrides.STARTING_BIOME_OVERRIDE)) {
if (Overrides.STARTING_BIOME_OVERRIDE != null) {
return Overrides.STARTING_BIOME_OVERRIDE;
}
@ -234,7 +234,7 @@ export class GameMode implements GameModeConfig {
getOverrideSpecies(waveIndex: number): PokemonSpecies | null {
if (this.isDaily && this.isWaveFinal(waveIndex)) {
const eventBoss = getDailyEventSeedBoss(globalScene.seed);
if (!isNullOrUndefined(eventBoss)) {
if (eventBoss != null) {
// Cannot set form index here, it will be overriden when adding it as enemy pokemon.
return getPokemonSpecies(eventBoss.speciesId);
}

View File

@ -11,7 +11,7 @@ import { initMoves } from "#moves/move";
import { initMysteryEncounters } from "#mystery-encounters/mystery-encounters";
import { initAchievements } from "#system/achv";
import { initVouchers } from "#system/voucher";
import { initStatsKeys } from "#ui/handlers/game-stats-ui-handler";
import { initStatsKeys } from "#ui/game-stats-ui-handler";
/** Initialize the game. */
export function initializeGame() {

View File

@ -31,7 +31,6 @@ import {
} from "#modifiers/modifier-pools";
import { WeightedModifierType } from "#modifiers/modifier-type";
import type { WeightedModifierTypeWeightFunc } from "#types/modifier-types";
import { isNullOrUndefined } from "#utils/common";
/**
* Initialize the wild modifier pool
@ -409,7 +408,7 @@ function initUltraModifierPool() {
if (!isHoldingOrb) {
const moveset = p
.getMoveset(true)
.filter(m => !isNullOrUndefined(m))
.filter(m => m != null)
.map(m => m.moveId);
const canSetStatus = p.canSetStatus(StatusEffect.TOXIC, true, true, null, true);
@ -455,7 +454,7 @@ function initUltraModifierPool() {
if (!isHoldingOrb) {
const moveset = p
.getMoveset(true)
.filter(m => !isNullOrUndefined(m))
.filter(m => m != null)
.map(m => m.moveId);
const canSetStatus = p.canSetStatus(StatusEffect.BURN, true, true, null, true);

View File

@ -115,19 +115,11 @@ import {
import type { PokemonMove } from "#moves/pokemon-move";
import { getVoucherTypeIcon, getVoucherTypeName, VoucherType } from "#system/voucher";
import type { ModifierTypeFunc, WeightedModifierTypeWeightFunc } from "#types/modifier-types";
import type { PokemonMoveSelectFilter, PokemonSelectFilter } from "#ui/handlers/party-ui-handler";
import { PartyUiHandler } from "#ui/handlers/party-ui-handler";
import type { PokemonMoveSelectFilter, PokemonSelectFilter } from "#ui/party-ui-handler";
import { PartyUiHandler } from "#ui/party-ui-handler";
import { getModifierTierTextTint } from "#ui/text";
import { applyChallenges } from "#utils/challenge-utils";
import {
BooleanHolder,
formatMoney,
isNullOrUndefined,
NumberHolder,
padInt,
randSeedInt,
randSeedItem,
} from "#utils/common";
import { BooleanHolder, formatMoney, NumberHolder, padInt, randSeedInt, randSeedItem } from "#utils/common";
import { getEnumKeys, getEnumValues } from "#utils/enums";
import { getModifierPoolForType, getModifierType } from "#utils/modifier-utils";
import { toCamelCase } from "#utils/strings";
@ -263,7 +255,7 @@ export class ModifierType {
this.tier = modifier.modifierType.tier;
return this;
}
if (isNullOrUndefined(defaultTier)) {
if (defaultTier == null) {
// If weight is 0, keep track of the first tier where the item was found
defaultTier = modifier.modifierType.tier;
}
@ -2920,7 +2912,7 @@ export function getPartyLuckValue(party: Pokemon[]): number {
globalScene.executeWithSeedOffset(
() => {
const eventLuck = getDailyEventSeedLuck(globalScene.seed);
if (!isNullOrUndefined(eventLuck)) {
if (eventLuck != null) {
DailyLuck.value = eventLuck;
return;
}

View File

@ -42,7 +42,7 @@ import type {
import type { VoucherType } from "#system/voucher";
import type { ModifierInstanceMap, ModifierString } from "#types/modifier-types";
import { addTextObject } from "#ui/text";
import { BooleanHolder, hslToHex, isNullOrUndefined, NumberHolder, randSeedFloat, toDmgValue } from "#utils/common";
import { BooleanHolder, hslToHex, NumberHolder, randSeedFloat, toDmgValue } from "#utils/common";
import { getModifierType } from "#utils/modifier-utils";
import i18next from "i18next";
@ -728,7 +728,7 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier {
}
getPokemon(): Pokemon | undefined {
return globalScene.getPokemonById(this.pokemonId) ?? undefined;
return globalScene.getPokemonById(this.pokemonId);
}
getScoreMultiplier(): number {
@ -2113,10 +2113,7 @@ export class PokemonHpRestoreModifier extends ConsumablePokemonModifier {
* @returns `true` if the {@linkcode PokemonHpRestoreModifier} should be applied
*/
override shouldApply(playerPokemon?: PlayerPokemon, multiplier?: number): boolean {
return (
super.shouldApply(playerPokemon)
&& (this.fainted || (!isNullOrUndefined(multiplier) && typeof multiplier === "number"))
);
return super.shouldApply(playerPokemon) && (this.fainted || (multiplier != null && typeof multiplier === "number"));
}
/**
@ -2753,10 +2750,10 @@ export class PokemonMultiHitModifier extends PokemonHeldItemModifier {
return false;
}
if (!isNullOrUndefined(count)) {
if (count != null) {
return this.applyHitCountBoost(count);
}
if (!isNullOrUndefined(damageMultiplier)) {
if (damageMultiplier != null) {
return this.applyDamageModifier(pokemon, damageMultiplier);
}

View File

@ -1,4 +1,4 @@
import { type PokeballCounts } from "#app/battle-scene";
import type { PokeballCounts } from "#app/battle-scene";
import { EvolutionItem } from "#balance/pokemon-evolutions";
import { Gender } from "#data/gender";
import { AbilityId } from "#enums/ability-id";
@ -18,10 +18,11 @@ import { Stat } from "#enums/stat";
import { StatusEffect } from "#enums/status-effect";
import { TimeOfDay } from "#enums/time-of-day";
import { TrainerType } from "#enums/trainer-type";
import { TrainerVariant } from "#enums/trainer-variant";
import { Unlockables } from "#enums/unlockables";
import { VariantTier } from "#enums/variant-tier";
import { WeatherType } from "#enums/weather-type";
import { type ModifierOverride } from "#modifiers/modifier-type";
import type { ModifierOverride } from "#modifiers/modifier-type";
import { Variant } from "#sprites/variant";
/**
@ -311,8 +312,12 @@ export type BattleStyle = "double" | "single" | "even-doubles" | "odd-doubles";
export type RandomTrainerOverride = {
/** The Type of trainer to force */
trainerType: Exclude<TrainerType, TrainerType.UNKNOWN>;
/* If the selected trainer type has a double version, it will always use its double version. */
alwaysDouble?: boolean;
/**
* The {@linkcode TrainerVariant} to force.
* @remarks
* `TrainerVariant.DOUBLE` cannot be forced on the first wave of a game due to issues with trainer party generation.
*/
trainerVariant?: TrainerVariant;
};
/** The type of the {@linkcode DefaultOverrides} class */

View File

@ -1,3 +1,12 @@
/**
* Manager for phases used by battle scene.
*
* @remarks
* **This file must not be imported or used directly.**
* The manager is exclusively used by the Battle Scene and is NOT intended for external use.
* @module
*/
import { PHASE_START_COLOR } from "#app/constants/colors";
import { globalScene } from "#app/global-scene";
import type { Phase } from "#app/phase";
@ -103,15 +112,6 @@ import { WeatherEffectPhase } from "#phases/weather-effect-phase";
import type { PhaseMap, PhaseString } from "#types/phase-types";
import { type Constructor, coerceArray } from "#utils/common";
/**
* @module
* Manager for phases used by battle scene.
*
* @remarks
* **This file must not be imported or used directly.**
* The manager is exclusively used by the Battle Scene and is NOT intended for external use.
*/
/**
* Object that holds all of the phase constructors.
* This is used to create new phases dynamically using the `newPhase` method in the `PhaseManager`.

View File

@ -21,9 +21,9 @@ import type { EnemyPokemon } from "#field/pokemon";
import { PokemonHeldItemModifier } from "#modifiers/modifier";
import { PokemonPhase } from "#phases/pokemon-phase";
import { achvs } from "#system/achv";
import type { PartyOption } from "#ui/handlers/party-ui-handler";
import { PartyUiMode } from "#ui/handlers/party-ui-handler";
import { SummaryUiMode } from "#ui/handlers/summary-ui-handler";
import type { PartyOption } from "#ui/party-ui-handler";
import { PartyUiMode } from "#ui/party-ui-handler";
import { SummaryUiMode } from "#ui/summary-ui-handler";
import { applyChallenges } from "#utils/challenge-utils";
import { BooleanHolder } from "#utils/common";
import i18next from "i18next";

View File

@ -220,7 +220,7 @@ export class CommandPhase extends FieldPhase {
if (!moveStatus.value) {
cannotSelectKey = "battle:moveCannotUseChallenge";
} else if (move.getPpRatio() === 0) {
cannotSelectKey = "battle:moveNoPP";
cannotSelectKey = "battle:moveNoPp";
} else if (move.getName().endsWith(" (N)")) {
cannotSelectKey = "battle:moveNotImplemented";
} else if (user.isMoveRestricted(move.moveId, user)) {

View File

@ -9,9 +9,9 @@ import { doShinySparkleAnim } from "#field/anims";
import type { PlayerPokemon } from "#field/pokemon";
import type { EggLapsePhase } from "#phases/egg-lapse-phase";
import { achvs } from "#system/achv";
import { EggCounterContainer } from "#ui/containers/egg-counter-container";
import { PokemonInfoContainer } from "#ui/containers/pokemon-info-container";
import type { EggHatchSceneUiHandler } from "#ui/handlers/egg-hatch-scene-ui-handler";
import { EggCounterContainer } from "#ui/egg-counter-container";
import type { EggHatchSceneUiHandler } from "#ui/egg-hatch-scene-ui-handler";
import { PokemonInfoContainer } from "#ui/pokemon-info-container";
import { fixedInt, getFrameMs, randInt } from "#utils/common";
import i18next from "i18next";
import SoundFade from "phaser3-rex-plugins/plugins/soundfade";

View File

@ -10,7 +10,7 @@ import { LearnMoveSituation } from "#enums/learn-move-situation";
import { UiMode } from "#enums/ui-mode";
import { cos, sin } from "#field/anims";
import type { PlayerPokemon, Pokemon } from "#field/pokemon";
import type { EvolutionSceneUiHandler } from "#ui/handlers/evolution-scene-ui-handler";
import type { EvolutionSceneUiHandler } from "#ui/evolution-scene-ui-handler";
import { fixedInt, getFrameMs, randInt } from "#utils/common";
import i18next from "i18next";
import SoundFade from "phaser3-rex-plugins/plugins/soundfade";

View File

@ -17,7 +17,6 @@ import type { EnemyPokemon, PlayerPokemon, Pokemon } from "#field/pokemon";
import { PokemonInstantReviveModifier } from "#modifiers/modifier";
import { PokemonMove } from "#moves/pokemon-move";
import { PokemonPhase } from "#phases/pokemon-phase";
import { isNullOrUndefined } from "#utils/common";
import i18next from "i18next";
export class FaintPhase extends PokemonPhase {
@ -187,7 +186,7 @@ export class FaintPhase extends PokemonPhase {
// in double battles redirect potential moves off fainted pokemon
const allyPokemon = pokemon.getAlly();
if (globalScene.currentBattle.double && !isNullOrUndefined(allyPokemon)) {
if (globalScene.currentBattle.double && allyPokemon != null) {
globalScene.redirectPokemonMoves(pokemon, allyPokemon);
}

View File

@ -8,7 +8,7 @@ import { UiMode } from "#enums/ui-mode";
import type { PlayerPokemon, Pokemon } from "#field/pokemon";
import { EvolutionPhase } from "#phases/evolution-phase";
import { achvs } from "#system/achv";
import type { PartyUiHandler } from "#ui/handlers/party-ui-handler";
import type { PartyUiHandler } from "#ui/party-ui-handler";
import { fixedInt } from "#utils/common";
export class FormChangePhase extends EvolutionPhase {

View File

@ -10,8 +10,8 @@ import { UiMode } from "#enums/ui-mode";
import type { Pokemon } from "#field/pokemon";
import type { Move } from "#moves/move";
import { PlayerPartyMemberPokemonPhase } from "#phases/player-party-member-pokemon-phase";
import { EvolutionSceneUiHandler } from "#ui/handlers/evolution-scene-ui-handler";
import { SummaryUiMode } from "#ui/handlers/summary-ui-handler";
import { EvolutionSceneUiHandler } from "#ui/evolution-scene-ui-handler";
import { SummaryUiMode } from "#ui/summary-ui-handler";
import i18next from "i18next";
export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {

View File

@ -33,7 +33,7 @@ export class LoginPhase extends Phase {
globalScene.ui.showText(i18next.t("menu:logInOrCreateAccount"));
}
globalScene.playSound("menu_open");
globalScene.playSound("ui/menu_open");
const loadData = () => {
updateUserInfo().then(success => {
@ -53,7 +53,7 @@ export class LoginPhase extends Phase {
loadData();
},
() => {
globalScene.playSound("menu_open");
globalScene.playSound("ui/menu_open");
globalScene.ui.setMode(UiMode.REGISTRATION_FORM, {
buttonActions: [
() => {

View File

@ -40,7 +40,7 @@ import { DamageAchv } from "#system/achv";
import type { DamageResult } from "#types/damage-result";
import type { TurnMove } from "#types/turn-move";
import type { nil } from "#utils/common";
import { BooleanHolder, isNullOrUndefined, NumberHolder } from "#utils/common";
import { BooleanHolder, NumberHolder } from "#utils/common";
import i18next from "i18next";
export type HitCheckEntry = [HitCheckResult, TypeDamageMultiplier];
@ -645,13 +645,18 @@ export class MoveEffectPhase extends PokemonPhase {
return move.getAttrs("HitsTagAttr").some(hta => hta.tagType === semiInvulnerableTag.tagType);
}
/** @returns The {@linkcode Pokemon} using this phase's invoked move */
public getUserPokemon(): Pokemon | null {
/**
* @todo Investigate why this doesn't use `BattlerIndex`
* @returns The {@linkcode Pokemon} using this phase's invoked move
*/
public getUserPokemon(): Pokemon | undefined {
// TODO: Make this purely a battler index
if (this.battlerIndex > BattlerIndex.ENEMY_2) {
return globalScene.getPokemonById(this.battlerIndex);
}
return (this.player ? globalScene.getPlayerField() : globalScene.getEnemyField())[this.fieldIndex];
// TODO: Figure out why this uses `fieldIndex` instead of `BattlerIndex`
// TODO: Remove `?? undefined` once field pokemon getters are made sane
return (this.player ? globalScene.getPlayerField() : globalScene.getEnemyField())[this.fieldIndex] ?? undefined;
}
/**
@ -740,7 +745,7 @@ export class MoveEffectPhase extends PokemonPhase {
(attr: MoveAttr) =>
attr.is("MoveEffectAttr")
&& attr.trigger === triggerType
&& (isNullOrUndefined(selfTarget) || attr.selfTarget === selfTarget)
&& (selfTarget == null || attr.selfTarget === selfTarget)
&& (!attr.firstHitOnly || this.firstHit)
&& (!attr.lastHitOnly || this.lastHit)
&& (!attr.firstTargetOnly || (firstTarget ?? true)),
@ -765,7 +770,7 @@ export class MoveEffectPhase extends PokemonPhase {
*/
protected applyMoveEffects(target: Pokemon, effectiveness: TypeDamageMultiplier, firstTarget: boolean): void {
const user = this.getUserPokemon();
if (isNullOrUndefined(user)) {
if (user == null) {
return;
}
@ -932,7 +937,7 @@ export class MoveEffectPhase extends PokemonPhase {
msg = i18next.t("battle:hitResultNotVeryEffective");
break;
case HitResult.ONE_HIT_KO:
msg = i18next.t("battle:hitResultOneHitKO");
msg = i18next.t("battle:hitResultOneHitKo");
break;
}
if (msg) {

View File

@ -14,7 +14,7 @@ import type { OptionSelectSettings } from "#mystery-encounters/encounter-phase-u
import { transitionMysteryEncounterIntroVisuals } from "#mystery-encounters/encounter-phase-utils";
import type { MysteryEncounterOption, OptionPhaseCallback } from "#mystery-encounters/mystery-encounter-option";
import { SeenEncounterData } from "#mystery-encounters/mystery-encounter-save-data";
import { isNullOrUndefined, randSeedItem } from "#utils/common";
import { randSeedItem } from "#utils/common";
import i18next from "i18next";
/**
@ -93,7 +93,7 @@ export class MysteryEncounterPhase extends Phase {
if (option.onPreOptionPhase) {
globalScene.executeWithSeedOffset(async () => {
return await option.onPreOptionPhase!().then(result => {
if (isNullOrUndefined(result) || result) {
if (result == null || result) {
this.continueEncounter();
}
});
@ -578,7 +578,7 @@ export class PostMysteryEncounterPhase extends Phase {
if (this.onPostOptionSelect) {
globalScene.executeWithSeedOffset(async () => {
return await this.onPostOptionSelect!().then(result => {
if (isNullOrUndefined(result) || result) {
if (result == null || result) {
this.continueEncounter();
}
});

View File

@ -23,6 +23,7 @@ export class ObtainStatusEffectPhase extends PokemonPhase {
* @param sourceText - The text to show for the source of the status effect, if any; default `null`.
* @param statusMessage - A string containing text to be displayed upon status setting;
* defaults to normal key for status if empty or omitted.
* @todo stop passing `null` to the phase
*/
constructor(
battlerIndex: BattlerIndex,

View File

@ -4,7 +4,6 @@ import { PokemonAnimType } from "#enums/pokemon-anim-type";
import { SpeciesId } from "#enums/species-id";
import type { Pokemon } from "#field/pokemon";
import { BattlePhase } from "#phases/battle-phase";
import { isNullOrUndefined } from "#utils/common";
export class PokemonAnimPhase extends BattlePhase {
public readonly phaseName = "PokemonAnimPhase";
@ -52,7 +51,7 @@ export class PokemonAnimPhase extends BattlePhase {
private doSubstituteAddAnim(): void {
const substitute = this.pokemon.getTag(SubstituteTag);
if (isNullOrUndefined(substitute)) {
if (substitute == null) {
this.end();
return;
}
@ -336,7 +335,7 @@ export class PokemonAnimPhase extends BattlePhase {
// Note: unlike the other Commander animation, this is played through the
// Dondozo instead of the Tatsugiri.
const tatsugiri = this.pokemon.getAlly();
if (isNullOrUndefined(tatsugiri)) {
if (tatsugiri == null) {
console.warn("Aborting COMMANDER_REMOVE anim: Tatsugiri is undefined");
this.end();
return;

View File

@ -9,7 +9,9 @@ export abstract class PokemonPhase extends FieldPhase {
* TODO: Make this either use IDs or `BattlerIndex`es, not a weird mix of both
*/
protected battlerIndex: BattlerIndex | number;
// TODO: Why is this needed?
public player: boolean;
/** @todo Remove in favor of `battlerIndex` pleas for fuck's sake */
public fieldIndex: number;
constructor(battlerIndex?: BattlerIndex | number) {
@ -32,10 +34,11 @@ export abstract class PokemonPhase extends FieldPhase {
this.fieldIndex = battlerIndex % 2;
}
// TODO: This should have `undefined` in its signature
getPokemon(): Pokemon {
if (this.battlerIndex > BattlerIndex.ENEMY_2) {
return globalScene.getPokemonById(this.battlerIndex)!; //TODO: is this bang correct?
return globalScene.getPokemonById(this.battlerIndex)!;
}
return globalScene.getField()[this.battlerIndex]!; //TODO: is this bang correct?
return globalScene.getField()[this.battlerIndex]!;
}
}

View File

@ -3,9 +3,9 @@ import { SwitchType } from "#enums/switch-type";
import { UiMode } from "#enums/ui-mode";
import type { PlayerPokemon } from "#field/pokemon";
import { BattlePhase } from "#phases/battle-phase";
import type { PartyOption } from "#ui/handlers/party-ui-handler";
import { PartyUiHandler, PartyUiMode } from "#ui/handlers/party-ui-handler";
import { isNullOrUndefined, toDmgValue } from "#utils/common";
import type { PartyOption } from "#ui/party-ui-handler";
import { PartyUiHandler, PartyUiMode } from "#ui/party-ui-handler";
import { toDmgValue } from "#utils/common";
import i18next from "i18next";
/**
@ -42,11 +42,7 @@ export class RevivalBlessingPhase extends BattlePhase {
);
const allyPokemon = this.user.getAlly();
if (
globalScene.currentBattle.double
&& globalScene.getPlayerParty().length > 1
&& !isNullOrUndefined(allyPokemon)
) {
if (globalScene.currentBattle.double && globalScene.getPlayerParty().length > 1 && allyPokemon != null) {
if (slotIndex <= 1) {
// Revived ally pokemon
globalScene.phaseManager.unshiftNew(

View File

@ -5,7 +5,7 @@ import { ChallengeType } from "#enums/challenge-type";
import { UiMode } from "#enums/ui-mode";
import { MapModifier, MoneyInterestModifier } from "#modifiers/modifier";
import { BattlePhase } from "#phases/battle-phase";
import type { OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import type { OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { applyChallenges } from "#utils/challenge-utils";
import { BooleanHolder, randSeedInt } from "#utils/common";

View File

@ -24,10 +24,10 @@ import {
TmModifierType,
} from "#modifiers/modifier-type";
import { BattlePhase } from "#phases/battle-phase";
import type { ModifierSelectUiHandler } from "#ui/handlers/modifier-select-ui-handler";
import { SHOP_OPTIONS_ROW_LIMIT } from "#ui/handlers/modifier-select-ui-handler";
import { PartyOption, PartyUiHandler, PartyUiMode } from "#ui/handlers/party-ui-handler";
import { isNullOrUndefined, NumberHolder } from "#utils/common";
import type { ModifierSelectUiHandler } from "#ui/modifier-select-ui-handler";
import { SHOP_OPTIONS_ROW_LIMIT } from "#ui/modifier-select-ui-handler";
import { PartyOption, PartyUiHandler, PartyUiMode } from "#ui/party-ui-handler";
import { NumberHolder } from "#utils/common";
import i18next from "i18next";
export type ModifierSelectCallback = (rowCursor: number, cursor: number) => boolean;
@ -429,7 +429,7 @@ export class SelectModifierPhase extends BattlePhase {
}
let multiplier = 1;
if (!isNullOrUndefined(this.customModifierSettings?.rerollMultiplier)) {
if (this.customModifierSettings?.rerollMultiplier != null) {
if (this.customModifierSettings.rerollMultiplier < 0) {
// Completely overrides reroll cost to -1 and early exits
return -1;

View File

@ -7,10 +7,9 @@ import { ChallengeType } from "#enums/challenge-type";
import type { SpeciesId } from "#enums/species-id";
import { UiMode } from "#enums/ui-mode";
import { overrideHeldItems, overrideModifiers } from "#modifiers/modifier";
import { SaveSlotUiMode } from "#ui/handlers/save-slot-select-ui-handler";
import type { Starter } from "#ui/handlers/starter-select-ui-handler";
import { SaveSlotUiMode } from "#ui/save-slot-select-ui-handler";
import type { Starter } from "#ui/starter-select-ui-handler";
import { applyChallenges } from "#utils/challenge-utils";
import { isNullOrUndefined } from "#utils/common";
import { getPokemonSpecies } from "#utils/pokemon-utils";
import SoundFade from "phaser3-rex-plugins/plugins/soundfade";
@ -51,7 +50,7 @@ export class SelectStarterPhase extends Phase {
let starterFormIndex = Math.min(starterProps.formIndex, Math.max(starter.species.forms.length - 1, 0));
if (
starter.species.speciesId in Overrides.STARTER_FORM_OVERRIDES
&& !isNullOrUndefined(Overrides.STARTER_FORM_OVERRIDES[starter.species.speciesId])
&& Overrides.STARTER_FORM_OVERRIDES[starter.species.speciesId] != null
&& starter.species.forms[Overrides.STARTER_FORM_OVERRIDES[starter.species.speciesId]!]
) {
starterFormIndex = Overrides.STARTER_FORM_OVERRIDES[starter.species.speciesId]!;
@ -89,7 +88,7 @@ export class SelectStarterPhase extends Phase {
starterPokemon.nickname = starter.nickname;
}
if (!isNullOrUndefined(starter.teraType)) {
if (starter.teraType != null) {
starterPokemon.teraType = starter.teraType;
} else {
starterPokemon.teraType = starterPokemon.species.type1;

View File

@ -13,7 +13,7 @@ import type { Pokemon } from "#field/pokemon";
import { ResetNegativeStatStageModifier } from "#modifiers/modifier";
import { PokemonPhase } from "#phases/pokemon-phase";
import type { ConditionalUserFieldProtectStatAbAttrParams, PreStatStageChangeAbAttrParams } from "#types/ability-types";
import { BooleanHolder, isNullOrUndefined, NumberHolder } from "#utils/common";
import { BooleanHolder, NumberHolder } from "#utils/common";
import i18next from "i18next";
export type StatStageChangeCallback = (
@ -153,7 +153,7 @@ export class StatStageChangePhase extends PokemonPhase {
applyAbAttrs("ConditionalUserFieldProtectStatAbAttr", abAttrParams);
// TODO: Consider skipping this call if `cancelled` is false.
const ally = pokemon.getAlly();
if (!isNullOrUndefined(ally)) {
if (ally != null) {
applyAbAttrs("ConditionalUserFieldProtectStatAbAttr", { ...abAttrParams, pokemon: ally });
}

View File

@ -3,7 +3,7 @@ import { DynamicPhaseType } from "#enums/dynamic-phase-type";
import { SwitchType } from "#enums/switch-type";
import { UiMode } from "#enums/ui-mode";
import { BattlePhase } from "#phases/battle-phase";
import { PartyOption, PartyUiHandler, PartyUiMode } from "#ui/handlers/party-ui-handler";
import { PartyOption, PartyUiHandler, PartyUiMode } from "#ui/party-ui-handler";
/**
* Opens the party selector UI and transitions into a {@linkcode SwitchSummonPhase}

View File

@ -16,9 +16,9 @@ import type { Modifier } from "#modifiers/modifier";
import { getDailyRunStarterModifiers, regenerateModifierPoolThresholds } from "#modifiers/modifier-type";
import { vouchers } from "#system/voucher";
import type { SessionSaveData } from "#types/save-data";
import type { OptionSelectConfig, OptionSelectItem } from "#ui/handlers/abstract-option-select-ui-handler";
import { SaveSlotUiMode } from "#ui/handlers/save-slot-select-ui-handler";
import { isLocal, isLocalServerConnected, isNullOrUndefined } from "#utils/common";
import type { OptionSelectConfig, OptionSelectItem } from "#ui/abstract-option-select-ui-handler";
import { SaveSlotUiMode } from "#ui/save-slot-select-ui-handler";
import { isLocal, isLocalServerConnected } from "#utils/common";
import i18next from "i18next";
export class TitlePhase extends Phase {
@ -289,7 +289,7 @@ export class TitlePhase extends Phase {
} else {
// Grab first 10 chars of ISO date format (YYYY-MM-DD) and convert to base64
let seed: string = btoa(new Date().toISOString().substring(0, 10));
if (!isNullOrUndefined(Overrides.DAILY_RUN_SEED_OVERRIDE)) {
if (Overrides.DAILY_RUN_SEED_OVERRIDE != null) {
seed = Overrides.DAILY_RUN_SEED_OVERRIDE;
}
generateDaily(seed);

View File

@ -1,6 +1,6 @@
import { ApiBase } from "#api/api-base";
import type { GetDailyRankingsPageCountRequest, GetDailyRankingsRequest } from "#types/api/pokerogue-daily-api";
import type { RankingEntry } from "#ui/containers/daily-run-scoreboard";
import type { RankingEntry } from "#ui/daily-run-scoreboard";
/**
* A wrapper for daily-run PokéRogue API requests.

View File

@ -2,7 +2,6 @@ import { globalScene } from "#app/global-scene";
import { VariantTier } from "#enums/variant-tier";
import type { Pokemon } from "#field/pokemon";
import { hasExpSprite } from "#sprites/sprite-utils";
import { isNullOrUndefined } from "#utils/common";
export type Variant = 0 | 1 | 2;
@ -138,7 +137,7 @@ export async function populateVariantColorCache(
return fallbackVariantColor(cacheKey, spritePath, useExpSprite, battleSpritePath, error);
})
.then(c => {
if (!isNullOrUndefined(c)) {
if (c != null) {
variantColorCache[cacheKey] = c;
}
});

View File

@ -72,7 +72,7 @@ import type {
VoucherCounts,
VoucherUnlocks,
} from "#types/save-data";
import { RUN_HISTORY_LIMIT } from "#ui/handlers/run-history-ui-handler";
import { RUN_HISTORY_LIMIT } from "#ui/run-history-ui-handler";
import { applyChallenges } from "#utils/challenge-utils";
import { executeIf, fixedInt, isLocal, NumberHolder, randInt, randSeedItem } from "#utils/common";
import { decrypt, encrypt } from "#utils/data";

View File

@ -2,7 +2,6 @@ import { globalScene } from "#app/global-scene";
import { pokemonPrevolutions } from "#balance/pokemon-evolutions";
import type { SpeciesId } from "#enums/species-id";
import type { RibbonFlag } from "#system/ribbons/ribbon-data";
import { isNullOrUndefined } from "#utils/common";
/**
* Award one or more ribbons to a species and its pre-evolutions
@ -14,7 +13,7 @@ export function awardRibbonsToSpeciesLine(id: SpeciesId, ribbons: RibbonFlag): v
const dexData = globalScene.gameData.dexData;
dexData[id].ribbons.award(ribbons);
// Mark all pre-evolutions of the Pokémon with the same ribbon flags.
for (let prevoId = pokemonPrevolutions[id]; !isNullOrUndefined(prevoId); prevoId = pokemonPrevolutions[prevoId]) {
for (let prevoId = pokemonPrevolutions[id]; prevoId != null; prevoId = pokemonPrevolutions[prevoId]) {
dexData[prevoId].ribbons.award(ribbons);
}
}

View File

@ -8,7 +8,6 @@ import type { SessionSaveData, SystemSaveData } from "#types/save-data";
import type { SessionSaveMigrator } from "#types/session-save-migrator";
import type { SettingsSaveMigrator } from "#types/settings-save-migrator";
import type { SystemSaveMigrator } from "#types/system-save-migrator";
import { isNullOrUndefined } from "#utils/common";
/**
* Migrate ability starter data if empty for caught species.
@ -82,7 +81,7 @@ const fixLegendaryStats: SystemSaveMigrator = {
const fixStarterData: SystemSaveMigrator = {
version: "1.0.4",
migrate: (data: SystemSaveData): void => {
if (!isNullOrUndefined(data.starterData)) {
if (data.starterData != null) {
for (const starterId of defaultStarterSpecies) {
if (data.starterData[starterId]?.abilityAttr) {
data.starterData[starterId].abilityAttr |= AbilityAttr.ABILITY_1;
@ -198,7 +197,7 @@ const migrateCustomPokemonData: SessionSaveMigrator = {
pokemon["fusionMysteryEncounterPokemonData"] = null;
}
pokemon.customPokemonData = pokemon.customPokemonData ?? new CustomPokemonData();
if (!isNullOrUndefined(pokemon["natureOverride"]) && pokemon["natureOverride"] >= 0) {
if (pokemon["natureOverride"] != null && pokemon["natureOverride"] >= 0) {
pokemon.customPokemonData.nature = pokemon["natureOverride"];
pokemon["natureOverride"] = -1;
}

View File

@ -3,7 +3,6 @@ import { DexAttr } from "#enums/dex-attr";
import type { SessionSaveData, SystemSaveData } from "#types/save-data";
import type { SessionSaveMigrator } from "#types/session-save-migrator";
import type { SystemSaveMigrator } from "#types/system-save-migrator";
import { isNullOrUndefined } from "#utils/common";
import { getPokemonSpecies, getPokemonSpeciesForm } from "#utils/pokemon-utils";
/**
@ -68,13 +67,13 @@ const migrateTera: SessionSaveMigrator = {
}
data.party.forEach(p => {
if (isNullOrUndefined(p.teraType)) {
if (p.teraType == null) {
p.teraType = getPokemonSpeciesForm(p.species, p.formIndex).type1;
}
});
data.enemyParty.forEach(p => {
if (isNullOrUndefined(p.teraType)) {
if (p.teraType == null) {
p.teraType = getPokemonSpeciesForm(p.species, p.formIndex).type1;
}
});

View File

@ -9,7 +9,6 @@ import { TextStyle } from "#enums/text-style";
import { WeatherType } from "#enums/weather-type";
import { addTextObject } from "#ui/text";
import type { nil } from "#utils/common";
import { isNullOrUndefined } from "#utils/common";
import i18next from "i18next";
export enum EventType {
@ -428,7 +427,7 @@ export class TimedEventManager {
getEventBannerLangs(): string[] {
const ret: string[] = [];
ret.push(...timedEvents.find(te => this.isActive(te) && !isNullOrUndefined(te.availableLangs))?.availableLangs!);
ret.push(...timedEvents.find(te => this.isActive(te) && te.availableLangs != null)?.availableLangs!);
return ret;
}
@ -437,7 +436,7 @@ export class TimedEventManager {
timedEvents
.filter(te => this.isActive(te))
.map(te => {
if (!isNullOrUndefined(te.eventEncounters)) {
if (te.eventEncounters != null) {
ret.push(...te.eventEncounters);
}
});
@ -452,7 +451,7 @@ export class TimedEventManager {
let multiplier = CLASSIC_CANDY_FRIENDSHIP_MULTIPLIER;
const classicFriendshipEvents = timedEvents.filter(te => this.isActive(te));
for (const fe of classicFriendshipEvents) {
if (!isNullOrUndefined(fe.classicFriendshipMultiplier) && fe.classicFriendshipMultiplier > multiplier) {
if (fe.classicFriendshipMultiplier != null && fe.classicFriendshipMultiplier > multiplier) {
multiplier = fe.classicFriendshipMultiplier;
}
}
@ -476,7 +475,7 @@ export class TimedEventManager {
timedEvents
.filter(te => this.isActive(te))
.map(te => {
if (!isNullOrUndefined(te.delibirdyBuff)) {
if (te.delibirdyBuff != null) {
ret.push(...te.delibirdyBuff);
}
});
@ -492,7 +491,7 @@ export class TimedEventManager {
timedEvents
.filter(te => this.isActive(te))
.map(te => {
if (!isNullOrUndefined(te.weather)) {
if (te.weather != null) {
ret.push(...te.weather);
}
});
@ -504,7 +503,7 @@ export class TimedEventManager {
timedEvents
.filter(te => this.isActive(te))
.map(te => {
if (!isNullOrUndefined(te.mysteryEncounterTierChanges)) {
if (te.mysteryEncounterTierChanges != null) {
ret.push(...te.mysteryEncounterTierChanges);
}
});
@ -514,7 +513,7 @@ export class TimedEventManager {
getEventMysteryEncountersDisabled(): MysteryEncounterType[] {
const ret: MysteryEncounterType[] = [];
timedEvents
.filter(te => this.isActive(te) && !isNullOrUndefined(te.mysteryEncounterTierChanges))
.filter(te => this.isActive(te) && te.mysteryEncounterTierChanges != null)
.map(te => {
te.mysteryEncounterTierChanges?.map(metc => {
if (metc.disable) {
@ -531,7 +530,7 @@ export class TimedEventManager {
): MysteryEncounterTier {
let ret = normal;
timedEvents
.filter(te => this.isActive(te) && !isNullOrUndefined(te.mysteryEncounterTierChanges))
.filter(te => this.isActive(te) && te.mysteryEncounterTierChanges != null)
.map(te => {
te.mysteryEncounterTierChanges?.map(metc => {
if (metc.mysteryEncounter === encounterType) {
@ -544,7 +543,7 @@ export class TimedEventManager {
getEventLuckBoost(): number {
let ret = 0;
const luckEvents = timedEvents.filter(te => this.isActive(te) && !isNullOrUndefined(te.luckBoost));
const luckEvents = timedEvents.filter(te => this.isActive(te) && te.luckBoost != null);
for (const le of luckEvents) {
ret += le.luckBoost!;
}
@ -556,7 +555,7 @@ export class TimedEventManager {
timedEvents
.filter(te => this.isActive(te))
.map(te => {
if (!isNullOrUndefined(te.luckBoostedSpecies)) {
if (te.luckBoostedSpecies != null) {
ret.push(...te.luckBoostedSpecies.filter(s => !ret.includes(s)));
}
});
@ -576,7 +575,7 @@ export class TimedEventManager {
getFixedBattleEventRewards(wave: number): string[] {
const ret: string[] = [];
timedEvents
.filter(te => this.isActive(te) && !isNullOrUndefined(te.classicWaveRewards))
.filter(te => this.isActive(te) && te.classicWaveRewards != null)
.map(te => {
ret.push(...te.classicWaveRewards!.filter(cwr => cwr.wave === wave).map(cwr => cwr.type));
});
@ -586,7 +585,7 @@ export class TimedEventManager {
// Gets the extra shiny chance for trainers due to event (odds/65536)
getClassicTrainerShinyChance(): number {
let ret = 0;
const tsEvents = timedEvents.filter(te => this.isActive(te) && !isNullOrUndefined(te.trainerShinyChance));
const tsEvents = timedEvents.filter(te => this.isActive(te) && te.trainerShinyChance != null);
tsEvents.map(t => (ret += t.trainerShinyChance!));
return ret;
}
@ -594,7 +593,7 @@ export class TimedEventManager {
getEventBgmReplacement(bgm: string): string {
let ret = bgm;
timedEvents.map(te => {
if (this.isActive(te) && !isNullOrUndefined(te.music)) {
if (this.isActive(te) && te.music != null) {
te.music.map(mr => {
if (mr[0] === bgm) {
console.log(`it is ${te.name} so instead of ${mr[0]} we play ${mr[1]}`);

View File

@ -1,8 +1,8 @@
import { globalScene } from "#app/global-scene";
import Overrides from "#app/overrides";
import { UiMode } from "#enums/ui-mode";
import { AwaitableUiHandler } from "#ui/handlers/awaitable-ui-handler";
import type { UiHandler } from "#ui/handlers/ui-handler";
import { AwaitableUiHandler } from "#ui/awaitable-ui-handler";
import type { UiHandler } from "#ui/ui-handler";
import i18next from "i18next";
export enum Tutorial {

View File

@ -3,16 +3,16 @@ import type { InputsController } from "#app/inputs-controller";
import { Button } from "#enums/buttons";
import { UiMode } from "#enums/ui-mode";
import { Setting, SettingKeys, settingIndex } from "#system/settings";
import type { MessageUiHandler } from "#ui/handlers/message-ui-handler";
import { PokedexPageUiHandler } from "#ui/handlers/pokedex-page-ui-handler";
import { PokedexUiHandler } from "#ui/handlers/pokedex-ui-handler";
import { RunInfoUiHandler } from "#ui/handlers/run-info-ui-handler";
import { StarterSelectUiHandler } from "#ui/handlers/starter-select-ui-handler";
import type { MessageUiHandler } from "#ui/message-ui-handler";
import { PokedexPageUiHandler } from "#ui/pokedex-page-ui-handler";
import { PokedexUiHandler } from "#ui/pokedex-ui-handler";
import { RunInfoUiHandler } from "#ui/run-info-ui-handler";
import { SettingsAudioUiHandler } from "#ui/settings-audio-ui-handler";
import { SettingsDisplayUiHandler } from "#ui/settings-display-ui-handler";
import { SettingsGamepadUiHandler } from "#ui/settings-gamepad-ui-handler";
import { SettingsKeyboardUiHandler } from "#ui/settings-keyboard-ui-handler";
import { SettingsUiHandler } from "#ui/settings-ui-handler";
import { StarterSelectUiHandler } from "#ui/starter-select-ui-handler";
import Phaser from "phaser";
type ActionKeys = Record<Button, () => void>;

View File

@ -3,9 +3,9 @@ import { Stat } from "#enums/stat";
import { TextStyle } from "#enums/text-style";
import { UiTheme } from "#enums/ui-theme";
import type { EnemyPokemon } from "#field/pokemon";
import { BattleFlyout } from "#ui/battle-flyout";
import type { BattleInfoParamList } from "#ui/battle-info";
import { BattleInfo } from "#ui/battle-info";
import { BattleFlyout } from "#ui/containers/battle-flyout";
import { addTextObject } from "#ui/text";
import { addWindow, WindowVariant } from "#ui/ui-theme";
import { getLocalizedSpriteKey } from "#utils/common";

View File

@ -15,8 +15,8 @@ import {
} from "#events/arena";
import type { TurnEndEvent } from "#events/battle-scene";
import { BattleSceneEventType } from "#events/battle-scene";
import { TimeOfDayWidget } from "#ui/containers/time-of-day-widget";
import { addTextObject } from "#ui/text";
import { TimeOfDayWidget } from "#ui/time-of-day-widget";
import { addWindow, WindowVariant } from "#ui/ui-theme";
import { fixedInt } from "#utils/common";
import { toCamelCase, toTitleCase } from "#utils/strings";

View File

@ -1,6 +1,6 @@
import { globalScene } from "#app/global-scene";
import { TextStyle } from "#enums/text-style";
import { ScrollBar } from "#ui/containers/scroll-bar";
import { ScrollBar } from "#ui/scroll-bar";
import { addTextObject } from "#ui/text";
import { addWindow, WindowVariant } from "#ui/ui-theme";
import i18next from "i18next";

View File

@ -2,7 +2,7 @@ import { globalScene } from "#app/global-scene";
import { TextStyle } from "#enums/text-style";
import type { EggCountChangedEvent } from "#events/egg";
import { EggEventType } from "#events/egg";
import type { EggHatchSceneUiHandler } from "#ui/handlers/egg-hatch-scene-ui-handler";
import type { EggHatchSceneUiHandler } from "#ui/egg-hatch-scene-ui-handler";
import { addTextObject } from "#ui/text";
import { addWindow } from "#ui/ui-theme";

View File

@ -2,9 +2,9 @@ import { globalScene } from "#app/global-scene";
import type { DropDownColumn } from "#enums/drop-down-column";
import { TextStyle } from "#enums/text-style";
import type { UiTheme } from "#enums/ui-theme";
import type { DropDown } from "#ui/containers/dropdown";
import { DropDownType } from "#ui/containers/dropdown";
import type { StarterContainer } from "#ui/containers/starter-container";
import type { DropDown } from "#ui/dropdown";
import { DropDownType } from "#ui/dropdown";
import type { StarterContainer } from "#ui/starter-container";
import { addTextObject, getTextColor } from "#ui/text";
import { addWindow, WindowVariant } from "#ui/ui-theme";

View File

@ -2,8 +2,8 @@ import { globalScene } from "#app/global-scene";
import { TextStyle } from "#enums/text-style";
import { UiMode } from "#enums/ui-mode";
import type { UiTheme } from "#enums/ui-theme";
import type { StarterContainer } from "#ui/containers/starter-container";
import type { AwaitableUiHandler } from "#ui/handlers/awaitable-ui-handler";
import type { AwaitableUiHandler } from "#ui/awaitable-ui-handler";
import type { StarterContainer } from "#ui/starter-container";
import { addTextObject, getTextColor } from "#ui/text";
import type { UI } from "#ui/ui";
import { addWindow, WindowVariant } from "#ui/ui-theme";

View File

@ -4,8 +4,8 @@ import { Gender } from "#data/gender";
import type { PokemonSpecies } from "#data/pokemon-species";
import { DexAttr } from "#enums/dex-attr";
import { getVariantTint } from "#sprites/variant";
import type { PokemonIconAnimHelper } from "#ui/utils/pokemon-icon-anim-helper";
import { PokemonIconAnimMode } from "#ui/utils/pokemon-icon-anim-helper";
import type { PokemonIconAnimHelper } from "#ui/pokemon-icon-anim-helper";
import { PokemonIconAnimMode } from "#ui/pokemon-icon-anim-helper";
/**
* A container for a Pokemon's sprite and icons to get displayed in the egg summary screen

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