mirror of
https://github.com/pagefaultgames/pokerogue.git
synced 2025-08-20 14:29:28 +02:00
Merge branch 'beta' of https://github.com/pagefaultgames/pokerogue into catchingcharm
This commit is contained in:
commit
8a73cb8336
2
global.d.ts
vendored
2
global.d.ts
vendored
@ -10,5 +10,5 @@ declare global {
|
|||||||
*
|
*
|
||||||
* To set up your own server in a test see `game_data.test.ts`
|
* To set up your own server in a test see `game_data.test.ts`
|
||||||
*/
|
*/
|
||||||
var i18nServer: SetupServerApi;
|
var server: SetupServerApi;
|
||||||
}
|
}
|
||||||
|
17
src/@types/PokerogueAccountApi.ts
Normal file
17
src/@types/PokerogueAccountApi.ts
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import type { UserInfo } from "#app/@types/UserInfo";
|
||||||
|
|
||||||
|
export interface AccountInfoResponse extends UserInfo {}
|
||||||
|
|
||||||
|
export interface AccountLoginRequest {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccountLoginResponse {
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AccountRegisterRequest {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
}
|
31
src/@types/PokerogueAdminApi.ts
Normal file
31
src/@types/PokerogueAdminApi.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
export interface LinkAccountToDiscordIdRequest {
|
||||||
|
username: string;
|
||||||
|
discordId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnlinkAccountFromDiscordIdRequest {
|
||||||
|
username: string;
|
||||||
|
discordId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LinkAccountToGoogledIdRequest {
|
||||||
|
username: string;
|
||||||
|
googleId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UnlinkAccountFromGoogledIdRequest {
|
||||||
|
username: string;
|
||||||
|
googleId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SearchAccountRequest {
|
||||||
|
username: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SearchAccountResponse {
|
||||||
|
username: string;
|
||||||
|
discordId: string;
|
||||||
|
googleId: string;
|
||||||
|
lastLoggedIn: string;
|
||||||
|
registered: string;
|
||||||
|
}
|
4
src/@types/PokerogueApi.ts
Normal file
4
src/@types/PokerogueApi.ts
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
export interface TitleStatsResponse {
|
||||||
|
playerCount: number;
|
||||||
|
battleCount: number;
|
||||||
|
}
|
10
src/@types/PokerogueDailyApi.ts
Normal file
10
src/@types/PokerogueDailyApi.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import type { ScoreboardCategory } from "#app/ui/daily-run-scoreboard";
|
||||||
|
|
||||||
|
export interface GetDailyRankingsRequest {
|
||||||
|
category: ScoreboardCategory;
|
||||||
|
page?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetDailyRankingsPageCountRequest {
|
||||||
|
category: ScoreboardCategory;
|
||||||
|
}
|
8
src/@types/PokerogueSavedataApi.ts
Normal file
8
src/@types/PokerogueSavedataApi.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import type { SessionSaveData, SystemSaveData } from "#app/system/game-data";
|
||||||
|
|
||||||
|
export interface UpdateAllSavedataRequest {
|
||||||
|
system: SystemSaveData;
|
||||||
|
session: SessionSaveData;
|
||||||
|
sessionSlotId: number;
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
39
src/@types/PokerogueSessionSavedataApi.ts
Normal file
39
src/@types/PokerogueSessionSavedataApi.ts
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
export class UpdateSessionSavedataRequest {
|
||||||
|
slot: number;
|
||||||
|
trainerId: number;
|
||||||
|
secretId: number;
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** This is **NOT** similar to {@linkcode ClearSessionSavedataRequest} */
|
||||||
|
export interface NewClearSessionSavedataRequest {
|
||||||
|
slot: number;
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetSessionSavedataRequest {
|
||||||
|
slot: number;
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeleteSessionSavedataRequest {
|
||||||
|
slot: number;
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** This is **NOT** similar to {@linkcode NewClearSessionSavedataRequest} */
|
||||||
|
export interface ClearSessionSavedataRequest {
|
||||||
|
slot: number;
|
||||||
|
trainerId: number;
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pokerogue API response for path: `/savedata/session/clear`
|
||||||
|
*/
|
||||||
|
export interface ClearSessionSavedataResponse {
|
||||||
|
/** Contains the error message if any occured */
|
||||||
|
error?: string;
|
||||||
|
/** Is `true` if the request was successfully processed */
|
||||||
|
success?: boolean;
|
||||||
|
}
|
20
src/@types/PokerogueSystemSavedataApi.ts
Normal file
20
src/@types/PokerogueSystemSavedataApi.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import type { SystemSaveData } from "#app/system/game-data";
|
||||||
|
|
||||||
|
export interface GetSystemSavedataRequest {
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UpdateSystemSavedataRequest {
|
||||||
|
clientSessionId: string;
|
||||||
|
trainerId?: number;
|
||||||
|
secretId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VerifySystemSavedataRequest {
|
||||||
|
clientSessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VerifySystemSavedataResponse {
|
||||||
|
valid: boolean;
|
||||||
|
systemData: SystemSaveData;
|
||||||
|
}
|
7
src/@types/UserInfo.ts
Normal file
7
src/@types/UserInfo.ts
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
export interface UserInfo {
|
||||||
|
username: string;
|
||||||
|
lastSessionSlot: number;
|
||||||
|
discordId: string;
|
||||||
|
googleId: string;
|
||||||
|
hasAdminRole: boolean;
|
||||||
|
}
|
@ -1,9 +0,0 @@
|
|||||||
/**
|
|
||||||
* Pokerogue API response for path: `/savedata/session/clear`
|
|
||||||
*/
|
|
||||||
export interface PokerogueApiClearSessionData {
|
|
||||||
/** Contains the error message if any occured */
|
|
||||||
error?: string;
|
|
||||||
/** Is `true` if the request was successfully processed */
|
|
||||||
success?: boolean;
|
|
||||||
}
|
|
@ -1,14 +1,8 @@
|
|||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
import type { UserInfo } from "#app/@types/UserInfo";
|
||||||
import { bypassLogin } from "./battle-scene";
|
import { bypassLogin } from "./battle-scene";
|
||||||
import * as Utils from "./utils";
|
import * as Utils from "./utils";
|
||||||
|
|
||||||
export interface UserInfo {
|
|
||||||
username: string;
|
|
||||||
lastSessionSlot: integer;
|
|
||||||
discordId: string;
|
|
||||||
googleId: string;
|
|
||||||
hasAdminRole: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export let loggedInUser: UserInfo | null = null;
|
export let loggedInUser: UserInfo | null = null;
|
||||||
// This is a random string that is used to identify the client session - unique per session (tab or window) so that the game will only save on the one that the server is expecting
|
// This is a random string that is used to identify the client session - unique per session (tab or window) so that the game will only save on the one that the server is expecting
|
||||||
export const clientSessionId = Utils.randomString(32);
|
export const clientSessionId = Utils.randomString(32);
|
||||||
@ -43,18 +37,14 @@ export function updateUserInfo(): Promise<[boolean, integer]> {
|
|||||||
});
|
});
|
||||||
return resolve([ true, 200 ]);
|
return resolve([ true, 200 ]);
|
||||||
}
|
}
|
||||||
Utils.apiFetch("account/info", true).then(response => {
|
pokerogueApi.account.getInfo().then(([ accountInfo, status ]) => {
|
||||||
if (!response.ok) {
|
if (!accountInfo) {
|
||||||
resolve([ false, response.status ]);
|
resolve([ false, status ]);
|
||||||
return;
|
return;
|
||||||
|
} else {
|
||||||
|
loggedInUser = accountInfo;
|
||||||
|
resolve([ true, 200 ]);
|
||||||
}
|
}
|
||||||
return response.json();
|
|
||||||
}).then(jsonResponse => {
|
|
||||||
loggedInUser = jsonResponse;
|
|
||||||
resolve([ true, 200 ]);
|
|
||||||
}).catch(err => {
|
|
||||||
console.error(err);
|
|
||||||
resolve([ false, 500 ]);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -38,7 +38,7 @@ import PokemonData from "#app/system/pokemon-data";
|
|||||||
import { Nature } from "#app/data/nature";
|
import { Nature } from "#app/data/nature";
|
||||||
import { FormChangeItem, pokemonFormChanges, SpeciesFormChange, SpeciesFormChangeManualTrigger, SpeciesFormChangeTimeOfDayTrigger, SpeciesFormChangeTrigger } from "#app/data/pokemon-forms";
|
import { FormChangeItem, pokemonFormChanges, SpeciesFormChange, SpeciesFormChangeManualTrigger, SpeciesFormChangeTimeOfDayTrigger, SpeciesFormChangeTrigger } from "#app/data/pokemon-forms";
|
||||||
import { FormChangePhase } from "#app/phases/form-change-phase";
|
import { FormChangePhase } from "#app/phases/form-change-phase";
|
||||||
import { getTypeRgb } from "#app/data/type";
|
import { getTypeRgb, Type } from "#app/data/type";
|
||||||
import PokemonSpriteSparkleHandler from "#app/field/pokemon-sprite-sparkle-handler";
|
import PokemonSpriteSparkleHandler from "#app/field/pokemon-sprite-sparkle-handler";
|
||||||
import CharSprite from "#app/ui/char-sprite";
|
import CharSprite from "#app/ui/char-sprite";
|
||||||
import DamageNumberHandler from "#app/field/damage-number-handler";
|
import DamageNumberHandler from "#app/field/damage-number-handler";
|
||||||
@ -96,7 +96,9 @@ import { ExpPhase } from "#app/phases/exp-phase";
|
|||||||
import { ShowPartyExpBarPhase } from "#app/phases/show-party-exp-bar-phase";
|
import { ShowPartyExpBarPhase } from "#app/phases/show-party-exp-bar-phase";
|
||||||
import { MysteryEncounterMode } from "#enums/mystery-encounter-mode";
|
import { MysteryEncounterMode } from "#enums/mystery-encounter-mode";
|
||||||
import { ExpGainsSpeed } from "#enums/exp-gains-speed";
|
import { ExpGainsSpeed } from "#enums/exp-gains-speed";
|
||||||
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
import { FRIENDSHIP_GAIN_FROM_BATTLE } from "#app/data/balance/starters";
|
import { FRIENDSHIP_GAIN_FROM_BATTLE } from "#app/data/balance/starters";
|
||||||
|
import { StatusEffect } from "#enums/status-effect";
|
||||||
|
|
||||||
export const bypassLogin = import.meta.env.VITE_BYPASS_LOGIN === "1";
|
export const bypassLogin = import.meta.env.VITE_BYPASS_LOGIN === "1";
|
||||||
|
|
||||||
@ -1278,6 +1280,8 @@ export default class BattleScene extends SceneBase {
|
|||||||
if (resetArenaState) {
|
if (resetArenaState) {
|
||||||
this.arena.resetArenaEffects();
|
this.arena.resetArenaEffects();
|
||||||
|
|
||||||
|
playerField.forEach((pokemon) => pokemon.lapseTag(BattlerTagType.COMMANDED));
|
||||||
|
|
||||||
playerField.forEach((pokemon, p) => {
|
playerField.forEach((pokemon, p) => {
|
||||||
if (pokemon.isOnField()) {
|
if (pokemon.isOnField()) {
|
||||||
this.pushPhase(new ReturnPhase(this, p));
|
this.pushPhase(new ReturnPhase(this, p));
|
||||||
@ -2979,12 +2983,21 @@ export default class BattleScene extends SceneBase {
|
|||||||
|
|
||||||
updateGameInfo(): void {
|
updateGameInfo(): void {
|
||||||
const gameInfo = {
|
const gameInfo = {
|
||||||
playTime: this.sessionPlayTime ? this.sessionPlayTime : 0,
|
playTime: this.sessionPlayTime ?? 0,
|
||||||
gameMode: this.currentBattle ? this.gameMode.getName() : "Title",
|
gameMode: this.currentBattle ? this.gameMode.getName() : "Title",
|
||||||
biome: this.currentBattle ? getBiomeName(this.arena.biomeType) : "",
|
biome: this.currentBattle ? getBiomeName(this.arena.biomeType) : "",
|
||||||
wave: this.currentBattle?.waveIndex || 0,
|
wave: this.currentBattle?.waveIndex ?? 0,
|
||||||
party: this.party ? this.party.map(p => {
|
party: this.party ? this.party.map((p) => {
|
||||||
return { name: p.name, level: p.level };
|
return {
|
||||||
|
name: p.name,
|
||||||
|
form: p.getFormKey(),
|
||||||
|
types: p.getTypes().map((type) => Type[type]),
|
||||||
|
teraType: p.getTeraType() !== Type.UNKNOWN ? Type[p.getTeraType()] : "",
|
||||||
|
level: p.level,
|
||||||
|
currentHP: p.hp,
|
||||||
|
maxHP: p.getMaxHp(),
|
||||||
|
status: p.status?.effect ? StatusEffect[p.status.effect] : ""
|
||||||
|
};
|
||||||
}) : [],
|
}) : [],
|
||||||
modeChain: this.ui?.getModeChain() ?? [],
|
modeChain: this.ui?.getModeChain() ?? [],
|
||||||
};
|
};
|
||||||
|
@ -3,3 +3,9 @@ export const PLAYER_PARTY_MAX_SIZE: number = 6;
|
|||||||
|
|
||||||
/** Whether to use seasonal splash messages in general */
|
/** Whether to use seasonal splash messages in general */
|
||||||
export const USE_SEASONAL_SPLASH_MESSAGES: boolean = false;
|
export const USE_SEASONAL_SPLASH_MESSAGES: boolean = false;
|
||||||
|
|
||||||
|
/** Name of the session ID cookie */
|
||||||
|
export const SESSION_ID_COOKIE_NAME: string = "pokerogue_sessionId";
|
||||||
|
|
||||||
|
/** Max value for an integer attribute in {@linkcode SystemSaveData} */
|
||||||
|
export const MAX_INT_ATTR_VALUE = 0x80000000;
|
||||||
|
@ -4,7 +4,7 @@ import { Constructor } from "#app/utils";
|
|||||||
import * as Utils from "../utils";
|
import * as Utils from "../utils";
|
||||||
import { getPokemonNameWithAffix } from "../messages";
|
import { getPokemonNameWithAffix } from "../messages";
|
||||||
import { Weather, WeatherType } from "./weather";
|
import { Weather, WeatherType } from "./weather";
|
||||||
import { BattlerTag, GroundedTag } from "./battler-tags";
|
import { BattlerTag, BattlerTagLapseType, GroundedTag } from "./battler-tags";
|
||||||
import { StatusEffect, getNonVolatileStatusEffects, getStatusEffectDescriptor, getStatusEffectHealText } from "./status-effect";
|
import { StatusEffect, getNonVolatileStatusEffects, getStatusEffectDescriptor, getStatusEffectHealText } from "./status-effect";
|
||||||
import { Gender } from "./gender";
|
import { Gender } from "./gender";
|
||||||
import Move, { AttackMove, MoveCategory, MoveFlags, MoveTarget, FlinchAttr, OneHitKOAttr, HitHealAttr, allMoves, StatusMove, SelfStatusMove, VariablePowerAttr, applyMoveAttrs, IncrementMovePriorityAttr, VariableMoveTypeAttr, RandomMovesetMoveAttr, RandomMoveAttr, NaturePowerAttr, CopyMoveAttr, MoveAttr, MultiHitAttr, SacrificialAttr, SacrificialAttrOnHit, NeutralDamageAgainstFlyingTypeMultiplierAttr, FixedDamageAttr } from "./move";
|
import Move, { AttackMove, MoveCategory, MoveFlags, MoveTarget, FlinchAttr, OneHitKOAttr, HitHealAttr, allMoves, StatusMove, SelfStatusMove, VariablePowerAttr, applyMoveAttrs, IncrementMovePriorityAttr, VariableMoveTypeAttr, RandomMovesetMoveAttr, RandomMoveAttr, NaturePowerAttr, CopyMoveAttr, MoveAttr, MultiHitAttr, SacrificialAttr, SacrificialAttrOnHit, NeutralDamageAgainstFlyingTypeMultiplierAttr, FixedDamageAttr } from "./move";
|
||||||
@ -35,6 +35,7 @@ import { SwitchSummonPhase } from "#app/phases/switch-summon-phase";
|
|||||||
import { BattleEndPhase } from "#app/phases/battle-end-phase";
|
import { BattleEndPhase } from "#app/phases/battle-end-phase";
|
||||||
import { NewBattlePhase } from "#app/phases/new-battle-phase";
|
import { NewBattlePhase } from "#app/phases/new-battle-phase";
|
||||||
import { MoveEndPhase } from "#app/phases/move-end-phase";
|
import { MoveEndPhase } from "#app/phases/move-end-phase";
|
||||||
|
import { PokemonAnimType } from "#enums/pokemon-anim-type";
|
||||||
|
|
||||||
export class Ability implements Localizable {
|
export class Ability implements Localizable {
|
||||||
public id: Abilities;
|
public id: Abilities;
|
||||||
@ -511,7 +512,11 @@ export class NonSuperEffectiveImmunityAbAttr extends TypeImmunityAbAttr {
|
|||||||
}
|
}
|
||||||
|
|
||||||
applyPreDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, cancelled: Utils.BooleanHolder, args: any[]): boolean {
|
applyPreDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, cancelled: Utils.BooleanHolder, args: any[]): boolean {
|
||||||
if (move instanceof AttackMove && pokemon.getAttackTypeEffectiveness(attacker.getMoveType(move), attacker) < 2) {
|
const modifierValue = args.length > 0
|
||||||
|
? (args[0] as Utils.NumberHolder).value
|
||||||
|
: pokemon.getAttackTypeEffectiveness(attacker.getMoveType(move), attacker);
|
||||||
|
|
||||||
|
if (move instanceof AttackMove && modifierValue < 2) {
|
||||||
cancelled.value = true; // Suppresses "No Effect" message
|
cancelled.value = true; // Suppresses "No Effect" message
|
||||||
(args[0] as Utils.NumberHolder).value = 0;
|
(args[0] as Utils.NumberHolder).value = 0;
|
||||||
return true;
|
return true;
|
||||||
@ -2591,6 +2596,42 @@ export class PostSummonFormChangeByWeatherAbAttr extends PostSummonAbAttr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attribute implementing the effects of {@link https://bulbapedia.bulbagarden.net/wiki/Commander_(Ability) | Commander}.
|
||||||
|
* When the source of an ability with this attribute detects a Dondozo as their active ally, the source "jumps
|
||||||
|
* into the Dondozo's mouth," sharply boosting the Dondozo's stats, cancelling the source's moves, and
|
||||||
|
* causing attacks that target the source to always miss.
|
||||||
|
*/
|
||||||
|
export class CommanderAbAttr extends AbAttr {
|
||||||
|
constructor() {
|
||||||
|
super(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
override apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: null, args: any[]): boolean {
|
||||||
|
// TODO: Should this work with X + Dondozo fusions?
|
||||||
|
if (pokemon.scene.currentBattle?.double && pokemon.getAlly()?.species.speciesId === Species.DONDOZO) {
|
||||||
|
// If the ally Dondozo is fainted or was previously "commanded" by
|
||||||
|
// another Pokemon, this effect cannot apply.
|
||||||
|
if (pokemon.getAlly().isFainted() || pokemon.getAlly().getTag(BattlerTagType.COMMANDED)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!simulated) {
|
||||||
|
// Lapse the source's semi-invulnerable tags (to avoid visual inconsistencies)
|
||||||
|
pokemon.lapseTags(BattlerTagLapseType.MOVE_EFFECT);
|
||||||
|
// Play an animation of the source jumping into the ally Dondozo's mouth
|
||||||
|
pokemon.scene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
// Apply boosts from this effect to the ally Dondozo
|
||||||
|
pokemon.getAlly().addTag(BattlerTagType.COMMANDED, 0, Moves.NONE, pokemon.id);
|
||||||
|
// Cancel the source Pokemon's next move (if a move is queued)
|
||||||
|
pokemon.scene.tryRemovePhase((phase) => phase instanceof MovePhase && phase.pokemon === pokemon);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class PreSwitchOutAbAttr extends AbAttr {
|
export class PreSwitchOutAbAttr extends AbAttr {
|
||||||
constructor() {
|
constructor() {
|
||||||
super(true);
|
super(true);
|
||||||
@ -5392,8 +5433,7 @@ export function initAbilities() {
|
|||||||
.attr(EffectSporeAbAttr),
|
.attr(EffectSporeAbAttr),
|
||||||
new Ability(Abilities.SYNCHRONIZE, 3)
|
new Ability(Abilities.SYNCHRONIZE, 3)
|
||||||
.attr(SyncEncounterNatureAbAttr)
|
.attr(SyncEncounterNatureAbAttr)
|
||||||
.attr(SynchronizeStatusAbAttr)
|
.attr(SynchronizeStatusAbAttr),
|
||||||
.partial(), // interaction with psycho shift needs work, keeping to old Gen interaction for now
|
|
||||||
new Ability(Abilities.CLEAR_BODY, 3)
|
new Ability(Abilities.CLEAR_BODY, 3)
|
||||||
.attr(ProtectStatAbAttr)
|
.attr(ProtectStatAbAttr)
|
||||||
.ignorable(),
|
.ignorable(),
|
||||||
@ -5995,7 +6035,7 @@ export function initAbilities() {
|
|||||||
.bypassFaint(),
|
.bypassFaint(),
|
||||||
new Ability(Abilities.CORROSION, 7)
|
new Ability(Abilities.CORROSION, 7)
|
||||||
.attr(IgnoreTypeStatusEffectImmunityAbAttr, [ StatusEffect.POISON, StatusEffect.TOXIC ], [ Type.STEEL, Type.POISON ])
|
.attr(IgnoreTypeStatusEffectImmunityAbAttr, [ StatusEffect.POISON, StatusEffect.TOXIC ], [ Type.STEEL, Type.POISON ])
|
||||||
.edgeCase(), // Should interact correctly with magic coat/bounce (not yet implemented), fling with toxic orb (not implemented yet), and synchronize (not fully implemented yet)
|
.edgeCase(), // Should interact correctly with magic coat/bounce (not yet implemented) + fling with toxic orb (not implemented yet)
|
||||||
new Ability(Abilities.COMATOSE, 7)
|
new Ability(Abilities.COMATOSE, 7)
|
||||||
.attr(UncopiableAbilityAbAttr)
|
.attr(UncopiableAbilityAbAttr)
|
||||||
.attr(UnswappableAbilityAbAttr)
|
.attr(UnswappableAbilityAbAttr)
|
||||||
@ -6099,7 +6139,8 @@ export function initAbilities() {
|
|||||||
.attr(NoFusionAbilityAbAttr)
|
.attr(NoFusionAbilityAbAttr)
|
||||||
.attr(UncopiableAbilityAbAttr)
|
.attr(UncopiableAbilityAbAttr)
|
||||||
.attr(UnswappableAbilityAbAttr)
|
.attr(UnswappableAbilityAbAttr)
|
||||||
.bypassFaint(),
|
.bypassFaint()
|
||||||
|
.edgeCase(), // Soft-locks the game if a form-changed Cramorant and its attacker both faint at the same time (ex. using Self-Destruct)
|
||||||
new Ability(Abilities.STALWART, 8)
|
new Ability(Abilities.STALWART, 8)
|
||||||
.attr(BlockRedirectAbAttr),
|
.attr(BlockRedirectAbAttr),
|
||||||
new Ability(Abilities.STEAM_ENGINE, 8)
|
new Ability(Abilities.STEAM_ENGINE, 8)
|
||||||
@ -6242,9 +6283,11 @@ export function initAbilities() {
|
|||||||
.attr(PreSwitchOutFormChangeAbAttr, (pokemon) => !pokemon.isFainted() ? 1 : pokemon.formIndex)
|
.attr(PreSwitchOutFormChangeAbAttr, (pokemon) => !pokemon.isFainted() ? 1 : pokemon.formIndex)
|
||||||
.bypassFaint(),
|
.bypassFaint(),
|
||||||
new Ability(Abilities.COMMANDER, 9)
|
new Ability(Abilities.COMMANDER, 9)
|
||||||
|
.attr(CommanderAbAttr)
|
||||||
|
.attr(DoubleBattleChanceAbAttr)
|
||||||
.attr(UncopiableAbilityAbAttr)
|
.attr(UncopiableAbilityAbAttr)
|
||||||
.attr(UnswappableAbilityAbAttr)
|
.attr(UnswappableAbilityAbAttr)
|
||||||
.unimplemented(),
|
.edgeCase(), // Encore, Frenzy, and other non-`TURN_END` tags don't lapse correctly on the commanding Pokemon.
|
||||||
new Ability(Abilities.ELECTROMORPHOSIS, 9)
|
new Ability(Abilities.ELECTROMORPHOSIS, 9)
|
||||||
.attr(PostDefendApplyBattlerTagAbAttr, (target, user, move) => move.category !== MoveCategory.STATUS, BattlerTagType.CHARGED),
|
.attr(PostDefendApplyBattlerTagAbAttr, (target, user, move) => move.category !== MoveCategory.STATUS, BattlerTagType.CHARGED),
|
||||||
new Ability(Abilities.PROTOSYNTHESIS, 9)
|
new Ability(Abilities.PROTOSYNTHESIS, 9)
|
||||||
|
@ -780,13 +780,14 @@ class ToxicSpikesTag extends ArenaTrapTag {
|
|||||||
* Delays the attack's effect by a set amount of turns, usually 3 (including the turn the move is used),
|
* Delays the attack's effect by a set amount of turns, usually 3 (including the turn the move is used),
|
||||||
* and deals damage after the turn count is reached.
|
* and deals damage after the turn count is reached.
|
||||||
*/
|
*/
|
||||||
class DelayedAttackTag extends ArenaTag {
|
export class DelayedAttackTag extends ArenaTag {
|
||||||
public targetIndex: BattlerIndex;
|
public targetIndex: BattlerIndex;
|
||||||
|
|
||||||
constructor(tagType: ArenaTagType, sourceMove: Moves | undefined, sourceId: number, targetIndex: BattlerIndex) {
|
constructor(tagType: ArenaTagType, sourceMove: Moves | undefined, sourceId: number, targetIndex: BattlerIndex, side: ArenaTagSide = ArenaTagSide.BOTH) {
|
||||||
super(tagType, 3, sourceMove, sourceId);
|
super(tagType, 3, sourceMove, sourceId, side);
|
||||||
|
|
||||||
this.targetIndex = targetIndex;
|
this.targetIndex = targetIndex;
|
||||||
|
this.side = side;
|
||||||
}
|
}
|
||||||
|
|
||||||
lapse(arena: Arena): boolean {
|
lapse(arena: Arena): boolean {
|
||||||
@ -1250,7 +1251,7 @@ export function getArenaTag(tagType: ArenaTagType, turnCount: number, sourceMove
|
|||||||
return new ToxicSpikesTag(sourceId, side);
|
return new ToxicSpikesTag(sourceId, side);
|
||||||
case ArenaTagType.FUTURE_SIGHT:
|
case ArenaTagType.FUTURE_SIGHT:
|
||||||
case ArenaTagType.DOOM_DESIRE:
|
case ArenaTagType.DOOM_DESIRE:
|
||||||
return new DelayedAttackTag(tagType, sourceMove, sourceId, targetIndex!); // TODO:questionable bang
|
return new DelayedAttackTag(tagType, sourceMove, sourceId, targetIndex!, side); // TODO:questionable bang
|
||||||
case ArenaTagType.WISH:
|
case ArenaTagType.WISH:
|
||||||
return new WishTag(turnCount, sourceId, side);
|
return new WishTag(turnCount, sourceId, side);
|
||||||
case ArenaTagType.STEALTH_ROCK:
|
case ArenaTagType.STEALTH_ROCK:
|
||||||
|
@ -7666,7 +7666,7 @@ export function initBiomes() {
|
|||||||
if (biome === Biome.END) {
|
if (biome === Biome.END) {
|
||||||
const biomeList = Object.keys(Biome).filter(key => !isNaN(Number(key)));
|
const biomeList = Object.keys(Biome).filter(key => !isNaN(Number(key)));
|
||||||
biomeList.pop(); // Removes Biome.END from the list
|
biomeList.pop(); // Removes Biome.END from the list
|
||||||
const randIndex = Utils.randInt(biomeList.length, 1); // Will never be Biome.TOWN
|
const randIndex = Utils.randSeedInt(biomeList.length, 1); // Will never be Biome.TOWN
|
||||||
biome = Biome[biomeList[randIndex]];
|
biome = Biome[biomeList[randIndex]];
|
||||||
}
|
}
|
||||||
const linkedBiomes: (Biome | [ Biome, integer ])[] = Array.isArray(biomeLinks[biome])
|
const linkedBiomes: (Biome | [ Biome, integer ])[] = Array.isArray(biomeLinks[biome])
|
||||||
|
@ -18,7 +18,7 @@ import Move, {
|
|||||||
StatusCategoryOnAllyAttr
|
StatusCategoryOnAllyAttr
|
||||||
} from "#app/data/move";
|
} from "#app/data/move";
|
||||||
import { SpeciesFormChangeManualTrigger } from "#app/data/pokemon-forms";
|
import { SpeciesFormChangeManualTrigger } from "#app/data/pokemon-forms";
|
||||||
import { StatusEffect } from "#app/data/status-effect";
|
import { getStatusEffectHealText, StatusEffect } from "#app/data/status-effect";
|
||||||
import { TerrainType } from "#app/data/terrain";
|
import { TerrainType } from "#app/data/terrain";
|
||||||
import { Type } from "#app/data/type";
|
import { Type } from "#app/data/type";
|
||||||
import { WeatherType } from "#app/data/weather";
|
import { WeatherType } from "#app/data/weather";
|
||||||
@ -2091,6 +2091,37 @@ export class IceFaceBlockDamageTag extends FormBlockDamageTag {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Battler tag indicating a Tatsugiri with {@link https://bulbapedia.bulbagarden.net/wiki/Commander_(Ability) | Commander}
|
||||||
|
* has entered the tagged Pokemon's mouth.
|
||||||
|
*/
|
||||||
|
export class CommandedTag extends BattlerTag {
|
||||||
|
private _tatsugiriFormKey: string;
|
||||||
|
|
||||||
|
constructor(sourceId: number) {
|
||||||
|
super(BattlerTagType.COMMANDED, BattlerTagLapseType.CUSTOM, 0, Moves.NONE, sourceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public get tatsugiriFormKey(): string {
|
||||||
|
return this._tatsugiriFormKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Caches the Tatsugiri's form key and sharply boosts the tagged Pokemon's stats */
|
||||||
|
override onAdd(pokemon: Pokemon): void {
|
||||||
|
this._tatsugiriFormKey = this.getSourcePokemon(pokemon.scene)?.getFormKey() ?? "curly";
|
||||||
|
pokemon.scene.unshiftPhase(new StatStageChangePhase(
|
||||||
|
pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ], 2
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Triggers an {@linkcode PokemonAnimType | animation} of the tagged Pokemon "spitting out" Tatsugiri */
|
||||||
|
override onRemove(pokemon: Pokemon): void {
|
||||||
|
if (this.getSourcePokemon(pokemon.scene)?.isActive(true)) {
|
||||||
|
pokemon.scene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.COMMANDER_REMOVE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Battler tag enabling the Stockpile mechanic. This tag handles:
|
* Battler tag enabling the Stockpile mechanic. This tag handles:
|
||||||
* - Stack tracking, including max limit enforcement (which is replicated in Stockpile for redundancy).
|
* - Stack tracking, including max limit enforcement (which is replicated in Stockpile for redundancy).
|
||||||
@ -2796,6 +2827,67 @@ export class PowerTrickTag extends BattlerTag {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tag associated with the move Grudge.
|
||||||
|
* If this tag is active when the bearer faints from an opponent's move, the tag reduces that move's PP to 0.
|
||||||
|
* Otherwise, it lapses when the bearer makes another move.
|
||||||
|
*/
|
||||||
|
export class GrudgeTag extends BattlerTag {
|
||||||
|
constructor() {
|
||||||
|
super(BattlerTagType.GRUDGE, [ BattlerTagLapseType.CUSTOM, BattlerTagLapseType.PRE_MOVE ], 1, Moves.GRUDGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
onAdd(pokemon: Pokemon) {
|
||||||
|
super.onAdd(pokemon);
|
||||||
|
pokemon.scene.queueMessage(i18next.t("battlerTags:grudgeOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Activates Grudge's special effect on the attacking Pokemon and lapses the tag.
|
||||||
|
* @param pokemon
|
||||||
|
* @param lapseType
|
||||||
|
* @param sourcePokemon {@linkcode Pokemon} the source of the move that fainted the tag's bearer
|
||||||
|
* @returns `false` if Grudge activates its effect or lapses
|
||||||
|
*/
|
||||||
|
override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType, sourcePokemon?: Pokemon): boolean {
|
||||||
|
if (lapseType === BattlerTagLapseType.CUSTOM && sourcePokemon) {
|
||||||
|
if (sourcePokemon.isActive() && pokemon.isOpponent(sourcePokemon)) {
|
||||||
|
const lastMove = pokemon.turnData.attacksReceived[0];
|
||||||
|
const lastMoveData = sourcePokemon.getMoveset().find(m => m?.moveId === lastMove.move);
|
||||||
|
if (lastMoveData && lastMove.move !== Moves.STRUGGLE) {
|
||||||
|
lastMoveData.ppUsed = lastMoveData.getMovePp();
|
||||||
|
pokemon.scene.queueMessage(i18next.t("battlerTags:grudgeLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: lastMoveData.getName() }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
return super.lapse(pokemon, lapseType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tag used to heal the user of Psycho Shift of its status effect if Psycho Shift succeeds in transferring its status effect to the target Pokemon
|
||||||
|
*/
|
||||||
|
export class PsychoShiftTag extends BattlerTag {
|
||||||
|
constructor() {
|
||||||
|
super(BattlerTagType.PSYCHO_SHIFT, BattlerTagLapseType.AFTER_MOVE, 1, Moves.PSYCHO_SHIFT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Heals Psycho Shift's user of its status effect after it uses a move
|
||||||
|
* @returns `false` to expire the tag immediately
|
||||||
|
*/
|
||||||
|
override lapse(pokemon: Pokemon, _lapseType: BattlerTagLapseType): boolean {
|
||||||
|
if (pokemon.status && pokemon.isActive(true)) {
|
||||||
|
pokemon.scene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon)));
|
||||||
|
pokemon.resetStatus();
|
||||||
|
pokemon.updateInfo();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a {@linkcode BattlerTag} based on the provided tag type, turn count, source move, and source ID.
|
* Retrieves a {@linkcode BattlerTag} based on the provided tag type, turn count, source move, and source ID.
|
||||||
* @param sourceId - The ID of the pokemon adding the tag
|
* @param sourceId - The ID of the pokemon adding the tag
|
||||||
@ -2932,6 +3024,8 @@ export function getBattlerTag(tagType: BattlerTagType, turnCount: number, source
|
|||||||
return new IceFaceBlockDamageTag(tagType);
|
return new IceFaceBlockDamageTag(tagType);
|
||||||
case BattlerTagType.DISGUISE:
|
case BattlerTagType.DISGUISE:
|
||||||
return new FormBlockDamageTag(tagType);
|
return new FormBlockDamageTag(tagType);
|
||||||
|
case BattlerTagType.COMMANDED:
|
||||||
|
return new CommandedTag(sourceId);
|
||||||
case BattlerTagType.STOCKPILING:
|
case BattlerTagType.STOCKPILING:
|
||||||
return new StockpilingTag(sourceMove);
|
return new StockpilingTag(sourceMove);
|
||||||
case BattlerTagType.OCTOLOCK:
|
case BattlerTagType.OCTOLOCK:
|
||||||
@ -2975,6 +3069,10 @@ export function getBattlerTag(tagType: BattlerTagType, turnCount: number, source
|
|||||||
return new TelekinesisTag(sourceMove);
|
return new TelekinesisTag(sourceMove);
|
||||||
case BattlerTagType.POWER_TRICK:
|
case BattlerTagType.POWER_TRICK:
|
||||||
return new PowerTrickTag(sourceMove, sourceId);
|
return new PowerTrickTag(sourceMove, sourceId);
|
||||||
|
case BattlerTagType.GRUDGE:
|
||||||
|
return new GrudgeTag();
|
||||||
|
case BattlerTagType.PSYCHO_SHIFT:
|
||||||
|
return new PsychoShiftTag();
|
||||||
case BattlerTagType.NONE:
|
case BattlerTagType.NONE:
|
||||||
default:
|
default:
|
||||||
return new BattlerTag(tagType, BattlerTagLapseType.CUSTOM, turnCount, sourceMove, sourceId);
|
return new BattlerTag(tagType, BattlerTagLapseType.CUSTOM, turnCount, sourceMove, sourceId);
|
||||||
|
@ -6,6 +6,7 @@ import { Starter } from "#app/ui/starter-select-ui-handler";
|
|||||||
import * as Utils from "#app/utils";
|
import * as Utils from "#app/utils";
|
||||||
import PokemonSpecies, { PokemonSpeciesForm, getPokemonSpecies, getPokemonSpeciesForm } from "#app/data/pokemon-species";
|
import PokemonSpecies, { PokemonSpeciesForm, getPokemonSpecies, getPokemonSpeciesForm } from "#app/data/pokemon-species";
|
||||||
import { speciesStarterCosts } from "#app/data/balance/starters";
|
import { speciesStarterCosts } from "#app/data/balance/starters";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
export interface DailyRunConfig {
|
export interface DailyRunConfig {
|
||||||
seed: integer;
|
seed: integer;
|
||||||
@ -14,14 +15,9 @@ export interface DailyRunConfig {
|
|||||||
|
|
||||||
export function fetchDailyRunSeed(): Promise<string | null> {
|
export function fetchDailyRunSeed(): Promise<string | null> {
|
||||||
return new Promise<string | null>((resolve, reject) => {
|
return new Promise<string | null>((resolve, reject) => {
|
||||||
Utils.apiFetch("daily/seed").then(response => {
|
pokerogueApi.daily.getSeed().then(dailySeed => {
|
||||||
if (!response.ok) {
|
resolve(dailySeed);
|
||||||
resolve(null);
|
});
|
||||||
return;
|
|
||||||
}
|
|
||||||
return response.text();
|
|
||||||
}).then(seed => resolve(seed ?? null))
|
|
||||||
.catch(err => reject(err));
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
103
src/data/move.ts
103
src/data/move.ts
@ -1,5 +1,5 @@
|
|||||||
import { ChargeAnim, initMoveAnim, loadMoveAnimAssets, MoveChargeAnim } from "./battle-anims";
|
import { ChargeAnim, initMoveAnim, loadMoveAnimAssets, MoveChargeAnim } from "./battle-anims";
|
||||||
import { EncoreTag, GulpMissileTag, HelpingHandTag, SemiInvulnerableTag, ShellTrapTag, StockpilingTag, SubstituteTag, TrappedTag, TypeBoostTag } from "./battler-tags";
|
import { CommandedTag, EncoreTag, GulpMissileTag, HelpingHandTag, SemiInvulnerableTag, ShellTrapTag, StockpilingTag, SubstituteTag, TrappedTag, TypeBoostTag } from "./battler-tags";
|
||||||
import { getPokemonNameWithAffix } from "../messages";
|
import { getPokemonNameWithAffix } from "../messages";
|
||||||
import Pokemon, { AttackMoveResult, EnemyPokemon, HitResult, MoveResult, PlayerPokemon, PokemonMove, TurnMove } from "../field/pokemon";
|
import Pokemon, { AttackMoveResult, EnemyPokemon, HitResult, MoveResult, PlayerPokemon, PokemonMove, TurnMove } from "../field/pokemon";
|
||||||
import { getNonVolatileStatusEffects, getStatusEffectHealText, isNonVolatileStatusEffect, StatusEffect } from "./status-effect";
|
import { getNonVolatileStatusEffects, getStatusEffectHealText, isNonVolatileStatusEffect, StatusEffect } from "./status-effect";
|
||||||
@ -714,6 +714,10 @@ export default class Move implements Localizable {
|
|||||||
getTargetBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer {
|
getTargetBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer {
|
||||||
let score = 0;
|
let score = 0;
|
||||||
|
|
||||||
|
if (target.getAlly()?.getTag(BattlerTagType.COMMANDED)?.getSourcePokemon(target.scene) === target) {
|
||||||
|
return 20 * (target.isPlayer() === user.isPlayer() ? -1 : 1); // always -20 with how the AI handles this score
|
||||||
|
}
|
||||||
|
|
||||||
for (const attr of this.attrs) {
|
for (const attr of this.attrs) {
|
||||||
// conditionals to check if the move is self targeting (if so then you are applying the move to yourself, not the target)
|
// conditionals to check if the move is self targeting (if so then you are applying the move to yourself, not the target)
|
||||||
score += attr.getTargetBenefitScore(user, !attr.selfTarget ? target : user, move) * (target !== user && attr.selfTarget ? -1 : 1);
|
score += attr.getTargetBenefitScore(user, !attr.selfTarget ? target : user, move) * (target !== user && attr.selfTarget ? -1 : 1);
|
||||||
@ -2266,24 +2270,26 @@ export class PsychoShiftEffectAttr extends MoveEffectAttr {
|
|||||||
super(false, { trigger: MoveEffectTrigger.HIT });
|
super(false, { trigger: MoveEffectTrigger.HIT });
|
||||||
}
|
}
|
||||||
|
|
||||||
apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean {
|
/**
|
||||||
|
* Applies the effect of Psycho Shift to its target
|
||||||
|
* Psycho Shift takes the user's status effect and passes it onto the target. The user is then healed after the move has been successfully executed.
|
||||||
|
* @returns `true` if Psycho Shift's effect is able to be applied to the target
|
||||||
|
*/
|
||||||
|
apply(user: Pokemon, target: Pokemon, _move: Move, _args: any[]): boolean {
|
||||||
const statusToApply: StatusEffect | undefined = user.status?.effect ?? (user.hasAbility(Abilities.COMATOSE) ? StatusEffect.SLEEP : undefined);
|
const statusToApply: StatusEffect | undefined = user.status?.effect ?? (user.hasAbility(Abilities.COMATOSE) ? StatusEffect.SLEEP : undefined);
|
||||||
|
|
||||||
if (target.status) {
|
if (target.status) {
|
||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
const canSetStatus = target.canSetStatus(statusToApply, true, false, user);
|
const canSetStatus = target.canSetStatus(statusToApply, true, false, user);
|
||||||
|
const trySetStatus = canSetStatus ? target.trySetStatus(statusToApply, true, user) : false;
|
||||||
|
|
||||||
if (canSetStatus) {
|
if (trySetStatus && user.status) {
|
||||||
if (user.status) {
|
// PsychoShiftTag is added to the user if move succeeds so that the user is healed of its status effect after its move
|
||||||
user.scene.queueMessage(getStatusEffectHealText(user.status.effect, getPokemonNameWithAffix(user)));
|
user.addTag(BattlerTagType.PSYCHO_SHIFT);
|
||||||
}
|
|
||||||
user.resetStatus();
|
|
||||||
user.updateInfo();
|
|
||||||
target.trySetStatus(statusToApply, true, user);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return canSetStatus;
|
return trySetStatus;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2785,6 +2791,14 @@ export class OverrideMoveEffectAttr extends MoveAttr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attack Move that doesn't hit the turn it is played and doesn't allow for multiple
|
||||||
|
* uses on the same target. Examples are Future Sight or Doom Desire.
|
||||||
|
* @extends OverrideMoveEffectAttr
|
||||||
|
* @param tagType The {@linkcode ArenaTagType} that will be placed on the field when the move is used
|
||||||
|
* @param chargeAnim The {@linkcode ChargeAnim | Charging Animation} used for the move
|
||||||
|
* @param chargeText The text to display when the move is used
|
||||||
|
*/
|
||||||
export class DelayedAttackAttr extends OverrideMoveEffectAttr {
|
export class DelayedAttackAttr extends OverrideMoveEffectAttr {
|
||||||
public tagType: ArenaTagType;
|
public tagType: ArenaTagType;
|
||||||
public chargeAnim: ChargeAnim;
|
public chargeAnim: ChargeAnim;
|
||||||
@ -2799,13 +2813,18 @@ export class DelayedAttackAttr extends OverrideMoveEffectAttr {
|
|||||||
}
|
}
|
||||||
|
|
||||||
apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise<boolean> {
|
apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise<boolean> {
|
||||||
|
// Edge case for the move applied on a pokemon that has fainted
|
||||||
|
if (!target) {
|
||||||
|
return Promise.resolve(true);
|
||||||
|
}
|
||||||
|
const side = target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
if (args.length < 2 || !args[1]) {
|
if (args.length < 2 || !args[1]) {
|
||||||
new MoveChargeAnim(this.chargeAnim, move.id, user).play(user.scene, false, () => {
|
new MoveChargeAnim(this.chargeAnim, move.id, user).play(user.scene, false, () => {
|
||||||
(args[0] as Utils.BooleanHolder).value = true;
|
(args[0] as Utils.BooleanHolder).value = true;
|
||||||
user.scene.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user)));
|
user.scene.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user)));
|
||||||
user.pushMoveHistory({ move: move.id, targets: [ target.getBattlerIndex() ], result: MoveResult.OTHER });
|
user.pushMoveHistory({ move: move.id, targets: [ target.getBattlerIndex() ], result: MoveResult.OTHER });
|
||||||
user.scene.arena.addTag(this.tagType, 3, move.id, user.id, ArenaTagSide.BOTH, false, target.getBattlerIndex());
|
user.scene.arena.addTag(this.tagType, 3, move.id, user.id, side, false, target.getBattlerIndex());
|
||||||
|
|
||||||
resolve(true);
|
resolve(true);
|
||||||
});
|
});
|
||||||
@ -3232,6 +3251,41 @@ export class CutHpStatStageBoostAttr extends StatStageChangeAttr {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attribute implementing the stat boosting effect of {@link https://bulbapedia.bulbagarden.net/wiki/Order_Up_(move) | Order Up}.
|
||||||
|
* If the user has a Pokemon with {@link https://bulbapedia.bulbagarden.net/wiki/Commander_(Ability) | Commander} in their mouth,
|
||||||
|
* one of the user's stats are increased by 1 stage, depending on the "commanding" Pokemon's form. This effect does not respect
|
||||||
|
* effect chance, but Order Up itself may be boosted by Sheer Force.
|
||||||
|
*/
|
||||||
|
export class OrderUpStatBoostAttr extends MoveEffectAttr {
|
||||||
|
constructor() {
|
||||||
|
super(true, { trigger: MoveEffectTrigger.HIT });
|
||||||
|
}
|
||||||
|
|
||||||
|
override apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean {
|
||||||
|
const commandedTag = user.getTag(CommandedTag);
|
||||||
|
if (!commandedTag) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let increasedStat: EffectiveStat = Stat.ATK;
|
||||||
|
switch (commandedTag.tatsugiriFormKey) {
|
||||||
|
case "curly":
|
||||||
|
increasedStat = Stat.ATK;
|
||||||
|
break;
|
||||||
|
case "droopy":
|
||||||
|
increasedStat = Stat.DEF;
|
||||||
|
break;
|
||||||
|
case "stretchy":
|
||||||
|
increasedStat = Stat.SPD;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
user.scene.unshiftPhase(new StatStageChangePhase(user.scene, user.getBattlerIndex(), this.selfTarget, [ increasedStat ], 1));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class CopyStatsAttr extends MoveEffectAttr {
|
export class CopyStatsAttr extends MoveEffectAttr {
|
||||||
apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean {
|
apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean {
|
||||||
if (!super.apply(user, target, move, args)) {
|
if (!super.apply(user, target, move, args)) {
|
||||||
@ -5534,7 +5588,8 @@ export class AddArenaTagAttr extends MoveEffectAttr {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ((move.chance < 0 || move.chance === 100 || user.randSeedInt(100) < move.chance) && user.getLastXMoves(1)[0]?.result === MoveResult.SUCCESS) {
|
if ((move.chance < 0 || move.chance === 100 || user.randSeedInt(100) < move.chance) && user.getLastXMoves(1)[0]?.result === MoveResult.SUCCESS) {
|
||||||
user.scene.arena.addTag(this.tagType, this.turnCount, move.id, user.id, (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY);
|
const side = (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
|
||||||
|
user.scene.arena.addTag(this.tagType, this.turnCount, move.id, user.id, side);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -5838,7 +5893,13 @@ export class ForceSwitchOutAttr extends MoveEffectAttr {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The {@linkcode Pokemon} to be switched out with this effect */
|
||||||
const switchOutTarget = this.selfSwitch ? user : target;
|
const switchOutTarget = this.selfSwitch ? user : target;
|
||||||
|
|
||||||
|
// If the switch-out target is a Dondozo with a Tatsugiri in its mouth
|
||||||
|
// (e.g. when it uses Flip Turn), make it spit out the Tatsugiri before switching out.
|
||||||
|
switchOutTarget.lapseTag(BattlerTagType.COMMANDED);
|
||||||
|
|
||||||
if (switchOutTarget instanceof PlayerPokemon) {
|
if (switchOutTarget instanceof PlayerPokemon) {
|
||||||
/**
|
/**
|
||||||
* Check if Wimp Out/Emergency Exit activates due to being hit by U-turn or Volt Switch
|
* Check if Wimp Out/Emergency Exit activates due to being hit by U-turn or Volt Switch
|
||||||
@ -5941,6 +6002,12 @@ export class ForceSwitchOutAttr extends MoveEffectAttr {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dondozo with an allied Tatsugiri in its mouth cannot be forced out
|
||||||
|
const commandedTag = switchOutTarget.getTag(BattlerTagType.COMMANDED);
|
||||||
|
if (commandedTag?.getSourcePokemon(switchOutTarget.scene)?.isActive(true)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (!player && user.scene.currentBattle.isBattleMysteryEncounter() && !user.scene.currentBattle.mysteryEncounter?.fleeAllowed) {
|
if (!player && user.scene.currentBattle.isBattleMysteryEncounter() && !user.scene.currentBattle.mysteryEncounter?.fleeAllowed) {
|
||||||
// Don't allow wild opponents to be force switched during MEs with flee disabled
|
// Don't allow wild opponents to be force switched during MEs with flee disabled
|
||||||
return false;
|
return false;
|
||||||
@ -8297,7 +8364,8 @@ export function initMoves() {
|
|||||||
.attr(StatStageChangeAttr, [ Stat.SPDEF ], -1)
|
.attr(StatStageChangeAttr, [ Stat.SPDEF ], -1)
|
||||||
.ballBombMove(),
|
.ballBombMove(),
|
||||||
new AttackMove(Moves.FUTURE_SIGHT, Type.PSYCHIC, MoveCategory.SPECIAL, 120, 100, 10, -1, 0, 2)
|
new AttackMove(Moves.FUTURE_SIGHT, Type.PSYCHIC, MoveCategory.SPECIAL, 120, 100, 10, -1, 0, 2)
|
||||||
.partial() // Complete buggy mess
|
.partial() // cannot be used on multiple Pokemon on the same side in a double battle, hits immediately when called by Metronome/etc
|
||||||
|
.ignoresProtect()
|
||||||
.attr(DelayedAttackAttr, ArenaTagType.FUTURE_SIGHT, ChargeAnim.FUTURE_SIGHT_CHARGING, i18next.t("moveTriggers:foresawAnAttack", { pokemonName: "{USER}" })),
|
.attr(DelayedAttackAttr, ArenaTagType.FUTURE_SIGHT, ChargeAnim.FUTURE_SIGHT_CHARGING, i18next.t("moveTriggers:foresawAnAttack", { pokemonName: "{USER}" })),
|
||||||
new AttackMove(Moves.ROCK_SMASH, Type.FIGHTING, MoveCategory.PHYSICAL, 40, 100, 15, 50, 0, 2)
|
new AttackMove(Moves.ROCK_SMASH, Type.FIGHTING, MoveCategory.PHYSICAL, 40, 100, 15, 50, 0, 2)
|
||||||
.attr(StatStageChangeAttr, [ Stat.DEF ], -1),
|
.attr(StatStageChangeAttr, [ Stat.DEF ], -1),
|
||||||
@ -8423,7 +8491,7 @@ export function initMoves() {
|
|||||||
.attr(HealStatusEffectAttr, true, StatusEffect.PARALYSIS, StatusEffect.POISON, StatusEffect.TOXIC, StatusEffect.BURN)
|
.attr(HealStatusEffectAttr, true, StatusEffect.PARALYSIS, StatusEffect.POISON, StatusEffect.TOXIC, StatusEffect.BURN)
|
||||||
.condition((user, target, move) => !!user.status && (user.status.effect === StatusEffect.PARALYSIS || user.status.effect === StatusEffect.POISON || user.status.effect === StatusEffect.TOXIC || user.status.effect === StatusEffect.BURN)),
|
.condition((user, target, move) => !!user.status && (user.status.effect === StatusEffect.PARALYSIS || user.status.effect === StatusEffect.POISON || user.status.effect === StatusEffect.TOXIC || user.status.effect === StatusEffect.BURN)),
|
||||||
new SelfStatusMove(Moves.GRUDGE, Type.GHOST, -1, 5, -1, 0, 3)
|
new SelfStatusMove(Moves.GRUDGE, Type.GHOST, -1, 5, -1, 0, 3)
|
||||||
.unimplemented(),
|
.attr(AddBattlerTagAttr, BattlerTagType.GRUDGE, true, undefined, 1),
|
||||||
new SelfStatusMove(Moves.SNATCH, Type.DARK, -1, 10, -1, 4, 3)
|
new SelfStatusMove(Moves.SNATCH, Type.DARK, -1, 10, -1, 4, 3)
|
||||||
.unimplemented(),
|
.unimplemented(),
|
||||||
new AttackMove(Moves.SECRET_POWER, Type.NORMAL, MoveCategory.PHYSICAL, 70, 100, 20, 30, 0, 3)
|
new AttackMove(Moves.SECRET_POWER, Type.NORMAL, MoveCategory.PHYSICAL, 70, 100, 20, 30, 0, 3)
|
||||||
@ -8604,7 +8672,8 @@ export function initMoves() {
|
|||||||
.attr(ConfuseAttr)
|
.attr(ConfuseAttr)
|
||||||
.pulseMove(),
|
.pulseMove(),
|
||||||
new AttackMove(Moves.DOOM_DESIRE, Type.STEEL, MoveCategory.SPECIAL, 140, 100, 5, -1, 0, 3)
|
new AttackMove(Moves.DOOM_DESIRE, Type.STEEL, MoveCategory.SPECIAL, 140, 100, 5, -1, 0, 3)
|
||||||
.partial() // Complete buggy mess
|
.partial() // cannot be used on multiple Pokemon on the same side in a double battle, hits immediately when called by Metronome/etc
|
||||||
|
.ignoresProtect()
|
||||||
.attr(DelayedAttackAttr, ArenaTagType.DOOM_DESIRE, ChargeAnim.DOOM_DESIRE_CHARGING, i18next.t("moveTriggers:choseDoomDesireAsDestiny", { pokemonName: "{USER}" })),
|
.attr(DelayedAttackAttr, ArenaTagType.DOOM_DESIRE, ChargeAnim.DOOM_DESIRE_CHARGING, i18next.t("moveTriggers:choseDoomDesireAsDestiny", { pokemonName: "{USER}" })),
|
||||||
new AttackMove(Moves.PSYCHO_BOOST, Type.PSYCHIC, MoveCategory.SPECIAL, 140, 90, 5, -1, 0, 3)
|
new AttackMove(Moves.PSYCHO_BOOST, Type.PSYCHIC, MoveCategory.SPECIAL, 140, 90, 5, -1, 0, 3)
|
||||||
.attr(StatStageChangeAttr, [ Stat.SPATK ], -2, true),
|
.attr(StatStageChangeAttr, [ Stat.SPATK ], -2, true),
|
||||||
@ -10284,8 +10353,8 @@ export function initMoves() {
|
|||||||
new AttackMove(Moves.LUMINA_CRASH, Type.PSYCHIC, MoveCategory.SPECIAL, 80, 100, 10, 100, 0, 9)
|
new AttackMove(Moves.LUMINA_CRASH, Type.PSYCHIC, MoveCategory.SPECIAL, 80, 100, 10, 100, 0, 9)
|
||||||
.attr(StatStageChangeAttr, [ Stat.SPDEF ], -2),
|
.attr(StatStageChangeAttr, [ Stat.SPDEF ], -2),
|
||||||
new AttackMove(Moves.ORDER_UP, Type.DRAGON, MoveCategory.PHYSICAL, 80, 100, 10, 100, 0, 9)
|
new AttackMove(Moves.ORDER_UP, Type.DRAGON, MoveCategory.PHYSICAL, 80, 100, 10, 100, 0, 9)
|
||||||
.makesContact(false)
|
.attr(OrderUpStatBoostAttr)
|
||||||
.partial(), // No effect implemented (requires Commander)
|
.makesContact(false),
|
||||||
new AttackMove(Moves.JET_PUNCH, Type.WATER, MoveCategory.PHYSICAL, 60, 100, 15, -1, 1, 9)
|
new AttackMove(Moves.JET_PUNCH, Type.WATER, MoveCategory.PHYSICAL, 60, 100, 15, -1, 1, 9)
|
||||||
.punchingMove(),
|
.punchingMove(),
|
||||||
new StatusMove(Moves.SPICY_EXTRACT, Type.GRASS, -1, 15, -1, 0, 9)
|
new StatusMove(Moves.SPICY_EXTRACT, Type.GRASS, -1, 15, -1, 0, 9)
|
||||||
|
@ -367,10 +367,11 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
|
|||||||
})
|
})
|
||||||
.withOptionPhase(async (scene: BattleScene) => {
|
.withOptionPhase(async (scene: BattleScene) => {
|
||||||
const encounter = scene.currentBattle.mysteryEncounter!;
|
const encounter = scene.currentBattle.mysteryEncounter!;
|
||||||
const modifier = encounter.misc.chosenModifier;
|
const modifier = encounter.misc.chosenModifier as PokemonHeldItemModifier;
|
||||||
|
const party = scene.getPlayerParty();
|
||||||
|
|
||||||
// Check tier of the traded item, the received item will be one tier up
|
// Check tier of the traded item, the received item will be one tier up
|
||||||
const type = modifier.type.withTierFromPool();
|
const type = modifier.type.withTierFromPool(ModifierPoolType.PLAYER, party);
|
||||||
let tier = type.tier ?? ModifierTier.GREAT;
|
let tier = type.tier ?? ModifierTier.GREAT;
|
||||||
// Eggs and White Herb are not in the pool
|
// Eggs and White Herb are not in the pool
|
||||||
if (type.id === "WHITE_HERB") {
|
if (type.id === "WHITE_HERB") {
|
||||||
@ -385,11 +386,11 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
|
|||||||
tier++;
|
tier++;
|
||||||
}
|
}
|
||||||
|
|
||||||
regenerateModifierPoolThresholds(scene.getPlayerParty(), ModifierPoolType.PLAYER, 0);
|
regenerateModifierPoolThresholds(party, ModifierPoolType.PLAYER, 0);
|
||||||
let item: ModifierTypeOption | null = null;
|
let item: ModifierTypeOption | null = null;
|
||||||
// TMs excluded from possible rewards
|
// TMs excluded from possible rewards
|
||||||
while (!item || item.type.id.includes("TM_")) {
|
while (!item || item.type.id.includes("TM_")) {
|
||||||
item = getPlayerModifierTypeOptions(1, scene.getPlayerParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0];
|
item = getPlayerModifierTypeOptions(1, party, [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
encounter.setDialogueToken("itemName", item.type.name);
|
encounter.setDialogueToken("itemName", item.type.name);
|
||||||
|
@ -23,6 +23,7 @@ import { ReturnPhase } from "#app/phases/return-phase";
|
|||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import { ModifierTier } from "#app/modifier/modifier-tier";
|
import { ModifierTier } from "#app/modifier/modifier-tier";
|
||||||
import { CLASSIC_MODE_MYSTERY_ENCOUNTER_WAVES } from "#app/game-mode";
|
import { CLASSIC_MODE_MYSTERY_ENCOUNTER_WAVES } from "#app/game-mode";
|
||||||
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
|
|
||||||
/** the i18n namespace for the encounter */
|
/** the i18n namespace for the encounter */
|
||||||
const namespace = "mysteryEncounters/theWinstrateChallenge";
|
const namespace = "mysteryEncounters/theWinstrateChallenge";
|
||||||
@ -187,6 +188,7 @@ function endTrainerBattleAndShowDialogue(scene: BattleScene): Promise<void> {
|
|||||||
} else {
|
} else {
|
||||||
scene.arena.resetArenaEffects();
|
scene.arena.resetArenaEffects();
|
||||||
const playerField = scene.getPlayerField();
|
const playerField = scene.getPlayerField();
|
||||||
|
playerField.forEach((pokemon) => pokemon.lapseTag(BattlerTagType.COMMANDED));
|
||||||
playerField.forEach((_, p) => scene.unshiftPhase(new ReturnPhase(scene, p)));
|
playerField.forEach((_, p) => scene.unshiftPhase(new ReturnPhase(scene, p)));
|
||||||
|
|
||||||
for (const pokemon of scene.getPlayerParty()) {
|
for (const pokemon of scene.getPlayerParty()) {
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { NumberHolder } from "#app/utils";
|
||||||
import { PokeballType } from "#enums/pokeball";
|
import { PokeballType } from "#enums/pokeball";
|
||||||
import BattleScene from "../battle-scene";
|
import BattleScene from "../battle-scene";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
@ -82,11 +83,38 @@ export function getPokeballTintColor(type: PokeballType): number {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function doPokeballBounceAnim(scene: BattleScene, pokeball: Phaser.GameObjects.Sprite, y1: number, y2: number, baseBounceDuration: integer, callback: Function) {
|
/**
|
||||||
|
* Gets the critical capture chance based on number of mons registered in Dex and modified {@link https://bulbapedia.bulbagarden.net/wiki/Catch_rate Catch rate}
|
||||||
|
* Formula from {@link https://www.dragonflycave.com/mechanics/gen-vi-vii-capturing Dragonfly Cave Gen 6 Capture Mechanics page}
|
||||||
|
* @param scene {@linkcode BattleScene} current BattleScene
|
||||||
|
* @param modifiedCatchRate the modified catch rate as calculated in {@linkcode AttemptCapturePhase}
|
||||||
|
* @returns the chance of getting a critical capture, out of 256
|
||||||
|
*/
|
||||||
|
export function getCriticalCaptureChance(scene: BattleScene, modifiedCatchRate: number): number {
|
||||||
|
if (scene.gameMode.isFreshStartChallenge()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const dexCount = scene.gameData.getSpeciesCount(d => !!d.caughtAttr);
|
||||||
|
const catchingCharmMultiplier = new NumberHolder(1);
|
||||||
|
//scene.findModifier(m => m instanceof CriticalCatchChanceBoosterModifier)?.apply(catchingCharmMultiplier);
|
||||||
|
const dexMultiplier = scene.gameMode.isDaily || dexCount > 800 ? 2.5
|
||||||
|
: dexCount > 600 ? 2
|
||||||
|
: dexCount > 400 ? 1.5
|
||||||
|
: dexCount > 200 ? 1
|
||||||
|
: dexCount > 100 ? 0.5
|
||||||
|
: 0;
|
||||||
|
return Math.floor(catchingCharmMultiplier.value * dexMultiplier * Math.min(255, modifiedCatchRate) / 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function doPokeballBounceAnim(scene: BattleScene, pokeball: Phaser.GameObjects.Sprite, y1: number, y2: number, baseBounceDuration: number, callback: Function, isCritical: boolean = false) {
|
||||||
let bouncePower = 1;
|
let bouncePower = 1;
|
||||||
let bounceYOffset = y1;
|
let bounceYOffset = y1;
|
||||||
let bounceY = y2;
|
let bounceY = y2;
|
||||||
const yd = y2 - y1;
|
const yd = y2 - y1;
|
||||||
|
const x0 = pokeball.x;
|
||||||
|
const x1 = x0 + 3;
|
||||||
|
const x2 = x0 - 3;
|
||||||
|
let critShakes = 4;
|
||||||
|
|
||||||
const doBounce = () => {
|
const doBounce = () => {
|
||||||
scene.tweens.add({
|
scene.tweens.add({
|
||||||
@ -117,5 +145,40 @@ export function doPokeballBounceAnim(scene: BattleScene, pokeball: Phaser.GameOb
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
doBounce();
|
const doCritShake = () => {
|
||||||
|
scene.tweens.add({
|
||||||
|
targets: pokeball,
|
||||||
|
x: x2,
|
||||||
|
duration: 125,
|
||||||
|
ease: "Linear",
|
||||||
|
onComplete: () => {
|
||||||
|
scene.tweens.add({
|
||||||
|
targets: pokeball,
|
||||||
|
x: x1,
|
||||||
|
duration: 125,
|
||||||
|
ease: "Linear",
|
||||||
|
onComplete: () => {
|
||||||
|
critShakes--;
|
||||||
|
if (critShakes > 0) {
|
||||||
|
doCritShake();
|
||||||
|
} else {
|
||||||
|
scene.tweens.add({
|
||||||
|
targets: pokeball,
|
||||||
|
x: x0,
|
||||||
|
duration: 60,
|
||||||
|
ease: "Linear",
|
||||||
|
onComplete: () => scene.time.delayedCall(500, doBounce)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isCritical) {
|
||||||
|
scene.time.delayedCall(500, doCritShake);
|
||||||
|
} else {
|
||||||
|
doBounce();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -88,5 +88,8 @@ export enum BattlerTagType {
|
|||||||
IMPRISON = "IMPRISON",
|
IMPRISON = "IMPRISON",
|
||||||
SYRUP_BOMB = "SYRUP_BOMB",
|
SYRUP_BOMB = "SYRUP_BOMB",
|
||||||
ELECTRIFIED = "ELECTRIFIED",
|
ELECTRIFIED = "ELECTRIFIED",
|
||||||
TELEKINESIS = "TELEKINESIS"
|
TELEKINESIS = "TELEKINESIS",
|
||||||
|
COMMANDED = "COMMANDED",
|
||||||
|
GRUDGE = "GRUDGE",
|
||||||
|
PSYCHO_SHIFT = "PSYCHO_SHIFT",
|
||||||
}
|
}
|
||||||
|
@ -12,5 +12,15 @@ export enum PokemonAnimType {
|
|||||||
* Removes a Pokemon's Substitute doll from the field.
|
* Removes a Pokemon's Substitute doll from the field.
|
||||||
* The Pokemon then moves back to its original position.
|
* The Pokemon then moves back to its original position.
|
||||||
*/
|
*/
|
||||||
SUBSTITUTE_REMOVE
|
SUBSTITUTE_REMOVE,
|
||||||
|
/**
|
||||||
|
* Brings Tatsugiri and Dondozo to the center of the field, with
|
||||||
|
* Tatsugiri jumping into the Dondozo's mouth
|
||||||
|
*/
|
||||||
|
COMMANDER_APPLY,
|
||||||
|
/**
|
||||||
|
* Dondozo "spits out" Tatsugiri, moving Tatsugiri back to its original
|
||||||
|
* field position.
|
||||||
|
*/
|
||||||
|
COMMANDER_REMOVE
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import Move, { HighCritAttr, HitsTagAttr, applyMoveAttrs, FixedDamageAttr, Varia
|
|||||||
import { default as PokemonSpecies, PokemonSpeciesForm, getFusedSpeciesName, getPokemonSpecies, getPokemonSpeciesForm } from "#app/data/pokemon-species";
|
import { default as PokemonSpecies, PokemonSpeciesForm, getFusedSpeciesName, getPokemonSpecies, getPokemonSpeciesForm } from "#app/data/pokemon-species";
|
||||||
import { CLASSIC_CANDY_FRIENDSHIP_MULTIPLIER, getStarterValueFriendshipCap, speciesStarterCosts } from "#app/data/balance/starters";
|
import { CLASSIC_CANDY_FRIENDSHIP_MULTIPLIER, getStarterValueFriendshipCap, speciesStarterCosts } from "#app/data/balance/starters";
|
||||||
import { starterPassiveAbilities } from "#app/data/balance/passives";
|
import { starterPassiveAbilities } from "#app/data/balance/passives";
|
||||||
import { Constructor, isNullOrUndefined, randSeedInt } from "#app/utils";
|
import { Constructor, isNullOrUndefined, randSeedInt, type nil } from "#app/utils";
|
||||||
import * as Utils from "#app/utils";
|
import * as Utils from "#app/utils";
|
||||||
import { Type, TypeDamageMultiplier, getTypeDamageMultiplier, getTypeRgb } from "#app/data/type";
|
import { Type, TypeDamageMultiplier, getTypeDamageMultiplier, getTypeRgb } from "#app/data/type";
|
||||||
import { getLevelTotalExp } from "#app/data/exp";
|
import { getLevelTotalExp } from "#app/data/exp";
|
||||||
@ -1563,6 +1563,11 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
|
|||||||
* @returns `true` if the pokemon is trapped
|
* @returns `true` if the pokemon is trapped
|
||||||
*/
|
*/
|
||||||
public isTrapped(trappedAbMessages: string[] = [], simulated: boolean = true): boolean {
|
public isTrapped(trappedAbMessages: string[] = [], simulated: boolean = true): boolean {
|
||||||
|
const commandedTag = this.getTag(BattlerTagType.COMMANDED);
|
||||||
|
if (commandedTag?.getSourcePokemon(this.scene)?.isActive(true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (this.isOfType(Type.GHOST)) {
|
if (this.isOfType(Type.GHOST)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -2836,6 +2841,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
|
|||||||
|
|
||||||
// In case of fatal damage, this tag would have gotten cleared before we could lapse it.
|
// In case of fatal damage, this tag would have gotten cleared before we could lapse it.
|
||||||
const destinyTag = this.getTag(BattlerTagType.DESTINY_BOND);
|
const destinyTag = this.getTag(BattlerTagType.DESTINY_BOND);
|
||||||
|
const grudgeTag = this.getTag(BattlerTagType.GRUDGE);
|
||||||
|
|
||||||
const isOneHitKo = result === HitResult.ONE_HIT_KO;
|
const isOneHitKo = result === HitResult.ONE_HIT_KO;
|
||||||
|
|
||||||
@ -2907,13 +2913,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
|
|||||||
if (this.isFainted()) {
|
if (this.isFainted()) {
|
||||||
// set splice index here, so future scene queues happen before FaintedPhase
|
// set splice index here, so future scene queues happen before FaintedPhase
|
||||||
this.scene.setPhaseQueueSplice();
|
this.scene.setPhaseQueueSplice();
|
||||||
if (!isNullOrUndefined(destinyTag) && dmg) {
|
this.scene.unshiftPhase(new FaintPhase(this.scene, this.getBattlerIndex(), isOneHitKo, destinyTag, grudgeTag, source));
|
||||||
// Destiny Bond will activate during FaintPhase
|
|
||||||
this.scene.unshiftPhase(new FaintPhase(this.scene, this.getBattlerIndex(), isOneHitKo, destinyTag, source));
|
|
||||||
} else {
|
|
||||||
this.scene.unshiftPhase(new FaintPhase(this.scene, this.getBattlerIndex(), isOneHitKo));
|
|
||||||
}
|
|
||||||
this.destroySubstitute();
|
this.destroySubstitute();
|
||||||
|
this.lapseTag(BattlerTagType.COMMANDED);
|
||||||
this.resetSummonData();
|
this.resetSummonData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2962,6 +2965,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
|
|||||||
this.scene.setPhaseQueueSplice();
|
this.scene.setPhaseQueueSplice();
|
||||||
this.scene.unshiftPhase(new FaintPhase(this.scene, this.getBattlerIndex(), preventEndure));
|
this.scene.unshiftPhase(new FaintPhase(this.scene, this.getBattlerIndex(), preventEndure));
|
||||||
this.destroySubstitute();
|
this.destroySubstitute();
|
||||||
|
this.lapseTag(BattlerTagType.COMMANDED);
|
||||||
this.resetSummonData();
|
this.resetSummonData();
|
||||||
}
|
}
|
||||||
return damage;
|
return damage;
|
||||||
@ -3044,19 +3048,19 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @overload */
|
/** @overload */
|
||||||
getTag(tagType: BattlerTagType): BattlerTag | null;
|
getTag(tagType: BattlerTagType): BattlerTag | nil;
|
||||||
|
|
||||||
/** @overload */
|
/** @overload */
|
||||||
getTag<T extends BattlerTag>(tagType: Constructor<T>): T | null;
|
getTag<T extends BattlerTag>(tagType: Constructor<T>): T | nil;
|
||||||
|
|
||||||
getTag(tagType: BattlerTagType | Constructor<BattlerTag>): BattlerTag | null {
|
getTag(tagType: BattlerTagType | Constructor<BattlerTag>): BattlerTag | nil {
|
||||||
if (!this.summonData) {
|
if (!this.summonData) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
return (tagType instanceof Function
|
return (tagType instanceof Function
|
||||||
? this.summonData.tags.find(t => t instanceof tagType)
|
? this.summonData.tags.find(t => t instanceof tagType)
|
||||||
: this.summonData.tags.find(t => t.tagType === tagType)
|
: this.summonData.tags.find(t => t.tagType === tagType)
|
||||||
)!; // TODO: is this bang correct?
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
findTag(tagFilter: ((tag: BattlerTag) => boolean)) {
|
findTag(tagFilter: ((tag: BattlerTag) => boolean)) {
|
||||||
|
@ -31,6 +31,7 @@ import i18next from "i18next";
|
|||||||
import { type DoubleBattleChanceBoosterModifierType, type EvolutionItemModifierType, type FormChangeItemModifierType, type ModifierOverride, type ModifierType, type PokemonBaseStatTotalModifierType, type PokemonExpBoosterModifierType, type PokemonFriendshipBoosterModifierType, type PokemonMoveAccuracyBoosterModifierType, type PokemonMultiHitModifierType, type TerastallizeModifierType, type TmModifierType, getModifierType, ModifierPoolType, ModifierTypeGenerator, modifierTypes, PokemonHeldItemModifierType } from "./modifier-type";
|
import { type DoubleBattleChanceBoosterModifierType, type EvolutionItemModifierType, type FormChangeItemModifierType, type ModifierOverride, type ModifierType, type PokemonBaseStatTotalModifierType, type PokemonExpBoosterModifierType, type PokemonFriendshipBoosterModifierType, type PokemonMoveAccuracyBoosterModifierType, type PokemonMultiHitModifierType, type TerastallizeModifierType, type TmModifierType, getModifierType, ModifierPoolType, ModifierTypeGenerator, modifierTypes, PokemonHeldItemModifierType } from "./modifier-type";
|
||||||
import { Color, ShadowColor } from "#enums/color";
|
import { Color, ShadowColor } from "#enums/color";
|
||||||
import { FRIENDSHIP_GAIN_FROM_RARE_CANDY } from "#app/data/balance/starters";
|
import { FRIENDSHIP_GAIN_FROM_RARE_CANDY } from "#app/data/balance/starters";
|
||||||
|
import { applyAbAttrs, CommanderAbAttr } from "#app/data/ability";
|
||||||
|
|
||||||
export type ModifierPredicate = (modifier: Modifier) => boolean;
|
export type ModifierPredicate = (modifier: Modifier) => boolean;
|
||||||
|
|
||||||
@ -1937,10 +1938,16 @@ export class PokemonInstantReviveModifier extends PokemonHeldItemModifier {
|
|||||||
* @returns always `true`
|
* @returns always `true`
|
||||||
*/
|
*/
|
||||||
override apply(pokemon: Pokemon): boolean {
|
override apply(pokemon: Pokemon): boolean {
|
||||||
|
// Restore the Pokemon to half HP
|
||||||
pokemon.scene.unshiftPhase(new PokemonHealPhase(pokemon.scene, pokemon.getBattlerIndex(),
|
pokemon.scene.unshiftPhase(new PokemonHealPhase(pokemon.scene, pokemon.getBattlerIndex(),
|
||||||
toDmgValue(pokemon.getMaxHp() / 2), i18next.t("modifier:pokemonInstantReviveApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }), false, false, true));
|
toDmgValue(pokemon.getMaxHp() / 2), i18next.t("modifier:pokemonInstantReviveApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }), false, false, true));
|
||||||
|
|
||||||
|
// Remove the Pokemon's FAINT status
|
||||||
pokemon.resetStatus(true, false, true);
|
pokemon.resetStatus(true, false, true);
|
||||||
|
|
||||||
|
// Reapply Commander on the Pokemon's side of the field, if applicable
|
||||||
|
const field = pokemon.isPlayer() ? pokemon.scene.getPlayerField() : pokemon.scene.getEnemyField();
|
||||||
|
field.forEach((p) => applyAbAttrs(CommanderAbAttr, p, null, false));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@ import { BattlerIndex } from "#app/battle";
|
|||||||
import BattleScene from "#app/battle-scene";
|
import BattleScene from "#app/battle-scene";
|
||||||
import { PLAYER_PARTY_MAX_SIZE } from "#app/constants";
|
import { PLAYER_PARTY_MAX_SIZE } from "#app/constants";
|
||||||
import { SubstituteTag } from "#app/data/battler-tags";
|
import { SubstituteTag } from "#app/data/battler-tags";
|
||||||
import { doPokeballBounceAnim, getPokeballAtlasKey, getPokeballCatchMultiplier, getPokeballTintColor } from "#app/data/pokeball";
|
import { doPokeballBounceAnim, getPokeballAtlasKey, getPokeballCatchMultiplier, getPokeballTintColor, getCriticalCaptureChance } from "#app/data/pokeball";
|
||||||
import { getStatusEffectCatchRateMultiplier } from "#app/data/status-effect";
|
import { getStatusEffectCatchRateMultiplier } from "#app/data/status-effect";
|
||||||
import { addPokeballCaptureStars, addPokeballOpenParticles } from "#app/field/anims";
|
import { addPokeballCaptureStars, addPokeballOpenParticles } from "#app/field/anims";
|
||||||
import { EnemyPokemon } from "#app/field/pokemon";
|
import { EnemyPokemon } from "#app/field/pokemon";
|
||||||
@ -52,8 +52,10 @@ export class AttemptCapturePhase extends PokemonPhase {
|
|||||||
const catchRate = pokemon.species.catchRate;
|
const catchRate = pokemon.species.catchRate;
|
||||||
const pokeballMultiplier = getPokeballCatchMultiplier(this.pokeballType);
|
const pokeballMultiplier = getPokeballCatchMultiplier(this.pokeballType);
|
||||||
const statusMultiplier = pokemon.status ? getStatusEffectCatchRateMultiplier(pokemon.status.effect) : 1;
|
const statusMultiplier = pokemon.status ? getStatusEffectCatchRateMultiplier(pokemon.status.effect) : 1;
|
||||||
const x = Math.round((((_3m - _2h) * catchRate * pokeballMultiplier) / _3m) * statusMultiplier);
|
const modifiedCatchRate = Math.round((((_3m - _2h) * catchRate * pokeballMultiplier) / _3m) * statusMultiplier);
|
||||||
const y = Math.round(65536 / Math.sqrt(Math.sqrt(255 / x)));
|
const shakeProbability = Math.round(65536 / Math.pow((255 / modifiedCatchRate), 0.1875)); // Formula taken from gen 6
|
||||||
|
const criticalCaptureChance = getCriticalCaptureChance(this.scene, modifiedCatchRate);
|
||||||
|
const isCritical = pokemon.randSeedInt(256) < criticalCaptureChance;
|
||||||
const fpOffset = pokemon.getFieldPositionOffset();
|
const fpOffset = pokemon.getFieldPositionOffset();
|
||||||
|
|
||||||
const pokeballAtlasKey = getPokeballAtlasKey(this.pokeballType);
|
const pokeballAtlasKey = getPokeballAtlasKey(this.pokeballType);
|
||||||
@ -61,17 +63,19 @@ export class AttemptCapturePhase extends PokemonPhase {
|
|||||||
this.pokeball.setOrigin(0.5, 0.625);
|
this.pokeball.setOrigin(0.5, 0.625);
|
||||||
this.scene.field.add(this.pokeball);
|
this.scene.field.add(this.pokeball);
|
||||||
|
|
||||||
this.scene.playSound("se/pb_throw");
|
this.scene.playSound("se/pb_throw", isCritical ? { rate: 0.2 } : undefined); // Crit catch throws are higher pitched
|
||||||
this.scene.time.delayedCall(300, () => {
|
this.scene.time.delayedCall(300, () => {
|
||||||
this.scene.field.moveBelow(this.pokeball as Phaser.GameObjects.GameObject, pokemon);
|
this.scene.field.moveBelow(this.pokeball as Phaser.GameObjects.GameObject, pokemon);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.scene.tweens.add({
|
this.scene.tweens.add({
|
||||||
|
// Throw animation
|
||||||
targets: this.pokeball,
|
targets: this.pokeball,
|
||||||
x: { value: 236 + fpOffset[0], ease: "Linear" },
|
x: { value: 236 + fpOffset[0], ease: "Linear" },
|
||||||
y: { value: 16 + fpOffset[1], ease: "Cubic.easeOut" },
|
y: { value: 16 + fpOffset[1], ease: "Cubic.easeOut" },
|
||||||
duration: 500,
|
duration: 500,
|
||||||
onComplete: () => {
|
onComplete: () => {
|
||||||
|
// Ball opens
|
||||||
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
|
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
|
||||||
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
|
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
|
||||||
this.scene.playSound("se/pb_rel");
|
this.scene.playSound("se/pb_rel");
|
||||||
@ -80,30 +84,33 @@ export class AttemptCapturePhase extends PokemonPhase {
|
|||||||
addPokeballOpenParticles(this.scene, this.pokeball.x, this.pokeball.y, this.pokeballType);
|
addPokeballOpenParticles(this.scene, this.pokeball.x, this.pokeball.y, this.pokeballType);
|
||||||
|
|
||||||
this.scene.tweens.add({
|
this.scene.tweens.add({
|
||||||
|
// Mon enters ball
|
||||||
targets: pokemon,
|
targets: pokemon,
|
||||||
duration: 500,
|
duration: 500,
|
||||||
ease: "Sine.easeIn",
|
ease: "Sine.easeIn",
|
||||||
scale: 0.25,
|
scale: 0.25,
|
||||||
y: 20,
|
y: 20,
|
||||||
onComplete: () => {
|
onComplete: () => {
|
||||||
|
// Ball closes
|
||||||
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
|
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
|
||||||
pokemon.setVisible(false);
|
pokemon.setVisible(false);
|
||||||
this.scene.playSound("se/pb_catch");
|
this.scene.playSound("se/pb_catch");
|
||||||
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}`));
|
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}`));
|
||||||
|
|
||||||
const doShake = () => {
|
const doShake = () => {
|
||||||
|
// After the overall catch rate check, the game does 3 shake checks before confirming the catch.
|
||||||
let shakeCount = 0;
|
let shakeCount = 0;
|
||||||
const pbX = this.pokeball.x;
|
const pbX = this.pokeball.x;
|
||||||
const shakeCounter = this.scene.tweens.addCounter({
|
const shakeCounter = this.scene.tweens.addCounter({
|
||||||
from: 0,
|
from: 0,
|
||||||
to: 1,
|
to: 1,
|
||||||
repeat: 4,
|
repeat: isCritical ? 2 : 4, // Critical captures only perform 1 shake check
|
||||||
yoyo: true,
|
yoyo: true,
|
||||||
ease: "Cubic.easeOut",
|
ease: "Cubic.easeOut",
|
||||||
duration: 250,
|
duration: 250,
|
||||||
repeatDelay: 500,
|
repeatDelay: 500,
|
||||||
onUpdate: t => {
|
onUpdate: t => {
|
||||||
if (shakeCount && shakeCount < 4) {
|
if (shakeCount && shakeCount < (isCritical ? 2 : 4)) {
|
||||||
const value = t.getValue();
|
const value = t.getValue();
|
||||||
const directionMultiplier = shakeCount % 2 === 1 ? 1 : -1;
|
const directionMultiplier = shakeCount % 2 === 1 ? 1 : -1;
|
||||||
this.pokeball.setX(pbX + value * 4 * directionMultiplier);
|
this.pokeball.setX(pbX + value * 4 * directionMultiplier);
|
||||||
@ -114,13 +121,18 @@ export class AttemptCapturePhase extends PokemonPhase {
|
|||||||
if (!pokemon.species.isObtainable()) {
|
if (!pokemon.species.isObtainable()) {
|
||||||
shakeCounter.stop();
|
shakeCounter.stop();
|
||||||
this.failCatch(shakeCount);
|
this.failCatch(shakeCount);
|
||||||
} else if (shakeCount++ < 3) {
|
} else if (shakeCount++ < (isCritical ? 1 : 3)) {
|
||||||
if (pokeballMultiplier === -1 || pokemon.randSeedInt(65536) < y) {
|
// Shake check (skip check for critical or guaranteed captures, but still play the sound)
|
||||||
|
if (pokeballMultiplier === -1 || isCritical || modifiedCatchRate >= 255 || pokemon.randSeedInt(65536) < shakeProbability) {
|
||||||
this.scene.playSound("se/pb_move");
|
this.scene.playSound("se/pb_move");
|
||||||
} else {
|
} else {
|
||||||
shakeCounter.stop();
|
shakeCounter.stop();
|
||||||
this.failCatch(shakeCount);
|
this.failCatch(shakeCount);
|
||||||
}
|
}
|
||||||
|
} else if (isCritical && pokemon.randSeedInt(65536) >= shakeProbability) {
|
||||||
|
// Above, perform the one shake check for critical captures after the ball shakes once
|
||||||
|
shakeCounter.stop();
|
||||||
|
this.failCatch(shakeCount);
|
||||||
} else {
|
} else {
|
||||||
this.scene.playSound("se/pb_lock");
|
this.scene.playSound("se/pb_lock");
|
||||||
addPokeballCaptureStars(this.scene, this.pokeball);
|
addPokeballCaptureStars(this.scene, this.pokeball);
|
||||||
@ -153,7 +165,8 @@ export class AttemptCapturePhase extends PokemonPhase {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
this.scene.time.delayedCall(250, () => doPokeballBounceAnim(this.scene, this.pokeball, 16, 72, 350, doShake));
|
// Ball bounces (handled in pokemon.ts)
|
||||||
|
this.scene.time.delayedCall(250, () => doPokeballBounceAnim(this.scene, this.pokeball, 16, 72, 350, doShake, isCritical));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -32,6 +32,8 @@ export class CommandPhase extends FieldPhase {
|
|||||||
start() {
|
start() {
|
||||||
super.start();
|
super.start();
|
||||||
|
|
||||||
|
this.scene.updateGameInfo();
|
||||||
|
|
||||||
const commandUiHandler = this.scene.ui.handlers[Mode.COMMAND];
|
const commandUiHandler = this.scene.ui.handlers[Mode.COMMAND];
|
||||||
if (commandUiHandler) {
|
if (commandUiHandler) {
|
||||||
if (this.scene.currentBattle.turn === 1 || commandUiHandler.getCursor() === Command.POKEMON) {
|
if (this.scene.currentBattle.turn === 1 || commandUiHandler.getCursor() === Command.POKEMON) {
|
||||||
@ -54,6 +56,11 @@ export class CommandPhase extends FieldPhase {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If the Pokemon has applied Commander's effects to its ally, skip this command
|
||||||
|
if (this.scene.currentBattle?.double && this.getPokemon().getAlly()?.getTag(BattlerTagType.COMMANDED)?.getSourcePokemon(this.scene) === this.getPokemon()) {
|
||||||
|
this.scene.currentBattle.turnCommands[this.fieldIndex] = { command: Command.FIGHT, move: { move: Moves.NONE, targets: []}, skip: true };
|
||||||
|
}
|
||||||
|
|
||||||
if (this.scene.currentBattle.turnCommands[this.fieldIndex]?.skip) {
|
if (this.scene.currentBattle.turnCommands[this.fieldIndex]?.skip) {
|
||||||
return this.end();
|
return this.end();
|
||||||
}
|
}
|
||||||
@ -92,7 +99,7 @@ export class CommandPhase extends FieldPhase {
|
|||||||
|
|
||||||
handleCommand(command: Command, cursor: integer, ...args: any[]): boolean {
|
handleCommand(command: Command, cursor: integer, ...args: any[]): boolean {
|
||||||
const playerPokemon = this.scene.getPlayerField()[this.fieldIndex];
|
const playerPokemon = this.scene.getPlayerField()[this.fieldIndex];
|
||||||
let success: boolean;
|
let success: boolean = false;
|
||||||
|
|
||||||
switch (command) {
|
switch (command) {
|
||||||
case Command.FIGHT:
|
case Command.FIGHT:
|
||||||
@ -232,11 +239,8 @@ export class CommandPhase extends FieldPhase {
|
|||||||
const trapTag = playerPokemon.getTag(TrappedTag);
|
const trapTag = playerPokemon.getTag(TrappedTag);
|
||||||
const fairyLockTag = playerPokemon.scene.arena.getTagOnSide(ArenaTagType.FAIRY_LOCK, ArenaTagSide.PLAYER);
|
const fairyLockTag = playerPokemon.scene.arena.getTagOnSide(ArenaTagType.FAIRY_LOCK, ArenaTagSide.PLAYER);
|
||||||
|
|
||||||
// trapTag should be defined at this point, but just in case...
|
|
||||||
if (!trapTag && !fairyLockTag) {
|
if (!trapTag && !fairyLockTag) {
|
||||||
currentBattle.turnCommands[this.fieldIndex] = isSwitch
|
i18next.t(`battle:noEscape${isSwitch ? "Switch" : "Flee"}`);
|
||||||
? { command: Command.POKEMON, cursor: cursor, args: args }
|
|
||||||
: { command: Command.RUN };
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!isSwitch) {
|
if (!isSwitch) {
|
||||||
@ -272,11 +276,11 @@ export class CommandPhase extends FieldPhase {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (success!) { // TODO: is the bang correct?
|
if (success) {
|
||||||
this.end();
|
this.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
return success!; // TODO: is the bang correct?
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
cancel() {
|
cancel() {
|
||||||
|
@ -36,6 +36,7 @@ import { PlayerGender } from "#enums/player-gender";
|
|||||||
import { Species } from "#enums/species";
|
import { Species } from "#enums/species";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import { WEIGHT_INCREMENT_ON_SPAWN_MISS } from "#app/data/mystery-encounters/mystery-encounters";
|
import { WEIGHT_INCREMENT_ON_SPAWN_MISS } from "#app/data/mystery-encounters/mystery-encounters";
|
||||||
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
|
|
||||||
export class EncounterPhase extends BattlePhase {
|
export class EncounterPhase extends BattlePhase {
|
||||||
private loaded: boolean;
|
private loaded: boolean;
|
||||||
@ -482,6 +483,7 @@ export class EncounterPhase extends BattlePhase {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) {
|
if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) {
|
||||||
|
this.scene.getPlayerField().forEach((pokemon) => pokemon.lapseTag(BattlerTagType.COMMANDED));
|
||||||
this.scene.pushPhase(new ReturnPhase(this.scene, 1));
|
this.scene.pushPhase(new ReturnPhase(this.scene, 1));
|
||||||
}
|
}
|
||||||
this.scene.pushPhase(new ToggleDoublePositionPhase(this.scene, false));
|
this.scene.pushPhase(new ToggleDoublePositionPhase(this.scene, false));
|
||||||
|
@ -2,6 +2,8 @@ import BattleScene from "#app/battle-scene";
|
|||||||
import { BattlerIndex } from "#app/battle";
|
import { BattlerIndex } from "#app/battle";
|
||||||
import { Command } from "#app/ui/command-ui-handler";
|
import { Command } from "#app/ui/command-ui-handler";
|
||||||
import { FieldPhase } from "./field-phase";
|
import { FieldPhase } from "./field-phase";
|
||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Phase for determining an enemy AI's action for the next turn.
|
* Phase for determining an enemy AI's action for the next turn.
|
||||||
@ -34,6 +36,11 @@ export class EnemyCommandPhase extends FieldPhase {
|
|||||||
|
|
||||||
const trainer = battle.trainer;
|
const trainer = battle.trainer;
|
||||||
|
|
||||||
|
if (battle.double && enemyPokemon.hasAbility(Abilities.COMMANDER)
|
||||||
|
&& enemyPokemon.getAlly().getTag(BattlerTagType.COMMANDED)) {
|
||||||
|
this.skipTurn = true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If the enemy has a trainer, decide whether or not the enemy should switch
|
* If the enemy has a trainer, decide whether or not the enemy should switch
|
||||||
* to another member in its party.
|
* to another member in its party.
|
||||||
|
@ -39,8 +39,6 @@ export class EvolutionPhase extends Phase {
|
|||||||
this.pokemon = pokemon;
|
this.pokemon = pokemon;
|
||||||
this.evolution = evolution;
|
this.evolution = evolution;
|
||||||
this.lastLevel = lastLevel;
|
this.lastLevel = lastLevel;
|
||||||
this.evolutionBgm = this.scene.playSoundWithoutBgm("evolution");
|
|
||||||
this.preEvolvedPokemonName = getPokemonNameWithAffix(this.pokemon);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
validate(): boolean {
|
validate(): boolean {
|
||||||
@ -62,9 +60,9 @@ export class EvolutionPhase extends Phase {
|
|||||||
|
|
||||||
this.scene.fadeOutBgm(undefined, false);
|
this.scene.fadeOutBgm(undefined, false);
|
||||||
|
|
||||||
const evolutionHandler = this.scene.ui.getHandler() as EvolutionSceneHandler;
|
this.evolutionHandler = this.scene.ui.getHandler() as EvolutionSceneHandler;
|
||||||
|
|
||||||
this.evolutionContainer = evolutionHandler.evolutionContainer;
|
this.evolutionContainer = this.evolutionHandler.evolutionContainer;
|
||||||
|
|
||||||
this.evolutionBaseBg = this.scene.add.image(0, 0, "default_bg");
|
this.evolutionBaseBg = this.scene.add.image(0, 0, "default_bg");
|
||||||
this.evolutionBaseBg.setOrigin(0, 0);
|
this.evolutionBaseBg.setOrigin(0, 0);
|
||||||
@ -117,14 +115,12 @@ export class EvolutionPhase extends Phase {
|
|||||||
sprite.pipelineData[k] = this.pokemon.getSprite().pipelineData[k];
|
sprite.pipelineData[k] = this.pokemon.getSprite().pipelineData[k];
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
this.preEvolvedPokemonName = getPokemonNameWithAffix(this.pokemon);
|
||||||
this.doEvolution();
|
this.doEvolution();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
doEvolution(): void {
|
doEvolution(): void {
|
||||||
this.evolutionHandler = this.scene.ui.getHandler() as EvolutionSceneHandler;
|
|
||||||
|
|
||||||
this.scene.ui.showText(i18next.t("menu:evolving", { pokemonName: this.preEvolvedPokemonName }), null, () => {
|
this.scene.ui.showText(i18next.t("menu:evolving", { pokemonName: this.preEvolvedPokemonName }), null, () => {
|
||||||
this.pokemon.cry();
|
this.pokemon.cry();
|
||||||
|
|
||||||
@ -145,6 +141,7 @@ export class EvolutionPhase extends Phase {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.scene.time.delayedCall(1000, () => {
|
this.scene.time.delayedCall(1000, () => {
|
||||||
|
this.evolutionBgm = this.scene.playSoundWithoutBgm("evolution");
|
||||||
this.scene.tweens.add({
|
this.scene.tweens.add({
|
||||||
targets: this.evolutionBgOverlay,
|
targets: this.evolutionBgOverlay,
|
||||||
alpha: 1,
|
alpha: 1,
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import { BattlerIndex, BattleType } from "#app/battle";
|
import { BattlerIndex, BattleType } from "#app/battle";
|
||||||
import BattleScene from "#app/battle-scene";
|
import BattleScene from "#app/battle-scene";
|
||||||
import { applyPostFaintAbAttrs, applyPostKnockOutAbAttrs, applyPostVictoryAbAttrs, PostFaintAbAttr, PostKnockOutAbAttr, PostVictoryAbAttr } from "#app/data/ability";
|
import { applyPostFaintAbAttrs, applyPostKnockOutAbAttrs, applyPostVictoryAbAttrs, PostFaintAbAttr, PostKnockOutAbAttr, PostVictoryAbAttr } from "#app/data/ability";
|
||||||
import { BattlerTagLapseType, DestinyBondTag } from "#app/data/battler-tags";
|
import { BattlerTagLapseType, DestinyBondTag, GrudgeTag } from "#app/data/battler-tags";
|
||||||
import { battleSpecDialogue } from "#app/data/dialogue";
|
import { battleSpecDialogue } from "#app/data/dialogue";
|
||||||
import { allMoves, PostVictoryStatStageChangeAttr } from "#app/data/move";
|
import { allMoves, PostVictoryStatStageChangeAttr } from "#app/data/move";
|
||||||
import { SpeciesFormChangeActiveTrigger } from "#app/data/pokemon-forms";
|
import { SpeciesFormChangeActiveTrigger } from "#app/data/pokemon-forms";
|
||||||
@ -31,18 +31,24 @@ export class FaintPhase extends PokemonPhase {
|
|||||||
/**
|
/**
|
||||||
* Destiny Bond tag belonging to the currently fainting Pokemon, if applicable
|
* Destiny Bond tag belonging to the currently fainting Pokemon, if applicable
|
||||||
*/
|
*/
|
||||||
private destinyTag?: DestinyBondTag;
|
private destinyTag?: DestinyBondTag | null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The source Pokemon that dealt fatal damage and should get KO'd by Destiny Bond, if applicable
|
* Grudge tag belonging to the currently fainting Pokemon, if applicable
|
||||||
|
*/
|
||||||
|
private grudgeTag?: GrudgeTag | null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The source Pokemon that dealt fatal damage
|
||||||
*/
|
*/
|
||||||
private source?: Pokemon;
|
private source?: Pokemon;
|
||||||
|
|
||||||
constructor(scene: BattleScene, battlerIndex: BattlerIndex, preventEndure: boolean = false, destinyTag?: DestinyBondTag, source?: Pokemon) {
|
constructor(scene: BattleScene, battlerIndex: BattlerIndex, preventEndure: boolean = false, destinyTag?: DestinyBondTag | null, grudgeTag?: GrudgeTag | null, source?: Pokemon) {
|
||||||
super(scene, battlerIndex);
|
super(scene, battlerIndex);
|
||||||
|
|
||||||
this.preventEndure = preventEndure;
|
this.preventEndure = preventEndure;
|
||||||
this.destinyTag = destinyTag;
|
this.destinyTag = destinyTag;
|
||||||
|
this.grudgeTag = grudgeTag;
|
||||||
this.source = source;
|
this.source = source;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -53,6 +59,10 @@ export class FaintPhase extends PokemonPhase {
|
|||||||
this.destinyTag.lapse(this.source, BattlerTagLapseType.CUSTOM);
|
this.destinyTag.lapse(this.source, BattlerTagLapseType.CUSTOM);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isNullOrUndefined(this.grudgeTag) && !isNullOrUndefined(this.source)) {
|
||||||
|
this.grudgeTag.lapse(this.getPokemon(), BattlerTagLapseType.CUSTOM, this.source);
|
||||||
|
}
|
||||||
|
|
||||||
if (!this.preventEndure) {
|
if (!this.preventEndure) {
|
||||||
const instantReviveModifier = this.scene.applyModifier(PokemonInstantReviveModifier, this.player, this.getPokemon()) as PokemonInstantReviveModifier;
|
const instantReviveModifier = this.scene.applyModifier(PokemonInstantReviveModifier, this.player, this.getPokemon()) as PokemonInstantReviveModifier;
|
||||||
|
|
||||||
|
@ -23,6 +23,7 @@ import * as Utils from "#app/utils";
|
|||||||
import { PlayerGender } from "#enums/player-gender";
|
import { PlayerGender } from "#enums/player-gender";
|
||||||
import { TrainerType } from "#enums/trainer-type";
|
import { TrainerType } from "#enums/trainer-type";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
export class GameOverPhase extends BattlePhase {
|
export class GameOverPhase extends BattlePhase {
|
||||||
private victory: boolean;
|
private victory: boolean;
|
||||||
@ -176,10 +177,9 @@ export class GameOverPhase extends BattlePhase {
|
|||||||
If Online, execute apiFetch as intended
|
If Online, execute apiFetch as intended
|
||||||
If Offline, execute offlineNewClear(), a localStorage implementation of newClear daily run checks */
|
If Offline, execute offlineNewClear(), a localStorage implementation of newClear daily run checks */
|
||||||
if (this.victory) {
|
if (this.victory) {
|
||||||
if (!Utils.isLocal) {
|
if (!Utils.isLocal || Utils.isLocalServerConnected) {
|
||||||
Utils.apiFetch(`savedata/session/newclear?slot=${this.scene.sessionSlotId}&clientSessionId=${clientSessionId}`, true)
|
pokerogueApi.savedata.session.newclear({ slot: this.scene.sessionSlotId, clientSessionId })
|
||||||
.then(response => response.json())
|
.then((success) => doGameOver(!!success));
|
||||||
.then(newClear => doGameOver(newClear));
|
|
||||||
} else {
|
} else {
|
||||||
this.scene.gameData.offlineNewClear(this.scene).then(result => {
|
this.scene.gameData.offlineNewClear(this.scene).then(result => {
|
||||||
doGameOver(result);
|
doGameOver(result);
|
||||||
|
@ -25,6 +25,7 @@ import {
|
|||||||
applyFilteredMoveAttrs,
|
applyFilteredMoveAttrs,
|
||||||
applyMoveAttrs,
|
applyMoveAttrs,
|
||||||
AttackMove,
|
AttackMove,
|
||||||
|
DelayedAttackAttr,
|
||||||
FixedDamageAttr,
|
FixedDamageAttr,
|
||||||
HitsTagAttr,
|
HitsTagAttr,
|
||||||
MissEffectAttr,
|
MissEffectAttr,
|
||||||
@ -85,8 +86,13 @@ export class MoveEffectPhase extends PokemonPhase {
|
|||||||
/** All Pokemon targeted by this phase's invoked move */
|
/** All Pokemon targeted by this phase's invoked move */
|
||||||
const targets = this.getTargets();
|
const targets = this.getTargets();
|
||||||
|
|
||||||
/** If the user was somehow removed from the field, end this phase */
|
if (!user) {
|
||||||
if (!user?.isOnField()) {
|
return super.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
const isDelayedAttack = this.move.getMove().hasAttr(DelayedAttackAttr);
|
||||||
|
/** If the user was somehow removed from the field and it's not a delayed attack, end this phase */
|
||||||
|
if (!user.isOnField() && !isDelayedAttack) {
|
||||||
return super.end();
|
return super.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -142,9 +148,9 @@ export class MoveEffectPhase extends PokemonPhase {
|
|||||||
const hasActiveTargets = targets.some(t => t.isActive(true));
|
const hasActiveTargets = targets.some(t => t.isActive(true));
|
||||||
|
|
||||||
/** Check if the target is immune via ability to the attacking move, and NOT in semi invulnerable state */
|
/** Check if the target is immune via ability to the attacking move, and NOT in semi invulnerable state */
|
||||||
const isImmune = targets[0].hasAbilityWithAttr(TypeImmunityAbAttr)
|
const isImmune = targets[0]?.hasAbilityWithAttr(TypeImmunityAbAttr)
|
||||||
&& (targets[0].getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move))
|
&& (targets[0]?.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move))
|
||||||
&& !targets[0].getTag(SemiInvulnerableTag);
|
&& !targets[0]?.getTag(SemiInvulnerableTag);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If no targets are left for the move to hit (FAIL), or the invoked move is single-target
|
* If no targets are left for the move to hit (FAIL), or the invoked move is single-target
|
||||||
@ -156,7 +162,7 @@ export class MoveEffectPhase extends PokemonPhase {
|
|||||||
if (hasActiveTargets) {
|
if (hasActiveTargets) {
|
||||||
this.scene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: this.getFirstTarget() ? getPokemonNameWithAffix(this.getFirstTarget()!) : "" }));
|
this.scene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: this.getFirstTarget() ? getPokemonNameWithAffix(this.getFirstTarget()!) : "" }));
|
||||||
moveHistoryEntry.result = MoveResult.MISS;
|
moveHistoryEntry.result = MoveResult.MISS;
|
||||||
applyMoveAttrs(MissEffectAttr, user, null, move);
|
applyMoveAttrs(MissEffectAttr, user, null, this.move.getMove());
|
||||||
} else {
|
} else {
|
||||||
this.scene.queueMessage(i18next.t("battle:attackFailed"));
|
this.scene.queueMessage(i18next.t("battle:attackFailed"));
|
||||||
moveHistoryEntry.result = MoveResult.FAIL;
|
moveHistoryEntry.result = MoveResult.FAIL;
|
||||||
@ -205,11 +211,14 @@ export class MoveEffectPhase extends PokemonPhase {
|
|||||||
&& (target.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move))
|
&& (target.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move))
|
||||||
&& !target.getTag(SemiInvulnerableTag);
|
&& !target.getTag(SemiInvulnerableTag);
|
||||||
|
|
||||||
|
/** Is the target hidden by the effects of its Commander ability? */
|
||||||
|
const isCommanding = this.scene.currentBattle.double && target.getAlly()?.getTag(BattlerTagType.COMMANDED)?.getSourcePokemon(this.scene) === target;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If the move missed a target, stop all future hits against that target
|
* If the move missed a target, stop all future hits against that target
|
||||||
* and move on to the next target (if there is one).
|
* and move on to the next target (if there is one).
|
||||||
*/
|
*/
|
||||||
if (!isImmune && !isProtected && !targetHitChecks[target.getBattlerIndex()]) {
|
if (isCommanding || (!isImmune && !isProtected && !targetHitChecks[target.getBattlerIndex()])) {
|
||||||
this.stopMultiHit(target);
|
this.stopMultiHit(target);
|
||||||
this.scene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: getPokemonNameWithAffix(target) }));
|
this.scene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: getPokemonNameWithAffix(target) }));
|
||||||
if (moveHistoryEntry.result === MoveResult.PENDING) {
|
if (moveHistoryEntry.result === MoveResult.PENDING) {
|
||||||
|
@ -1,9 +1,31 @@
|
|||||||
import { BattlerIndex } from "#app/battle";
|
import { BattlerIndex } from "#app/battle";
|
||||||
import BattleScene from "#app/battle-scene";
|
import BattleScene from "#app/battle-scene";
|
||||||
import { applyAbAttrs, applyPostMoveUsedAbAttrs, applyPreAttackAbAttrs, BlockRedirectAbAttr, IncreasePpAbAttr, PokemonTypeChangeAbAttr, PostMoveUsedAbAttr, RedirectMoveAbAttr, ReduceStatusEffectDurationAbAttr } from "#app/data/ability";
|
import {
|
||||||
|
applyAbAttrs,
|
||||||
|
applyPostMoveUsedAbAttrs,
|
||||||
|
applyPreAttackAbAttrs,
|
||||||
|
BlockRedirectAbAttr,
|
||||||
|
IncreasePpAbAttr,
|
||||||
|
PokemonTypeChangeAbAttr,
|
||||||
|
PostMoveUsedAbAttr,
|
||||||
|
RedirectMoveAbAttr,
|
||||||
|
ReduceStatusEffectDurationAbAttr
|
||||||
|
} from "#app/data/ability";
|
||||||
|
import { DelayedAttackTag } from "#app/data/arena-tag";
|
||||||
import { CommonAnim } from "#app/data/battle-anims";
|
import { CommonAnim } from "#app/data/battle-anims";
|
||||||
import { BattlerTagLapseType, CenterOfAttentionTag } from "#app/data/battler-tags";
|
import { BattlerTagLapseType, CenterOfAttentionTag } from "#app/data/battler-tags";
|
||||||
import { allMoves, applyMoveAttrs, BypassRedirectAttr, BypassSleepAttr, CopyMoveAttr, frenzyMissFunc, HealStatusEffectAttr, MoveFlags, PreMoveMessageAttr } from "#app/data/move";
|
import {
|
||||||
|
allMoves,
|
||||||
|
applyMoveAttrs,
|
||||||
|
BypassRedirectAttr,
|
||||||
|
BypassSleepAttr,
|
||||||
|
CopyMoveAttr,
|
||||||
|
DelayedAttackAttr,
|
||||||
|
frenzyMissFunc,
|
||||||
|
HealStatusEffectAttr,
|
||||||
|
MoveFlags,
|
||||||
|
PreMoveMessageAttr
|
||||||
|
} from "#app/data/move";
|
||||||
import { SpeciesFormChangePreMoveTrigger } from "#app/data/pokemon-forms";
|
import { SpeciesFormChangePreMoveTrigger } from "#app/data/pokemon-forms";
|
||||||
import { getStatusEffectActivationText, getStatusEffectHealText } from "#app/data/status-effect";
|
import { getStatusEffectActivationText, getStatusEffectHealText } from "#app/data/status-effect";
|
||||||
import { Type } from "#app/data/type";
|
import { Type } from "#app/data/type";
|
||||||
@ -14,16 +36,17 @@ import { getPokemonNameWithAffix } from "#app/messages";
|
|||||||
import Overrides from "#app/overrides";
|
import Overrides from "#app/overrides";
|
||||||
import { BattlePhase } from "#app/phases/battle-phase";
|
import { BattlePhase } from "#app/phases/battle-phase";
|
||||||
import { CommonAnimPhase } from "#app/phases/common-anim-phase";
|
import { CommonAnimPhase } from "#app/phases/common-anim-phase";
|
||||||
|
import { MoveChargePhase } from "#app/phases/move-charge-phase";
|
||||||
import { MoveEffectPhase } from "#app/phases/move-effect-phase";
|
import { MoveEffectPhase } from "#app/phases/move-effect-phase";
|
||||||
import { MoveEndPhase } from "#app/phases/move-end-phase";
|
import { MoveEndPhase } from "#app/phases/move-end-phase";
|
||||||
import { ShowAbilityPhase } from "#app/phases/show-ability-phase";
|
import { ShowAbilityPhase } from "#app/phases/show-ability-phase";
|
||||||
import { BooleanHolder, NumberHolder } from "#app/utils";
|
import { BooleanHolder, NumberHolder } from "#app/utils";
|
||||||
import { Abilities } from "#enums/abilities";
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { ArenaTagType } from "#enums/arena-tag-type";
|
||||||
import { BattlerTagType } from "#enums/battler-tag-type";
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
import { Moves } from "#enums/moves";
|
import { Moves } from "#enums/moves";
|
||||||
import { StatusEffect } from "#enums/status-effect";
|
import { StatusEffect } from "#enums/status-effect";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import { MoveChargePhase } from "#app/phases/move-charge-phase";
|
|
||||||
|
|
||||||
export class MovePhase extends BattlePhase {
|
export class MovePhase extends BattlePhase {
|
||||||
protected _pokemon: Pokemon;
|
protected _pokemon: Pokemon;
|
||||||
@ -227,6 +250,32 @@ export class MovePhase extends BattlePhase {
|
|||||||
// form changes happen even before we know that the move wll execute.
|
// form changes happen even before we know that the move wll execute.
|
||||||
this.scene.triggerPokemonFormChange(this.pokemon, SpeciesFormChangePreMoveTrigger);
|
this.scene.triggerPokemonFormChange(this.pokemon, SpeciesFormChangePreMoveTrigger);
|
||||||
|
|
||||||
|
const isDelayedAttack = this.move.getMove().hasAttr(DelayedAttackAttr);
|
||||||
|
if (isDelayedAttack) {
|
||||||
|
// Check the player side arena if future sight is active
|
||||||
|
const futureSightTags = this.scene.arena.findTags(t => t.tagType === ArenaTagType.FUTURE_SIGHT);
|
||||||
|
const doomDesireTags = this.scene.arena.findTags(t => t.tagType === ArenaTagType.DOOM_DESIRE);
|
||||||
|
let fail = false;
|
||||||
|
const currentTargetIndex = targets[0].getBattlerIndex();
|
||||||
|
for (const tag of futureSightTags) {
|
||||||
|
if ((tag as DelayedAttackTag).targetIndex === currentTargetIndex) {
|
||||||
|
fail = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const tag of doomDesireTags) {
|
||||||
|
if ((tag as DelayedAttackTag).targetIndex === currentTargetIndex) {
|
||||||
|
fail = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fail) {
|
||||||
|
this.showMoveText();
|
||||||
|
this.showFailedText();
|
||||||
|
return this.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.showMoveText();
|
this.showMoveText();
|
||||||
|
|
||||||
if (moveQueue.length > 0) {
|
if (moveQueue.length > 0) {
|
||||||
|
@ -417,6 +417,7 @@ export class MysteryEncounterBattlePhase extends Phase {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) {
|
if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) {
|
||||||
|
scene.getPlayerField().forEach((pokemon) => pokemon.lapseTag(BattlerTagType.COMMANDED));
|
||||||
scene.pushPhase(new ReturnPhase(scene, 1));
|
scene.pushPhase(new ReturnPhase(scene, 1));
|
||||||
}
|
}
|
||||||
scene.pushPhase(new ToggleDoublePositionPhase(scene, false));
|
scene.pushPhase(new ToggleDoublePositionPhase(scene, false));
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
import BattleScene from "#app/battle-scene";
|
import BattleScene from "#app/battle-scene";
|
||||||
import { SubstituteTag } from "#app/data/battler-tags";
|
import { SubstituteTag } from "#app/data/battler-tags";
|
||||||
import { PokemonAnimType } from "#enums/pokemon-anim-type";
|
|
||||||
import Pokemon from "#app/field/pokemon";
|
import Pokemon from "#app/field/pokemon";
|
||||||
import { BattlePhase } from "#app/phases/battle-phase";
|
import { BattlePhase } from "#app/phases/battle-phase";
|
||||||
|
import { isNullOrUndefined } from "#app/utils";
|
||||||
|
import { PokemonAnimType } from "#enums/pokemon-anim-type";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
|
||||||
|
|
||||||
export class PokemonAnimPhase extends BattlePhase {
|
export class PokemonAnimPhase extends BattlePhase {
|
||||||
@ -37,14 +39,20 @@ export class PokemonAnimPhase extends BattlePhase {
|
|||||||
case PokemonAnimType.SUBSTITUTE_REMOVE:
|
case PokemonAnimType.SUBSTITUTE_REMOVE:
|
||||||
this.doSubstituteRemoveAnim();
|
this.doSubstituteRemoveAnim();
|
||||||
break;
|
break;
|
||||||
|
case PokemonAnimType.COMMANDER_APPLY:
|
||||||
|
this.doCommanderApplyAnim();
|
||||||
|
break;
|
||||||
|
case PokemonAnimType.COMMANDER_REMOVE:
|
||||||
|
this.doCommanderRemoveAnim();
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
this.end();
|
this.end();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
doSubstituteAddAnim(): void {
|
private doSubstituteAddAnim(): void {
|
||||||
const substitute = this.pokemon.getTag(SubstituteTag);
|
const substitute = this.pokemon.getTag(SubstituteTag);
|
||||||
if (substitute === null) {
|
if (isNullOrUndefined(substitute)) {
|
||||||
return this.end();
|
return this.end();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -106,7 +114,7 @@ export class PokemonAnimPhase extends BattlePhase {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
doSubstitutePreMoveAnim(): void {
|
private doSubstitutePreMoveAnim(): void {
|
||||||
if (this.fieldAssets.length !== 1) {
|
if (this.fieldAssets.length !== 1) {
|
||||||
return this.end();
|
return this.end();
|
||||||
}
|
}
|
||||||
@ -135,7 +143,7 @@ export class PokemonAnimPhase extends BattlePhase {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
doSubstitutePostMoveAnim(): void {
|
private doSubstitutePostMoveAnim(): void {
|
||||||
if (this.fieldAssets.length !== 1) {
|
if (this.fieldAssets.length !== 1) {
|
||||||
return this.end();
|
return this.end();
|
||||||
}
|
}
|
||||||
@ -164,7 +172,7 @@ export class PokemonAnimPhase extends BattlePhase {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
doSubstituteRemoveAnim(): void {
|
private doSubstituteRemoveAnim(): void {
|
||||||
if (this.fieldAssets.length !== 1) {
|
if (this.fieldAssets.length !== 1) {
|
||||||
return this.end();
|
return this.end();
|
||||||
}
|
}
|
||||||
@ -233,4 +241,121 @@ export class PokemonAnimPhase extends BattlePhase {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private doCommanderApplyAnim(): void {
|
||||||
|
if (!this.scene.currentBattle?.double) {
|
||||||
|
return this.end();
|
||||||
|
}
|
||||||
|
const dondozo = this.pokemon.getAlly();
|
||||||
|
|
||||||
|
if (dondozo?.species?.speciesId !== Species.DONDOZO) {
|
||||||
|
return this.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
const tatsugiriX = this.pokemon.x + this.pokemon.getSprite().x;
|
||||||
|
const tatsugiriY = this.pokemon.y + this.pokemon.getSprite().y;
|
||||||
|
|
||||||
|
const getSourceSprite = () => {
|
||||||
|
const sprite = this.scene.addPokemonSprite(this.pokemon, tatsugiriX, tatsugiriY, this.pokemon.getSprite().texture, this.pokemon.getSprite()!.frame.name, true);
|
||||||
|
[ "spriteColors", "fusionSpriteColors" ].map(k => sprite.pipelineData[k] = this.pokemon.getSprite().pipelineData[k]);
|
||||||
|
sprite.setPipelineData("spriteKey", this.pokemon.getBattleSpriteKey());
|
||||||
|
sprite.setPipelineData("shiny", this.pokemon.shiny);
|
||||||
|
sprite.setPipelineData("variant", this.pokemon.variant);
|
||||||
|
sprite.setPipelineData("ignoreFieldPos", true);
|
||||||
|
sprite.setOrigin(0.5, 1);
|
||||||
|
this.pokemon.getSprite().on("animationupdate", (_anim, frame) => sprite.setFrame(frame.textureFrame));
|
||||||
|
this.scene.field.add(sprite);
|
||||||
|
return sprite;
|
||||||
|
};
|
||||||
|
|
||||||
|
const sourceSprite = getSourceSprite();
|
||||||
|
|
||||||
|
this.pokemon.setVisible(false);
|
||||||
|
|
||||||
|
const sourceFpOffset = this.pokemon.getFieldPositionOffset();
|
||||||
|
const dondozoFpOffset = dondozo.getFieldPositionOffset();
|
||||||
|
|
||||||
|
this.scene.playSound("se/pb_throw");
|
||||||
|
|
||||||
|
this.scene.tweens.add({
|
||||||
|
targets: sourceSprite,
|
||||||
|
duration: 375,
|
||||||
|
scale: 0.5,
|
||||||
|
x: { value: tatsugiriX + (dondozoFpOffset[0] - sourceFpOffset[0]) / 2, ease: "Linear" },
|
||||||
|
y: { value: (this.pokemon.isPlayer() ? 100 : 65) + sourceFpOffset[1], ease: "Sine.easeOut" },
|
||||||
|
onComplete: () => {
|
||||||
|
this.scene.field.bringToTop(dondozo);
|
||||||
|
this.scene.tweens.add({
|
||||||
|
targets: sourceSprite,
|
||||||
|
duration: 375,
|
||||||
|
scale: 0.01,
|
||||||
|
x: { value: dondozo.x, ease: "Linear" },
|
||||||
|
y: { value: dondozo.y + dondozo.height / 2, ease: "Sine.easeIn" },
|
||||||
|
onComplete: () => {
|
||||||
|
sourceSprite.destroy();
|
||||||
|
this.scene.playSound("battle_anims/PRSFX- Liquidation1.wav");
|
||||||
|
this.scene.tweens.add({
|
||||||
|
targets: dondozo,
|
||||||
|
duration: 250,
|
||||||
|
ease: "Sine.easeInOut",
|
||||||
|
scale: 0.85,
|
||||||
|
yoyo: true,
|
||||||
|
onComplete: () => this.end()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private doCommanderRemoveAnim(): void {
|
||||||
|
// Note: unlike the other Commander animation, this is played through the
|
||||||
|
// Dondozo instead of the Tatsugiri.
|
||||||
|
const tatsugiri = this.pokemon.getAlly();
|
||||||
|
|
||||||
|
const tatsuSprite = this.scene.addPokemonSprite(
|
||||||
|
tatsugiri,
|
||||||
|
this.pokemon.x + this.pokemon.getSprite().x,
|
||||||
|
this.pokemon.y + this.pokemon.getSprite().y + this.pokemon.height / 2,
|
||||||
|
tatsugiri.getSprite().texture,
|
||||||
|
tatsugiri.getSprite()!.frame.name,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
[ "spriteColors", "fusionSpriteColors" ].map(k => tatsuSprite.pipelineData[k] = tatsugiri.getSprite().pipelineData[k]);
|
||||||
|
tatsuSprite.setPipelineData("spriteKey", tatsugiri.getBattleSpriteKey());
|
||||||
|
tatsuSprite.setPipelineData("shiny", tatsugiri.shiny);
|
||||||
|
tatsuSprite.setPipelineData("variant", tatsugiri.variant);
|
||||||
|
tatsuSprite.setPipelineData("ignoreFieldPos", true);
|
||||||
|
this.pokemon.getSprite().on("animationupdate", (_anim, frame) => tatsuSprite.setFrame(frame.textureFrame));
|
||||||
|
|
||||||
|
tatsuSprite.setOrigin(0.5, 1);
|
||||||
|
tatsuSprite.setScale(0.01);
|
||||||
|
|
||||||
|
this.scene.field.add(tatsuSprite);
|
||||||
|
this.scene.field.bringToTop(this.pokemon);
|
||||||
|
tatsuSprite.setVisible(true);
|
||||||
|
|
||||||
|
this.scene.tweens.add({
|
||||||
|
targets: this.pokemon,
|
||||||
|
duration: 250,
|
||||||
|
ease: "Sine.easeInOut",
|
||||||
|
scale: 1.15,
|
||||||
|
yoyo: true,
|
||||||
|
onComplete: () => {
|
||||||
|
this.scene.playSound("battle_anims/PRSFX- Liquidation4.wav");
|
||||||
|
this.scene.tweens.add({
|
||||||
|
targets: tatsuSprite,
|
||||||
|
duration: 500,
|
||||||
|
scale: 1,
|
||||||
|
x: { value: tatsugiri.x + tatsugiri.getSprite().x, ease: "Linear" },
|
||||||
|
y: { value: tatsugiri.y + tatsugiri.getSprite().y, ease: "Sine.easeIn" },
|
||||||
|
onComplete: () => {
|
||||||
|
tatsugiri.setVisible(true);
|
||||||
|
tatsuSprite.destroy();
|
||||||
|
this.end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import BattleScene from "#app/battle-scene";
|
import BattleScene from "#app/battle-scene";
|
||||||
import { BattlerIndex } from "#app/battle";
|
import { BattlerIndex } from "#app/battle";
|
||||||
import { applyPostSummonAbAttrs, PostSummonAbAttr } from "#app/data/ability";
|
import { applyAbAttrs, applyPostSummonAbAttrs, CommanderAbAttr, PostSummonAbAttr } from "#app/data/ability";
|
||||||
import { ArenaTrapTag } from "#app/data/arena-tag";
|
import { ArenaTrapTag } from "#app/data/arena-tag";
|
||||||
import { StatusEffect } from "#app/enums/status-effect";
|
import { StatusEffect } from "#app/enums/status-effect";
|
||||||
import { PokemonPhase } from "./pokemon-phase";
|
import { PokemonPhase } from "./pokemon-phase";
|
||||||
@ -28,5 +28,8 @@ export class PostSummonPhase extends PokemonPhase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
applyPostSummonAbAttrs(PostSummonAbAttr, pokemon).then(() => this.end());
|
applyPostSummonAbAttrs(PostSummonAbAttr, pokemon).then(() => this.end());
|
||||||
|
|
||||||
|
const field = pokemon.isPlayer() ? this.scene.getPlayerField() : this.scene.getEnemyField();
|
||||||
|
field.forEach((p) => applyAbAttrs(CommanderAbAttr, p, null, false));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -243,7 +243,7 @@ export class TitlePhase extends Phase {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// If Online, calls seed fetch from db to generate daily run. If Offline, generates a daily run based on current date.
|
// If Online, calls seed fetch from db to generate daily run. If Offline, generates a daily run based on current date.
|
||||||
if (!Utils.isLocal) {
|
if (!Utils.isLocal || Utils.isLocalServerConnected) {
|
||||||
fetchDailyRunSeed().then(seed => {
|
fetchDailyRunSeed().then(seed => {
|
||||||
if (seed) {
|
if (seed) {
|
||||||
generateDaily(seed);
|
generateDaily(seed);
|
||||||
|
91
src/plugins/api/api-base.ts
Normal file
91
src/plugins/api/api-base.ts
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
import { SESSION_ID_COOKIE_NAME } from "#app/constants";
|
||||||
|
import { getCookie } from "#app/utils";
|
||||||
|
|
||||||
|
type DataType = "json" | "form-urlencoded";
|
||||||
|
|
||||||
|
export abstract class ApiBase {
|
||||||
|
//#region Fields
|
||||||
|
|
||||||
|
public readonly ERR_GENERIC: string = "There was an error";
|
||||||
|
|
||||||
|
protected readonly base: string;
|
||||||
|
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
constructor(base: string) {
|
||||||
|
this.base = base;
|
||||||
|
}
|
||||||
|
|
||||||
|
//#region Protected
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a GET request.
|
||||||
|
* @param path The path to send the request to.
|
||||||
|
*/
|
||||||
|
protected async doGet(path: string) {
|
||||||
|
return this.doFetch(path, { method: "GET" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a POST request.
|
||||||
|
* @param path THe path to send the request to.
|
||||||
|
* @param bodyData The body-data to send.
|
||||||
|
* @param dataType The data-type of the {@linkcode bodyData}.
|
||||||
|
*/
|
||||||
|
protected async doPost<D = undefined>(path: string, bodyData?: D, dataType: DataType = "json") {
|
||||||
|
let body: string | undefined = undefined;
|
||||||
|
const headers: HeadersInit = {};
|
||||||
|
|
||||||
|
if (bodyData) {
|
||||||
|
if (dataType === "json") {
|
||||||
|
body = typeof bodyData === "string" ? bodyData : JSON.stringify(bodyData);
|
||||||
|
headers["Content-Type"] = "application/json";
|
||||||
|
} else if (dataType === "form-urlencoded") {
|
||||||
|
if (bodyData instanceof Object) {
|
||||||
|
body = this.toUrlSearchParams(bodyData).toString();
|
||||||
|
} else {
|
||||||
|
console.warn("Could not add body data to form-urlencoded!", bodyData);
|
||||||
|
}
|
||||||
|
headers["Content-Type"] = "application/x-www-form-urlencoded";
|
||||||
|
} else {
|
||||||
|
console.warn(`Unsupported data type: ${dataType}`);
|
||||||
|
body = String(bodyData);
|
||||||
|
headers["Content-Type"] = "text/plain";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.doFetch(path, { method: "POST", body, headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A generic request helper.
|
||||||
|
* @param path The path to send the request to.
|
||||||
|
* @param config The request {@linkcode RequestInit | Configuration}.
|
||||||
|
*/
|
||||||
|
protected async doFetch(path: string, config: RequestInit): Promise<Response> {
|
||||||
|
config.headers = {
|
||||||
|
...config.headers,
|
||||||
|
Authorization: getCookie(SESSION_ID_COOKIE_NAME),
|
||||||
|
"Content-Type": config.headers?.["Content-Type"] ?? "application/json",
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(`Sending ${config.method ?? "GET"} request to: `, this.base + path, config);
|
||||||
|
|
||||||
|
return await fetch(this.base + path, config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to transform data to {@linkcode URLSearchParams}
|
||||||
|
* Any key with a value of `undefined` will be ignored.
|
||||||
|
* Any key with a value of `null` will be included.
|
||||||
|
* @param data the data to transform to {@linkcode URLSearchParams}
|
||||||
|
* @returns a {@linkcode URLSearchParams} representaton of {@linkcode data}
|
||||||
|
*/
|
||||||
|
protected toUrlSearchParams<D extends Record<string, any>>(data: D) {
|
||||||
|
const arr = Object.entries(data)
|
||||||
|
.map(([ key, value ]) => (value !== undefined ? [ key, String(value) ] : [ key, "" ]))
|
||||||
|
.filter(([ , value ]) => value !== "");
|
||||||
|
|
||||||
|
return new URLSearchParams(arr);
|
||||||
|
}
|
||||||
|
}
|
101
src/plugins/api/pokerogue-account-api.ts
Normal file
101
src/plugins/api/pokerogue-account-api.ts
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
import type {
|
||||||
|
AccountInfoResponse,
|
||||||
|
AccountLoginRequest,
|
||||||
|
AccountLoginResponse,
|
||||||
|
AccountRegisterRequest,
|
||||||
|
} from "#app/@types/PokerogueAccountApi";
|
||||||
|
import { SESSION_ID_COOKIE_NAME } from "#app/constants";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
import { removeCookie, setCookie } from "#app/utils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper for PokéRogue account API requests.
|
||||||
|
*/
|
||||||
|
export class PokerogueAccountApi extends ApiBase {
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request the {@linkcode AccountInfoResponse | UserInfo} of the logged in user.
|
||||||
|
* The user is identified by the {@linkcode SESSION_ID_COOKIE_NAME | session cookie}.
|
||||||
|
*/
|
||||||
|
public async getInfo(): Promise<[data: AccountInfoResponse | null, status: number]> {
|
||||||
|
try {
|
||||||
|
const response = await this.doGet("/account/info");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const resData = (await response.json()) as AccountInfoResponse;
|
||||||
|
return [ resData, response.status ];
|
||||||
|
} else {
|
||||||
|
console.warn("Could not get account info!", response.status, response.statusText);
|
||||||
|
return [ null, response.status ];
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get account info!", err);
|
||||||
|
return [ null, 500 ];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a new account.
|
||||||
|
* @param registerData The {@linkcode AccountRegisterRequest} to send
|
||||||
|
* @returns An error message if something went wrong
|
||||||
|
*/
|
||||||
|
public async register(registerData: AccountRegisterRequest) {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/account/register", registerData, "form-urlencoded");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
return response.text();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Register failed!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Unknown error!";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a login request.
|
||||||
|
* Sets the session cookie on success.
|
||||||
|
* @param loginData The {@linkcode AccountLoginRequest} to send
|
||||||
|
* @returns An error message if something went wrong
|
||||||
|
*/
|
||||||
|
public async login(loginData: AccountLoginRequest) {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/account/login", loginData, "form-urlencoded");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const loginResponse = (await response.json()) as AccountLoginResponse;
|
||||||
|
setCookie(SESSION_ID_COOKIE_NAME, loginResponse.token);
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
console.warn("Login failed!", response.status, response.statusText);
|
||||||
|
return response.text();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Login failed!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Unknown error!";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a logout request.
|
||||||
|
* **Always** (no matter if failed or not) removes the session cookie.
|
||||||
|
*/
|
||||||
|
public async logout() {
|
||||||
|
try {
|
||||||
|
const response = await this.doGet("/account/logout");
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`${response.status}: ${response.statusText}`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Log out failed!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeCookie(SESSION_ID_COOKIE_NAME); // we are always clearing the cookie.
|
||||||
|
}
|
||||||
|
}
|
140
src/plugins/api/pokerogue-admin-api.ts
Normal file
140
src/plugins/api/pokerogue-admin-api.ts
Normal file
@ -0,0 +1,140 @@
|
|||||||
|
import type {
|
||||||
|
LinkAccountToDiscordIdRequest,
|
||||||
|
LinkAccountToGoogledIdRequest,
|
||||||
|
SearchAccountRequest,
|
||||||
|
SearchAccountResponse,
|
||||||
|
UnlinkAccountFromDiscordIdRequest,
|
||||||
|
UnlinkAccountFromGoogledIdRequest,
|
||||||
|
} from "#app/@types/PokerogueAdminApi";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
|
||||||
|
export class PokerogueAdminApi extends ApiBase {
|
||||||
|
public readonly ERR_USERNAME_NOT_FOUND: string = "Username not found!";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Links an account to a discord id.
|
||||||
|
* @param params The {@linkcode LinkAccountToDiscordIdRequest} to send
|
||||||
|
* @returns `null` if successful, error message if not
|
||||||
|
*/
|
||||||
|
public async linkAccountToDiscord(params: LinkAccountToDiscordIdRequest) {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/admin/account/discordLink", params, "form-urlencoded");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
console.warn("Could not link account with discord!", response.status, response.statusText);
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
return this.ERR_USERNAME_NOT_FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not link account with discord!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.ERR_GENERIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlinks an account from a discord id.
|
||||||
|
* @param params The {@linkcode UnlinkAccountFromDiscordIdRequest} to send
|
||||||
|
* @returns `null` if successful, error message if not
|
||||||
|
*/
|
||||||
|
public async unlinkAccountFromDiscord(params: UnlinkAccountFromDiscordIdRequest) {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/admin/account/discordUnlink", params, "form-urlencoded");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
console.warn("Could not unlink account from discord!", response.status, response.statusText);
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
return this.ERR_USERNAME_NOT_FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not unlink account from discord!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.ERR_GENERIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Links an account to a google id.
|
||||||
|
* @param params The {@linkcode LinkAccountToGoogledIdRequest} to send
|
||||||
|
* @returns `null` if successful, error message if not
|
||||||
|
*/
|
||||||
|
public async linkAccountToGoogleId(params: LinkAccountToGoogledIdRequest) {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/admin/account/googleLink", params, "form-urlencoded");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
console.warn("Could not link account with google!", response.status, response.statusText);
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
return this.ERR_USERNAME_NOT_FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not link account with google!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.ERR_GENERIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlinks an account from a google id.
|
||||||
|
* @param params The {@linkcode UnlinkAccountFromGoogledIdRequest} to send
|
||||||
|
* @returns `null` if successful, error message if not
|
||||||
|
*/
|
||||||
|
public async unlinkAccountFromGoogleId(params: UnlinkAccountFromGoogledIdRequest) {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/admin/account/googleUnlink", params, "form-urlencoded");
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
console.warn("Could not unlink account from google!", response.status, response.statusText);
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
return this.ERR_USERNAME_NOT_FOUND;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not unlink account from google!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.ERR_GENERIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search an account.
|
||||||
|
* @param params The {@linkcode SearchAccountRequest} to send
|
||||||
|
* @returns an array of {@linkcode SearchAccountResponse} and error. Both can be `undefined`
|
||||||
|
*/
|
||||||
|
public async searchAccount(params: SearchAccountRequest): Promise<[data?: SearchAccountResponse, error?: string]> {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/admin/account/adminSearch?${urlSearchParams}`);
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const resData: SearchAccountResponse = await response.json();
|
||||||
|
return [ resData, undefined ];
|
||||||
|
} else {
|
||||||
|
console.warn("Could not find account!", response.status, response.statusText);
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
return [ undefined, this.ERR_USERNAME_NOT_FOUND ];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not find account!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [ undefined, this.ERR_GENERIC ];
|
||||||
|
}
|
||||||
|
}
|
83
src/plugins/api/pokerogue-api.ts
Normal file
83
src/plugins/api/pokerogue-api.ts
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
import type { TitleStatsResponse } from "#app/@types/PokerogueApi";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
import { PokerogueAccountApi } from "#app/plugins/api/pokerogue-account-api";
|
||||||
|
import { PokerogueAdminApi } from "#app/plugins/api/pokerogue-admin-api";
|
||||||
|
import { PokerogueDailyApi } from "#app/plugins/api/pokerogue-daily-api";
|
||||||
|
import { PokerogueSavedataApi } from "#app/plugins/api/pokerogue-savedata-api";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper for PokéRogue API requests.
|
||||||
|
*/
|
||||||
|
export class PokerogueApi extends ApiBase {
|
||||||
|
//#region Fields∏
|
||||||
|
|
||||||
|
public readonly account: PokerogueAccountApi;
|
||||||
|
public readonly daily: PokerogueDailyApi;
|
||||||
|
public readonly admin: PokerogueAdminApi;
|
||||||
|
public readonly savedata: PokerogueSavedataApi;
|
||||||
|
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
constructor(base: string) {
|
||||||
|
super(base);
|
||||||
|
this.account = new PokerogueAccountApi(base);
|
||||||
|
this.daily = new PokerogueDailyApi(base);
|
||||||
|
this.admin = new PokerogueAdminApi(base);
|
||||||
|
this.savedata = new PokerogueSavedataApi(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request game title-stats.
|
||||||
|
*/
|
||||||
|
public async getGameTitleStats() {
|
||||||
|
try {
|
||||||
|
const response = await this.doGet("/game/titlestats");
|
||||||
|
return (await response.json()) as TitleStatsResponse;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get game title stats!", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlink the currently logged in user from Discord.
|
||||||
|
* @returns `true` if unlinking was successful, `false` if not
|
||||||
|
*/
|
||||||
|
public async unlinkDiscord() {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/auth/discord/logout");
|
||||||
|
if (response.ok) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
console.warn(`Discord unlink failed (${response.status}: ${response.statusText})`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not unlink Discord!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlink the currently logged in user from Google.
|
||||||
|
* @returns `true` if unlinking was successful, `false` if not
|
||||||
|
*/
|
||||||
|
public async unlinkGoogle() {
|
||||||
|
try {
|
||||||
|
const response = await this.doPost("/auth/google/logout");
|
||||||
|
if (response.ok) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
console.warn(`Google unlink failed (${response.status}: ${response.statusText})`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not unlink Google!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
//#endregion
|
||||||
|
}
|
||||||
|
|
||||||
|
export const pokerogueApi = new PokerogueApi(import.meta.env.VITE_SERVER_URL ?? "http://localhost:8001");
|
57
src/plugins/api/pokerogue-daily-api.ts
Normal file
57
src/plugins/api/pokerogue-daily-api.ts
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
import type { GetDailyRankingsPageCountRequest, GetDailyRankingsRequest } from "#app/@types/PokerogueDailyApi";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
import type { RankingEntry } from "#app/ui/daily-run-scoreboard";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper for daily-run PokéRogue API requests.
|
||||||
|
*/
|
||||||
|
export class PokerogueDailyApi extends ApiBase {
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request the daily-run seed.
|
||||||
|
* @returns The active daily-run seed as `string`.
|
||||||
|
*/
|
||||||
|
public async getSeed() {
|
||||||
|
try {
|
||||||
|
const response = await this.doGet("/daily/seed");
|
||||||
|
return response.text();
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get daily-run seed!", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the daily rankings for a {@linkcode ScoreboardCategory}.
|
||||||
|
* @param params The {@linkcode GetDailyRankingsRequest} to send
|
||||||
|
*/
|
||||||
|
public async getRankings(params: GetDailyRankingsRequest) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/daily/rankings?${urlSearchParams}`);
|
||||||
|
|
||||||
|
return (await response.json()) as RankingEntry[];
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get daily rankings!", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the page count of the daily rankings for a {@linkcode ScoreboardCategory}.
|
||||||
|
* @param params The {@linkcode GetDailyRankingsPageCountRequest} to send.
|
||||||
|
*/
|
||||||
|
public async getRankingsPageCount(params: GetDailyRankingsPageCountRequest) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/daily/rankingpagecount?${urlSearchParams}`);
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
return Number(json);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get daily rankings page count!", err);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
41
src/plugins/api/pokerogue-savedata-api.ts
Normal file
41
src/plugins/api/pokerogue-savedata-api.ts
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
import type { UpdateAllSavedataRequest } from "#app/@types/PokerogueSavedataApi";
|
||||||
|
import { MAX_INT_ATTR_VALUE } from "#app/constants";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
import { PokerogueSessionSavedataApi } from "#app/plugins/api/pokerogue-session-savedata-api";
|
||||||
|
import { PokerogueSystemSavedataApi } from "#app/plugins/api/pokerogue-system-savedata-api";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper for PokéRogue savedata API requests.
|
||||||
|
*/
|
||||||
|
export class PokerogueSavedataApi extends ApiBase {
|
||||||
|
//#region Fields
|
||||||
|
|
||||||
|
public readonly system: PokerogueSystemSavedataApi;
|
||||||
|
public readonly session: PokerogueSessionSavedataApi;
|
||||||
|
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
constructor(base: string) {
|
||||||
|
super(base);
|
||||||
|
this.system = new PokerogueSystemSavedataApi(base);
|
||||||
|
this.session = new PokerogueSessionSavedataApi(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update all savedata
|
||||||
|
* @param bodyData The {@linkcode UpdateAllSavedataRequest | request data} to send
|
||||||
|
* @returns An error message if something went wrong
|
||||||
|
*/
|
||||||
|
public async updateAll(bodyData: UpdateAllSavedataRequest) {
|
||||||
|
try {
|
||||||
|
const rawBodyData = JSON.stringify(bodyData, (_k: any, v: any) =>
|
||||||
|
typeof v === "bigint" ? (v <= MAX_INT_ATTR_VALUE ? Number(v) : v.toString()) : v
|
||||||
|
);
|
||||||
|
const response = await this.doPost("/savedata/updateall", rawBodyData);
|
||||||
|
return await response.text();
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not update all savedata!", err);
|
||||||
|
return "Unknown error";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
115
src/plugins/api/pokerogue-session-savedata-api.ts
Normal file
115
src/plugins/api/pokerogue-session-savedata-api.ts
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
import type {
|
||||||
|
ClearSessionSavedataRequest,
|
||||||
|
ClearSessionSavedataResponse,
|
||||||
|
DeleteSessionSavedataRequest,
|
||||||
|
GetSessionSavedataRequest,
|
||||||
|
NewClearSessionSavedataRequest,
|
||||||
|
UpdateSessionSavedataRequest,
|
||||||
|
} from "#app/@types/PokerogueSessionSavedataApi";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
import type { SessionSaveData } from "#app/system/game-data";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper for PokéRogue session savedata API requests.
|
||||||
|
*/
|
||||||
|
export class PokerogueSessionSavedataApi extends ApiBase {
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark a session as cleared aka "newclear".\
|
||||||
|
* *This is **NOT** the same as {@linkcode clear | clear()}.*
|
||||||
|
* @param params The {@linkcode NewClearSessionSavedataRequest} to send
|
||||||
|
* @returns The raw savedata as `string`.
|
||||||
|
*/
|
||||||
|
public async newclear(params: NewClearSessionSavedataRequest) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/savedata/session/newclear?${urlSearchParams}`);
|
||||||
|
const json = await response.json();
|
||||||
|
|
||||||
|
return Boolean(json);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not newclear session!", err);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a session savedata.
|
||||||
|
* @param params The {@linkcode GetSessionSavedataRequest} to send
|
||||||
|
* @returns The session as `string`
|
||||||
|
*/
|
||||||
|
public async get(params: GetSessionSavedataRequest) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/savedata/session/get?${urlSearchParams}`);
|
||||||
|
|
||||||
|
return await response.text();
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get session savedata!", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a session savedata.
|
||||||
|
* @param params The {@linkcode UpdateSessionSavedataRequest} to send
|
||||||
|
* @param rawSavedata The raw savedata (as `string`)
|
||||||
|
* @returns An error message if something went wrong
|
||||||
|
*/
|
||||||
|
public async update(params: UpdateSessionSavedataRequest, rawSavedata: string) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doPost(`/savedata/session/update?${urlSearchParams}`, rawSavedata);
|
||||||
|
|
||||||
|
return await response.text();
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not update session savedata!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Unknown Error!";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a session savedata slot.
|
||||||
|
* @param params The {@linkcode DeleteSessionSavedataRequest} to send
|
||||||
|
* @returns An error message if something went wrong
|
||||||
|
*/
|
||||||
|
public async delete(params: DeleteSessionSavedataRequest) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/savedata/session/delete?${urlSearchParams}`);
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
return await response.text();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not delete session savedata!", err);
|
||||||
|
return "Unknown error";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears the session savedata of the given slot.\
|
||||||
|
* *This is **NOT** the same as {@linkcode newclear | newclear()}.*
|
||||||
|
* @param params The {@linkcode ClearSessionSavedataRequest} to send
|
||||||
|
* @param sessionData The {@linkcode SessionSaveData} object
|
||||||
|
*/
|
||||||
|
public async clear(params: ClearSessionSavedataRequest, sessionData: SessionSaveData) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doPost(`/savedata/session/clear?${urlSearchParams}`, sessionData);
|
||||||
|
|
||||||
|
return (await response.json()) as ClearSessionSavedataResponse;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not clear session savedata!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
error: "Unknown error",
|
||||||
|
success: false,
|
||||||
|
} as ClearSessionSavedataResponse;
|
||||||
|
}
|
||||||
|
}
|
77
src/plugins/api/pokerogue-system-savedata-api.ts
Normal file
77
src/plugins/api/pokerogue-system-savedata-api.ts
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
import type {
|
||||||
|
GetSystemSavedataRequest,
|
||||||
|
UpdateSystemSavedataRequest,
|
||||||
|
VerifySystemSavedataRequest,
|
||||||
|
VerifySystemSavedataResponse,
|
||||||
|
} from "#app/@types/PokerogueSystemSavedataApi";
|
||||||
|
import { ApiBase } from "#app/plugins/api/api-base";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper for PokéRogue system savedata API requests.
|
||||||
|
*/
|
||||||
|
export class PokerogueSystemSavedataApi extends ApiBase {
|
||||||
|
//#region Public
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a system savedata.
|
||||||
|
* @param params The {@linkcode GetSystemSavedataRequest} to send
|
||||||
|
* @returns The system savedata as `string` or `null` on error
|
||||||
|
*/
|
||||||
|
public async get(params: GetSystemSavedataRequest) {
|
||||||
|
try {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/savedata/system/get?${urlSearchParams}`);
|
||||||
|
const rawSavedata = await response.text();
|
||||||
|
|
||||||
|
return rawSavedata;
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not get system savedata!", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify if the session is valid.
|
||||||
|
* If not the {@linkcode SystemSaveData} is returned.
|
||||||
|
* @param params The {@linkcode VerifySystemSavedataRequest} to send
|
||||||
|
* @returns A {@linkcode SystemSaveData} if **NOT** valid, otherwise `null`.
|
||||||
|
*
|
||||||
|
* TODO: add handling for errors
|
||||||
|
*/
|
||||||
|
public async verify(params: VerifySystemSavedataRequest) {
|
||||||
|
const urlSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doGet(`/savedata/system/verify?${urlSearchParams}`);
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const verifySavedata = (await response.json()) as VerifySystemSavedataResponse;
|
||||||
|
|
||||||
|
if (!verifySavedata.valid) {
|
||||||
|
console.warn("Invalid system savedata!");
|
||||||
|
return verifySavedata.systemData;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn("System savedata verification failed!", response.status, response.statusText);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a system savedata.
|
||||||
|
* @param params The {@linkcode UpdateSystemSavedataRequest} to send
|
||||||
|
* @param rawSystemData The raw {@linkcode SystemSaveData}
|
||||||
|
* @returns An error message if something went wrong
|
||||||
|
*/
|
||||||
|
public async update(params: UpdateSystemSavedataRequest, rawSystemData: string) {
|
||||||
|
try {
|
||||||
|
const urSearchParams = this.toUrlSearchParams(params);
|
||||||
|
const response = await this.doPost(`/savedata/system/update?${urSearchParams}`, rawSystemData);
|
||||||
|
|
||||||
|
return await response.text();
|
||||||
|
} catch (err) {
|
||||||
|
console.warn("Could not update system savedata!", err);
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Unknown Error";
|
||||||
|
}
|
||||||
|
}
|
@ -48,7 +48,7 @@ import { RUN_HISTORY_LIMIT } from "#app/ui/run-history-ui-handler";
|
|||||||
import { applySessionVersionMigration, applySystemVersionMigration, applySettingsVersionMigration } from "./version_migration/version_converter";
|
import { applySessionVersionMigration, applySystemVersionMigration, applySettingsVersionMigration } from "./version_migration/version_converter";
|
||||||
import { MysteryEncounterSaveData } from "#app/data/mystery-encounters/mystery-encounter-save-data";
|
import { MysteryEncounterSaveData } from "#app/data/mystery-encounters/mystery-encounter-save-data";
|
||||||
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
|
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
|
||||||
import { PokerogueApiClearSessionData } from "#app/@types/pokerogue-api";
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
import { ArenaTrapTag } from "#app/data/arena-tag";
|
import { ArenaTrapTag } from "#app/data/arena-tag";
|
||||||
|
|
||||||
export const defaultStarterSpecies: Species[] = [
|
export const defaultStarterSpecies: Species[] = [
|
||||||
@ -397,8 +397,7 @@ export class GameData {
|
|||||||
localStorage.setItem(`data_${loggedInUser?.username}`, encrypt(systemData, bypassLogin));
|
localStorage.setItem(`data_${loggedInUser?.username}`, encrypt(systemData, bypassLogin));
|
||||||
|
|
||||||
if (!bypassLogin) {
|
if (!bypassLogin) {
|
||||||
Utils.apiPost(`savedata/system/update?clientSessionId=${clientSessionId}`, systemData, undefined, true)
|
pokerogueApi.savedata.system.update({ clientSessionId }, systemData)
|
||||||
.then(response => response.text())
|
|
||||||
.then(error => {
|
.then(error => {
|
||||||
this.scene.ui.savingIcon.hide();
|
this.scene.ui.savingIcon.hide();
|
||||||
if (error) {
|
if (error) {
|
||||||
@ -428,23 +427,22 @@ export class GameData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!bypassLogin) {
|
if (!bypassLogin) {
|
||||||
Utils.apiFetch(`savedata/system/get?clientSessionId=${clientSessionId}`, true)
|
pokerogueApi.savedata.system.get({ clientSessionId })
|
||||||
.then(response => response.text())
|
.then(saveDataOrErr => {
|
||||||
.then(response => {
|
if (!saveDataOrErr || saveDataOrErr.length === 0 || saveDataOrErr[0] !== "{") {
|
||||||
if (!response.length || response[0] !== "{") {
|
if (saveDataOrErr?.startsWith("sql: no rows in result set")) {
|
||||||
if (response.startsWith("sql: no rows in result set")) {
|
|
||||||
this.scene.queueMessage("Save data could not be found. If this is a new account, you can safely ignore this message.", null, true);
|
this.scene.queueMessage("Save data could not be found. If this is a new account, you can safely ignore this message.", null, true);
|
||||||
return resolve(true);
|
return resolve(true);
|
||||||
} else if (response.indexOf("Too many connections") > -1) {
|
} else if (saveDataOrErr?.includes("Too many connections")) {
|
||||||
this.scene.queueMessage("Too many people are trying to connect and the server is overloaded. Please try again later.", null, true);
|
this.scene.queueMessage("Too many people are trying to connect and the server is overloaded. Please try again later.", null, true);
|
||||||
return resolve(false);
|
return resolve(false);
|
||||||
}
|
}
|
||||||
console.error(response);
|
console.error(saveDataOrErr);
|
||||||
return resolve(false);
|
return resolve(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cachedSystem = localStorage.getItem(`data_${loggedInUser?.username}`);
|
const cachedSystem = localStorage.getItem(`data_${loggedInUser?.username}`);
|
||||||
this.initSystem(response, cachedSystem ? AES.decrypt(cachedSystem, saveKey).toString(enc.Utf8) : undefined).then(resolve);
|
this.initSystem(saveDataOrErr, cachedSystem ? AES.decrypt(cachedSystem, saveKey).toString(enc.Utf8) : undefined).then(resolve);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
this.initSystem(decrypt(localStorage.getItem(`data_${loggedInUser?.username}`)!, bypassLogin)).then(resolve); // TODO: is this bang correct?
|
this.initSystem(decrypt(localStorage.getItem(`data_${loggedInUser?.username}`)!, bypassLogin)).then(resolve); // TODO: is this bang correct?
|
||||||
@ -580,6 +578,7 @@ export class GameData {
|
|||||||
if (!Utils.isLocal) {
|
if (!Utils.isLocal) {
|
||||||
/**
|
/**
|
||||||
* Networking Code DO NOT DELETE!
|
* Networking Code DO NOT DELETE!
|
||||||
|
* Note: Might have to be migrated to `pokerogue-api.ts`
|
||||||
*
|
*
|
||||||
const response = await Utils.apiFetch("savedata/runHistory", true);
|
const response = await Utils.apiFetch("savedata/runHistory", true);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
@ -660,6 +659,7 @@ export class GameData {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
NOTE: should be adopted to `pokerogue-api.ts`
|
||||||
*/
|
*/
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -704,12 +704,11 @@ export class GameData {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await Utils.apiFetch(`savedata/system/verify?clientSessionId=${clientSessionId}`, true)
|
const systemData = await pokerogueApi.savedata.system.verify({ clientSessionId });
|
||||||
.then(response => response.json());
|
|
||||||
|
|
||||||
if (!response.valid) {
|
if (systemData) {
|
||||||
this.scene.clearPhaseQueue();
|
this.scene.clearPhaseQueue();
|
||||||
this.scene.unshiftPhase(new ReloadSessionPhase(this.scene, JSON.stringify(response.systemData)));
|
this.scene.unshiftPhase(new ReloadSessionPhase(this.scene, JSON.stringify(systemData)));
|
||||||
this.clearLocalData();
|
this.clearLocalData();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -984,10 +983,9 @@ export class GameData {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (!bypassLogin && !localStorage.getItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`)) {
|
if (!bypassLogin && !localStorage.getItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`)) {
|
||||||
Utils.apiFetch(`savedata/session/get?slot=${slotId}&clientSessionId=${clientSessionId}`, true)
|
pokerogueApi.savedata.session.get({ slot: slotId, clientSessionId })
|
||||||
.then(response => response.text())
|
|
||||||
.then(async response => {
|
.then(async response => {
|
||||||
if (!response.length || response[0] !== "{") {
|
if (!response || response?.length === 0 || response?.[0] !== "{") {
|
||||||
console.error(response);
|
console.error(response);
|
||||||
return resolve(null);
|
return resolve(null);
|
||||||
}
|
}
|
||||||
@ -1149,14 +1147,7 @@ export class GameData {
|
|||||||
if (success !== null && !success) {
|
if (success !== null && !success) {
|
||||||
return resolve(false);
|
return resolve(false);
|
||||||
}
|
}
|
||||||
Utils.apiFetch(`savedata/session/delete?slot=${slotId}&clientSessionId=${clientSessionId}`, true).then(response => {
|
pokerogueApi.savedata.session.delete({ slot: slotId, clientSessionId }).then(error => {
|
||||||
if (response.ok) {
|
|
||||||
loggedInUser!.lastSessionSlot = -1; // TODO: is the bang correct?
|
|
||||||
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
|
||||||
resolve(true);
|
|
||||||
}
|
|
||||||
return response.text();
|
|
||||||
}).then(error => {
|
|
||||||
if (error) {
|
if (error) {
|
||||||
if (error.startsWith("session out of date")) {
|
if (error.startsWith("session out of date")) {
|
||||||
this.scene.clearPhaseQueue();
|
this.scene.clearPhaseQueue();
|
||||||
@ -1164,8 +1155,15 @@ export class GameData {
|
|||||||
}
|
}
|
||||||
console.error(error);
|
console.error(error);
|
||||||
resolve(false);
|
resolve(false);
|
||||||
|
} else {
|
||||||
|
if (loggedInUser) {
|
||||||
|
loggedInUser.lastSessionSlot = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
||||||
|
resolve(true);
|
||||||
|
|
||||||
}
|
}
|
||||||
resolve(true);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -1215,17 +1213,15 @@ export class GameData {
|
|||||||
result = [ true, true ];
|
result = [ true, true ];
|
||||||
} else {
|
} else {
|
||||||
const sessionData = this.getSessionSaveData(scene);
|
const sessionData = this.getSessionSaveData(scene);
|
||||||
const response = await Utils.apiPost(`savedata/session/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`, JSON.stringify(sessionData), undefined, true);
|
const { trainerId } = this;
|
||||||
|
const jsonResponse = await pokerogueApi.savedata.session.clear({ slot: slotId, trainerId, clientSessionId }, sessionData);
|
||||||
|
|
||||||
if (response.ok) {
|
if (!jsonResponse?.error) {
|
||||||
loggedInUser!.lastSessionSlot = -1; // TODO: is the bang correct?
|
result = [ true, jsonResponse?.success ?? false ];
|
||||||
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
if (loggedInUser) {
|
||||||
}
|
loggedInUser!.lastSessionSlot = -1;
|
||||||
|
}
|
||||||
const jsonResponse: PokerogueApiClearSessionData = await response.json();
|
localStorage.removeItem(`sessionData${slotId ? slotId : ""}_${loggedInUser?.username}`);
|
||||||
|
|
||||||
if (!jsonResponse.error) {
|
|
||||||
result = [ true, jsonResponse.success ?? false ];
|
|
||||||
} else {
|
} else {
|
||||||
if (jsonResponse && jsonResponse.error?.startsWith("session out of date")) {
|
if (jsonResponse && jsonResponse.error?.startsWith("session out of date")) {
|
||||||
this.scene.clearPhaseQueue();
|
this.scene.clearPhaseQueue();
|
||||||
@ -1342,8 +1338,7 @@ export class GameData {
|
|||||||
console.debug("Session data saved");
|
console.debug("Session data saved");
|
||||||
|
|
||||||
if (!bypassLogin && sync) {
|
if (!bypassLogin && sync) {
|
||||||
Utils.apiPost("savedata/updateall", JSON.stringify(request, (k: any, v: any) => typeof v === "bigint" ? v <= maxIntAttrValue ? Number(v) : v.toString() : v), undefined, true)
|
pokerogueApi.savedata.updateAll(request)
|
||||||
.then(response => response.text())
|
|
||||||
.then(error => {
|
.then(error => {
|
||||||
if (sync) {
|
if (sync) {
|
||||||
this.scene.lastSavePlayTime = 0;
|
this.scene.lastSavePlayTime = 0;
|
||||||
@ -1387,18 +1382,24 @@ export class GameData {
|
|||||||
link.remove();
|
link.remove();
|
||||||
};
|
};
|
||||||
if (!bypassLogin && dataType < GameDataType.SETTINGS) {
|
if (!bypassLogin && dataType < GameDataType.SETTINGS) {
|
||||||
Utils.apiFetch(`savedata/${dataType === GameDataType.SYSTEM ? "system" : "session"}/get?clientSessionId=${clientSessionId}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ""}`, true)
|
let promise: Promise<string | null> = Promise.resolve(null);
|
||||||
.then(response => response.text())
|
|
||||||
.then(response => {
|
|
||||||
if (!response.length || response[0] !== "{") {
|
|
||||||
console.error(response);
|
|
||||||
resolve(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
handleData(response);
|
if (dataType === GameDataType.SYSTEM) {
|
||||||
resolve(true);
|
promise = pokerogueApi.savedata.system.get({ clientSessionId });
|
||||||
});
|
} else if (dataType === GameDataType.SESSION) {
|
||||||
|
promise = pokerogueApi.savedata.session.get({ slot: slotId, clientSessionId });
|
||||||
|
}
|
||||||
|
|
||||||
|
promise.then(response => {
|
||||||
|
if (!response?.length || response[0] !== "{") {
|
||||||
|
console.error(response);
|
||||||
|
resolve(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleData(response);
|
||||||
|
resolve(true);
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
const data = localStorage.getItem(dataKey);
|
const data = localStorage.getItem(dataKey);
|
||||||
if (data) {
|
if (data) {
|
||||||
@ -1477,14 +1478,14 @@ export class GameData {
|
|||||||
if (!success[0]) {
|
if (!success[0]) {
|
||||||
return displayError(`Could not contact the server. Your ${dataName} data could not be imported.`);
|
return displayError(`Could not contact the server. Your ${dataName} data could not be imported.`);
|
||||||
}
|
}
|
||||||
let url: string;
|
const { trainerId, secretId } = this;
|
||||||
|
let updatePromise: Promise<string | null>;
|
||||||
if (dataType === GameDataType.SESSION) {
|
if (dataType === GameDataType.SESSION) {
|
||||||
url = `savedata/session/update?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`;
|
updatePromise = pokerogueApi.savedata.session.update({ slot: slotId, trainerId, secretId, clientSessionId }, dataStr);
|
||||||
} else {
|
} else {
|
||||||
url = `savedata/system/update?trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`;
|
updatePromise = pokerogueApi.savedata.system.update({ trainerId, secretId, clientSessionId }, dataStr);
|
||||||
}
|
}
|
||||||
Utils.apiPost(url, dataStr, undefined, true)
|
updatePromise
|
||||||
.then(response => response.text())
|
|
||||||
.then(error => {
|
.then(error => {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
224
src/test/abilities/commander.test.ts
Normal file
224
src/test/abilities/commander.test.ts
Normal file
@ -0,0 +1,224 @@
|
|||||||
|
import { BattlerIndex } from "#app/battle";
|
||||||
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
|
import { PokemonAnimType } from "#enums/pokemon-anim-type";
|
||||||
|
import { EffectiveStat, Stat } from "#enums/stat";
|
||||||
|
import { StatusEffect } from "#enums/status-effect";
|
||||||
|
import { WeatherType } from "#enums/weather-type";
|
||||||
|
import { MoveResult } from "#app/field/pokemon";
|
||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
describe("Abilities - Commander", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.startingLevel(100)
|
||||||
|
.enemyLevel(100)
|
||||||
|
.moveset([ Moves.LIQUIDATION, Moves.MEMENTO, Moves.SPLASH, Moves.FLIP_TURN ])
|
||||||
|
.ability(Abilities.COMMANDER)
|
||||||
|
.battleType("double")
|
||||||
|
.disableCrits()
|
||||||
|
.enemySpecies(Species.SNORLAX)
|
||||||
|
.enemyAbility(Abilities.BALL_FETCH)
|
||||||
|
.enemyMoveset(Moves.TACKLE);
|
||||||
|
|
||||||
|
vi.spyOn(game.scene, "triggerPokemonBattleAnim").mockReturnValue(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("causes the source to jump into Dondozo's mouth, granting a stat boost and hiding the source", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
const affectedStats: EffectiveStat[] = [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ];
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
affectedStats.forEach((stat) => expect(dondozo.getStatStage(stat)).toBe(2));
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH, 1);
|
||||||
|
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
// Force both enemies to target the Tatsugiri
|
||||||
|
await game.forceEnemyMove(Moves.TACKLE, BattlerIndex.PLAYER);
|
||||||
|
await game.forceEnemyMove(Moves.TACKLE, BattlerIndex.PLAYER);
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("BerryPhase", false);
|
||||||
|
game.scene.getEnemyField().forEach(enemy => expect(enemy.getLastXMoves(1)[0].result).toBe(MoveResult.MISS));
|
||||||
|
expect(tatsugiri.isFullHp()).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should activate when a Dondozo switches in and cancel the source's move", async () => {
|
||||||
|
game.override.enemyMoveset(Moves.SPLASH);
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.MAGIKARP, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const tatsugiri = game.scene.getPlayerField()[0];
|
||||||
|
|
||||||
|
game.move.select(Moves.LIQUIDATION, 0, BattlerIndex.ENEMY);
|
||||||
|
game.doSwitchPokemon(2);
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("MovePhase", false);
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
|
||||||
|
const dondozo = game.scene.getPlayerField()[1];
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("BerryPhase", false);
|
||||||
|
expect(tatsugiri.getMoveHistory()).toHaveLength(0);
|
||||||
|
expect(game.scene.getEnemyField()[0].isFullHp()).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("source should reenter the field when Dondozo faints", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.MEMENTO, 1, BattlerIndex.ENEMY);
|
||||||
|
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.forceEnemyMove(Moves.TACKLE, BattlerIndex.PLAYER);
|
||||||
|
await game.forceEnemyMove(Moves.TACKLE, BattlerIndex.PLAYER);
|
||||||
|
|
||||||
|
await game.setTurnOrder([ BattlerIndex.PLAYER_2, BattlerIndex.ENEMY, BattlerIndex.ENEMY_2, BattlerIndex.PLAYER ]);
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("FaintPhase", false);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeUndefined();
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(dondozo, PokemonAnimType.COMMANDER_REMOVE);
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("BerryPhase", false);
|
||||||
|
expect(tatsugiri.isFullHp()).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("source should still take damage from Poison while hidden", async () => {
|
||||||
|
game.override
|
||||||
|
.statusEffect(StatusEffect.POISON)
|
||||||
|
.enemyMoveset(Moves.SPLASH);
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH, 1);
|
||||||
|
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("TurnEndPhase");
|
||||||
|
expect(tatsugiri.isFullHp()).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("source should still take damage from Salt Cure while hidden", async () => {
|
||||||
|
game.override.enemyMoveset(Moves.SPLASH);
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
tatsugiri.addTag(BattlerTagType.SALT_CURED, 0, Moves.NONE, game.scene.getField()[BattlerIndex.ENEMY].id);
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH, 1);
|
||||||
|
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("TurnEndPhase");
|
||||||
|
expect(tatsugiri.isFullHp()).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("source should still take damage from Sandstorm while hidden", async () => {
|
||||||
|
game.override
|
||||||
|
.weather(WeatherType.SANDSTORM)
|
||||||
|
.enemyMoveset(Moves.SPLASH);
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH, 1);
|
||||||
|
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("TurnEndPhase");
|
||||||
|
expect(tatsugiri.isFullHp()).toBeFalsy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should make Dondozo immune to being forced out", async () => {
|
||||||
|
game.override.enemyMoveset([ Moves.SPLASH, Moves.WHIRLWIND ]);
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH, 1);
|
||||||
|
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.forceEnemyMove(Moves.WHIRLWIND, BattlerIndex.PLAYER_2);
|
||||||
|
await game.forceEnemyMove(Moves.SPLASH);
|
||||||
|
|
||||||
|
// Test may time out here if Whirlwind forced out a Pokemon
|
||||||
|
await game.phaseInterceptor.to("TurnEndPhase");
|
||||||
|
expect(dondozo.isActive(true)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should interrupt the source's semi-invulnerability", async () => {
|
||||||
|
game.override
|
||||||
|
.moveset([ Moves.SPLASH, Moves.DIVE ])
|
||||||
|
.enemyMoveset(Moves.SPLASH);
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.MAGIKARP, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const tatsugiri = game.scene.getPlayerField()[0];
|
||||||
|
|
||||||
|
game.move.select(Moves.DIVE, 0, BattlerIndex.ENEMY);
|
||||||
|
game.move.select(Moves.SPLASH, 1);
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("CommandPhase");
|
||||||
|
await game.toNextTurn();
|
||||||
|
|
||||||
|
expect(tatsugiri.getTag(BattlerTagType.UNDERWATER)).toBeDefined();
|
||||||
|
game.doSwitchPokemon(2);
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("MovePhase", false);
|
||||||
|
const dondozo = game.scene.getPlayerField()[1];
|
||||||
|
expect(tatsugiri.getTag(BattlerTagType.UNDERWATER)).toBeUndefined();
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
await game.toNextTurn();
|
||||||
|
const enemy = game.scene.getEnemyField()[0];
|
||||||
|
expect(enemy.isFullHp()).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
46
src/test/abilities/corrosion.test.ts
Normal file
46
src/test/abilities/corrosion.test.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
describe("Abilities - Corrosion", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.moveset([ Moves.SPLASH ])
|
||||||
|
.battleType("single")
|
||||||
|
.disableCrits()
|
||||||
|
.enemySpecies(Species.GRIMER)
|
||||||
|
.enemyAbility(Abilities.CORROSION)
|
||||||
|
.enemyMoveset(Moves.TOXIC);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("If a Poison- or Steel-type Pokémon with this Ability poisons a target with Synchronize, Synchronize does not gain the ability to poison Poison- or Steel-type Pokémon.", async () => {
|
||||||
|
game.override.ability(Abilities.SYNCHRONIZE);
|
||||||
|
await game.classicMode.startBattle([ Species.FEEBAS ]);
|
||||||
|
|
||||||
|
const playerPokemon = game.scene.getPlayerPokemon();
|
||||||
|
const enemyPokemon = game.scene.getEnemyPokemon();
|
||||||
|
expect(playerPokemon!.status).toBeUndefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH);
|
||||||
|
await game.phaseInterceptor.to("BerryPhase");
|
||||||
|
expect(playerPokemon!.status).toBeDefined();
|
||||||
|
expect(enemyPokemon!.status).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
@ -94,16 +94,4 @@ describe("Abilities - Synchronize", () => {
|
|||||||
expect(game.scene.getEnemyPokemon()!.status?.effect).toBe(StatusEffect.PARALYSIS);
|
expect(game.scene.getEnemyPokemon()!.status?.effect).toBe(StatusEffect.PARALYSIS);
|
||||||
expect(game.phaseInterceptor.log).toContain("ShowAbilityPhase");
|
expect(game.phaseInterceptor.log).toContain("ShowAbilityPhase");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should activate with Psycho Shift after the move clears the status", async () => {
|
|
||||||
game.override.statusEffect(StatusEffect.PARALYSIS);
|
|
||||||
await game.classicMode.startBattle();
|
|
||||||
|
|
||||||
game.move.select(Moves.PSYCHO_SHIFT);
|
|
||||||
await game.phaseInterceptor.to("BerryPhase");
|
|
||||||
|
|
||||||
expect(game.scene.getPlayerPokemon()!.status?.effect).toBe(StatusEffect.PARALYSIS); // keeping old gen < V impl for now since it's buggy otherwise
|
|
||||||
expect(game.scene.getEnemyPokemon()!.status?.effect).toBe(StatusEffect.PARALYSIS);
|
|
||||||
expect(game.phaseInterceptor.log).toContain("ShowAbilityPhase");
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import * as battleScene from "#app/battle-scene";
|
import * as battleScene from "#app/battle-scene";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { initLoggedInUser, loggedInUser, updateUserInfo } from "../account";
|
import { initLoggedInUser, loggedInUser, updateUserInfo } from "../account";
|
||||||
import * as utils from "../utils";
|
|
||||||
|
|
||||||
describe("account", () => {
|
describe("account", () => {
|
||||||
describe("initLoggedInUser", () => {
|
describe("initLoggedInUser", () => {
|
||||||
@ -27,17 +27,16 @@ describe("account", () => {
|
|||||||
|
|
||||||
it("should fetch user info from the API if bypassLogin is false", async () => {
|
it("should fetch user info from the API if bypassLogin is false", async () => {
|
||||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
||||||
vi.spyOn(utils, "apiFetch").mockResolvedValue(
|
vi.spyOn(pokerogueApi.account, "getInfo").mockResolvedValue([
|
||||||
new Response(
|
{
|
||||||
JSON.stringify({
|
username: "test",
|
||||||
username: "test",
|
lastSessionSlot: 99,
|
||||||
lastSessionSlot: 99,
|
discordId: "",
|
||||||
}),
|
googleId: "",
|
||||||
{
|
hasAdminRole: false,
|
||||||
status: 200,
|
},
|
||||||
}
|
200,
|
||||||
)
|
]);
|
||||||
);
|
|
||||||
|
|
||||||
const [ success, status ] = await updateUserInfo();
|
const [ success, status ] = await updateUserInfo();
|
||||||
|
|
||||||
@ -49,9 +48,7 @@ describe("account", () => {
|
|||||||
|
|
||||||
it("should handle resolved API errors", async () => {
|
it("should handle resolved API errors", async () => {
|
||||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
||||||
vi.spyOn(utils, "apiFetch").mockResolvedValue(
|
vi.spyOn(pokerogueApi.account, "getInfo").mockResolvedValue([ null, 401 ]);
|
||||||
new Response(null, { status: 401 })
|
|
||||||
);
|
|
||||||
|
|
||||||
const [ success, status ] = await updateUserInfo();
|
const [ success, status ] = await updateUserInfo();
|
||||||
|
|
||||||
@ -59,16 +56,14 @@ describe("account", () => {
|
|||||||
expect(status).toBe(401);
|
expect(status).toBe(401);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should handle rejected API errors", async () => {
|
it("should handle 500 API errors", async () => {
|
||||||
const consoleErrorSpy = vi.spyOn(console, "error");
|
|
||||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(false);
|
||||||
vi.spyOn(utils, "apiFetch").mockRejectedValue(new Error("Api failed!"));
|
vi.spyOn(pokerogueApi.account, "getInfo").mockResolvedValue([ null, 500 ]);
|
||||||
|
|
||||||
const [ success, status ] = await updateUserInfo();
|
const [ success, status ] = await updateUserInfo();
|
||||||
|
|
||||||
expect(success).toBe(false);
|
expect(success).toBe(false);
|
||||||
expect(status).toBe(500);
|
expect(status).toBe(500);
|
||||||
expect(consoleErrorSpy).toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -1,11 +1,12 @@
|
|||||||
import { MapModifier } from "#app/modifier/modifier";
|
|
||||||
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
|
||||||
import GameManager from "./utils/gameManager";
|
|
||||||
import { Moves } from "#app/enums/moves";
|
|
||||||
import { Biome } from "#app/enums/biome";
|
import { Biome } from "#app/enums/biome";
|
||||||
import { Mode } from "#app/ui/ui";
|
import { Moves } from "#app/enums/moves";
|
||||||
|
import { MapModifier } from "#app/modifier/modifier";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
import ModifierSelectUiHandler from "#app/ui/modifier-select-ui-handler";
|
import ModifierSelectUiHandler from "#app/ui/modifier-select-ui-handler";
|
||||||
import { Species } from "#enums/species";
|
import { Species } from "#enums/species";
|
||||||
|
import { Mode } from "#app/ui/ui";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import GameManager from "#app/test/utils/gameManager";
|
||||||
|
|
||||||
//const TIMEOUT = 20 * 1000;
|
//const TIMEOUT = 20 * 1000;
|
||||||
|
|
||||||
@ -21,6 +22,7 @@ describe("Daily Mode", () => {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
game = new GameManager(phaserGame);
|
game = new GameManager(phaserGame);
|
||||||
|
vi.spyOn(pokerogueApi.daily, "getSeed").mockResolvedValue("test-seed");
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@ -32,7 +34,7 @@ describe("Daily Mode", () => {
|
|||||||
|
|
||||||
const party = game.scene.getPlayerParty();
|
const party = game.scene.getPlayerParty();
|
||||||
expect(party).toHaveLength(3);
|
expect(party).toHaveLength(3);
|
||||||
party.forEach(pkm => {
|
party.forEach((pkm) => {
|
||||||
expect(pkm.level).toBe(20);
|
expect(pkm.level).toBe(20);
|
||||||
expect(pkm.moveset.length).toBeGreaterThan(0);
|
expect(pkm.moveset.length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
@ -63,6 +65,7 @@ describe("Shop modifications", async () => {
|
|||||||
game.modifiers
|
game.modifiers
|
||||||
.addCheck("EVIOLITE")
|
.addCheck("EVIOLITE")
|
||||||
.addCheck("MINI_BLACK_HOLE");
|
.addCheck("MINI_BLACK_HOLE");
|
||||||
|
vi.spyOn(pokerogueApi.daily, "getSeed").mockResolvedValue("test-seed");
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { apiFetch } from "#app/utils";
|
// import { apiFetch } from "#app/utils";
|
||||||
import GameManager from "#test/utils/gameManager";
|
import GameManager from "#test/utils/gameManager";
|
||||||
import { waitUntil } from "#test/utils/gameManagerUtils";
|
import { waitUntil } from "#test/utils/gameManagerUtils";
|
||||||
import Phaser from "phaser";
|
import Phaser from "phaser";
|
||||||
@ -35,18 +35,18 @@ describe("Test misc", () => {
|
|||||||
expect(spy).toHaveBeenCalled();
|
expect(spy).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("test apifetch mock async", async () => {
|
// it.skip("test apifetch mock async", async () => {
|
||||||
const spy = vi.fn();
|
// const spy = vi.fn();
|
||||||
await apiFetch("https://localhost:8080/account/info").then(response => {
|
// await apiFetch("https://localhost:8080/account/info").then(response => {
|
||||||
expect(response.status).toBe(200);
|
// expect(response.status).toBe(200);
|
||||||
expect(response.ok).toBe(true);
|
// expect(response.ok).toBe(true);
|
||||||
return response.json();
|
// return response.json();
|
||||||
}).then(data => {
|
// }).then(data => {
|
||||||
spy(); // Call the spy function
|
// spy(); // Call the spy function
|
||||||
expect(data).toEqual({ "username": "greenlamp", "lastSessionSlot": 0 });
|
// expect(data).toEqual({ "username": "greenlamp", "lastSessionSlot": 0 });
|
||||||
});
|
// });
|
||||||
expect(spy).toHaveBeenCalled();
|
// expect(spy).toHaveBeenCalled();
|
||||||
});
|
// });
|
||||||
|
|
||||||
it("test fetch mock sync", async () => {
|
it("test fetch mock sync", async () => {
|
||||||
const response = await fetch("https://localhost:8080/account/info");
|
const response = await fetch("https://localhost:8080/account/info");
|
||||||
|
@ -72,6 +72,31 @@ describe("Moves - Freeze-Dry", () => {
|
|||||||
expect(enemy.getMoveEffectiveness).toHaveReturnedWith(1);
|
expect(enemy.getMoveEffectiveness).toHaveReturnedWith(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Freeze drys forced super effectiveness should overwrite wonder guard
|
||||||
|
*/
|
||||||
|
it("should deal 2x dmg against soaked wonder guard target", async () => {
|
||||||
|
game.override
|
||||||
|
.enemySpecies(Species.SHEDINJA)
|
||||||
|
.enemyMoveset(Moves.SPLASH)
|
||||||
|
.starterSpecies(Species.MAGIKARP)
|
||||||
|
.moveset([ Moves.SOAK, Moves.FREEZE_DRY ]);
|
||||||
|
await game.classicMode.startBattle();
|
||||||
|
|
||||||
|
const enemy = game.scene.getEnemyPokemon()!;
|
||||||
|
vi.spyOn(enemy, "getMoveEffectiveness");
|
||||||
|
|
||||||
|
game.move.select(Moves.SOAK);
|
||||||
|
await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY ]);
|
||||||
|
await game.toNextTurn();
|
||||||
|
|
||||||
|
game.move.select(Moves.FREEZE_DRY);
|
||||||
|
await game.phaseInterceptor.to("MoveEffectPhase");
|
||||||
|
|
||||||
|
expect(enemy.getMoveEffectiveness).toHaveReturnedWith(2);
|
||||||
|
expect(enemy.hp).toBeLessThan(enemy.getMaxHp());
|
||||||
|
});
|
||||||
|
|
||||||
// enable if this is ever fixed (lol)
|
// enable if this is ever fixed (lol)
|
||||||
it.todo("should deal 2x damage to water types under Normalize", async () => {
|
it.todo("should deal 2x damage to water types under Normalize", async () => {
|
||||||
game.override.ability(Abilities.NORMALIZE);
|
game.override.ability(Abilities.NORMALIZE);
|
||||||
|
45
src/test/moves/future_sight.test.ts
Normal file
45
src/test/moves/future_sight.test.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
describe("Moves - Future Sight", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.startingLevel(50)
|
||||||
|
.moveset([ Moves.FUTURE_SIGHT, Moves.SPLASH ])
|
||||||
|
.battleType("single")
|
||||||
|
.enemySpecies(Species.MAGIKARP)
|
||||||
|
.enemyAbility(Abilities.STURDY)
|
||||||
|
.enemyMoveset(Moves.SPLASH);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hits 2 turns after use, ignores user switch out", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.FEEBAS, Species.MILOTIC ]);
|
||||||
|
|
||||||
|
game.move.select(Moves.FUTURE_SIGHT);
|
||||||
|
await game.toNextTurn();
|
||||||
|
game.doSwitchPokemon(1);
|
||||||
|
await game.toNextTurn();
|
||||||
|
game.move.select(Moves.SPLASH);
|
||||||
|
await game.toNextTurn();
|
||||||
|
|
||||||
|
expect(game.scene.getEnemyPokemon()!.isFullHp()).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
90
src/test/moves/grudge.test.ts
Normal file
90
src/test/moves/grudge.test.ts
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import { BattlerIndex } from "#app/battle";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
describe("Moves - Grudge", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.moveset([ Moves.EMBER, Moves.SPLASH ])
|
||||||
|
.ability(Abilities.BALL_FETCH)
|
||||||
|
.battleType("single")
|
||||||
|
.disableCrits()
|
||||||
|
.enemySpecies(Species.SHEDINJA)
|
||||||
|
.enemyAbility(Abilities.WONDER_GUARD)
|
||||||
|
.enemyMoveset([ Moves.GRUDGE, Moves.SPLASH ]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should reduce the PP of the Pokemon's move to 0 when the user has fainted", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.FEEBAS ]);
|
||||||
|
|
||||||
|
const playerPokemon = game.scene.getPlayerPokemon();
|
||||||
|
game.move.select(Moves.EMBER);
|
||||||
|
await game.forceEnemyMove(Moves.GRUDGE);
|
||||||
|
await game.setTurnOrder([ BattlerIndex.ENEMY, BattlerIndex.PLAYER ]);
|
||||||
|
await game.phaseInterceptor.to("BerryPhase");
|
||||||
|
|
||||||
|
const playerMove = playerPokemon?.getMoveset().find(m => m?.moveId === Moves.EMBER);
|
||||||
|
|
||||||
|
expect(playerMove?.getPpRatio()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remain in effect until the user's next move", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.FEEBAS ]);
|
||||||
|
|
||||||
|
const playerPokemon = game.scene.getPlayerPokemon();
|
||||||
|
game.move.select(Moves.SPLASH);
|
||||||
|
await game.forceEnemyMove(Moves.GRUDGE);
|
||||||
|
await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY ]);
|
||||||
|
await game.toNextTurn();
|
||||||
|
|
||||||
|
game.move.select(Moves.EMBER);
|
||||||
|
await game.forceEnemyMove(Moves.SPLASH);
|
||||||
|
await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY ]);
|
||||||
|
await game.phaseInterceptor.to("BerryPhase");
|
||||||
|
|
||||||
|
const playerMove = playerPokemon?.getMoveset().find(m => m?.moveId === Moves.EMBER);
|
||||||
|
|
||||||
|
expect(playerMove?.getPpRatio()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should not reduce the opponent's PP if the user dies to weather/indirect damage", async () => {
|
||||||
|
// Opponent will be reduced to 1 HP by False Swipe, then faint to Sandstorm
|
||||||
|
game.override
|
||||||
|
.moveset([ Moves.FALSE_SWIPE ])
|
||||||
|
.startingLevel(100)
|
||||||
|
.ability(Abilities.SAND_STREAM)
|
||||||
|
.enemySpecies(Species.RATTATA);
|
||||||
|
await game.classicMode.startBattle([ Species.GEODUDE ]);
|
||||||
|
|
||||||
|
const enemyPokemon = game.scene.getEnemyPokemon();
|
||||||
|
const playerPokemon = game.scene.getPlayerPokemon();
|
||||||
|
|
||||||
|
game.move.select(Moves.FALSE_SWIPE);
|
||||||
|
await game.forceEnemyMove(Moves.GRUDGE);
|
||||||
|
await game.setTurnOrder([ BattlerIndex.ENEMY, BattlerIndex.PLAYER ]);
|
||||||
|
await game.phaseInterceptor.to("BerryPhase");
|
||||||
|
|
||||||
|
expect(enemyPokemon?.isFainted()).toBe(true);
|
||||||
|
|
||||||
|
const playerMove = playerPokemon?.getMoveset().find(m => m?.moveId === Moves.FALSE_SWIPE);
|
||||||
|
expect(playerMove?.getPpRatio()).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
});
|
85
src/test/moves/order_up.test.ts
Normal file
85
src/test/moves/order_up.test.ts
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
import { BattlerIndex } from "#app/battle";
|
||||||
|
import { BattlerTagType } from "#enums/battler-tag-type";
|
||||||
|
import { PokemonAnimType } from "#enums/pokemon-anim-type";
|
||||||
|
import { EffectiveStat, Stat } from "#enums/stat";
|
||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
describe("Moves - Order Up", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.moveset(Moves.ORDER_UP)
|
||||||
|
.ability(Abilities.COMMANDER)
|
||||||
|
.battleType("double")
|
||||||
|
.disableCrits()
|
||||||
|
.enemySpecies(Species.SNORLAX)
|
||||||
|
.enemyAbility(Abilities.BALL_FETCH)
|
||||||
|
.enemyMoveset(Moves.SPLASH)
|
||||||
|
.startingLevel(100)
|
||||||
|
.enemyLevel(100);
|
||||||
|
|
||||||
|
vi.spyOn(game.scene, "triggerPokemonBattleAnim").mockReturnValue(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{ formIndex: 0, formName: "Curly", stat: Stat.ATK, statName: "Attack" },
|
||||||
|
{ formIndex: 1, formName: "Droopy", stat: Stat.DEF, statName: "Defense" },
|
||||||
|
{ formIndex: 2, formName: "Stretchy", stat: Stat.SPD, statName: "Speed" }
|
||||||
|
])("should raise the user's $statName when the user is commanded by a $formName Tatsugiri", async ({ formIndex, stat }) => {
|
||||||
|
game.override.starterForms({ [Species.TATSUGIRI]: formIndex });
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.ORDER_UP, 1, BattlerIndex.ENEMY);
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("BerryPhase", false);
|
||||||
|
|
||||||
|
const affectedStats: EffectiveStat[] = [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ];
|
||||||
|
affectedStats.forEach(st => expect(dondozo.getStatStage(st)).toBe(st === stat ? 3 : 2));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be boosted by Sheer Force while still applying a stat boost", async () => {
|
||||||
|
game.override
|
||||||
|
.passiveAbility(Abilities.SHEER_FORCE)
|
||||||
|
.starterForms({ [Species.TATSUGIRI]: 0 });
|
||||||
|
|
||||||
|
await game.classicMode.startBattle([ Species.TATSUGIRI, Species.DONDOZO ]);
|
||||||
|
|
||||||
|
const [ tatsugiri, dondozo ] = game.scene.getPlayerField();
|
||||||
|
|
||||||
|
expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY);
|
||||||
|
expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.ORDER_UP, 1, BattlerIndex.ENEMY);
|
||||||
|
expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy();
|
||||||
|
|
||||||
|
await game.phaseInterceptor.to("BerryPhase", false);
|
||||||
|
|
||||||
|
expect(dondozo.battleData.abilitiesApplied.includes(Abilities.SHEER_FORCE)).toBeTruthy();
|
||||||
|
expect(dondozo.getStatStage(Stat.ATK)).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
49
src/test/moves/psycho_shift.test.ts
Normal file
49
src/test/moves/psycho_shift.test.ts
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
import { StatusEffect } from "#app/enums/status-effect";
|
||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
describe("Moves - Psycho Shift", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.moveset([ Moves.PSYCHO_SHIFT ])
|
||||||
|
.ability(Abilities.BALL_FETCH)
|
||||||
|
.statusEffect(StatusEffect.POISON)
|
||||||
|
.battleType("single")
|
||||||
|
.disableCrits()
|
||||||
|
.enemySpecies(Species.MAGIKARP)
|
||||||
|
.enemyLevel(20)
|
||||||
|
.enemyAbility(Abilities.SYNCHRONIZE)
|
||||||
|
.enemyMoveset(Moves.SPLASH);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("If Psycho Shift is used on a Pokémon with Synchronize, the user of Psycho Shift will already be afflicted with a status condition when Synchronize activates", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.FEEBAS ]);
|
||||||
|
|
||||||
|
const playerPokemon = game.scene.getPlayerPokemon();
|
||||||
|
const enemyPokemon = game.scene.getEnemyPokemon();
|
||||||
|
expect(enemyPokemon?.status).toBeUndefined();
|
||||||
|
|
||||||
|
game.move.select(Moves.PSYCHO_SHIFT);
|
||||||
|
await game.phaseInterceptor.to("TurnEndPhase");
|
||||||
|
expect(playerPokemon?.status).toBeNull();
|
||||||
|
expect(enemyPokemon?.status).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
60
src/test/phases/form-change-phase.test.ts
Normal file
60
src/test/phases/form-change-phase.test.ts
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
import { Abilities } from "#enums/abilities";
|
||||||
|
import { Moves } from "#enums/moves";
|
||||||
|
import { Species } from "#enums/species";
|
||||||
|
import GameManager from "#test/utils/gameManager";
|
||||||
|
import Phaser from "phaser";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { Type } from "#app/data/type";
|
||||||
|
import { generateModifierType } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
|
||||||
|
import { modifierTypes } from "#app/modifier/modifier-type";
|
||||||
|
|
||||||
|
describe("Form Change Phase", () => {
|
||||||
|
let phaserGame: Phaser.Game;
|
||||||
|
let game: GameManager;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
phaserGame = new Phaser.Game({
|
||||||
|
type: Phaser.HEADLESS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
game.phaseInterceptor.restoreOg();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
game = new GameManager(phaserGame);
|
||||||
|
game.override
|
||||||
|
.moveset([ Moves.SPLASH ])
|
||||||
|
.ability(Abilities.BALL_FETCH)
|
||||||
|
.battleType("single")
|
||||||
|
.disableCrits()
|
||||||
|
.enemySpecies(Species.MAGIKARP)
|
||||||
|
.enemyAbility(Abilities.BALL_FETCH)
|
||||||
|
.enemyMoveset(Moves.SPLASH);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Zacian should successfully change into Crowned form", async () => {
|
||||||
|
await game.classicMode.startBattle([ Species.ZACIAN ]);
|
||||||
|
|
||||||
|
// Before the form change: Should be Hero form
|
||||||
|
const zacian = game.scene.getPlayerParty()[0];
|
||||||
|
expect(zacian.getFormKey()).toBe("hero-of-many-battles");
|
||||||
|
expect(zacian.getTypes()).toStrictEqual([ Type.FAIRY ]);
|
||||||
|
expect(zacian.calculateBaseStats()).toStrictEqual([ 92, 120, 115, 80, 115, 138 ]);
|
||||||
|
|
||||||
|
// Give Zacian a Rusted Sword
|
||||||
|
const rustedSwordType = generateModifierType(game.scene, modifierTypes.RARE_FORM_CHANGE_ITEM)!;
|
||||||
|
const rustedSword = rustedSwordType.newModifier(zacian);
|
||||||
|
await game.scene.addModifier(rustedSword);
|
||||||
|
|
||||||
|
game.move.select(Moves.SPLASH);
|
||||||
|
await game.toNextTurn();
|
||||||
|
|
||||||
|
// After the form change: Should be Crowned form
|
||||||
|
expect(game.phaseInterceptor.log.includes("FormChangePhase")).toBe(true);
|
||||||
|
expect(zacian.getFormKey()).toBe("crowned");
|
||||||
|
expect(zacian.getTypes()).toStrictEqual([ Type.FAIRY, Type.STEEL ]);
|
||||||
|
expect(zacian.calculateBaseStats()).toStrictEqual([ 92, 150, 115, 80, 115, 148 ]);
|
||||||
|
});
|
||||||
|
});
|
157
src/test/plugins/api/pokerogue-account-api.test.ts
Normal file
157
src/test/plugins/api/pokerogue-account-api.test.ts
Normal file
@ -0,0 +1,157 @@
|
|||||||
|
import type { AccountInfoResponse } from "#app/@types/PokerogueAccountApi";
|
||||||
|
import { SESSION_ID_COOKIE_NAME } from "#app/constants";
|
||||||
|
import { PokerogueAccountApi } from "#app/plugins/api/pokerogue-account-api";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import * as Utils from "#app/utils";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const accountApi = new PokerogueAccountApi(apiBase);
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue Account API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Get Info", () => {
|
||||||
|
it("should return account-info & 200 on SUCCESS", async () => {
|
||||||
|
const expectedAccountInfo: AccountInfoResponse = {
|
||||||
|
username: "test",
|
||||||
|
lastSessionSlot: -1,
|
||||||
|
discordId: "23235353543535",
|
||||||
|
googleId: "1ed1d1d11d1d1d1d1d1",
|
||||||
|
hasAdminRole: false,
|
||||||
|
};
|
||||||
|
server.use(http.get(`${apiBase}/account/info`, () => HttpResponse.json(expectedAccountInfo)));
|
||||||
|
|
||||||
|
const [ accountInfo, status ] = await accountApi.getInfo();
|
||||||
|
|
||||||
|
expect(accountInfo).toEqual(expectedAccountInfo);
|
||||||
|
expect(status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null + status-code anad report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/account/info`, () => new HttpResponse("", { status: 401 })));
|
||||||
|
|
||||||
|
const [ accountInfo, status ] = await accountApi.getInfo();
|
||||||
|
|
||||||
|
expect(accountInfo).toBeNull();
|
||||||
|
expect(status).toBe(401);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get account info!", 401, "Unauthorized");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null + 500 anad report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/account/info`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const [ accountInfo, status ] = await accountApi.getInfo();
|
||||||
|
|
||||||
|
expect(accountInfo).toBeNull();
|
||||||
|
expect(status).toBe(500);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get account info!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Register", () => {
|
||||||
|
const registerParams = { username: "test", password: "test" };
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/account/register`, () => HttpResponse.text()));
|
||||||
|
|
||||||
|
const error = await accountApi.register(registerParams);
|
||||||
|
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return error message on FAILURE", async () => {
|
||||||
|
server.use(
|
||||||
|
http.post(`${apiBase}/account/register`, () => new HttpResponse("Username is already taken", { status: 400 }))
|
||||||
|
);
|
||||||
|
|
||||||
|
const error = await accountApi.register(registerParams);
|
||||||
|
|
||||||
|
expect(error).toBe("Username is already taken");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return \"Unknown error\" and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/account/register`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const error = await accountApi.register(registerParams);
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown error!");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Register failed!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Login", () => {
|
||||||
|
const loginParams = { username: "test", password: "test" };
|
||||||
|
|
||||||
|
it("should return null and set the cookie on SUCCESS", async () => {
|
||||||
|
vi.spyOn(Utils, "setCookie");
|
||||||
|
server.use(http.post(`${apiBase}/account/login`, () => HttpResponse.json({ token: "abctest" })));
|
||||||
|
|
||||||
|
const error = await accountApi.login(loginParams);
|
||||||
|
|
||||||
|
expect(error).toBeNull();
|
||||||
|
expect(Utils.setCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME, "abctest");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return error message and report a warning on FAILURE", async () => {
|
||||||
|
server.use(
|
||||||
|
http.post(`${apiBase}/account/login`, () => new HttpResponse("Password is incorrect", { status: 401 }))
|
||||||
|
);
|
||||||
|
|
||||||
|
const error = await accountApi.login(loginParams);
|
||||||
|
|
||||||
|
expect(error).toBe("Password is incorrect");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Login failed!", 401, "Unauthorized");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return \"Unknown error\" and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/account/login`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const error = await accountApi.login(loginParams);
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown error!");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Login failed!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Logout", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(Utils, "removeCookie");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove cookie on success", async () => {
|
||||||
|
vi.spyOn(Utils, "setCookie");
|
||||||
|
server.use(http.get(`${apiBase}/account/logout`, () => new HttpResponse("", { status: 200 })));
|
||||||
|
|
||||||
|
await accountApi.logout();
|
||||||
|
|
||||||
|
expect(Utils.removeCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should report a warning on and remove cookie on FAILURE", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/account/logout`, () => new HttpResponse("", { status: 401 })));
|
||||||
|
|
||||||
|
await accountApi.logout();
|
||||||
|
|
||||||
|
expect(Utils.removeCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Log out failed!", expect.any(Error));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should report a warning on and remove cookie on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/account/logout`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
await accountApi.logout();
|
||||||
|
|
||||||
|
expect(Utils.removeCookie).toHaveBeenCalledWith(SESSION_ID_COOKIE_NAME);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Log out failed!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
232
src/test/plugins/api/pokerogue-admin-api.test.ts
Normal file
232
src/test/plugins/api/pokerogue-admin-api.test.ts
Normal file
@ -0,0 +1,232 @@
|
|||||||
|
import type {
|
||||||
|
LinkAccountToDiscordIdRequest,
|
||||||
|
LinkAccountToGoogledIdRequest,
|
||||||
|
SearchAccountRequest,
|
||||||
|
SearchAccountResponse,
|
||||||
|
UnlinkAccountFromDiscordIdRequest,
|
||||||
|
UnlinkAccountFromGoogledIdRequest,
|
||||||
|
} from "#app/@types/PokerogueAdminApi";
|
||||||
|
import { PokerogueAdminApi } from "#app/plugins/api/pokerogue-admin-api";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const adminApi = new PokerogueAdminApi(apiBase);
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue Admin API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Link Account to Discord", () => {
|
||||||
|
const params: LinkAccountToDiscordIdRequest = { username: "test", discordId: "test-12575756" };
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => HttpResponse.json(true)));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => new HttpResponse("", { status: 400 })));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not link account with discord!", 400, "Bad Request");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => new HttpResponse("", { status: 404 })));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not link account with discord!", 404, "Not Found");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordLink`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not link account with discord!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Unlink Account from Discord", () => {
|
||||||
|
const params: UnlinkAccountFromDiscordIdRequest = { username: "test", discordId: "test-12575756" };
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => HttpResponse.json(true)));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => new HttpResponse("", { status: 400 })));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from discord!", 400, "Bad Request");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => new HttpResponse("", { status: 404 })));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from discord!", 404, "Not Found");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/discordUnlink`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromDiscord(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from discord!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Link Account to Google", () => {
|
||||||
|
const params: LinkAccountToGoogledIdRequest = { username: "test", googleId: "test-12575756" };
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => HttpResponse.json(true)));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => new HttpResponse("", { status: 400 })));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not link account with google!", 400, "Bad Request");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => new HttpResponse("", { status: 404 })));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not link account with google!", 404, "Not Found");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleLink`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await adminApi.linkAccountToGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not link account with google!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Unlink Account from Google", () => {
|
||||||
|
const params: UnlinkAccountFromGoogledIdRequest = { username: "test", googleId: "test-12575756" };
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => HttpResponse.json(true)));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => new HttpResponse("", { status: 400 })));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from google!", 400, "Bad Request");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_USERNAME_NOT_FOUND and report a warning on 404", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => new HttpResponse("", { status: 404 })));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from google!", 404, "Not Found");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return a ERR_GENERIC and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/admin/account/googleUnlink`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await adminApi.unlinkAccountFromGoogleId(params);
|
||||||
|
|
||||||
|
expect(success).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink account from google!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Search Account", () => {
|
||||||
|
const params: SearchAccountRequest = { username: "test" };
|
||||||
|
|
||||||
|
it("should return [data, undefined] on SUCCESS", async () => {
|
||||||
|
const responseData: SearchAccountResponse = {
|
||||||
|
username: "test",
|
||||||
|
discordId: "discord-test-123",
|
||||||
|
googleId: "google-test-123",
|
||||||
|
lastLoggedIn: "2022-01-01",
|
||||||
|
registered: "2022-01-01",
|
||||||
|
};
|
||||||
|
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => HttpResponse.json(responseData)));
|
||||||
|
|
||||||
|
const [ data, err ] = await adminApi.searchAccount(params);
|
||||||
|
|
||||||
|
expect(data).toStrictEqual(responseData);
|
||||||
|
expect(err).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return [undefined, ERR_GENERIC] and report a warning on on FAILURE", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => new HttpResponse("", { status: 400 })));
|
||||||
|
|
||||||
|
const [ data, err ] = await adminApi.searchAccount(params);
|
||||||
|
|
||||||
|
expect(data).toBeUndefined();
|
||||||
|
expect(err).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not find account!", 400, "Bad Request");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return [undefined, ERR_USERNAME_NOT_FOUND] and report a warning on on 404", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => new HttpResponse("", { status: 404 })));
|
||||||
|
|
||||||
|
const [ data, err ] = await adminApi.searchAccount(params);
|
||||||
|
|
||||||
|
expect(data).toBeUndefined();
|
||||||
|
expect(err).toBe(adminApi.ERR_USERNAME_NOT_FOUND);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not find account!", 404, "Not Found");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return [undefined, ERR_GENERIC] and report a warning on on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/admin/account/adminSearch`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const [ data, err ] = await adminApi.searchAccount(params);
|
||||||
|
|
||||||
|
expect(data).toBeUndefined();
|
||||||
|
expect(err).toBe(adminApi.ERR_GENERIC);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not find account!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
97
src/test/plugins/api/pokerogue-api.test.ts
Normal file
97
src/test/plugins/api/pokerogue-api.test.ts
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
import type { TitleStatsResponse } from "#app/@types/PokerogueApi";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Game Title Stats", () => {
|
||||||
|
const expectedTitleStats: TitleStatsResponse = {
|
||||||
|
playerCount: 9999999,
|
||||||
|
battleCount: 9999999,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return the stats on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/game/titlestats`, () => HttpResponse.json(expectedTitleStats)));
|
||||||
|
|
||||||
|
const titleStats = await pokerogueApi.getGameTitleStats();
|
||||||
|
|
||||||
|
expect(titleStats).toEqual(expectedTitleStats);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/game/titlestats`, () => HttpResponse.error()));
|
||||||
|
const titleStats = await pokerogueApi.getGameTitleStats();
|
||||||
|
|
||||||
|
expect(titleStats).toBeNull();
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get game title stats!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Unlink Discord", () => {
|
||||||
|
it("should return true on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/auth/discord/logout`, () => new HttpResponse("", { status: 200 })));
|
||||||
|
|
||||||
|
const success = await pokerogueApi.unlinkDiscord();
|
||||||
|
|
||||||
|
expect(success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false and report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/auth/discord/logout`, () => new HttpResponse("", { status: 401 })));
|
||||||
|
|
||||||
|
const success = await pokerogueApi.unlinkDiscord();
|
||||||
|
|
||||||
|
expect(success).toBe(false);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Discord unlink failed (401: Unauthorized)");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/auth/discord/logout`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await pokerogueApi.unlinkDiscord();
|
||||||
|
|
||||||
|
expect(success).toBe(false);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink Discord!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Unlink Google", () => {
|
||||||
|
it("should return true on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/auth/google/logout`, () => new HttpResponse("", { status: 200 })));
|
||||||
|
|
||||||
|
const success = await pokerogueApi.unlinkGoogle();
|
||||||
|
|
||||||
|
expect(success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false and report a warning on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/auth/google/logout`, () => new HttpResponse("", { status: 401 })));
|
||||||
|
|
||||||
|
const success = await pokerogueApi.unlinkGoogle();
|
||||||
|
|
||||||
|
expect(success).toBe(false);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Google unlink failed (401: Unauthorized)");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/auth/google/logout`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await pokerogueApi.unlinkGoogle();
|
||||||
|
|
||||||
|
expect(success).toBe(false);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not unlink Google!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
89
src/test/plugins/api/pokerogue-daily-api.test.ts
Normal file
89
src/test/plugins/api/pokerogue-daily-api.test.ts
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
import type { GetDailyRankingsPageCountRequest, GetDailyRankingsRequest } from "#app/@types/PokerogueDailyApi";
|
||||||
|
import { PokerogueDailyApi } from "#app/plugins/api/pokerogue-daily-api";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import { ScoreboardCategory, type RankingEntry } from "#app/ui/daily-run-scoreboard";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const dailyApi = new PokerogueDailyApi(apiBase);
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue Daily API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Get Seed", () => {
|
||||||
|
it("should return seed string on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/daily/seed`, () => HttpResponse.text("this-is-a-test-seed")));
|
||||||
|
|
||||||
|
const seed = await dailyApi.getSeed();
|
||||||
|
|
||||||
|
expect(seed).toBe("this-is-a-test-seed");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/daily/seed`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const seed = await dailyApi.getSeed();
|
||||||
|
|
||||||
|
expect(seed).toBeNull();
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get daily-run seed!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Get Rankings", () => {
|
||||||
|
const params: GetDailyRankingsRequest = {
|
||||||
|
category: ScoreboardCategory.DAILY,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return ranking entries on SUCCESS", async () => {
|
||||||
|
const expectedRankings: RankingEntry[] = [
|
||||||
|
{ rank: 1, score: 999, username: "Player 1", wave: 200 },
|
||||||
|
{ rank: 2, score: 10, username: "Player 2", wave: 1 },
|
||||||
|
];
|
||||||
|
server.use(http.get(`${apiBase}/daily/rankings`, () => HttpResponse.json(expectedRankings)));
|
||||||
|
|
||||||
|
const rankings = await dailyApi.getRankings(params);
|
||||||
|
|
||||||
|
expect(rankings).toStrictEqual(expectedRankings);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/daily/rankings`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const rankings = await dailyApi.getRankings(params);
|
||||||
|
|
||||||
|
expect(rankings).toBeNull();
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get daily rankings!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Get Rankings Page Count", () => {
|
||||||
|
const params: GetDailyRankingsPageCountRequest = {
|
||||||
|
category: ScoreboardCategory.DAILY,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return a number on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/daily/rankingpagecount`, () => HttpResponse.json(5)));
|
||||||
|
|
||||||
|
const pageCount = await dailyApi.getRankingsPageCount(params);
|
||||||
|
|
||||||
|
expect(pageCount).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return 1 and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/daily/rankingpagecount`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const pageCount = await dailyApi.getRankingsPageCount(params);
|
||||||
|
|
||||||
|
expect(pageCount).toBe(1);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get daily rankings page count!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
46
src/test/plugins/api/pokerogue-savedata-api.test.ts
Normal file
46
src/test/plugins/api/pokerogue-savedata-api.test.ts
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
import type { UpdateAllSavedataRequest } from "#app/@types/PokerogueSavedataApi";
|
||||||
|
import { PokerogueSavedataApi } from "#app/plugins/api/pokerogue-savedata-api";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const savedataApi = new PokerogueSavedataApi(apiBase);
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue Savedata API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Update All", () => {
|
||||||
|
it("should return an empty string on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/updateall`, () => HttpResponse.text(null)));
|
||||||
|
|
||||||
|
const error = await savedataApi.updateAll({} as UpdateAllSavedataRequest);
|
||||||
|
|
||||||
|
expect(error).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return an error message on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/updateall`, () => HttpResponse.text("Failed to update all!")));
|
||||||
|
|
||||||
|
const error = await savedataApi.updateAll({} as UpdateAllSavedataRequest);
|
||||||
|
|
||||||
|
expect(error).toBe("Failed to update all!");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return 'Unknown error' and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/updateall`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const error = await savedataApi.updateAll({} as UpdateAllSavedataRequest);
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown error");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not update all savedata!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
199
src/test/plugins/api/pokerogue-session-savedata-api.test.ts
Normal file
199
src/test/plugins/api/pokerogue-session-savedata-api.test.ts
Normal file
@ -0,0 +1,199 @@
|
|||||||
|
import type {
|
||||||
|
ClearSessionSavedataRequest,
|
||||||
|
ClearSessionSavedataResponse,
|
||||||
|
DeleteSessionSavedataRequest,
|
||||||
|
GetSessionSavedataRequest,
|
||||||
|
NewClearSessionSavedataRequest,
|
||||||
|
UpdateSessionSavedataRequest,
|
||||||
|
} from "#app/@types/PokerogueSessionSavedataApi";
|
||||||
|
import { PokerogueSessionSavedataApi } from "#app/plugins/api/pokerogue-session-savedata-api";
|
||||||
|
import type { SessionSaveData } from "#app/system/game-data";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const sessionSavedataApi = new PokerogueSessionSavedataApi(apiBase);
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue Session Savedata API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Newclear", () => {
|
||||||
|
const params: NewClearSessionSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
slot: 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return true on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/newclear`, () => HttpResponse.json(true)));
|
||||||
|
|
||||||
|
const success = await sessionSavedataApi.newclear(params);
|
||||||
|
|
||||||
|
expect(success).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false on FAILURE", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/newclear`, () => HttpResponse.json(false)));
|
||||||
|
|
||||||
|
const success = await sessionSavedataApi.newclear(params);
|
||||||
|
|
||||||
|
expect(success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return false and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/newclear`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const success = await sessionSavedataApi.newclear(params);
|
||||||
|
|
||||||
|
expect(success).toBe(false);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not newclear session!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Get ", () => {
|
||||||
|
const params: GetSessionSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
slot: 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return session-savedata string on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/get`, () => HttpResponse.text("TEST SESSION SAVEDATA")));
|
||||||
|
|
||||||
|
const savedata = await sessionSavedataApi.get(params);
|
||||||
|
|
||||||
|
expect(savedata).toBe("TEST SESSION SAVEDATA");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/get`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const savedata = await sessionSavedataApi.get(params);
|
||||||
|
|
||||||
|
expect(savedata).toBeNull();
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get session savedata!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Update", () => {
|
||||||
|
const params: UpdateSessionSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
slot: 3,
|
||||||
|
secretId: 9876543321,
|
||||||
|
trainerId: 123456789,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return an empty string on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/session/update`, () => HttpResponse.text(null)));
|
||||||
|
|
||||||
|
const error = await sessionSavedataApi.update(params, "UPDATED SESSION SAVEDATA");
|
||||||
|
|
||||||
|
expect(error).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return an error string on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/session/update`, () => HttpResponse.text("Failed to update!")));
|
||||||
|
|
||||||
|
const error = await sessionSavedataApi.update(params, "UPDATED SESSION SAVEDATA");
|
||||||
|
|
||||||
|
expect(error).toBe("Failed to update!");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return 'Unknown Error!' and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/session/update`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const error = await sessionSavedataApi.update(params, "UPDATED SESSION SAVEDATA");
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown Error!");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not update session savedata!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Delete", () => {
|
||||||
|
const params: DeleteSessionSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
slot: 3,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/delete`, () => HttpResponse.text(null)));
|
||||||
|
|
||||||
|
const error = await sessionSavedataApi.delete(params);
|
||||||
|
|
||||||
|
expect(error).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return an error string on FAILURE", async () => {
|
||||||
|
server.use(
|
||||||
|
http.get(`${apiBase}/savedata/session/delete`, () => new HttpResponse("Failed to delete!", { status: 400 }))
|
||||||
|
);
|
||||||
|
|
||||||
|
const error = await sessionSavedataApi.delete(params);
|
||||||
|
|
||||||
|
expect(error).toBe("Failed to delete!");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return 'Unknown error' and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/session/delete`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const error = await sessionSavedataApi.delete(params);
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown error");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not delete session savedata!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Clear", () => {
|
||||||
|
const params: ClearSessionSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
slot: 3,
|
||||||
|
trainerId: 123456789,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return sucess=true on SUCCESS", async () => {
|
||||||
|
server.use(
|
||||||
|
http.post(`${apiBase}/savedata/session/clear`, () =>
|
||||||
|
HttpResponse.json<ClearSessionSavedataResponse>({
|
||||||
|
success: true,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const { success, error } = await sessionSavedataApi.clear(params, {} as SessionSaveData);
|
||||||
|
|
||||||
|
expect(success).toBe(true);
|
||||||
|
expect(error).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return sucess=false & an error string on FAILURE", async () => {
|
||||||
|
server.use(
|
||||||
|
http.post(`${apiBase}/savedata/session/clear`, () =>
|
||||||
|
HttpResponse.json<ClearSessionSavedataResponse>({
|
||||||
|
success: false,
|
||||||
|
error: "Failed to clear!",
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const { success, error } = await sessionSavedataApi.clear(params, {} as SessionSaveData);
|
||||||
|
|
||||||
|
expect(error).toBe("Failed to clear!");
|
||||||
|
expect(success).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return success=false & error='Unknown error' and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const { success, error } = await sessionSavedataApi.clear(params, {} as SessionSaveData);
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown error");
|
||||||
|
expect(success).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
122
src/test/plugins/api/pokerogue-system-savedata-api.test.ts
Normal file
122
src/test/plugins/api/pokerogue-system-savedata-api.test.ts
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
import type {
|
||||||
|
GetSystemSavedataRequest,
|
||||||
|
UpdateSystemSavedataRequest,
|
||||||
|
VerifySystemSavedataRequest,
|
||||||
|
VerifySystemSavedataResponse,
|
||||||
|
} from "#app/@types/PokerogueSystemSavedataApi";
|
||||||
|
import { PokerogueSystemSavedataApi } from "#app/plugins/api/pokerogue-system-savedata-api";
|
||||||
|
import type { SystemSaveData } from "#app/system/game-data";
|
||||||
|
import { getApiBaseUrl } from "#app/test/utils/testUtils";
|
||||||
|
import { http, HttpResponse } from "msw";
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const apiBase = getApiBaseUrl();
|
||||||
|
const systemSavedataApi = new PokerogueSystemSavedataApi(getApiBaseUrl());
|
||||||
|
const { server } = global;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
server.resetHandlers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Pokerogue System Savedata API", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(console, "warn");
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Get", () => {
|
||||||
|
const params: GetSystemSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return system-savedata string on SUCCESS", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/system/get`, () => HttpResponse.text("TEST SYSTEM SAVEDATA")));
|
||||||
|
|
||||||
|
const savedata = await systemSavedataApi.get(params);
|
||||||
|
|
||||||
|
expect(savedata).toBe("TEST SYSTEM SAVEDATA");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return null and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.get(`${apiBase}/savedata/system/get`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const savedata = await systemSavedataApi.get(params);
|
||||||
|
|
||||||
|
expect(savedata).toBeNull();
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not get system savedata!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Verify", () => {
|
||||||
|
const params: VerifySystemSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return null on SUCCESS", async () => {
|
||||||
|
server.use(
|
||||||
|
http.get(`${apiBase}/savedata/system/verify`, () =>
|
||||||
|
HttpResponse.json<VerifySystemSavedataResponse>({
|
||||||
|
systemData: {
|
||||||
|
trainerId: 123456789,
|
||||||
|
} as SystemSaveData,
|
||||||
|
valid: true,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const savedata = await systemSavedataApi.verify(params);
|
||||||
|
|
||||||
|
expect(savedata).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return system-savedata and report a warning on FAILURE", async () => {
|
||||||
|
server.use(
|
||||||
|
http.get(`${apiBase}/savedata/system/verify`, () =>
|
||||||
|
HttpResponse.json<VerifySystemSavedataResponse>({
|
||||||
|
systemData: {
|
||||||
|
trainerId: 123456789,
|
||||||
|
} as SystemSaveData,
|
||||||
|
valid: false,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const savedata = await systemSavedataApi.verify(params);
|
||||||
|
|
||||||
|
expect(savedata?.trainerId).toBe(123456789);
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Invalid system savedata!");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Update", () => {
|
||||||
|
const params: UpdateSystemSavedataRequest = {
|
||||||
|
clientSessionId: "test-session-id",
|
||||||
|
secretId: 9876543321,
|
||||||
|
trainerId: 123456789,
|
||||||
|
};
|
||||||
|
|
||||||
|
it("should return an empty string on SUCCESS", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/system/update`, () => HttpResponse.text(null)));
|
||||||
|
|
||||||
|
const error = await systemSavedataApi.update(params, "UPDATED SYSTEM SAVEDATA");
|
||||||
|
|
||||||
|
expect(error).toBe("");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return an error string on FAILURE", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/system/update`, () => HttpResponse.text("Failed to update!")));
|
||||||
|
|
||||||
|
const error = await systemSavedataApi.update(params, "UPDATED SYSTEM SAVEDATA");
|
||||||
|
|
||||||
|
expect(error).toBe("Failed to update!");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return 'Unknown Error' and report a warning on ERROR", async () => {
|
||||||
|
server.use(http.post(`${apiBase}/savedata/system/update`, () => HttpResponse.error()));
|
||||||
|
|
||||||
|
const error = await systemSavedataApi.update(params, "UPDATED SYSTEM SAVEDATA");
|
||||||
|
|
||||||
|
expect(error).toBe("Unknown Error");
|
||||||
|
expect(console.warn).toHaveBeenCalledWith("Could not update system savedata!", expect.any(Error));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
@ -1,4 +1,5 @@
|
|||||||
import { GameModes } from "#app/game-mode";
|
import { GameModes } from "#app/game-mode";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
import OptionSelectUiHandler from "#app/ui/settings/option-select-ui-handler";
|
import OptionSelectUiHandler from "#app/ui/settings/option-select-ui-handler";
|
||||||
import { Mode } from "#app/ui/ui";
|
import { Mode } from "#app/ui/ui";
|
||||||
import { Biome } from "#enums/biome";
|
import { Biome } from "#enums/biome";
|
||||||
@ -7,7 +8,7 @@ import { Moves } from "#enums/moves";
|
|||||||
import { Species } from "#enums/species";
|
import { Species } from "#enums/species";
|
||||||
import GameManager from "#test/utils/gameManager";
|
import GameManager from "#test/utils/gameManager";
|
||||||
import { MockClock } from "#test/utils/mocks/mockClock";
|
import { MockClock } from "#test/utils/mocks/mockClock";
|
||||||
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
describe("Reload", () => {
|
describe("Reload", () => {
|
||||||
let phaserGame: Phaser.Game;
|
let phaserGame: Phaser.Game;
|
||||||
@ -25,6 +26,8 @@ describe("Reload", () => {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
game = new GameManager(phaserGame);
|
game = new GameManager(phaserGame);
|
||||||
|
vi.spyOn(pokerogueApi, "getGameTitleStats").mockResolvedValue({ battleCount: -1, playerCount: -1 });
|
||||||
|
vi.spyOn(pokerogueApi.daily, "getSeed").mockResolvedValue("test-seed");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should not have RNG inconsistencies in a Classic run", async () => {
|
it("should not have RNG inconsistencies in a Classic run", async () => {
|
||||||
@ -110,8 +113,7 @@ describe("Reload", () => {
|
|||||||
}, 20000);
|
}, 20000);
|
||||||
|
|
||||||
it("should not have RNG inconsistencies at a Daily run double battle", async () => {
|
it("should not have RNG inconsistencies at a Daily run double battle", async () => {
|
||||||
game.override
|
game.override.battleType("double");
|
||||||
.battleType("double");
|
|
||||||
await game.dailyMode.startBattle();
|
await game.dailyMode.startBattle();
|
||||||
|
|
||||||
const preReloadRngState = Phaser.Math.RND.state();
|
const preReloadRngState = Phaser.Math.RND.state();
|
||||||
@ -124,9 +126,7 @@ describe("Reload", () => {
|
|||||||
}, 20000);
|
}, 20000);
|
||||||
|
|
||||||
it("should not have RNG inconsistencies at a Daily run Gym Leader fight", async () => {
|
it("should not have RNG inconsistencies at a Daily run Gym Leader fight", async () => {
|
||||||
game.override
|
game.override.battleType("single").startingWave(40);
|
||||||
.battleType("single")
|
|
||||||
.startingWave(40);
|
|
||||||
await game.dailyMode.startBattle();
|
await game.dailyMode.startBattle();
|
||||||
|
|
||||||
const preReloadRngState = Phaser.Math.RND.state();
|
const preReloadRngState = Phaser.Math.RND.state();
|
||||||
@ -139,9 +139,7 @@ describe("Reload", () => {
|
|||||||
}, 20000);
|
}, 20000);
|
||||||
|
|
||||||
it("should not have RNG inconsistencies at a Daily run regular trainer fight", async () => {
|
it("should not have RNG inconsistencies at a Daily run regular trainer fight", async () => {
|
||||||
game.override
|
game.override.battleType("single").startingWave(45);
|
||||||
.battleType("single")
|
|
||||||
.startingWave(45);
|
|
||||||
await game.dailyMode.startBattle();
|
await game.dailyMode.startBattle();
|
||||||
|
|
||||||
const preReloadRngState = Phaser.Math.RND.state();
|
const preReloadRngState = Phaser.Math.RND.state();
|
||||||
@ -154,9 +152,7 @@ describe("Reload", () => {
|
|||||||
}, 20000);
|
}, 20000);
|
||||||
|
|
||||||
it("should not have RNG inconsistencies at a Daily run wave 50 Boss fight", async () => {
|
it("should not have RNG inconsistencies at a Daily run wave 50 Boss fight", async () => {
|
||||||
game.override
|
game.override.battleType("single").startingWave(50);
|
||||||
.battleType("single")
|
|
||||||
.startingWave(50);
|
|
||||||
await game.runToFinalBossEncounter([ Species.BULBASAUR ], GameModes.DAILY);
|
await game.runToFinalBossEncounter([ Species.BULBASAUR ], GameModes.DAILY);
|
||||||
|
|
||||||
const preReloadRngState = Phaser.Math.RND.state();
|
const preReloadRngState = Phaser.Math.RND.state();
|
||||||
|
@ -1,36 +1,23 @@
|
|||||||
import * as BattleScene from "#app/battle-scene";
|
import * as BattleScene from "#app/battle-scene";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
import { SessionSaveData } from "#app/system/game-data";
|
import { SessionSaveData } from "#app/system/game-data";
|
||||||
import { Abilities } from "#enums/abilities";
|
import { Abilities } from "#enums/abilities";
|
||||||
import { Moves } from "#enums/moves";
|
import { Moves } from "#enums/moves";
|
||||||
import GameManager from "#test/utils/gameManager";
|
import GameManager from "#test/utils/gameManager";
|
||||||
import { http, HttpResponse } from "msw";
|
|
||||||
import { setupServer } from "msw/node";
|
|
||||||
import Phaser from "phaser";
|
import Phaser from "phaser";
|
||||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import * as account from "../../account";
|
import * as account from "../../account";
|
||||||
|
|
||||||
const apiBase = import.meta.env.VITE_API_BASE_URL ?? "http://localhost:8001";
|
|
||||||
|
|
||||||
/** We need a custom server. For some reasons I can't extend the listeners of {@linkcode global.i18nServer} with {@linkcode global.i18nServer.use} */
|
|
||||||
const server = setupServer();
|
|
||||||
|
|
||||||
describe("System - Game Data", () => {
|
describe("System - Game Data", () => {
|
||||||
let phaserGame: Phaser.Game;
|
let phaserGame: Phaser.Game;
|
||||||
let game: GameManager;
|
let game: GameManager;
|
||||||
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
global.i18nServer.close();
|
|
||||||
server.listen();
|
|
||||||
phaserGame = new Phaser.Game({
|
phaserGame = new Phaser.Game({
|
||||||
type: Phaser.HEADLESS,
|
type: Phaser.HEADLESS,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
afterAll(() => {
|
|
||||||
server.close();
|
|
||||||
global.i18nServer.listen();
|
|
||||||
});
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
game = new GameManager(phaserGame);
|
game = new GameManager(phaserGame);
|
||||||
game.override
|
game.override
|
||||||
@ -41,7 +28,6 @@ describe("System - Game Data", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
server.resetHandlers();
|
|
||||||
game.phaseInterceptor.restoreOg();
|
game.phaseInterceptor.restoreOg();
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -61,7 +47,7 @@ describe("System - Game Data", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should return [true, true] if successful", async () => {
|
it("should return [true, true] if successful", async () => {
|
||||||
server.use(http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.json({ success: true })));
|
vi.spyOn(pokerogueApi.savedata.session, "clear").mockResolvedValue({ success: true });
|
||||||
|
|
||||||
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
||||||
|
|
||||||
@ -70,7 +56,7 @@ describe("System - Game Data", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should return [true, false] if not successful", async () => {
|
it("should return [true, false] if not successful", async () => {
|
||||||
server.use(http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.json({ success: false })));
|
vi.spyOn(pokerogueApi.savedata.session, "clear").mockResolvedValue({ success: false });
|
||||||
|
|
||||||
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
||||||
|
|
||||||
@ -79,9 +65,7 @@ describe("System - Game Data", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should return [false, false] session is out of date", async () => {
|
it("should return [false, false] session is out of date", async () => {
|
||||||
server.use(
|
vi.spyOn(pokerogueApi.savedata.session, "clear").mockResolvedValue({ error: "session out of date" });
|
||||||
http.post(`${apiBase}/savedata/session/clear`, () => HttpResponse.json({ error: "session out of date" }))
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
const result = await game.scene.gameData.tryClearSession(game.scene, 0);
|
||||||
|
|
||||||
|
@ -79,7 +79,7 @@ export default class GameWrapper {
|
|||||||
|
|
||||||
constructor(phaserGame: Phaser.Game, bypassLogin: boolean) {
|
constructor(phaserGame: Phaser.Game, bypassLogin: boolean) {
|
||||||
Phaser.Math.RND.sow([ 'test' ]);
|
Phaser.Math.RND.sow([ 'test' ]);
|
||||||
vi.spyOn(Utils, "apiFetch", "get").mockReturnValue(fetch);
|
// vi.spyOn(Utils, "apiFetch", "get").mockReturnValue(fetch);
|
||||||
if (bypassLogin) {
|
if (bypassLogin) {
|
||||||
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(true);
|
vi.spyOn(battleScene, "bypassLogin", "get").mockReturnValue(true);
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,7 @@ export class ClassicModeHelper extends GameManagerHelper {
|
|||||||
selectStarterPhase.initBattle(starters);
|
selectStarterPhase.initBattle(starters);
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.game.phaseInterceptor.run(EncounterPhase);
|
await this.game.phaseInterceptor.to(EncounterPhase);
|
||||||
if (overrides.OPP_HELD_ITEMS_OVERRIDE.length === 0 && this.game.override.removeEnemyStartingItems) {
|
if (overrides.OPP_HELD_ITEMS_OVERRIDE.length === 0 && this.game.override.removeEnemyStartingItems) {
|
||||||
this.game.removeEnemyHeldItems();
|
this.game.removeEnemyHeldItems();
|
||||||
}
|
}
|
||||||
|
@ -12,6 +12,7 @@ import { EndEvolutionPhase } from "#app/phases/end-evolution-phase";
|
|||||||
import { EnemyCommandPhase } from "#app/phases/enemy-command-phase";
|
import { EnemyCommandPhase } from "#app/phases/enemy-command-phase";
|
||||||
import { EvolutionPhase } from "#app/phases/evolution-phase";
|
import { EvolutionPhase } from "#app/phases/evolution-phase";
|
||||||
import { FaintPhase } from "#app/phases/faint-phase";
|
import { FaintPhase } from "#app/phases/faint-phase";
|
||||||
|
import { FormChangePhase } from "#app/phases/form-change-phase";
|
||||||
import { LearnMovePhase } from "#app/phases/learn-move-phase";
|
import { LearnMovePhase } from "#app/phases/learn-move-phase";
|
||||||
import { LevelCapPhase } from "#app/phases/level-cap-phase";
|
import { LevelCapPhase } from "#app/phases/level-cap-phase";
|
||||||
import { LoginPhase } from "#app/phases/login-phase";
|
import { LoginPhase } from "#app/phases/login-phase";
|
||||||
@ -67,7 +68,6 @@ type PhaseClass =
|
|||||||
| typeof LoginPhase
|
| typeof LoginPhase
|
||||||
| typeof TitlePhase
|
| typeof TitlePhase
|
||||||
| typeof SelectGenderPhase
|
| typeof SelectGenderPhase
|
||||||
| typeof EncounterPhase
|
|
||||||
| typeof NewBiomeEncounterPhase
|
| typeof NewBiomeEncounterPhase
|
||||||
| typeof SelectStarterPhase
|
| typeof SelectStarterPhase
|
||||||
| typeof PostSummonPhase
|
| typeof PostSummonPhase
|
||||||
@ -102,6 +102,7 @@ type PhaseClass =
|
|||||||
| typeof SwitchPhase
|
| typeof SwitchPhase
|
||||||
| typeof SwitchSummonPhase
|
| typeof SwitchSummonPhase
|
||||||
| typeof PartyHealPhase
|
| typeof PartyHealPhase
|
||||||
|
| typeof FormChangePhase
|
||||||
| typeof EvolutionPhase
|
| typeof EvolutionPhase
|
||||||
| typeof EndEvolutionPhase
|
| typeof EndEvolutionPhase
|
||||||
| typeof LevelCapPhase
|
| typeof LevelCapPhase
|
||||||
@ -114,13 +115,13 @@ type PhaseClass =
|
|||||||
| typeof PostMysteryEncounterPhase
|
| typeof PostMysteryEncounterPhase
|
||||||
| typeof ModifierRewardPhase
|
| typeof ModifierRewardPhase
|
||||||
| typeof PartyExpPhase
|
| typeof PartyExpPhase
|
||||||
| typeof ExpPhase;
|
| typeof ExpPhase
|
||||||
|
| typeof EncounterPhase;
|
||||||
|
|
||||||
type PhaseString =
|
type PhaseString =
|
||||||
| "LoginPhase"
|
| "LoginPhase"
|
||||||
| "TitlePhase"
|
| "TitlePhase"
|
||||||
| "SelectGenderPhase"
|
| "SelectGenderPhase"
|
||||||
| "EncounterPhase"
|
|
||||||
| "NewBiomeEncounterPhase"
|
| "NewBiomeEncounterPhase"
|
||||||
| "SelectStarterPhase"
|
| "SelectStarterPhase"
|
||||||
| "PostSummonPhase"
|
| "PostSummonPhase"
|
||||||
@ -155,6 +156,7 @@ type PhaseString =
|
|||||||
| "SwitchPhase"
|
| "SwitchPhase"
|
||||||
| "SwitchSummonPhase"
|
| "SwitchSummonPhase"
|
||||||
| "PartyHealPhase"
|
| "PartyHealPhase"
|
||||||
|
| "FormChangePhase"
|
||||||
| "EvolutionPhase"
|
| "EvolutionPhase"
|
||||||
| "EndEvolutionPhase"
|
| "EndEvolutionPhase"
|
||||||
| "LevelCapPhase"
|
| "LevelCapPhase"
|
||||||
@ -167,7 +169,8 @@ type PhaseString =
|
|||||||
| "PostMysteryEncounterPhase"
|
| "PostMysteryEncounterPhase"
|
||||||
| "ModifierRewardPhase"
|
| "ModifierRewardPhase"
|
||||||
| "PartyExpPhase"
|
| "PartyExpPhase"
|
||||||
| "ExpPhase";
|
| "ExpPhase"
|
||||||
|
| "EncounterPhase";
|
||||||
|
|
||||||
type PhaseInterceptorPhase = PhaseClass | PhaseString;
|
type PhaseInterceptorPhase = PhaseClass | PhaseString;
|
||||||
|
|
||||||
@ -187,12 +190,16 @@ export default class PhaseInterceptor {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* List of phases with their corresponding start methods.
|
* List of phases with their corresponding start methods.
|
||||||
|
*
|
||||||
|
* CAUTION: If a phase and its subclasses (if any) both appear in this list,
|
||||||
|
* make sure that this list contains said phase AFTER all of its subclasses.
|
||||||
|
* This way, the phase's `prototype.start` is properly preserved during
|
||||||
|
* `initPhases()` so that its subclasses can use `super.start()` properly.
|
||||||
*/
|
*/
|
||||||
private PHASES = [
|
private PHASES = [
|
||||||
[ LoginPhase, this.startPhase ],
|
[ LoginPhase, this.startPhase ],
|
||||||
[ TitlePhase, this.startPhase ],
|
[ TitlePhase, this.startPhase ],
|
||||||
[ SelectGenderPhase, this.startPhase ],
|
[ SelectGenderPhase, this.startPhase ],
|
||||||
[ EncounterPhase, this.startPhase ],
|
|
||||||
[ NewBiomeEncounterPhase, this.startPhase ],
|
[ NewBiomeEncounterPhase, this.startPhase ],
|
||||||
[ SelectStarterPhase, this.startPhase ],
|
[ SelectStarterPhase, this.startPhase ],
|
||||||
[ PostSummonPhase, this.startPhase ],
|
[ PostSummonPhase, this.startPhase ],
|
||||||
@ -227,6 +234,7 @@ export default class PhaseInterceptor {
|
|||||||
[ SwitchPhase, this.startPhase ],
|
[ SwitchPhase, this.startPhase ],
|
||||||
[ SwitchSummonPhase, this.startPhase ],
|
[ SwitchSummonPhase, this.startPhase ],
|
||||||
[ PartyHealPhase, this.startPhase ],
|
[ PartyHealPhase, this.startPhase ],
|
||||||
|
[ FormChangePhase, this.startPhase ],
|
||||||
[ EvolutionPhase, this.startPhase ],
|
[ EvolutionPhase, this.startPhase ],
|
||||||
[ EndEvolutionPhase, this.startPhase ],
|
[ EndEvolutionPhase, this.startPhase ],
|
||||||
[ LevelCapPhase, this.startPhase ],
|
[ LevelCapPhase, this.startPhase ],
|
||||||
@ -240,6 +248,7 @@ export default class PhaseInterceptor {
|
|||||||
[ ModifierRewardPhase, this.startPhase ],
|
[ ModifierRewardPhase, this.startPhase ],
|
||||||
[ PartyExpPhase, this.startPhase ],
|
[ PartyExpPhase, this.startPhase ],
|
||||||
[ ExpPhase, this.startPhase ],
|
[ ExpPhase, this.startPhase ],
|
||||||
|
[ EncounterPhase, this.startPhase ],
|
||||||
];
|
];
|
||||||
|
|
||||||
private endBySetMode = [
|
private endBySetMode = [
|
||||||
|
File diff suppressed because one or more lines are too long
@ -21,3 +21,11 @@ export function mockI18next() {
|
|||||||
export function arrayOfRange(start: integer, end: integer) {
|
export function arrayOfRange(start: integer, end: integer) {
|
||||||
return Array.from({ length: end - start }, (_v, k) => k + start);
|
return Array.from({ length: end - start }, (_v, k) => k + start);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility to get the API base URL from the environment variable (or the default/fallback).
|
||||||
|
* @returns the API base URL
|
||||||
|
*/
|
||||||
|
export function getApiBaseUrl() {
|
||||||
|
return import.meta.env.VITE_SERVER_URL ?? "http://localhost:8001";
|
||||||
|
}
|
||||||
|
@ -38,7 +38,7 @@ vi.mock("i18next", async (importOriginal) => {
|
|||||||
const { setupServer } = await import("msw/node");
|
const { setupServer } = await import("msw/node");
|
||||||
const { http, HttpResponse } = await import("msw");
|
const { http, HttpResponse } = await import("msw");
|
||||||
|
|
||||||
global.i18nServer = setupServer(
|
global.server = setupServer(
|
||||||
http.get("/locales/en/*", async (req) => {
|
http.get("/locales/en/*", async (req) => {
|
||||||
const filename = req.params[0];
|
const filename = req.params[0];
|
||||||
|
|
||||||
@ -50,9 +50,12 @@ vi.mock("i18next", async (importOriginal) => {
|
|||||||
console.log(`Failed to load locale ${filename}!`, err);
|
console.log(`Failed to load locale ${filename}!`, err);
|
||||||
return HttpResponse.json({});
|
return HttpResponse.json({});
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
|
http.get("https://fonts.googleapis.com/*", () => {
|
||||||
|
return HttpResponse.text("");
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
global.i18nServer.listen({ onUnhandledRequest: "error" });
|
global.server.listen({ onUnhandledRequest: "error" });
|
||||||
console.log("i18n MSW server listening!");
|
console.log("i18n MSW server listening!");
|
||||||
|
|
||||||
return await importOriginal();
|
return await importOriginal();
|
||||||
@ -83,6 +86,6 @@ beforeAll(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
global.i18nServer.close();
|
global.server.close();
|
||||||
console.log("Closing i18n MSW server!");
|
console.log("Closing i18n MSW server!");
|
||||||
});
|
});
|
||||||
|
@ -1,10 +1,14 @@
|
|||||||
import BattleScene from "#app/battle-scene";
|
import BattleScene from "#app/battle-scene";
|
||||||
import { ModalConfig } from "./modal-ui-handler";
|
|
||||||
import { Mode } from "./ui";
|
|
||||||
import * as Utils from "../utils";
|
|
||||||
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
|
||||||
import { Button } from "#app/enums/buttons";
|
import { Button } from "#app/enums/buttons";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
import { formatText } from "#app/utils";
|
||||||
|
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
||||||
|
import { ModalConfig } from "./modal-ui-handler";
|
||||||
import { TextStyle } from "./text";
|
import { TextStyle } from "./text";
|
||||||
|
import { Mode } from "./ui";
|
||||||
|
|
||||||
|
type AdminUiHandlerService = "discord" | "google";
|
||||||
|
type AdminUiHandlerServiceMode = "Link" | "Unlink";
|
||||||
|
|
||||||
export default class AdminUiHandler extends FormModalUiHandler {
|
export default class AdminUiHandler extends FormModalUiHandler {
|
||||||
|
|
||||||
@ -17,17 +21,15 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
|||||||
private readonly httpUserNotFoundErrorCode: number = 404;
|
private readonly httpUserNotFoundErrorCode: number = 404;
|
||||||
private readonly ERR_REQUIRED_FIELD = (field: string) => {
|
private readonly ERR_REQUIRED_FIELD = (field: string) => {
|
||||||
if (field === "username") {
|
if (field === "username") {
|
||||||
return `${Utils.formatText(field)} is required`;
|
return `${formatText(field)} is required`;
|
||||||
} else {
|
} else {
|
||||||
return `${Utils.formatText(field)} Id is required`;
|
return `${formatText(field)} Id is required`;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// returns a string saying whether a username has been successfully linked/unlinked to discord/google
|
// returns a string saying whether a username has been successfully linked/unlinked to discord/google
|
||||||
private readonly SUCCESS_SERVICE_MODE = (service: string, mode: string) => {
|
private readonly SUCCESS_SERVICE_MODE = (service: string, mode: string) => {
|
||||||
return `Username and ${service} successfully ${mode.toLowerCase()}ed`;
|
return `Username and ${service} successfully ${mode.toLowerCase()}ed`;
|
||||||
};
|
};
|
||||||
private readonly ERR_USERNAME_NOT_FOUND: string = "Username not found!";
|
|
||||||
private readonly ERR_GENERIC_ERROR: string = "There was an error";
|
|
||||||
|
|
||||||
constructor(scene: BattleScene, mode: Mode | null = null) {
|
constructor(scene: BattleScene, mode: Mode | null = null) {
|
||||||
super(scene, mode);
|
super(scene, mode);
|
||||||
@ -148,7 +150,6 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
|||||||
} else if (this.adminMode === AdminMode.ADMIN) {
|
} else if (this.adminMode === AdminMode.ADMIN) {
|
||||||
this.updateAdminPanelInfo(adminSearchResult, AdminMode.SEARCH);
|
this.updateAdminPanelInfo(adminSearchResult, AdminMode.SEARCH);
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
};
|
};
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -196,7 +197,7 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
|||||||
this.scene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error
|
this.scene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error
|
||||||
return this.showMessage(validFields.errorMessage ?? "", adminResult, true);
|
return this.showMessage(validFields.errorMessage ?? "", adminResult, true);
|
||||||
}
|
}
|
||||||
this.adminLinkUnlink(this.convertInputsToAdmin(), service, mode).then(response => { // attempts to link/unlink depending on the service
|
this.adminLinkUnlink(this.convertInputsToAdmin(), service as AdminUiHandlerService, mode).then(response => { // attempts to link/unlink depending on the service
|
||||||
if (response.error) {
|
if (response.error) {
|
||||||
this.scene.ui.setMode(Mode.LOADING, { buttonActions: []});
|
this.scene.ui.setMode(Mode.LOADING, { buttonActions: []});
|
||||||
return this.showMessage(response.errorType, adminResult, true); // fail
|
return this.showMessage(response.errorType, adminResult, true); // fail
|
||||||
@ -276,12 +277,11 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
|||||||
|
|
||||||
private async adminSearch(adminSearchResult: AdminSearchInfo) {
|
private async adminSearch(adminSearchResult: AdminSearchInfo) {
|
||||||
try {
|
try {
|
||||||
const adminInfo = await Utils.apiFetch(`admin/account/adminSearch?username=${encodeURIComponent(adminSearchResult.username)}`, true);
|
const [ adminInfo, errorType ] = await pokerogueApi.admin.searchAccount({ username: adminSearchResult.username });
|
||||||
if (!adminInfo.ok) { // error - if adminInfo.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
if (errorType || !adminInfo) { // error - if adminInfo.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
||||||
return { adminSearchResult: adminSearchResult, error: true, errorType: adminInfo.status === this.httpUserNotFoundErrorCode ? this.ERR_USERNAME_NOT_FOUND : this.ERR_GENERIC_ERROR };
|
return { adminSearchResult: adminSearchResult, error: true, errorType };
|
||||||
} else { // success
|
} else { // success
|
||||||
const adminInfoJson: AdminSearchInfo = await adminInfo.json();
|
return { adminSearchResult: adminInfo, error: false };
|
||||||
return { adminSearchResult: adminInfoJson, error: false };
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
@ -289,12 +289,47 @@ export default class AdminUiHandler extends FormModalUiHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async adminLinkUnlink(adminSearchResult: AdminSearchInfo, service: string, mode: string) {
|
private async adminLinkUnlink(adminSearchResult: AdminSearchInfo, service: AdminUiHandlerService, mode: AdminUiHandlerServiceMode) {
|
||||||
try {
|
try {
|
||||||
const response = await Utils.apiPost(`admin/account/${service}${mode}`, `username=${encodeURIComponent(adminSearchResult.username)}&${service}Id=${encodeURIComponent(service === "discord" ? adminSearchResult.discordId : adminSearchResult.googleId)}`, "application/x-www-form-urlencoded", true);
|
let errorType: string | null = null;
|
||||||
if (!response.ok) { // error - if response.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
|
||||||
return { adminSearchResult: adminSearchResult, error: true, errorType: response.status === this.httpUserNotFoundErrorCode ? this.ERR_USERNAME_NOT_FOUND : this.ERR_GENERIC_ERROR };
|
if (service === "discord") {
|
||||||
} else { // success!
|
if (mode === "Link") {
|
||||||
|
errorType = await pokerogueApi.admin.linkAccountToDiscord({
|
||||||
|
discordId: adminSearchResult.discordId,
|
||||||
|
username: adminSearchResult.username,
|
||||||
|
});
|
||||||
|
} else if (mode === "Unlink") {
|
||||||
|
errorType = await pokerogueApi.admin.unlinkAccountFromDiscord({
|
||||||
|
discordId: adminSearchResult.discordId,
|
||||||
|
username: adminSearchResult.username,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.warn("Unknown mode", mode, "for service", service);
|
||||||
|
}
|
||||||
|
} else if (service === "google") {
|
||||||
|
if (mode === "Link") {
|
||||||
|
errorType = await pokerogueApi.admin.linkAccountToGoogleId({
|
||||||
|
googleId: adminSearchResult.googleId,
|
||||||
|
username: adminSearchResult.username,
|
||||||
|
});
|
||||||
|
} else if (mode === "Unlink") {
|
||||||
|
errorType = await pokerogueApi.admin.unlinkAccountFromGoogleId({
|
||||||
|
googleId: adminSearchResult.googleId,
|
||||||
|
username: adminSearchResult.username,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.warn("Unknown mode", mode, "for service", service);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn("Unknown service", service);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errorType) {
|
||||||
|
// error - if response.status === this.httpUserNotFoundErrorCode that means the username can't be found in the db
|
||||||
|
return { adminSearchResult: adminSearchResult, error: true, errorType };
|
||||||
|
} else {
|
||||||
|
// success!
|
||||||
return { adminSearchResult: adminSearchResult, error: false };
|
return { adminSearchResult: adminSearchResult, error: false };
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
@ -3,8 +3,9 @@ import BattleScene from "../battle-scene";
|
|||||||
import * as Utils from "../utils";
|
import * as Utils from "../utils";
|
||||||
import { TextStyle, addTextObject } from "./text";
|
import { TextStyle, addTextObject } from "./text";
|
||||||
import { WindowVariant, addWindow } from "./ui-theme";
|
import { WindowVariant, addWindow } from "./ui-theme";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
interface RankingEntry {
|
export interface RankingEntry {
|
||||||
rank: integer,
|
rank: integer,
|
||||||
username: string,
|
username: string,
|
||||||
score: integer,
|
score: integer,
|
||||||
@ -12,7 +13,7 @@ interface RankingEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Don't forget to update translations when adding a new category
|
// Don't forget to update translations when adding a new category
|
||||||
enum ScoreboardCategory {
|
export enum ScoreboardCategory {
|
||||||
DAILY,
|
DAILY,
|
||||||
WEEKLY
|
WEEKLY
|
||||||
}
|
}
|
||||||
@ -191,18 +192,17 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Utils.executeIf(category !== this.category || this.pageCount === undefined,
|
Utils.executeIf(category !== this.category || this.pageCount === undefined,
|
||||||
() => Utils.apiFetch(`daily/rankingpagecount?category=${category}`).then(response => response.json()).then(count => this.pageCount = count)
|
() => pokerogueApi.daily.getRankingsPageCount({ category }).then(count => this.pageCount = count)
|
||||||
).then(() => {
|
).then(() => {
|
||||||
Utils.apiFetch(`daily/rankings?category=${category}&page=${page}`)
|
pokerogueApi.daily.getRankings({ category, page })
|
||||||
.then(response => response.json())
|
.then(rankings => {
|
||||||
.then(jsonResponse => {
|
|
||||||
this.page = page;
|
this.page = page;
|
||||||
this.category = category;
|
this.category = category;
|
||||||
this.titleLabel.setText(`${i18next.t(`menu:${ScoreboardCategory[category].toLowerCase()}Rankings`)}`);
|
this.titleLabel.setText(`${i18next.t(`menu:${ScoreboardCategory[category].toLowerCase()}Rankings`)}`);
|
||||||
this.pageNumberLabel.setText(page.toString());
|
this.pageNumberLabel.setText(page.toString());
|
||||||
if (jsonResponse) {
|
if (rankings) {
|
||||||
this.loadingLabel.setVisible(false);
|
this.loadingLabel.setVisible(false);
|
||||||
this.updateRankings(jsonResponse);
|
this.updateRankings(rankings);
|
||||||
} else {
|
} else {
|
||||||
this.loadingLabel.setText(i18next.t("menu:noRankings"));
|
this.loadingLabel.setText(i18next.t("menu:noRankings"));
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@ import BattleScene from "#app/battle-scene";
|
|||||||
import { addTextObject, TextStyle } from "./text";
|
import { addTextObject, TextStyle } from "./text";
|
||||||
import { addWindow } from "./ui-theme";
|
import { addWindow } from "./ui-theme";
|
||||||
import { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
|
import { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
interface BuildInteractableImageOpts {
|
interface BuildInteractableImageOpts {
|
||||||
scale?: number;
|
scale?: number;
|
||||||
@ -135,21 +136,16 @@ export default class LoginFormUiHandler extends FormModalUiHandler {
|
|||||||
if (!this.inputs[0].text) {
|
if (!this.inputs[0].text) {
|
||||||
return onFail(i18next.t("menu:emptyUsername"));
|
return onFail(i18next.t("menu:emptyUsername"));
|
||||||
}
|
}
|
||||||
Utils.apiPost("account/login", `username=${encodeURIComponent(this.inputs[0].text)}&password=${encodeURIComponent(this.inputs[1].text)}`, "application/x-www-form-urlencoded")
|
|
||||||
.then(response => {
|
const [ usernameInput, passwordInput ] = this.inputs;
|
||||||
if (!response.ok) {
|
|
||||||
return response.text();
|
pokerogueApi.account.login({ username: usernameInput.text, password: passwordInput.text }).then(error => {
|
||||||
}
|
if (!error) {
|
||||||
return response.json();
|
originalLoginAction && originalLoginAction();
|
||||||
})
|
} else {
|
||||||
.then(response => {
|
onFail(error);
|
||||||
if (response.hasOwnProperty("token")) {
|
}
|
||||||
Utils.setCookie(Utils.sessionIdKey, response.token);
|
});
|
||||||
originalLoginAction && originalLoginAction();
|
|
||||||
} else {
|
|
||||||
onFail(response);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
@ -14,6 +14,7 @@ import BgmBar from "#app/ui/bgm-bar";
|
|||||||
import AwaitableUiHandler from "./awaitable-ui-handler";
|
import AwaitableUiHandler from "./awaitable-ui-handler";
|
||||||
import { SelectModifierPhase } from "#app/phases/select-modifier-phase";
|
import { SelectModifierPhase } from "#app/phases/select-modifier-phase";
|
||||||
import { AdminMode, getAdminModeName } from "./admin-ui-handler";
|
import { AdminMode, getAdminModeName } from "./admin-ui-handler";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
enum MenuOptions {
|
enum MenuOptions {
|
||||||
GAME_SETTINGS,
|
GAME_SETTINGS,
|
||||||
@ -539,10 +540,7 @@ export default class MenuUiHandler extends MessageUiHandler {
|
|||||||
window.open(discordUrl, "_self");
|
window.open(discordUrl, "_self");
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
Utils.apiPost("/auth/discord/logout", undefined, undefined, true).then(res => {
|
pokerogueApi.unlinkDiscord().then(_isSuccess => {
|
||||||
if (!res.ok) {
|
|
||||||
console.error(`Unlink failed (${res.status}: ${res.statusText})`);
|
|
||||||
}
|
|
||||||
updateUserInfo().then(() => this.scene.reset(true, true));
|
updateUserInfo().then(() => this.scene.reset(true, true));
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
@ -560,10 +558,7 @@ export default class MenuUiHandler extends MessageUiHandler {
|
|||||||
window.open(googleUrl, "_self");
|
window.open(googleUrl, "_self");
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
Utils.apiPost("/auth/google/logout", undefined, undefined, true).then(res => {
|
pokerogueApi.unlinkGoogle().then(_isSuccess => {
|
||||||
if (!res.ok) {
|
|
||||||
console.error(`Unlink failed (${res.status}: ${res.statusText})`);
|
|
||||||
}
|
|
||||||
updateUserInfo().then(() => this.scene.reset(true, true));
|
updateUserInfo().then(() => this.scene.reset(true, true));
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
@ -612,11 +607,7 @@ export default class MenuUiHandler extends MessageUiHandler {
|
|||||||
success = true;
|
success = true;
|
||||||
const doLogout = () => {
|
const doLogout = () => {
|
||||||
ui.setMode(Mode.LOADING, {
|
ui.setMode(Mode.LOADING, {
|
||||||
buttonActions: [], fadeOut: () => Utils.apiFetch("account/logout", true).then(res => {
|
buttonActions: [], fadeOut: () => pokerogueApi.account.logout().then(() => {
|
||||||
if (!res.ok) {
|
|
||||||
console.error(`Log out failed (${res.status}: ${res.statusText})`);
|
|
||||||
}
|
|
||||||
Utils.removeCookie(Utils.sessionIdKey);
|
|
||||||
updateUserInfo().then(() => this.scene.reset(true, true));
|
updateUserInfo().then(() => this.scene.reset(true, true));
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler";
|
||||||
import { ModalConfig } from "./modal-ui-handler";
|
import { ModalConfig } from "./modal-ui-handler";
|
||||||
import * as Utils from "../utils";
|
|
||||||
import { Mode } from "./ui";
|
import { Mode } from "./ui";
|
||||||
import { TextStyle, addTextObject } from "./text";
|
import { TextStyle, addTextObject } from "./text";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
|
|
||||||
interface LanguageSetting {
|
interface LanguageSetting {
|
||||||
@ -110,27 +110,20 @@ export default class RegistrationFormUiHandler extends FormModalUiHandler {
|
|||||||
if (this.inputs[1].text !== this.inputs[2].text) {
|
if (this.inputs[1].text !== this.inputs[2].text) {
|
||||||
return onFail(i18next.t("menu:passwordNotMatchingConfirmPassword"));
|
return onFail(i18next.t("menu:passwordNotMatchingConfirmPassword"));
|
||||||
}
|
}
|
||||||
Utils.apiPost("account/register", `username=${encodeURIComponent(this.inputs[0].text)}&password=${encodeURIComponent(this.inputs[1].text)}`, "application/x-www-form-urlencoded")
|
const [ usernameInput, passwordInput ] = this.inputs;
|
||||||
.then(response => response.text())
|
pokerogueApi.account.register({ username: usernameInput.text, password: passwordInput.text })
|
||||||
.then(response => {
|
.then(registerError => {
|
||||||
if (!response) {
|
if (!registerError) {
|
||||||
Utils.apiPost("account/login", `username=${encodeURIComponent(this.inputs[0].text)}&password=${encodeURIComponent(this.inputs[1].text)}`, "application/x-www-form-urlencoded")
|
pokerogueApi.account.login({ username: usernameInput.text, password: passwordInput.text })
|
||||||
.then(response => {
|
.then(loginError => {
|
||||||
if (!response.ok) {
|
if (!loginError) {
|
||||||
return response.text();
|
|
||||||
}
|
|
||||||
return response.json();
|
|
||||||
})
|
|
||||||
.then(response => {
|
|
||||||
if (response.hasOwnProperty("token")) {
|
|
||||||
Utils.setCookie(Utils.sessionIdKey, response.token);
|
|
||||||
originalRegistrationAction && originalRegistrationAction();
|
originalRegistrationAction && originalRegistrationAction();
|
||||||
} else {
|
} else {
|
||||||
onFail(response);
|
onFail(loginError);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
onFail(response);
|
onFail(registerError);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
@ -242,6 +242,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
private pokemonEggMoveContainers: Phaser.GameObjects.Container[];
|
private pokemonEggMoveContainers: Phaser.GameObjects.Container[];
|
||||||
private pokemonEggMoveBgs: Phaser.GameObjects.NineSlice[];
|
private pokemonEggMoveBgs: Phaser.GameObjects.NineSlice[];
|
||||||
private pokemonEggMoveLabels: Phaser.GameObjects.Text[];
|
private pokemonEggMoveLabels: Phaser.GameObjects.Text[];
|
||||||
|
private pokemonCandyContainer: Phaser.GameObjects.Container;
|
||||||
private pokemonCandyIcon: Phaser.GameObjects.Sprite;
|
private pokemonCandyIcon: Phaser.GameObjects.Sprite;
|
||||||
private pokemonCandyDarknessOverlay: Phaser.GameObjects.Sprite;
|
private pokemonCandyDarknessOverlay: Phaser.GameObjects.Sprite;
|
||||||
private pokemonCandyOverlayIcon: Phaser.GameObjects.Sprite;
|
private pokemonCandyOverlayIcon: Phaser.GameObjects.Sprite;
|
||||||
@ -686,31 +687,36 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
this.pokemonLuckText.setOrigin(0, 0);
|
this.pokemonLuckText.setOrigin(0, 0);
|
||||||
this.starterSelectContainer.add(this.pokemonLuckText);
|
this.starterSelectContainer.add(this.pokemonLuckText);
|
||||||
|
|
||||||
this.pokemonCandyIcon = this.scene.add.sprite(4.5, 18, "candy");
|
// Candy icon and count
|
||||||
|
this.pokemonCandyContainer = this.scene.add.container(4.5, 18);
|
||||||
|
|
||||||
|
this.pokemonCandyIcon = this.scene.add.sprite(0, 0, "candy");
|
||||||
this.pokemonCandyIcon.setScale(0.5);
|
this.pokemonCandyIcon.setScale(0.5);
|
||||||
this.pokemonCandyIcon.setOrigin(0, 0);
|
this.pokemonCandyIcon.setOrigin(0, 0);
|
||||||
this.starterSelectContainer.add(this.pokemonCandyIcon);
|
this.pokemonCandyContainer.add(this.pokemonCandyIcon);
|
||||||
|
|
||||||
this.pokemonFormText = addTextObject(this.scene, 6, 42, "Form", TextStyle.WINDOW_ALT, { fontSize: "42px" });
|
this.pokemonCandyOverlayIcon = this.scene.add.sprite(0, 0, "candy_overlay");
|
||||||
this.pokemonFormText.setOrigin(0, 0);
|
|
||||||
this.starterSelectContainer.add(this.pokemonFormText);
|
|
||||||
|
|
||||||
this.pokemonCandyOverlayIcon = this.scene.add.sprite(4.5, 18, "candy_overlay");
|
|
||||||
this.pokemonCandyOverlayIcon.setScale(0.5);
|
this.pokemonCandyOverlayIcon.setScale(0.5);
|
||||||
this.pokemonCandyOverlayIcon.setOrigin(0, 0);
|
this.pokemonCandyOverlayIcon.setOrigin(0, 0);
|
||||||
this.starterSelectContainer.add(this.pokemonCandyOverlayIcon);
|
this.pokemonCandyContainer.add(this.pokemonCandyOverlayIcon);
|
||||||
|
|
||||||
this.pokemonCandyDarknessOverlay = this.scene.add.sprite(4.5, 18, "candy");
|
this.pokemonCandyDarknessOverlay = this.scene.add.sprite(0, 0, "candy");
|
||||||
this.pokemonCandyDarknessOverlay.setScale(0.5);
|
this.pokemonCandyDarknessOverlay.setScale(0.5);
|
||||||
this.pokemonCandyDarknessOverlay.setOrigin(0, 0);
|
this.pokemonCandyDarknessOverlay.setOrigin(0, 0);
|
||||||
this.pokemonCandyDarknessOverlay.setTint(0x000000);
|
this.pokemonCandyDarknessOverlay.setTint(0x000000);
|
||||||
this.pokemonCandyDarknessOverlay.setAlpha(0.50);
|
this.pokemonCandyDarknessOverlay.setAlpha(0.50);
|
||||||
this.pokemonCandyDarknessOverlay.setInteractive(new Phaser.Geom.Rectangle(0, 0, 16, 16), Phaser.Geom.Rectangle.Contains);
|
this.pokemonCandyContainer.add(this.pokemonCandyDarknessOverlay);
|
||||||
this.starterSelectContainer.add(this.pokemonCandyDarknessOverlay);
|
|
||||||
|
|
||||||
this.pokemonCandyCountText = addTextObject(this.scene, 14, 18, "x0", TextStyle.WINDOW_ALT, { fontSize: "56px" });
|
this.pokemonCandyCountText = addTextObject(this.scene, 9.5, 0, "x0", TextStyle.WINDOW_ALT, { fontSize: "56px" });
|
||||||
this.pokemonCandyCountText.setOrigin(0, 0);
|
this.pokemonCandyCountText.setOrigin(0, 0);
|
||||||
this.starterSelectContainer.add(this.pokemonCandyCountText);
|
this.pokemonCandyContainer.add(this.pokemonCandyCountText);
|
||||||
|
|
||||||
|
this.pokemonCandyContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, 30, 20), Phaser.Geom.Rectangle.Contains);
|
||||||
|
this.starterSelectContainer.add(this.pokemonCandyContainer);
|
||||||
|
|
||||||
|
this.pokemonFormText = addTextObject(this.scene, 6, 42, "Form", TextStyle.WINDOW_ALT, { fontSize: "42px" });
|
||||||
|
this.pokemonFormText.setOrigin(0, 0);
|
||||||
|
this.starterSelectContainer.add(this.pokemonFormText);
|
||||||
|
|
||||||
this.pokemonCaughtHatchedContainer = this.scene.add.container(2, 25);
|
this.pokemonCaughtHatchedContainer = this.scene.add.container(2, 25);
|
||||||
this.pokemonCaughtHatchedContainer.setScale(0.5);
|
this.pokemonCaughtHatchedContainer.setScale(0.5);
|
||||||
@ -2822,10 +2828,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
this.pokemonShinyIcon.setY(135);
|
this.pokemonShinyIcon.setY(135);
|
||||||
this.pokemonShinyIcon.setFrame(getVariantIcon(variant));
|
this.pokemonShinyIcon.setFrame(getVariantIcon(variant));
|
||||||
[
|
[
|
||||||
this.pokemonCandyIcon,
|
this.pokemonCandyContainer,
|
||||||
this.pokemonCandyOverlayIcon,
|
|
||||||
this.pokemonCandyDarknessOverlay,
|
|
||||||
this.pokemonCandyCountText,
|
|
||||||
this.pokemonHatchedIcon,
|
this.pokemonHatchedIcon,
|
||||||
this.pokemonHatchedCountText
|
this.pokemonHatchedCountText
|
||||||
].map(c => c.setVisible(false));
|
].map(c => c.setVisible(false));
|
||||||
@ -2834,31 +2837,26 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
this.pokemonCaughtHatchedContainer.setY(25);
|
this.pokemonCaughtHatchedContainer.setY(25);
|
||||||
this.pokemonShinyIcon.setY(117);
|
this.pokemonShinyIcon.setY(117);
|
||||||
this.pokemonCandyIcon.setTint(argbFromRgba(rgbHexToRgba(colorScheme[0])));
|
this.pokemonCandyIcon.setTint(argbFromRgba(rgbHexToRgba(colorScheme[0])));
|
||||||
this.pokemonCandyIcon.setVisible(true);
|
|
||||||
this.pokemonCandyOverlayIcon.setTint(argbFromRgba(rgbHexToRgba(colorScheme[1])));
|
this.pokemonCandyOverlayIcon.setTint(argbFromRgba(rgbHexToRgba(colorScheme[1])));
|
||||||
this.pokemonCandyOverlayIcon.setVisible(true);
|
|
||||||
this.pokemonCandyDarknessOverlay.setVisible(true);
|
|
||||||
this.pokemonCandyCountText.setText(`x${this.scene.gameData.starterData[species.speciesId].candyCount}`);
|
this.pokemonCandyCountText.setText(`x${this.scene.gameData.starterData[species.speciesId].candyCount}`);
|
||||||
this.pokemonCandyCountText.setVisible(true);
|
this.pokemonCandyContainer.setVisible(true);
|
||||||
this.pokemonFormText.setY(42);
|
this.pokemonFormText.setY(42);
|
||||||
this.pokemonHatchedIcon.setVisible(true);
|
this.pokemonHatchedIcon.setVisible(true);
|
||||||
this.pokemonHatchedCountText.setVisible(true);
|
this.pokemonHatchedCountText.setVisible(true);
|
||||||
|
|
||||||
const { currentFriendship, friendshipCap } = this.getFriendship(this.lastSpecies.speciesId);
|
const { currentFriendship, friendshipCap } = this.getFriendship(this.lastSpecies.speciesId);
|
||||||
const candyCropY = 16 - (16 * (currentFriendship / friendshipCap));
|
const candyCropY = 16 - (16 * (currentFriendship / friendshipCap));
|
||||||
|
|
||||||
if (this.pokemonCandyDarknessOverlay.visible) {
|
|
||||||
this.pokemonCandyDarknessOverlay.on("pointerover", () => {
|
|
||||||
this.scene.ui.showTooltip("", `${currentFriendship}/${friendshipCap}`, true);
|
|
||||||
this.activeTooltip = "CANDY";
|
|
||||||
});
|
|
||||||
this.pokemonCandyDarknessOverlay.on("pointerout", () => {
|
|
||||||
this.scene.ui.hideTooltip();
|
|
||||||
this.activeTooltip = undefined;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
this.pokemonCandyDarknessOverlay.setCrop(0, 0, 16, candyCropY);
|
this.pokemonCandyDarknessOverlay.setCrop(0, 0, 16, candyCropY);
|
||||||
|
|
||||||
|
this.pokemonCandyContainer.on("pointerover", () => {
|
||||||
|
this.scene.ui.showTooltip("", `${currentFriendship}/${friendshipCap}`, true);
|
||||||
|
this.activeTooltip = "CANDY";
|
||||||
|
});
|
||||||
|
this.pokemonCandyContainer.on("pointerout", () => {
|
||||||
|
this.scene.ui.hideTooltip();
|
||||||
|
this.activeTooltip = undefined;
|
||||||
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -2934,10 +2932,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
this.pokemonPassiveLabelText.setVisible(false);
|
this.pokemonPassiveLabelText.setVisible(false);
|
||||||
this.pokemonNatureLabelText.setVisible(false);
|
this.pokemonNatureLabelText.setVisible(false);
|
||||||
this.pokemonCaughtHatchedContainer.setVisible(false);
|
this.pokemonCaughtHatchedContainer.setVisible(false);
|
||||||
this.pokemonCandyIcon.setVisible(false);
|
this.pokemonCandyContainer.setVisible(false);
|
||||||
this.pokemonCandyOverlayIcon.setVisible(false);
|
|
||||||
this.pokemonCandyDarknessOverlay.setVisible(false);
|
|
||||||
this.pokemonCandyCountText.setVisible(false);
|
|
||||||
this.pokemonFormText.setVisible(false);
|
this.pokemonFormText.setVisible(false);
|
||||||
|
|
||||||
const defaultDexAttr = this.scene.gameData.getSpeciesDefaultDexAttr(species, true, true);
|
const defaultDexAttr = this.scene.gameData.getSpeciesDefaultDexAttr(species, true, true);
|
||||||
@ -2971,10 +2966,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
this.pokemonPassiveLabelText.setVisible(false);
|
this.pokemonPassiveLabelText.setVisible(false);
|
||||||
this.pokemonNatureLabelText.setVisible(false);
|
this.pokemonNatureLabelText.setVisible(false);
|
||||||
this.pokemonCaughtHatchedContainer.setVisible(false);
|
this.pokemonCaughtHatchedContainer.setVisible(false);
|
||||||
this.pokemonCandyIcon.setVisible(false);
|
this.pokemonCandyContainer.setVisible(false);
|
||||||
this.pokemonCandyOverlayIcon.setVisible(false);
|
|
||||||
this.pokemonCandyDarknessOverlay.setVisible(false);
|
|
||||||
this.pokemonCandyCountText.setVisible(false);
|
|
||||||
this.pokemonFormText.setVisible(false);
|
this.pokemonFormText.setVisible(false);
|
||||||
|
|
||||||
this.setSpeciesDetails(species!, { // TODO: is this bang correct?
|
this.setSpeciesDetails(species!, { // TODO: is this bang correct?
|
||||||
@ -3005,7 +2997,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
|| !isNullOrUndefined(formIndex) || !isNullOrUndefined(shiny) || !isNullOrUndefined(variant);
|
|| !isNullOrUndefined(formIndex) || !isNullOrUndefined(shiny) || !isNullOrUndefined(variant);
|
||||||
|
|
||||||
if (this.activeTooltip === "CANDY") {
|
if (this.activeTooltip === "CANDY") {
|
||||||
if (this.lastSpecies) {
|
if (this.lastSpecies && this.pokemonCandyContainer.visible) {
|
||||||
const { currentFriendship, friendshipCap } = this.getFriendship(this.lastSpecies.speciesId);
|
const { currentFriendship, friendshipCap } = this.getFriendship(this.lastSpecies.speciesId);
|
||||||
this.scene.ui.editTooltip("", `${currentFriendship}/${friendshipCap}`);
|
this.scene.ui.editTooltip("", `${currentFriendship}/${friendshipCap}`);
|
||||||
} else {
|
} else {
|
||||||
@ -3230,6 +3222,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler {
|
|||||||
this.pokemonPassiveLockedIcon.setVisible(!isUnlocked);
|
this.pokemonPassiveLockedIcon.setVisible(!isUnlocked);
|
||||||
this.pokemonPassiveLockedIcon.setPosition(iconPosition.x, iconPosition.y);
|
this.pokemonPassiveLockedIcon.setPosition(iconPosition.x, iconPosition.y);
|
||||||
|
|
||||||
|
} else if (this.activeTooltip === "PASSIVE") {
|
||||||
|
// No passive and passive tooltip is active > hide it
|
||||||
|
this.scene.ui.hideTooltip();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.pokemonNatureText.setText(getNatureName(natureIndex as unknown as Nature, true, true, false, this.scene.uiTheme));
|
this.pokemonNatureText.setText(getNatureName(natureIndex as unknown as Nature, true, true, false, this.scene.uiTheme));
|
||||||
|
@ -184,7 +184,7 @@ export default class SummaryUiHandler extends UiHandler {
|
|||||||
this.candyShadow.setTint(0x000000);
|
this.candyShadow.setTint(0x000000);
|
||||||
this.candyShadow.setAlpha(0.50);
|
this.candyShadow.setAlpha(0.50);
|
||||||
this.candyShadow.setScale(0.8);
|
this.candyShadow.setScale(0.8);
|
||||||
this.candyShadow.setInteractive(new Phaser.Geom.Rectangle(0, 0, 16, 16), Phaser.Geom.Rectangle.Contains);
|
this.candyShadow.setInteractive(new Phaser.Geom.Rectangle(0, 0, 30, 16), Phaser.Geom.Rectangle.Contains);
|
||||||
this.summaryContainer.add(this.candyShadow);
|
this.summaryContainer.add(this.candyShadow);
|
||||||
|
|
||||||
this.candyCountText = addTextObject(this.scene, 20, -146, "x0", TextStyle.WINDOW_ALT, { fontSize: "76px" });
|
this.candyCountText = addTextObject(this.scene, 20, -146, "x0", TextStyle.WINDOW_ALT, { fontSize: "76px" });
|
||||||
@ -203,7 +203,7 @@ export default class SummaryUiHandler extends UiHandler {
|
|||||||
this.friendshipShadow.setTint(0x000000);
|
this.friendshipShadow.setTint(0x000000);
|
||||||
this.friendshipShadow.setAlpha(0.50);
|
this.friendshipShadow.setAlpha(0.50);
|
||||||
this.friendshipShadow.setScale(0.8);
|
this.friendshipShadow.setScale(0.8);
|
||||||
this.friendshipShadow.setInteractive(new Phaser.Geom.Rectangle(0, 0, 16, 16), Phaser.Geom.Rectangle.Contains);
|
this.friendshipShadow.setInteractive(new Phaser.Geom.Rectangle(0, 0, 50, 16), Phaser.Geom.Rectangle.Contains);
|
||||||
this.summaryContainer.add(this.friendshipShadow);
|
this.summaryContainer.add(this.friendshipShadow);
|
||||||
|
|
||||||
this.friendshipText = addTextObject(this.scene, 20, -66, "x0", TextStyle.WINDOW_ALT, { fontSize: "76px" });
|
this.friendshipText = addTextObject(this.scene, 20, -66, "x0", TextStyle.WINDOW_ALT, { fontSize: "76px" });
|
||||||
|
@ -7,6 +7,7 @@ import { getSplashMessages } from "../data/splash-messages";
|
|||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import { TimedEventDisplay } from "#app/timed-event-manager";
|
import { TimedEventDisplay } from "#app/timed-event-manager";
|
||||||
import { version } from "../../package.json";
|
import { version } from "../../package.json";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
export default class TitleUiHandler extends OptionSelectUiHandler {
|
export default class TitleUiHandler extends OptionSelectUiHandler {
|
||||||
/** If the stats can not be retrieved, use this fallback value */
|
/** If the stats can not be retrieved, use this fallback value */
|
||||||
@ -78,12 +79,13 @@ export default class TitleUiHandler extends OptionSelectUiHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
updateTitleStats(): void {
|
updateTitleStats(): void {
|
||||||
Utils.apiFetch("game/titlestats")
|
pokerogueApi.getGameTitleStats()
|
||||||
.then(request => request.json())
|
|
||||||
.then(stats => {
|
.then(stats => {
|
||||||
this.playerCountLabel.setText(`${stats.playerCount} ${i18next.t("menu:playersOnline")}`);
|
if (stats) {
|
||||||
if (this.splashMessage === "splashMessages:battlesWon") {
|
this.playerCountLabel.setText(`${stats.playerCount} ${i18next.t("menu:playersOnline")}`);
|
||||||
this.splashMessageText.setText(i18next.t(this.splashMessage, { count: stats.battleCount }));
|
if (this.splashMessage === "splashMessages:battlesWon") {
|
||||||
|
this.splashMessageText.setText(i18next.t(this.splashMessage, { count: stats.battleCount }));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
|
35
src/ui/ui.ts
35
src/ui/ui.ts
@ -391,6 +391,7 @@ export default class UI extends Phaser.GameObjects.Container {
|
|||||||
this.tooltipContent.y = title ? 16 : 4;
|
this.tooltipContent.y = title ? 16 : 4;
|
||||||
this.tooltipBg.width = Math.min(Math.max(this.tooltipTitle.displayWidth, this.tooltipContent.displayWidth) + 12, 838);
|
this.tooltipBg.width = Math.min(Math.max(this.tooltipTitle.displayWidth, this.tooltipContent.displayWidth) + 12, 838);
|
||||||
this.tooltipBg.height = (title ? 31 : 19) + 10.5 * (wrappedContent.split("\n").length - 1);
|
this.tooltipBg.height = (title ? 31 : 19) + 10.5 * (wrappedContent.split("\n").length - 1);
|
||||||
|
this.tooltipTitle.x = this.tooltipBg.width / 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
hideTooltip(): void {
|
hideTooltip(): void {
|
||||||
@ -400,12 +401,34 @@ export default class UI extends Phaser.GameObjects.Container {
|
|||||||
|
|
||||||
update(): void {
|
update(): void {
|
||||||
if (this.tooltipContainer.visible) {
|
if (this.tooltipContainer.visible) {
|
||||||
const xReverse = this.scene.game.input.mousePointer && this.scene.game.input.mousePointer.x >= this.scene.game.canvas.width - this.tooltipBg.width * 6 - 12;
|
const isTouch = (this.scene as BattleScene).inputMethod === "touch";
|
||||||
const yReverse = this.scene.game.input.mousePointer && this.scene.game.input.mousePointer.y >= this.scene.game.canvas.height - this.tooltipBg.height * 6 - 12;
|
const pointerX = this.scene.game.input.activePointer.x;
|
||||||
this.tooltipContainer.setPosition(
|
const pointerY = this.scene.game.input.activePointer.y;
|
||||||
!xReverse ? this.scene.game.input.mousePointer!.x / 6 + 2 : this.scene.game.input.mousePointer!.x / 6 - this.tooltipBg.width - 2,
|
const tooltipWidth = this.tooltipBg.width;
|
||||||
!yReverse ? this.scene.game.input.mousePointer!.y / 6 + 2 : this.scene.game.input.mousePointer!.y / 6 - this.tooltipBg.height - 2,
|
const tooltipHeight = this.tooltipBg.height;
|
||||||
);
|
const padding = 2;
|
||||||
|
|
||||||
|
// Default placement is top left corner of the screen on mobile. Otherwise below the cursor, to the right
|
||||||
|
let x = isTouch ? padding : pointerX / 6 + padding;
|
||||||
|
let y = isTouch ? padding : pointerY / 6 + padding;
|
||||||
|
|
||||||
|
if (isTouch) {
|
||||||
|
// If we are in the top left quadrant on mobile, move the tooltip to the top right corner
|
||||||
|
if (pointerX <= this.scene.game.canvas.width / 2 && pointerY <= this.scene.game.canvas.height / 2) {
|
||||||
|
x = this.scene.game.canvas.width / 6 - tooltipWidth - padding;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If the tooltip would go offscreen on the right, or is close to it, move to the left of the cursor
|
||||||
|
if (x + tooltipWidth + padding > this.scene.game.canvas.width / 6) {
|
||||||
|
x = Math.max(padding, pointerX / 6 - tooltipWidth - padding);
|
||||||
|
}
|
||||||
|
// If the tooltip would go offscreen at the bottom, or is close to it, move above the cursor
|
||||||
|
if (y + tooltipHeight + padding > this.scene.game.canvas.height / 6) {
|
||||||
|
y = Math.max(padding, pointerY / 6 - tooltipHeight - padding);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.tooltipContainer.setPosition(x, y);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
52
src/utils.ts
52
src/utils.ts
@ -1,6 +1,7 @@
|
|||||||
import { MoneyFormat } from "#enums/money-format";
|
import { MoneyFormat } from "#enums/money-format";
|
||||||
import { Moves } from "#enums/moves";
|
import { Moves } from "#enums/moves";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
|
import { pokerogueApi } from "#app/plugins/api/pokerogue-api";
|
||||||
|
|
||||||
export type nil = null | undefined;
|
export type nil = null | undefined;
|
||||||
|
|
||||||
@ -258,9 +259,16 @@ export const isLocal = (
|
|||||||
/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(window.location.hostname)) &&
|
/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(window.location.hostname)) &&
|
||||||
window.location.port !== "") || window.location.hostname === "";
|
window.location.port !== "") || window.location.hostname === "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Refer to [pokerogue-api.ts](./plugins/api/pokerogue-api.ts) instead
|
||||||
|
*/
|
||||||
export const localServerUrl = import.meta.env.VITE_SERVER_URL ?? `http://${window.location.hostname}:${window.location.port + 1}`;
|
export const localServerUrl = import.meta.env.VITE_SERVER_URL ?? `http://${window.location.hostname}:${window.location.port + 1}`;
|
||||||
|
|
||||||
// Set the server URL based on whether it's local or not
|
/**
|
||||||
|
* Set the server URL based on whether it's local or not
|
||||||
|
*
|
||||||
|
* @deprecated Refer to [pokerogue-api.ts](./plugins/api/pokerogue-api.ts) instead
|
||||||
|
*/
|
||||||
export const apiUrl = localServerUrl ?? "https://api.pokerogue.net";
|
export const apiUrl = localServerUrl ?? "https://api.pokerogue.net";
|
||||||
// used to disable api calls when isLocal is true and a server is not found
|
// used to disable api calls when isLocal is true and a server is not found
|
||||||
export let isLocalServerConnected = true;
|
export let isLocalServerConnected = true;
|
||||||
@ -307,48 +315,14 @@ export function getCookie(cName: string): string {
|
|||||||
* with a GET request to verify if a server is running,
|
* with a GET request to verify if a server is running,
|
||||||
* sets isLocalServerConnected based on results
|
* sets isLocalServerConnected based on results
|
||||||
*/
|
*/
|
||||||
export function localPing() {
|
export async function localPing() {
|
||||||
if (isLocal) {
|
if (isLocal) {
|
||||||
apiFetch("game/titlestats")
|
const titleStats = await pokerogueApi.getGameTitleStats();
|
||||||
.then(resolved => isLocalServerConnected = true,
|
isLocalServerConnected = !!titleStats;
|
||||||
rejected => isLocalServerConnected = false
|
console.log("isLocalServerConnected:", isLocalServerConnected);
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function apiFetch(path: string, authed: boolean = false): Promise<Response> {
|
|
||||||
return (isLocal && isLocalServerConnected) || !isLocal ? new Promise((resolve, reject) => {
|
|
||||||
const request = {};
|
|
||||||
if (authed) {
|
|
||||||
const sId = getCookie(sessionIdKey);
|
|
||||||
if (sId) {
|
|
||||||
request["headers"] = { "Authorization": sId };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fetch(`${apiUrl}/${path}`, request)
|
|
||||||
.then(response => resolve(response))
|
|
||||||
.catch(err => reject(err));
|
|
||||||
}) : new Promise(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function apiPost(path: string, data?: any, contentType: string = "application/json", authed: boolean = false): Promise<Response> {
|
|
||||||
return (isLocal && isLocalServerConnected) || !isLocal ? new Promise((resolve, reject) => {
|
|
||||||
const headers = {
|
|
||||||
"Accept": contentType,
|
|
||||||
"Content-Type": contentType,
|
|
||||||
};
|
|
||||||
if (authed) {
|
|
||||||
const sId = getCookie(sessionIdKey);
|
|
||||||
if (sId) {
|
|
||||||
headers["Authorization"] = sId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fetch(`${apiUrl}/${path}`, { method: "POST", headers: headers, body: data })
|
|
||||||
.then(response => resolve(response))
|
|
||||||
.catch(err => reject(err));
|
|
||||||
}) : new Promise(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Alias for the constructor of a class */
|
/** Alias for the constructor of a class */
|
||||||
export type Constructor<T> = new(...args: unknown[]) => T;
|
export type Constructor<T> = new(...args: unknown[]) => T;
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user