diff --git a/src/account.ts b/src/account.ts index afb9aca35..357cd5af4 100644 --- a/src/account.ts +++ b/src/account.ts @@ -7,18 +7,20 @@ export interface UserInfo { } export let loggedInUser: UserInfo = null; +export const clientSessionId = Utils.randomString(32); export function updateUserInfo(): Promise<[boolean, integer]> { return new Promise<[boolean, integer]>(resolve => { if (bypassLogin) { + loggedInUser = { username: 'Guest', lastSessionSlot: -1 }; let lastSessionSlot = -1; for (let s = 0; s < 2; s++) { - if (localStorage.getItem(`sessionData${s ? s : ''}`)) { + if (localStorage.getItem(`sessionData${s ? s : ''}_${loggedInUser.username}`)) { lastSessionSlot = s; break; } } - loggedInUser = { username: 'Guest', lastSessionSlot: lastSessionSlot }; + loggedInUser.lastSessionSlot = lastSessionSlot; return resolve([ true, 200 ]); } Utils.apiFetch('account/info', true).then(response => { diff --git a/src/battle-scene.ts b/src/battle-scene.ts index 111e5439b..f15cf1a52 100644 --- a/src/battle-scene.ts +++ b/src/battle-scene.ts @@ -88,6 +88,7 @@ export default class BattleScene extends SceneBase { public uiInputs: UiInputs; public sessionPlayTime: integer = null; + public lastSavePlayTime: integer = null; public masterVolume: number = 0.5; public bgmVolume: number = 1; public seVolume: number = 1; @@ -452,6 +453,8 @@ export default class BattleScene extends SceneBase { initSession(): void { if (this.sessionPlayTime === null) this.sessionPlayTime = 0; + if (this.lastSavePlayTime === null) + this.lastSavePlayTime = 0; if (this.playTimeTimer) this.playTimeTimer.destroy(); @@ -464,6 +467,8 @@ export default class BattleScene extends SceneBase { this.gameData.gameStats.playTime++; if (this.sessionPlayTime !== null) this.sessionPlayTime++; + if (this.lastSavePlayTime !== null) + this.lastSavePlayTime++; } }); @@ -1007,6 +1012,7 @@ export default class BattleScene extends SceneBase { case Species.FLORGES: case Species.FURFROU: case Species.ORICORIO: + case Species.MAGEARNA: case Species.SQUAWKABILLY: case Species.TATSUGIRI: case Species.PALDEA_TAUROS: diff --git a/src/data/ability.ts b/src/data/ability.ts index 179d95045..8b4428dd4 100644 --- a/src/data/ability.ts +++ b/src/data/ability.ts @@ -1770,7 +1770,7 @@ export class StatusEffectImmunityAbAttr extends PreSetStatusAbAttr { } getTriggerMessage(pokemon: Pokemon, abilityName: string, ...args: any[]): string { - return getPokemonMessage(pokemon, `'s ${abilityName}\nprevents ${this.immuneEffects.length ? getStatusEffectDescriptor(args[0] as StatusEffect) : 'status problems'}!`); + return getPokemonMessage(pokemon, `'s ${abilityName}\nprevents ${this.immuneEffects.length ? getStatusEffectDescriptor(this.immuneEffects[0]) : 'status problems'}!`); } } diff --git a/src/data/biomes.ts b/src/data/biomes.ts index 61da0410d..db13158fa 100644 --- a/src/data/biomes.ts +++ b/src/data/biomes.ts @@ -48,7 +48,7 @@ export const biomeLinks: BiomeLinks = { [Biome.SEABED]: [ Biome.CAVE, [ Biome.VOLCANO, 4 ] ], [Biome.MOUNTAIN]: [ Biome.VOLCANO, [ Biome.WASTELAND, 3 ] ], [Biome.BADLANDS]: [ Biome.DESERT, Biome.MOUNTAIN ], - [Biome.CAVE]: [ Biome.BADLANDS, Biome.BEACH ], + [Biome.CAVE]: [ Biome.BADLANDS, Biome.LAKE ], [Biome.DESERT]: Biome.RUINS, [Biome.ICE_CAVE]: Biome.SNOWY_FOREST, [Biome.MEADOW]: [ Biome.PLAINS, [ Biome.FAIRY_CAVE, 2 ] ], @@ -7871,4 +7871,4 @@ export const biomeTrainerPools: BiomeTrainerPools = { } console.log(JSON.stringify(pokemonBiomes, null, ' '));*/ -} \ No newline at end of file +} diff --git a/src/data/daily-run.ts b/src/data/daily-run.ts index 5371b87a6..c1a1206f3 100644 --- a/src/data/daily-run.ts +++ b/src/data/daily-run.ts @@ -13,14 +13,15 @@ export interface DailyRunConfig { } export function fetchDailyRunSeed(): Promise { - return new Promise(resolve => { + return new Promise((resolve, reject) => { Utils.apiFetch('daily/seed').then(response => { if (!response.ok) { resolve(null); return; } return response.text(); - }).then(seed => resolve(seed)); + }).then(seed => resolve(seed)) + .catch(err => reject(err)); }); } diff --git a/src/data/move.ts b/src/data/move.ts index 3c99ad8c1..5f5765c1d 100644 --- a/src/data/move.ts +++ b/src/data/move.ts @@ -434,29 +434,66 @@ export class SelfStatusMove extends Move { } } +/** + * Base class defining all {@link Move} Attributes + * @abstract + */ export abstract class MoveAttr { + /** Should this {@link Move} target the user? */ public selfTarget: boolean; constructor(selfTarget: boolean = false) { this.selfTarget = selfTarget; } + /** + * Applies move attributes + * @see {@link applyMoveAttrsInternal} + * @virtual + * @param user The {@link Pokemon} using the move + * @param target The target {@link Pokemon} of the move + * @param move The {@link Move} being used + * @param args Set of unique arguments needed by this attribute + * @returns true if the application succeeds + */ apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean | Promise { return true; } + /** + * @virtual + * @returns the {@link MoveCondition} or {@link MoveConditionFunc} for this {@link Move} + */ getCondition(): MoveCondition | MoveConditionFunc { return null; } + /** + * @virtual + * @param user The {@link Pokemon} using the move + * @param target The target {@link Pokemon} of the move + * @param move The {@link Move} being used + * @param cancelled A {@link Utils.BooleanHolder} which stores if the move should fail + * @returns the string representing failure of this {@link Move} + */ getFailedText(user: Pokemon, target: Pokemon, move: Move, cancelled: Utils.BooleanHolder): string | null { return null; } + /** + * Used by the Enemy AI to rank an attack based on a given user + * @see {@link EnemyPokemon.getNextMove} + * @virtual + */ getUserBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer { return 0; } + /** + * Used by the Enemy AI to rank an attack based on a given target + * @see {@link EnemyPokemon.getNextMove} + * @virtual + */ getTargetBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer { return 0; } @@ -470,6 +507,9 @@ export enum MoveEffectTrigger { POST_TARGET, } +/** Base class defining all Move Effect Attributes + * @extends MoveAttr + */ export class MoveEffectAttr extends MoveAttr { public trigger: MoveEffectTrigger; public firstHitOnly: boolean; @@ -480,11 +520,21 @@ export class MoveEffectAttr extends MoveAttr { this.firstHitOnly = firstHitOnly; } + /** + * Determines whether the {@link Move}'s effects are valid to {@link apply} + * @virtual + * @param user The {@link Pokemon} using the move + * @param target The target {@link Pokemon} of the move + * @param move The {@link Move} being used + * @param args Set of unique arguments needed by this attribute + * @returns true if the application succeeds + */ canApply(user: Pokemon, target: Pokemon, move: Move, args: any[]) { return !!(this.selfTarget ? user.hp && !user.getTag(BattlerTagType.FRENZY) : target.hp) && (this.selfTarget || !target.getTag(BattlerTagType.PROTECTED) || move.hasFlag(MoveFlags.IGNORE_PROTECT)); } + /** Applies move effects so long as they are able based on {@link canApply} */ apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean | Promise { return this.canApply(user, target, move, args); } @@ -738,17 +788,65 @@ export class RecoilAttr extends MoveEffectAttr { } } + +/** + * Attribute used for moves which self KO the user regardless if the move hits a target + * @extends MoveEffectAttr + * @see {@link apply} + **/ export class SacrificialAttr extends MoveEffectAttr { constructor() { - super(true, MoveEffectTrigger.PRE_APPLY); + super(true, MoveEffectTrigger.POST_TARGET); } + /** + * Deals damage to the user equal to their current hp + * @param user Pokemon that used the move + * @param target The target of the move + * @param move Move with this attribute + * @param args N/A + * @returns true if the function succeeds + **/ apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + user.damageAndUpdate(user.hp, HitResult.OTHER, false, true, true); + user.turnData.damageTaken += user.hp; + + return true; + } + + getUserBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer { + if (user.isBoss()) + return -20; + return Math.ceil(((1 - user.getHpRatio()) * 10 - 10) * (target.getAttackTypeEffectiveness(move.type, user) - 0.5)); + } +} + +/** + * Attribute used for moves which self KO the user but only if the move hits a target + * @extends MoveEffectAttr + * @see {@link apply} + **/ +export class SacrificialAttrOnHit extends MoveEffectAttr { + constructor() { + super(true, MoveEffectTrigger.POST_TARGET); + } + + /** + * Deals damage to the user equal to their current hp if the move lands + * @param user Pokemon that used the move + * @param target The target of the move + * @param move Move with this attribute + * @param args N/A + * @returns true if the function succeeds + **/ + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + + // If the move fails to hit a target, then the user does not faint and the function returns false if (!super.apply(user, target, move, args)) return false; user.damageAndUpdate(user.hp, HitResult.OTHER, false, true, true); - user.turnData.damageTaken += user.hp; + user.turnData.damageTaken += user.hp; return true; } @@ -806,8 +904,15 @@ export enum MultiHitType { _1_TO_10, } +/** + * Heals the user or target by {@link healRatio} depending on the value of {@link selfTarget} + * @extends MoveEffectAttr + * @see {@link apply} + */ export class HealAttr extends MoveEffectAttr { + /** The percentage of {@link Stat.HP} to heal */ private healRatio: number; + /** Should an animation be shown? */ private showAnim: boolean; constructor(healRatio?: number, showAnim?: boolean, selfTarget?: boolean) { @@ -822,6 +927,10 @@ export class HealAttr extends MoveEffectAttr { return true; } + /** + * Creates a new {@link PokemonHealPhase}. + * This heals the target and shows the appropriate message. + */ addHealPhase(target: Pokemon, healRatio: number) { target.scene.unshiftPhase(new PokemonHealPhase(target.scene, target.getBattlerIndex(), Math.max(Math.floor(target.getMaxHp() * healRatio), 1), getPokemonMessage(target, ' \nhad its HP restored.'), true, !this.showAnim)); @@ -903,7 +1012,7 @@ export class IgnoreWeatherTypeDebuffAttr extends MoveAttr { * @param user Pokemon that used the move * @param target N/A * @param move Move with this attribute - * @param args Utils.NumberHolder for arenaAttackTypeMultiplier + * @param args [0] Utils.NumberHolder for arenaAttackTypeMultiplier * @returns true if the function succeeds */ apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { @@ -963,27 +1072,19 @@ export class SandHealAttr extends WeatherHealAttr { } /** - * Heals the target by either {@link normalHealRatio} or {@link boostedHealRatio} + * Heals the target or the user by either {@link normalHealRatio} or {@link boostedHealRatio} * depending on the evaluation of {@link condition} + * @extends HealAttr * @see {@link apply} - * @param user The Pokemon using this move - * @param target The target Pokemon of this move - * @param move This move - * @param args N/A - * @returns if the move was successful */ export class BoostHealAttr extends HealAttr { + /** Healing received when {@link condition} is false */ private normalHealRatio?: number; + /** Healing received when {@link condition} is true */ private boostedHealRatio?: number; + /** The lambda expression to check against when boosting the healing value */ private condition?: MoveConditionFunc; - /** - * @param normalHealRatio Healing received when {@link condition} is false - * @param boostedHealRatio Healing received when {@link condition} is true - * @param showAnim Should a healing animation be showed? - * @param selfTarget Should the move target the user? - * @param condition The condition to check against when boosting the healing value - */ constructor(normalHealRatio?: number, boostedHealRatio?: number, showAnim?: boolean, selfTarget?: boolean, condition?: MoveConditionFunc) { super(normalHealRatio, showAnim, selfTarget); this.normalHealRatio = normalHealRatio; @@ -991,6 +1092,13 @@ export class BoostHealAttr extends HealAttr { this.condition = condition; } + /** + * @param user The Pokemon using this move + * @param target The target Pokemon of this move + * @param move This move + * @param args N/A + * @returns true if the move was successful + */ apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const healRatio = this.condition(user, target, move) ? this.boostedHealRatio : this.normalHealRatio; this.addHealPhase(target, healRatio); @@ -4960,7 +5068,7 @@ export function initMoves() { new StatusMove(Moves.WILL_O_WISP, Type.FIRE, 85, 15, -1, 0, 3) .attr(StatusEffectAttr, StatusEffect.BURN), new StatusMove(Moves.MEMENTO, Type.DARK, 100, 10, -1, 0, 3) - .attr(SacrificialAttr) + .attr(SacrificialAttrOnHit) .attr(StatChangeAttr, [ BattleStat.ATK, BattleStat.SPATK ], -2), new AttackMove(Moves.FACADE, Type.NORMAL, MoveCategory.PHYSICAL, 70, 100, 20, -1, 0, 3) .attr(MovePowerMultiplierAttr, (user, target, move) => user.status @@ -5496,7 +5604,7 @@ export function initMoves() { new AttackMove(Moves.SPACIAL_REND, Type.DRAGON, MoveCategory.SPECIAL, 100, 95, 5, -1, 0, 4) .attr(HighCritAttr), new SelfStatusMove(Moves.LUNAR_DANCE, Type.PSYCHIC, -1, 10, -1, 0, 4) - .attr(SacrificialAttr) + .attr(SacrificialAttrOnHit) .danceMove() .triageMove() .unimplemented(), @@ -5645,7 +5753,7 @@ export function initMoves() { .partial(), new AttackMove(Moves.FINAL_GAMBIT, Type.FIGHTING, MoveCategory.SPECIAL, -1, 100, 5, -1, 0, 5) .attr(UserHpDamageAttr) - .attr(SacrificialAttr), + .attr(SacrificialAttrOnHit), new StatusMove(Moves.BESTOW, Type.NORMAL, -1, 15, -1, 0, 5) .ignoresProtect() .unimplemented(), diff --git a/src/locales/de/ability-trigger.ts b/src/locales/de/ability-trigger.ts index 889007412..27d2053b6 100644 --- a/src/locales/de/ability-trigger.ts +++ b/src/locales/de/ability-trigger.ts @@ -1,5 +1,5 @@ import { SimpleTranslationEntries } from "#app/plugins/i18n"; export const abilityTriggers: SimpleTranslationEntries = { - 'blockRecoilDamage' : `{{pokemonName}}'s {{abilityName}}\nprotected it from recoil!`, -} as const; \ No newline at end of file + 'blockRecoilDamage' : `{{pokemonName}} wurde durch {{abilityName}}\nvor Rückstoß geschützt!`, +} as const; diff --git a/src/locales/de/battle.ts b/src/locales/de/battle.ts index bff8c688d..ca0e60bf9 100644 --- a/src/locales/de/battle.ts +++ b/src/locales/de/battle.ts @@ -9,11 +9,11 @@ export const battle: SimpleTranslationEntries = { "trainerComeBack": "{{trainerName}} ruft {{pokemonName}} zurück!", "playerGo": "Los! {{pokemonName}}!", "trainerGo": "{{trainerName}} sendet {{pokemonName}} raus!", - "switchQuestion": "Willst du\n{{pokemonName}} auswechseln?", + "switchQuestion": "Möchtest du\n{{pokemonName}} auswechseln?", "trainerDefeated": `{{trainerName}}\nwurde besiegt!`, "pokemonCaught": "{{pokemonName}} wurde gefangen!", "pokemon": "Pokémon", - "sendOutPokemon": "Los! {{pokemonName}}!", + "sendOutPokemon": "Los, {{pokemonName}}!", "hitResultCriticalHit": "Ein Volltreffer!", "hitResultSuperEffective": "Das ist sehr effektiv!", "hitResultNotVeryEffective": "Das ist nicht sehr effektiv…", @@ -26,28 +26,28 @@ export const battle: SimpleTranslationEntries = { "learnMove": "{{pokemonName}} erlernt\n{{moveName}}!", "learnMovePrompt": "{{pokemonName}} versucht, {{moveName}} zu erlernen.", "learnMoveLimitReached": "Aber {{pokemonName}} kann nur\nmaximal vier Attacken erlernen.", - "learnMoveReplaceQuestion": "Soll eine andere Attacke durch\n{{moveName}} ersetzt werden?", + "learnMoveReplaceQuestion": "Soll eine bekannte Attacke durch\n{{moveName}} ersetzt werden?", "learnMoveStopTeaching": "{{moveName}} nicht\nerlernen?", "learnMoveNotLearned": "{{pokemonName}} hat\n{{moveName}} nicht erlernt.", "learnMoveForgetQuestion": "Welche Attacke soll vergessen werden?", "learnMoveForgetSuccess": "{{pokemonName}} hat\n{{moveName}} vergessen.", "levelCapUp": "Das Levellimit\nhat sich zu {{levelCap}} erhöht!", "moveNotImplemented": "{{moveName}} ist noch nicht implementiert und kann nicht ausgewählt werden.", - "moveNoPP": "Du hast keine AP für\ndiese Attacke mehr übrig!", + "moveNoPP": "Es sind keine AP für\ndiese Attacke mehr übrig!", "moveDisabled": "{{moveName}} ist deaktiviert!", "noPokeballForce": "Eine unsichtbare Kraft\nverhindert die Nutzung von Pokébällen.", "noPokeballTrainer": "Du kannst das Pokémon\neines anderen Trainers nicht fangen!", - "noPokeballMulti": "Du kannst erst einen Pokéball werden,\nwenn nur noch ein Pokémon übrig ist!", + "noPokeballMulti": "Du kannst erst einen Pokéball werfen,\nwenn nur noch ein Pokémon übrig ist!", "noPokeballStrong": "Das Ziel-Pokémon ist zu stark, um gefangen zu werden!\nDu musst es zuerst schwächen!", "noEscapeForce": "Eine unsichtbare Kraft\nverhindert die Flucht.", "noEscapeTrainer": "Du kannst nicht\naus einem Trainerkampf fliehen!", "noEscapePokemon": "{{pokemonName}}'s {{moveName}}\nverhindert {{escapeVerb}}!", "runAwaySuccess": "Du bist entkommen!", - "runAwayCannotEscape": 'Du kannst nicht fliehen!', + "runAwayCannotEscape": 'Flucht unmöglich!', "escapeVerbSwitch": "auswechseln", "escapeVerbFlee": "flucht", "skipItemQuestion": "Bist du sicher, dass du kein Item nehmen willst?", "notDisabled": "{{pokemonName}}'s {{moveName}} ist\nnicht mehr deaktiviert!", "eggHatching": "Oh?", "ivScannerUseQuestion": "IV-Scanner auf {{pokemonName}} benutzen?" -} as const; \ No newline at end of file +} as const; diff --git a/src/phases.ts b/src/phases.ts index 1b5197ff5..51d620aa2 100644 --- a/src/phases.ts +++ b/src/phases.ts @@ -2,7 +2,7 @@ import BattleScene, { AnySound, bypassLogin, startingWave } from "./battle-scene import { default as Pokemon, PlayerPokemon, EnemyPokemon, PokemonMove, MoveResult, DamageResult, FieldPosition, HitResult, TurnMove } from "./field/pokemon"; import * as Utils from './utils'; import { Moves } from "./data/enums/moves"; -import { allMoves, applyMoveAttrs, BypassSleepAttr, ChargeAttr, applyFilteredMoveAttrs, HitsTagAttr, MissEffectAttr, MoveAttr, MoveEffectAttr, MoveFlags, MultiHitAttr, OverrideMoveEffectAttr, VariableAccuracyAttr, MoveTarget, OneHitKOAttr, getMoveTargets, MoveTargetSet, MoveEffectTrigger, CopyMoveAttr, AttackMove, SelfStatusMove, DelayedAttackAttr, RechargeAttr, PreMoveMessageAttr, HealStatusEffectAttr, IgnoreOpponentStatChangesAttr, NoEffectAttr, BypassRedirectAttr, FixedDamageAttr, PostVictoryStatChangeAttr, OneHitKOAccuracyAttr, ForceSwitchOutAttr, VariableTargetAttr } from "./data/move"; +import { allMoves, applyMoveAttrs, BypassSleepAttr, ChargeAttr, applyFilteredMoveAttrs, HitsTagAttr, MissEffectAttr, MoveAttr, MoveEffectAttr, MoveFlags, MultiHitAttr, OverrideMoveEffectAttr, VariableAccuracyAttr, MoveTarget, OneHitKOAttr, getMoveTargets, MoveTargetSet, MoveEffectTrigger, CopyMoveAttr, AttackMove, SelfStatusMove, DelayedAttackAttr, RechargeAttr, PreMoveMessageAttr, HealStatusEffectAttr, IgnoreOpponentStatChangesAttr, NoEffectAttr, BypassRedirectAttr, FixedDamageAttr, PostVictoryStatChangeAttr, OneHitKOAccuracyAttr, ForceSwitchOutAttr, VariableTargetAttr, SacrificialAttr } from "./data/move"; import { Mode } from './ui/ui'; import { Command } from "./ui/command-ui-handler"; import { Stat } from "./data/pokemon-stat"; @@ -289,7 +289,7 @@ export class TitlePhase extends Phase { } this.scene.sessionSlotId = slotId; - fetchDailyRunSeed().then(seed => { + const generateDaily = (seed: string) => { this.scene.gameMode = gameModes[GameModes.DAILY]; this.scene.setSeed(seed); @@ -330,11 +330,21 @@ export class TitlePhase extends Phase { this.scene.newBattle(); this.scene.arena.init(); this.scene.sessionPlayTime = 0; + this.scene.lastSavePlayTime = 0; this.end(); }); - }).catch(err => { - console.error("Failed to load daily run:\n", err); - }); + }; + + // If Online, calls seed fetch from db to generate daily run. If Offline, generates a daily run based on current date. + if (!Utils.isLocal) { + fetchDailyRunSeed().then(seed => { + generateDaily(seed); + }).catch(err => { + console.error("Failed to load daily run:\n", err); + }); + } else { + generateDaily(btoa(new Date().toISOString().substring(0, 10))); + } }); } @@ -384,8 +394,12 @@ export class UnavailablePhase extends Phase { } export class ReloadSessionPhase extends Phase { - constructor(scene: BattleScene) { + private systemDataStr: string; + + constructor(scene: BattleScene, systemDataStr?: string) { super(scene); + + this.systemDataStr = systemDataStr; } start(): void { @@ -401,7 +415,9 @@ export class ReloadSessionPhase extends Phase { delayElapsed = true; }); - this.scene.gameData.loadSystem().then(() => { + this.scene.gameData.clearLocalData(); + + (this.systemDataStr ? this.scene.gameData.initSystem(this.systemDataStr) : this.scene.gameData.loadSystem()).then(() => { if (delayElapsed) this.end(); else @@ -522,6 +538,7 @@ export class SelectStarterPhase extends Phase { this.scene.newBattle(); this.scene.arena.init(); this.scene.sessionPlayTime = 0; + this.scene.lastSavePlayTime = 0; this.end(); }); }); @@ -775,7 +792,7 @@ export class EncounterPhase extends BattlePhase { this.scene.ui.setMode(Mode.MESSAGE).then(() => { if (!this.loaded) { - this.scene.gameData.saveAll(this.scene, true).then(success => { + this.scene.gameData.saveAll(this.scene, true, battle.waveIndex % 10 === 1 || this.scene.lastSavePlayTime >= 300).then(success => { this.scene.disableMenu = false; if (!success) return this.scene.reset(true); @@ -2287,8 +2304,8 @@ export class MovePhase extends BattlePhase { if (this.move.moveId) this.showMoveText(); - - if ((moveQueue.length && moveQueue[0].move === Moves.NONE) || !targets.length) { + + if ((moveQueue.length && moveQueue[0].move === Moves.NONE) || (!targets.length && !this.move.getMove().getAttrs(SacrificialAttr).length)) { moveQueue.shift(); this.cancel(); this.pokemon.pushMoveHistory({ move: Moves.NONE, result: MoveResult.FAIL }); @@ -2520,8 +2537,14 @@ export class MoveEffectPhase extends PokemonPhase { })); } // Trigger effect which should only apply one time after all targeted effects have already applied - applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && (attr as MoveEffectAttr).trigger === MoveEffectTrigger.POST_TARGET, - user, null, this.move.getMove()) + const postTarget = applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && (attr as MoveEffectAttr).trigger === MoveEffectTrigger.POST_TARGET, + user, null, this.move.getMove()); + + if (applyAttrs.length) // If there is a pending asynchronous move effect, do this after + applyAttrs[applyAttrs.length - 1]?.then(() => postTarget); + else // Otherwise, push a new asynchronous move effect + applyAttrs.push(postTarget); + Promise.allSettled(applyAttrs).then(() => this.end()); }); }); @@ -3615,10 +3638,20 @@ export class GameOverPhase extends BattlePhase { }); }); }; + + /* Added a local check to see if the game is running offline on victory + If Online, execute apiFetch as intended + If Offline, execute offlineNewClear(), a localStorage implementation of newClear daily run checks */ if (this.victory) { - Utils.apiFetch(`savedata/newclear?slot=${this.scene.sessionSlotId}`, true) + if (!Utils.isLocal) { + Utils.apiFetch(`savedata/newclear?slot=${this.scene.sessionSlotId}`, true) .then(response => response.json()) .then(newClear => doGameOver(newClear)); + } else { + this.scene.gameData.offlineNewClear(this.scene).then(result => { + doGameOver(result); + }); + } } else doGameOver(false); } @@ -3676,7 +3709,7 @@ export class PostGameOverPhase extends Phase { start() { super.start(); - this.scene.gameData.saveSystem().then(success => { + this.scene.gameData.saveAll(this.scene, true, true, true).then(success => { if (!success) return this.scene.reset(true); this.scene.gameData.tryClearSession(this.scene, this.scene.sessionSlotId).then((success: boolean | [boolean, boolean]) => { diff --git a/src/system/game-data.ts b/src/system/game-data.ts index 7f6e1475b..e7ffd281b 100644 --- a/src/system/game-data.ts +++ b/src/system/game-data.ts @@ -20,7 +20,7 @@ import { Egg } from "../data/egg"; import { VoucherType, vouchers } from "./voucher"; import { AES, enc } from "crypto-js"; import { Mode } from "../ui/ui"; -import { loggedInUser, updateUserInfo } from "../account"; +import { clientSessionId, loggedInUser, updateUserInfo } from "../account"; import { Nature } from "../data/nature"; import { GameStats } from "./game-stats"; import { Tutorial } from "../tutorial"; @@ -67,6 +67,18 @@ export function getDataTypeKey(dataType: GameDataType, slotId: integer = 0): str } } +function encrypt(data: string, bypassLogin: boolean): string { + return (bypassLogin + ? (data: string) => btoa(data) + : (data: string) => AES.encrypt(data, saveKey))(data); +} + +function decrypt(data: string, bypassLogin: boolean): string { + return (bypassLogin + ? (data: string) => atob(data) + : (data: string) => AES.decrypt(data, saveKey).toString(enc.Utf8))(data); +} + interface SystemSaveData { trainerId: integer; secretId: integer; @@ -277,8 +289,10 @@ export class GameData { const maxIntAttrValue = Math.pow(2, 31); const systemData = JSON.stringify(data, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v); + localStorage.setItem(`data_${loggedInUser.username}`, encrypt(systemData, bypassLogin)); + if (!bypassLogin) { - Utils.apiPost(`savedata/update?datatype=${GameDataType.SYSTEM}`, systemData, undefined, true) + Utils.apiPost(`savedata/update?datatype=${GameDataType.SYSTEM}&clientSessionId=${clientSessionId}`, systemData, undefined, true) .then(response => response.text()) .then(error => { this.scene.ui.savingIcon.hide(); @@ -296,10 +310,6 @@ export class GameData { resolve(true); }); } else { - localStorage.setItem('data_bak', localStorage.getItem('data')); - - localStorage.setItem('data', btoa(systemData)); - this.scene.ui.savingIcon.hide(); resolve(true); @@ -309,120 +319,13 @@ export class GameData { public loadSystem(): Promise { return new Promise(resolve => { - if (bypassLogin && !localStorage.hasOwnProperty('data')) + console.log('Client Session:', clientSessionId); + + if (bypassLogin && !localStorage.getItem(`data_${loggedInUser.username}`)) return resolve(false); - const handleSystemData = (systemDataStr: string) => { - try { - const systemData = this.parseSystemData(systemDataStr); - - console.debug(systemData); - - /*const versions = [ this.scene.game.config.gameVersion, data.gameVersion || '0.0.0' ]; - - if (versions[0] !== versions[1]) { - const [ versionNumbers, oldVersionNumbers ] = versions.map(ver => ver.split('.').map(v => parseInt(v))); - }*/ - - this.trainerId = systemData.trainerId; - this.secretId = systemData.secretId; - - this.gender = systemData.gender; - - this.saveSetting(Setting.Player_Gender, systemData.gender === PlayerGender.FEMALE ? 1 : 0); - - const initStarterData = !systemData.starterData; - - if (initStarterData) { - this.initStarterData(); - - if (systemData['starterMoveData']) { - const starterMoveData = systemData['starterMoveData']; - for (let s of Object.keys(starterMoveData)) - this.starterData[s].moveset = starterMoveData[s]; - } - - if (systemData['starterEggMoveData']) { - const starterEggMoveData = systemData['starterEggMoveData']; - for (let s of Object.keys(starterEggMoveData)) - this.starterData[s].eggMoves = starterEggMoveData[s]; - } - - this.migrateStarterAbilities(systemData, this.starterData); - } else { - if ([ '1.0.0', '1.0.1' ].includes(systemData.gameVersion)) - this.migrateStarterAbilities(systemData); - //this.fixVariantData(systemData); - this.fixStarterData(systemData); - // Migrate ability starter data if empty for caught species - Object.keys(systemData.starterData).forEach(sd => { - if (systemData.dexData[sd].caughtAttr && !systemData.starterData[sd].abilityAttr) - systemData.starterData[sd].abilityAttr = 1; - }); - this.starterData = systemData.starterData; - } - - if (systemData.gameStats) { - if (systemData.gameStats.legendaryPokemonCaught !== undefined && systemData.gameStats.subLegendaryPokemonCaught === undefined) - this.fixLegendaryStats(systemData); - this.gameStats = systemData.gameStats; - } - - if (systemData.unlocks) { - for (let key of Object.keys(systemData.unlocks)) { - if (this.unlocks.hasOwnProperty(key)) - this.unlocks[key] = systemData.unlocks[key]; - } - } - - if (systemData.achvUnlocks) { - for (let a of Object.keys(systemData.achvUnlocks)) { - if (achvs.hasOwnProperty(a)) - this.achvUnlocks[a] = systemData.achvUnlocks[a]; - } - } - - if (systemData.voucherUnlocks) { - for (let v of Object.keys(systemData.voucherUnlocks)) { - if (vouchers.hasOwnProperty(v)) - this.voucherUnlocks[v] = systemData.voucherUnlocks[v]; - } - } - - if (systemData.voucherCounts) { - Utils.getEnumKeys(VoucherType).forEach(key => { - const index = VoucherType[key]; - this.voucherCounts[index] = systemData.voucherCounts[index] || 0; - }); - } - - this.eggs = systemData.eggs - ? systemData.eggs.map(e => e.toEgg()) - : []; - - this.dexData = Object.assign(this.dexData, systemData.dexData); - this.consolidateDexData(this.dexData); - this.defaultDexData = null; - - if (initStarterData) { - const starterIds = Object.keys(this.starterData).map(s => parseInt(s) as Species); - for (let s of starterIds) { - this.starterData[s].candyCount += this.dexData[s].caughtCount; - this.starterData[s].candyCount += this.dexData[s].hatchedCount * 2; - if (this.dexData[s].caughtAttr & DexAttr.SHINY) - this.starterData[s].candyCount += 4; - } - } - - resolve(true); - } catch (err) { - console.error(err); - resolve(false); - } - } - if (!bypassLogin) { - Utils.apiFetch(`savedata/get?datatype=${GameDataType.SYSTEM}`, true) + Utils.apiFetch(`savedata/system?clientSessionId=${clientSessionId}`, true) .then(response => response.text()) .then(response => { if (!response.length || response[0] !== '{') { @@ -437,10 +340,132 @@ export class GameData { return resolve(false); } - handleSystemData(response); + const cachedSystem = localStorage.getItem(`data_${loggedInUser.username}`); + this.initSystem(response, cachedSystem ? AES.decrypt(cachedSystem, saveKey).toString(enc.Utf8) : null).then(resolve); }); } else - handleSystemData(atob(localStorage.getItem('data'))); + this.initSystem(decrypt(localStorage.getItem(`data_${loggedInUser.username}`), bypassLogin)).then(resolve); + }); + } + + public initSystem(systemDataStr: string, cachedSystemDataStr?: string): Promise { + return new Promise(resolve => { + try { + let systemData = this.parseSystemData(systemDataStr); + + if (cachedSystemDataStr) { + let cachedSystemData = this.parseSystemData(cachedSystemDataStr); + console.log(cachedSystemData.timestamp, systemData.timestamp) + if (cachedSystemData.timestamp > systemData.timestamp) { + console.debug('Use cached system'); + systemData = cachedSystemData; + } else + this.clearLocalData(); + } + + console.debug(systemData); + + /*const versions = [ this.scene.game.config.gameVersion, data.gameVersion || '0.0.0' ]; + + if (versions[0] !== versions[1]) { + const [ versionNumbers, oldVersionNumbers ] = versions.map(ver => ver.split('.').map(v => parseInt(v))); + }*/ + + this.trainerId = systemData.trainerId; + this.secretId = systemData.secretId; + + this.gender = systemData.gender; + + this.saveSetting(Setting.Player_Gender, systemData.gender === PlayerGender.FEMALE ? 1 : 0); + + const initStarterData = !systemData.starterData; + + if (initStarterData) { + this.initStarterData(); + + if (systemData['starterMoveData']) { + const starterMoveData = systemData['starterMoveData']; + for (let s of Object.keys(starterMoveData)) + this.starterData[s].moveset = starterMoveData[s]; + } + + if (systemData['starterEggMoveData']) { + const starterEggMoveData = systemData['starterEggMoveData']; + for (let s of Object.keys(starterEggMoveData)) + this.starterData[s].eggMoves = starterEggMoveData[s]; + } + + this.migrateStarterAbilities(systemData, this.starterData); + } else { + if ([ '1.0.0', '1.0.1' ].includes(systemData.gameVersion)) + this.migrateStarterAbilities(systemData); + //this.fixVariantData(systemData); + this.fixStarterData(systemData); + // Migrate ability starter data if empty for caught species + Object.keys(systemData.starterData).forEach(sd => { + if (systemData.dexData[sd].caughtAttr && !systemData.starterData[sd].abilityAttr) + systemData.starterData[sd].abilityAttr = 1; + }); + this.starterData = systemData.starterData; + } + + if (systemData.gameStats) { + if (systemData.gameStats.legendaryPokemonCaught !== undefined && systemData.gameStats.subLegendaryPokemonCaught === undefined) + this.fixLegendaryStats(systemData); + this.gameStats = systemData.gameStats; + } + + if (systemData.unlocks) { + for (let key of Object.keys(systemData.unlocks)) { + if (this.unlocks.hasOwnProperty(key)) + this.unlocks[key] = systemData.unlocks[key]; + } + } + + if (systemData.achvUnlocks) { + for (let a of Object.keys(systemData.achvUnlocks)) { + if (achvs.hasOwnProperty(a)) + this.achvUnlocks[a] = systemData.achvUnlocks[a]; + } + } + + if (systemData.voucherUnlocks) { + for (let v of Object.keys(systemData.voucherUnlocks)) { + if (vouchers.hasOwnProperty(v)) + this.voucherUnlocks[v] = systemData.voucherUnlocks[v]; + } + } + + if (systemData.voucherCounts) { + Utils.getEnumKeys(VoucherType).forEach(key => { + const index = VoucherType[key]; + this.voucherCounts[index] = systemData.voucherCounts[index] || 0; + }); + } + + this.eggs = systemData.eggs + ? systemData.eggs.map(e => e.toEgg()) + : []; + + this.dexData = Object.assign(this.dexData, systemData.dexData); + this.consolidateDexData(this.dexData); + this.defaultDexData = null; + + if (initStarterData) { + const starterIds = Object.keys(this.starterData).map(s => parseInt(s) as Species); + for (let s of starterIds) { + this.starterData[s].candyCount += this.dexData[s].caughtCount; + this.starterData[s].candyCount += this.dexData[s].hatchedCount * 2; + if (this.dexData[s].caughtAttr & DexAttr.SHINY) + this.starterData[s].candyCount += 4; + } + } + + resolve(true); + } catch (err) { + console.error(err); + resolve(false); + } }); } @@ -474,6 +499,31 @@ export class GameData { return dataStr; } + public async verify(): Promise { + if (bypassLogin) + return true; + + const response = await Utils.apiPost(`savedata/system/verify`, JSON.stringify({ clientSessionId: clientSessionId }), undefined, true) + .then(response => response.json()); + + if (!response.valid) { + this.scene.clearPhaseQueue(); + this.scene.unshiftPhase(new ReloadSessionPhase(this.scene, JSON.stringify(response.systemData))); + this.clearLocalData(); + return false; + } + + return true; + } + + public clearLocalData(): void { + if (bypassLogin) + return; + localStorage.removeItem(`data_${loggedInUser.username}`); + for (let s = 0; s < 5; s++) + localStorage.removeItem(`sessionData${s ? s : ''}_${loggedInUser.username}`); + } + public saveSetting(setting: Setting, valueIndex: integer): boolean { let settings: object = {}; if (localStorage.hasOwnProperty('settings')) @@ -557,40 +607,6 @@ export class GameData { } as SessionSaveData; } - saveSession(scene: BattleScene, skipVerification?: boolean): Promise { - return new Promise(resolve => { - Utils.executeIf(!skipVerification, updateUserInfo).then(success => { - if (success !== null && !success) - return resolve(false); - - const sessionData = this.getSessionSaveData(scene); - - if (!bypassLogin) { - Utils.apiPost(`savedata/update?datatype=${GameDataType.SESSION}&slot=${scene.sessionSlotId}&trainerId=${this.trainerId}&secretId=${this.secretId}`, JSON.stringify(sessionData), undefined, true) - .then(response => response.text()) - .then(error => { - if (error) { - if (error.startsWith('session out of date')) { - this.scene.clearPhaseQueue(); - this.scene.unshiftPhase(new ReloadSessionPhase(this.scene)); - } - console.error(error); - return resolve(false); - } - console.debug('Session data saved'); - resolve(true); - }); - } else { - localStorage.setItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}`, btoa(JSON.stringify(sessionData))); - - console.debug('Session data saved'); - - resolve(true); - } - }); - }); - } - getSession(slotId: integer): Promise { return new Promise(async (resolve, reject) => { if (slotId < 0) @@ -605,8 +621,8 @@ export class GameData { } }; - if (!bypassLogin) { - Utils.apiFetch(`savedata/get?datatype=${GameDataType.SESSION}&slot=${slotId}`, true) + if (!bypassLogin && !localStorage.getItem(`sessionData${slotId ? slotId : ''}_${loggedInUser.username}`)) { + Utils.apiFetch(`savedata/session?slot=${slotId}&clientSessionId=${clientSessionId}`, true) .then(response => response.text()) .then(async response => { if (!response.length || response[0] !== '{') { @@ -614,12 +630,14 @@ export class GameData { return resolve(null); } + localStorage.setItem(`sessionData${slotId ? slotId : ''}_${loggedInUser.username}`, encrypt(response, bypassLogin)); + await handleSessionData(response); }); } else { - const sessionData = localStorage.getItem(`sessionData${slotId ? slotId : ''}`); + const sessionData = localStorage.getItem(`sessionData${slotId ? slotId : ''}_${loggedInUser.username}`); if (sessionData) - await handleSessionData(atob(sessionData)); + await handleSessionData(decrypt(sessionData, bypassLogin)); else return resolve(null); } @@ -640,6 +658,7 @@ export class GameData { console.log('Seed:', scene.seed); scene.sessionPlayTime = sessionData.playTime || 0; + scene.lastSavePlayTime = 0; const loadPokemonAssets: Promise[] = []; @@ -731,16 +750,17 @@ export class GameData { deleteSession(slotId: integer): Promise { return new Promise(resolve => { if (bypassLogin) { - localStorage.removeItem('sessionData'); + localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}_${loggedInUser.username}`); return resolve(true); } updateUserInfo().then(success => { if (success !== null && !success) return resolve(false); - Utils.apiFetch(`savedata/delete?datatype=${GameDataType.SESSION}&slot=${slotId}`, true).then(response => { + Utils.apiFetch(`savedata/delete?datatype=${GameDataType.SESSION}&slot=${slotId}&clientSessionId=${clientSessionId}`, true).then(response => { if (response.ok) { loggedInUser.lastSessionSlot = -1; + localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}_${loggedInUser.username}`); resolve(true); } return response.text(); @@ -759,10 +779,40 @@ export class GameData { }); } + /* Defines a localStorage item 'daily' to check on clears, offline implementation of savedata/newclear API + If a GameModes clear other than Daily is checked, newClear = true as usual + If a Daily mode is cleared, checks if it was already cleared before, based on seed, and returns true only to new daily clear runs */ + offlineNewClear(scene: BattleScene): Promise { + return new Promise(resolve => { + const sessionData = this.getSessionSaveData(scene); + const seed = sessionData.seed; + let daily: string[] = []; + + if (sessionData.gameMode == GameModes.DAILY) { + if (localStorage.hasOwnProperty('daily')) { + daily = JSON.parse(atob(localStorage.getItem('daily'))); + if (daily.includes(seed)) { + return resolve(false); + } else { + daily.push(seed); + localStorage.setItem('daily', btoa(JSON.stringify(daily))); + return resolve(true); + } + } else { + daily.push(seed); + localStorage.setItem('daily', btoa(JSON.stringify(daily))); + return resolve(true); + } + } else { + return resolve(true); + } + }); + } + tryClearSession(scene: BattleScene, slotId: integer): Promise<[success: boolean, newClear: boolean]> { return new Promise<[boolean, boolean]>(resolve => { if (bypassLogin) { - localStorage.removeItem(`sessionData${slotId ? slotId : ''}`); + localStorage.removeItem(`sessionData${slotId ? slotId : ''}_${loggedInUser.username}`); return resolve([true, true]); } @@ -770,9 +820,11 @@ export class GameData { if (success !== null && !success) return resolve([false, false]); const sessionData = this.getSessionSaveData(scene); - Utils.apiPost(`savedata/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}`, JSON.stringify(sessionData), undefined, true).then(response => { - if (response.ok) + Utils.apiPost(`savedata/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`, JSON.stringify(sessionData), undefined, true).then(response => { + if (response.ok) { loggedInUser.lastSessionSlot = -1; + localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}_${loggedInUser.username}`); + } return response.json(); }).then(jsonResponse => { if (!jsonResponse.error) @@ -825,14 +877,14 @@ export class GameData { }) as SessionSaveData; } - saveAll(scene: BattleScene, skipVerification?: boolean): Promise { + saveAll(scene: BattleScene, skipVerification: boolean = false, sync: boolean = false, useCachedSession: boolean = false): Promise { return new Promise(resolve => { Utils.executeIf(!skipVerification, updateUserInfo).then(success => { if (success !== null && !success) return resolve(false); - this.scene.ui.savingIcon.show(); - const data = this.getSystemSaveData(); - const sessionData = this.getSessionSaveData(scene); + if (sync) + this.scene.ui.savingIcon.show(); + const sessionData = useCachedSession ? this.parseSessionData(decrypt(localStorage.getItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}_${loggedInUser.username}`), bypassLogin)) : this.getSessionSaveData(scene); const maxIntAttrValue = Math.pow(2, 31); const systemData = this.getSystemSaveData(); @@ -840,14 +892,24 @@ export class GameData { const request = { system: systemData, session: sessionData, - sessionSlotId: scene.sessionSlotId + sessionSlotId: scene.sessionSlotId, + clientSessionId: clientSessionId }; - if (!bypassLogin) { + localStorage.setItem(`data_${loggedInUser.username}`, encrypt(JSON.stringify(systemData, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v), bypassLogin)); + + localStorage.setItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}_${loggedInUser.username}`, encrypt(JSON.stringify(sessionData), bypassLogin)); + + console.debug('Session data saved'); + + 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) .then(response => response.text()) .then(error => { - this.scene.ui.savingIcon.hide(); + if (sync) { + this.scene.lastSavePlayTime = 0; + this.scene.ui.savingIcon.hide(); + } if (error) { if (error.startsWith('client version out of date')) { this.scene.clearPhaseQueue(); @@ -862,17 +924,10 @@ export class GameData { resolve(true); }); } else { - localStorage.setItem('data_bak', localStorage.getItem('data')); - - localStorage.setItem('data', btoa(JSON.stringify(systemData, (k: any, v: any) => typeof v === 'bigint' ? v <= maxIntAttrValue ? Number(v) : v.toString() : v))); - - localStorage.setItem(`sessionData${scene.sessionSlotId ? scene.sessionSlotId : ''}`, btoa(JSON.stringify(sessionData))); - - console.debug('Session data saved'); - - this.scene.ui.savingIcon.hide(); - - resolve(true); + this.verify().then(success => { + this.scene.ui.savingIcon.hide(); + resolve(success); + }); } }); }); @@ -880,7 +935,7 @@ export class GameData { public tryExportData(dataType: GameDataType, slotId: integer = 0): Promise { return new Promise(resolve => { - const dataKey: string = getDataTypeKey(dataType, slotId); + const dataKey: string = `${getDataTypeKey(dataType, slotId)}_${loggedInUser.username}`; const handleData = (dataStr: string) => { switch (dataType) { case GameDataType.SYSTEM: @@ -896,7 +951,7 @@ export class GameData { link.remove(); }; if (!bypassLogin && dataType < GameDataType.SETTINGS) { - Utils.apiFetch(`savedata/get?datatype=${dataType}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}`, true) + Utils.apiFetch(`savedata/${dataType === GameDataType.SYSTEM ? 'system' : 'session'}?clientSessionId=${clientSessionId}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}`, true) .then(response => response.text()) .then(response => { if (!response.length || response[0] !== '{') { @@ -911,14 +966,14 @@ export class GameData { } else { const data = localStorage.getItem(dataKey); if (data) - handleData(atob(data)); + handleData(decrypt(data, bypassLogin)); resolve(!!data); } }); } public importData(dataType: GameDataType, slotId: integer = 0): void { - const dataKey = getDataTypeKey(dataType, slotId); + const dataKey = `${getDataTypeKey(dataType, slotId)}_${loggedInUser.username}`; let saveFile: any = document.getElementById('saveFile'); if (saveFile) @@ -979,11 +1034,13 @@ export class GameData { return this.scene.ui.showText(`Your ${dataName} data could not be loaded. It may be corrupted.`, null, () => this.scene.ui.showText(null, 0), Utils.fixedInt(1500)); this.scene.ui.showText(`Your ${dataName} data will be overridden and the page will reload. Proceed?`, null, () => { this.scene.ui.setOverlayMode(Mode.CONFIRM, () => { + localStorage.setItem(dataKey, encrypt(dataStr, bypassLogin)); + if (!bypassLogin && dataType < GameDataType.SETTINGS) { updateUserInfo().then(success => { if (!success) return displayError(`Could not contact the server. Your ${dataName} data could not be imported.`); - Utils.apiPost(`savedata/update?datatype=${dataType}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}&trainerId=${this.trainerId}&secretId=${this.secretId}`, dataStr, undefined, true) + Utils.apiPost(`savedata/update?datatype=${dataType}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}&trainerId=${this.trainerId}&secretId=${this.secretId}&clientSessionId=${clientSessionId}`, dataStr, undefined, true) .then(response => response.text()) .then(error => { if (error) { @@ -993,10 +1050,8 @@ export class GameData { window.location = window.location; }); }); - } else { - localStorage.setItem(dataKey, btoa(dataStr)); + } else window.location = window.location; - } }, () => { this.scene.ui.revertMode(); this.scene.ui.showText(null, 0); diff --git a/src/ui/egg-gacha-ui-handler.ts b/src/ui/egg-gacha-ui-handler.ts index 315dfdbd3..a7fd61b30 100644 --- a/src/ui/egg-gacha-ui-handler.ts +++ b/src/ui/egg-gacha-ui-handler.ts @@ -372,7 +372,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { this.scene.gameData.gameStats.eggsPulled++; } - this.scene.gameData.saveSystem().then(success => { + (this.scene.currentBattle ? this.scene.gameData.saveAll(this.scene, true, true, true) : this.scene.gameData.saveSystem()).then(success => { if (!success) return this.scene.reset(true); doPull(); diff --git a/src/utils.ts b/src/utils.ts index 90dfe0a21..142de91c1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -192,7 +192,9 @@ export function formatLargeNumber(count: integer, threshold: integer): string { return '?'; } const digits = ((ret.length + 2) % 3) + 1; - const decimalNumber = parseInt(ret.slice(digits, digits + (3 - digits))); + let decimalNumber = ret.slice(digits, digits + 2); + while (decimalNumber.endsWith('0')) + decimalNumber = decimalNumber.slice(0, -1); return `${ret.slice(0, digits)}${decimalNumber ? `.${decimalNumber}` : ''}${suffix}`; }