Compare commits

..

No commits in common. "512016faef74ab77f821d3b22863be8bcee1c520" and "aeeebcbf383f69d6db952480658a263142f44df2" have entirely different histories.

8 changed files with 223 additions and 378 deletions

View File

@ -7,20 +7,18 @@ 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 : ''}_${loggedInUser.username}`)) {
if (localStorage.getItem(`sessionData${s ? s : ''}`)) {
lastSessionSlot = s;
break;
}
}
loggedInUser.lastSessionSlot = lastSessionSlot;
loggedInUser = { username: 'Guest', lastSessionSlot: lastSessionSlot };
return resolve([ true, 200 ]);
}
Utils.apiFetch('account/info', true).then(response => {

View File

@ -88,7 +88,6 @@ 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;
@ -453,8 +452,6 @@ 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();
@ -467,8 +464,6 @@ export default class BattleScene extends SceneBase {
this.gameData.gameStats.playTime++;
if (this.sessionPlayTime !== null)
this.sessionPlayTime++;
if (this.lastSavePlayTime !== null)
this.lastSavePlayTime++;
}
});
@ -1012,7 +1007,6 @@ 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:

View File

@ -1755,7 +1755,7 @@ export class StatusEffectImmunityAbAttr extends PreSetStatusAbAttr {
}
getTriggerMessage(pokemon: Pokemon, abilityName: string, ...args: any[]): string {
return getPokemonMessage(pokemon, `'s ${abilityName}\nprevents ${this.immuneEffects.length ? getStatusEffectDescriptor(this.immuneEffects[0]) : 'status problems'}!`);
return getPokemonMessage(pokemon, `'s ${abilityName}\nprevents ${this.immuneEffects.length ? getStatusEffectDescriptor(args[0] as StatusEffect) : 'status problems'}!`);
}
}
@ -2825,7 +2825,7 @@ export function applyPostStatChangeAbAttrs(attrType: { new(...args: any[]): Post
export function applyPreSetStatusAbAttrs(attrType: { new(...args: any[]): PreSetStatusAbAttr },
pokemon: Pokemon, effect: StatusEffect, cancelled: Utils.BooleanHolder, ...args: any[]): Promise<void> {
const simulated = args.length > 1 && args[1];
return applyAbAttrsInternal<PreSetStatusAbAttr>(attrType, pokemon, (attr, passive) => attr.applyPreSetStatus(pokemon, passive, effect, cancelled, args), args, false, false, simulated);
return applyAbAttrsInternal<PreSetStatusAbAttr>(attrType, pokemon, (attr, passive) => attr.applyPreSetStatus(pokemon, passive, effect, cancelled, args), args, false, false, !simulated);
}
export function applyPreApplyBattlerTagAbAttrs(attrType: { new(...args: any[]): PreApplyBattlerTagAbAttr },

View File

@ -434,66 +434,29 @@ 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<boolean> {
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;
}
@ -507,9 +470,6 @@ 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;
@ -520,21 +480,11 @@ 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<boolean> {
return this.canApply(user, target, move, args);
}
@ -788,65 +738,17 @@ 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.POST_TARGET);
super(true, MoveEffectTrigger.PRE_APPLY);
}
/**
* 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;
}
@ -904,15 +806,8 @@ 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) {
@ -927,10 +822,6 @@ 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));
@ -1012,7 +903,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 [0] Utils.NumberHolder for arenaAttackTypeMultiplier
* @param args Utils.NumberHolder for arenaAttackTypeMultiplier
* @returns true if the function succeeds
*/
apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean {
@ -1072,19 +963,27 @@ export class SandHealAttr extends WeatherHealAttr {
}
/**
* Heals the target or the user by either {@link normalHealRatio} or {@link boostedHealRatio}
* Heals the target 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;
@ -1092,13 +991,6 @@ 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);
@ -5068,7 +4960,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(SacrificialAttrOnHit)
.attr(SacrificialAttr)
.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
@ -5604,7 +5496,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(SacrificialAttrOnHit)
.attr(SacrificialAttr)
.danceMove()
.triageMove()
.unimplemented(),
@ -5753,7 +5645,7 @@ export function initMoves() {
.partial(),
new AttackMove(Moves.FINAL_GAMBIT, Type.FIGHTING, MoveCategory.SPECIAL, -1, 100, 5, -1, 0, 5)
.attr(UserHpDamageAttr)
.attr(SacrificialAttrOnHit),
.attr(SacrificialAttr),
new StatusMove(Moves.BESTOW, Type.NORMAL, -1, 15, -1, 0, 5)
.ignoresProtect()
.unimplemented(),

View File

@ -1,5 +1,5 @@
import { SimpleTranslationEntries } from "#app/plugins/i18n";
export const abilityTriggers: SimpleTranslationEntries = {
'blockRecoilDamage' : `{{pokemonName}} wurde durch {{abilityName}}\nvor Rückstoß geschützt!`,
} as const;
'blockRecoilDamage' : `{{pokemonName}}'s {{abilityName}}\nprotected it from recoil!`,
} as const;

View File

@ -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, SacrificialAttr } 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 } from "./data/move";
import { Mode } from './ui/ui';
import { Command } from "./ui/command-ui-handler";
import { Stat } from "./data/pokemon-stat";
@ -330,7 +330,6 @@ export class TitlePhase extends Phase {
this.scene.newBattle();
this.scene.arena.init();
this.scene.sessionPlayTime = 0;
this.scene.lastSavePlayTime = 0;
this.end();
});
};
@ -394,12 +393,8 @@ export class UnavailablePhase extends Phase {
}
export class ReloadSessionPhase extends Phase {
private systemDataStr: string;
constructor(scene: BattleScene, systemDataStr?: string) {
constructor(scene: BattleScene) {
super(scene);
this.systemDataStr = systemDataStr;
}
start(): void {
@ -415,9 +410,7 @@ export class ReloadSessionPhase extends Phase {
delayElapsed = true;
});
this.scene.gameData.clearLocalData();
(this.systemDataStr ? this.scene.gameData.initSystem(this.systemDataStr) : this.scene.gameData.loadSystem()).then(() => {
this.scene.gameData.loadSystem().then(() => {
if (delayElapsed)
this.end();
else
@ -538,7 +531,6 @@ export class SelectStarterPhase extends Phase {
this.scene.newBattle();
this.scene.arena.init();
this.scene.sessionPlayTime = 0;
this.scene.lastSavePlayTime = 0;
this.end();
});
});
@ -792,7 +784,7 @@ export class EncounterPhase extends BattlePhase {
this.scene.ui.setMode(Mode.MESSAGE).then(() => {
if (!this.loaded) {
this.scene.gameData.saveAll(this.scene, true, battle.waveIndex % 10 === 1 || this.scene.lastSavePlayTime >= 300).then(success => {
this.scene.gameData.saveAll(this.scene, true).then(success => {
this.scene.disableMenu = false;
if (!success)
return this.scene.reset(true);
@ -2304,8 +2296,8 @@ export class MovePhase extends BattlePhase {
if (this.move.moveId)
this.showMoveText();
if ((moveQueue.length && moveQueue[0].move === Moves.NONE) || (!targets.length && !this.move.getMove().getAttrs(SacrificialAttr).length)) {
if ((moveQueue.length && moveQueue[0].move === Moves.NONE) || !targets.length) {
moveQueue.shift();
this.cancel();
this.pokemon.pushMoveHistory({ move: Moves.NONE, result: MoveResult.FAIL });
@ -2537,14 +2529,8 @@ export class MoveEffectPhase extends PokemonPhase {
}));
}
// Trigger effect which should only apply one time after all targeted effects have already applied
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);
applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && (attr as MoveEffectAttr).trigger === MoveEffectTrigger.POST_TARGET,
user, null, this.move.getMove())
Promise.allSettled(applyAttrs).then(() => this.end());
});
});
@ -3706,7 +3692,7 @@ export class PostGameOverPhase extends Phase {
start() {
super.start();
this.scene.gameData.saveAll(this.scene, true, true, true).then(success => {
this.scene.gameData.saveSystem().then(success => {
if (!success)
return this.scene.reset(true);
this.scene.gameData.tryClearSession(this.scene, this.scene.sessionSlotId).then((success: boolean | [boolean, boolean]) => {

View File

@ -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 { clientSessionId, loggedInUser, updateUserInfo } from "../account";
import { loggedInUser, updateUserInfo } from "../account";
import { Nature } from "../data/nature";
import { GameStats } from "./game-stats";
import { Tutorial } from "../tutorial";
@ -67,18 +67,6 @@ 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;
@ -289,10 +277,8 @@ 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}&clientSessionId=${clientSessionId}`, systemData, undefined, true)
Utils.apiPost(`savedata/update?datatype=${GameDataType.SYSTEM}`, systemData, undefined, true)
.then(response => response.text())
.then(error => {
this.scene.ui.savingIcon.hide();
@ -310,6 +296,10 @@ 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);
@ -319,13 +309,120 @@ export class GameData {
public loadSystem(): Promise<boolean> {
return new Promise<boolean>(resolve => {
console.log('Client Session:', clientSessionId);
if (bypassLogin && !localStorage.getItem(`data_${loggedInUser.username}`))
if (bypassLogin && !localStorage.hasOwnProperty('data'))
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/system?clientSessionId=${clientSessionId}`, true)
Utils.apiFetch(`savedata/get?datatype=${GameDataType.SYSTEM}`, true)
.then(response => response.text())
.then(response => {
if (!response.length || response[0] !== '{') {
@ -340,132 +437,10 @@ export class GameData {
return resolve(false);
}
const cachedSystem = localStorage.getItem(`data_${loggedInUser.username}`);
this.initSystem(response, cachedSystem ? AES.decrypt(cachedSystem, saveKey).toString(enc.Utf8) : null).then(resolve);
handleSystemData(response);
});
} else
this.initSystem(decrypt(localStorage.getItem(`data_${loggedInUser.username}`), bypassLogin)).then(resolve);
});
}
public initSystem(systemDataStr: string, cachedSystemDataStr?: string): Promise<boolean> {
return new Promise<boolean>(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);
}
handleSystemData(atob(localStorage.getItem('data')));
});
}
@ -499,31 +474,6 @@ export class GameData {
return dataStr;
}
public async verify(): Promise<boolean> {
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'))
@ -607,6 +557,40 @@ export class GameData {
} as SessionSaveData;
}
saveSession(scene: BattleScene, skipVerification?: boolean): Promise<boolean> {
return new Promise<boolean>(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<SessionSaveData> {
return new Promise(async (resolve, reject) => {
if (slotId < 0)
@ -621,8 +605,8 @@ export class GameData {
}
};
if (!bypassLogin && !localStorage.getItem(`sessionData${slotId ? slotId : ''}_${loggedInUser.username}`)) {
Utils.apiFetch(`savedata/session?slot=${slotId}&clientSessionId=${clientSessionId}`, true)
if (!bypassLogin) {
Utils.apiFetch(`savedata/get?datatype=${GameDataType.SESSION}&slot=${slotId}`, true)
.then(response => response.text())
.then(async response => {
if (!response.length || response[0] !== '{') {
@ -630,14 +614,12 @@ 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 : ''}_${loggedInUser.username}`);
const sessionData = localStorage.getItem(`sessionData${slotId ? slotId : ''}`);
if (sessionData)
await handleSessionData(decrypt(sessionData, bypassLogin));
await handleSessionData(atob(sessionData));
else
return resolve(null);
}
@ -658,7 +640,6 @@ export class GameData {
console.log('Seed:', scene.seed);
scene.sessionPlayTime = sessionData.playTime || 0;
scene.lastSavePlayTime = 0;
const loadPokemonAssets: Promise<void>[] = [];
@ -750,17 +731,16 @@ export class GameData {
deleteSession(slotId: integer): Promise<boolean> {
return new Promise<boolean>(resolve => {
if (bypassLogin) {
localStorage.removeItem(`sessionData${this.scene.sessionSlotId ? this.scene.sessionSlotId : ''}_${loggedInUser.username}`);
localStorage.removeItem('sessionData');
return resolve(true);
}
updateUserInfo().then(success => {
if (success !== null && !success)
return resolve(false);
Utils.apiFetch(`savedata/delete?datatype=${GameDataType.SESSION}&slot=${slotId}&clientSessionId=${clientSessionId}`, true).then(response => {
Utils.apiFetch(`savedata/delete?datatype=${GameDataType.SESSION}&slot=${slotId}`, 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();
@ -812,7 +792,7 @@ export class GameData {
tryClearSession(scene: BattleScene, slotId: integer): Promise<[success: boolean, newClear: boolean]> {
return new Promise<[boolean, boolean]>(resolve => {
if (bypassLogin) {
localStorage.removeItem(`sessionData${slotId ? slotId : ''}_${loggedInUser.username}`);
localStorage.removeItem(`sessionData${slotId ? slotId : ''}`);
return resolve([true, true]);
}
@ -820,11 +800,9 @@ 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}&clientSessionId=${clientSessionId}`, JSON.stringify(sessionData), undefined, true).then(response => {
if (response.ok) {
Utils.apiPost(`savedata/clear?slot=${slotId}&trainerId=${this.trainerId}&secretId=${this.secretId}`, 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)
@ -877,14 +855,14 @@ export class GameData {
}) as SessionSaveData;
}
saveAll(scene: BattleScene, skipVerification: boolean = false, sync: boolean = false, useCachedSession: boolean = false): Promise<boolean> {
saveAll(scene: BattleScene, skipVerification?: boolean): Promise<boolean> {
return new Promise<boolean>(resolve => {
Utils.executeIf(!skipVerification, updateUserInfo).then(success => {
if (success !== null && !success)
return resolve(false);
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);
this.scene.ui.savingIcon.show();
const data = this.getSystemSaveData();
const sessionData = this.getSessionSaveData(scene);
const maxIntAttrValue = Math.pow(2, 31);
const systemData = this.getSystemSaveData();
@ -892,24 +870,14 @@ export class GameData {
const request = {
system: systemData,
session: sessionData,
sessionSlotId: scene.sessionSlotId,
clientSessionId: clientSessionId
sessionSlotId: scene.sessionSlotId
};
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) {
if (!bypassLogin) {
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 => {
if (sync) {
this.scene.lastSavePlayTime = 0;
this.scene.ui.savingIcon.hide();
}
this.scene.ui.savingIcon.hide();
if (error) {
if (error.startsWith('client version out of date')) {
this.scene.clearPhaseQueue();
@ -924,10 +892,17 @@ export class GameData {
resolve(true);
});
} else {
this.verify().then(success => {
this.scene.ui.savingIcon.hide();
resolve(success);
});
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);
}
});
});
@ -935,7 +910,7 @@ export class GameData {
public tryExportData(dataType: GameDataType, slotId: integer = 0): Promise<boolean> {
return new Promise<boolean>(resolve => {
const dataKey: string = `${getDataTypeKey(dataType, slotId)}_${loggedInUser.username}`;
const dataKey: string = getDataTypeKey(dataType, slotId);
const handleData = (dataStr: string) => {
switch (dataType) {
case GameDataType.SYSTEM:
@ -951,7 +926,7 @@ export class GameData {
link.remove();
};
if (!bypassLogin && dataType < GameDataType.SETTINGS) {
Utils.apiFetch(`savedata/${dataType === GameDataType.SYSTEM ? 'system' : 'session'}?clientSessionId=${clientSessionId}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}`, true)
Utils.apiFetch(`savedata/get?datatype=${dataType}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}`, true)
.then(response => response.text())
.then(response => {
if (!response.length || response[0] !== '{') {
@ -966,14 +941,14 @@ export class GameData {
} else {
const data = localStorage.getItem(dataKey);
if (data)
handleData(decrypt(data, bypassLogin));
handleData(atob(data));
resolve(!!data);
}
});
}
public importData(dataType: GameDataType, slotId: integer = 0): void {
const dataKey = `${getDataTypeKey(dataType, slotId)}_${loggedInUser.username}`;
const dataKey = getDataTypeKey(dataType, slotId);
let saveFile: any = document.getElementById('saveFile');
if (saveFile)
@ -1034,13 +1009,11 @@ 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}&clientSessionId=${clientSessionId}`, dataStr, undefined, true)
Utils.apiPost(`savedata/update?datatype=${dataType}${dataType === GameDataType.SESSION ? `&slot=${slotId}` : ''}&trainerId=${this.trainerId}&secretId=${this.secretId}`, dataStr, undefined, true)
.then(response => response.text())
.then(error => {
if (error) {
@ -1050,8 +1023,10 @@ export class GameData {
window.location = window.location;
});
});
} else
} else {
localStorage.setItem(dataKey, btoa(dataStr));
window.location = window.location;
}
}, () => {
this.scene.ui.revertMode();
this.scene.ui.showText(null, 0);

View File

@ -372,7 +372,7 @@ export default class EggGachaUiHandler extends MessageUiHandler {
this.scene.gameData.gameStats.eggsPulled++;
}
(this.scene.currentBattle ? this.scene.gameData.saveAll(this.scene, true, true, true) : this.scene.gameData.saveSystem()).then(success => {
this.scene.gameData.saveSystem().then(success => {
if (!success)
return this.scene.reset(true);
doPull();