import BasicObject from "../../Engine/Basic/BasicObject"; import EventManager from "../../Engine/Event/EventManager"; import JsonResources from "../../Engine/Resources/JsonResources"; import Tool from "../../Engine/Tool/Tool"; import { _EGameBehavior, _EGameJsonRes } from "../Data/GameDataType"; import { _IUserData, _IUserDataConfig } from "../Data/User/UserConfig"; import GameEventName from "../Event/GameEventName"; /** * 用户数据 * @param 设计目的 管理玩家信息 * @param 可能问题 数据复杂时,把多余部分拆分成组件 */ export default class UserData extends BasicObject { /**用户数据 */ public userData: _IUserData; constructor () { super(); this.read(); this.save(); EventManager.onEvent(GameEventName.UserData.UserData_SetUserData, this, this.onSetUserData); EventManager.onEvent(GameEventName.UserData.UserData_GetUserData, this, this.onGetUserData); } /** * 保存 * @param 使用范例 this.saveData(); * @param 设计目的 保存用户数据 * @param 可能问题 频繁、或在错误地点执行此方法,保存了错误数据 */ public save (): void { // 更新离线时间 let date: Date = new Date(); this.userData.offLineTime = { year: date.getFullYear(), month: date.getMonth(), day: date.getDay(), hour: date.getHours(), minute: date.getMinutes(), second: date.getSeconds(), }; // if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) { // window.sessionStorage.setItem("UserInfo", JSON.stringify(this.userData)); // } // else { // cc.sys.localStorage.setItem("UserInfo", JSON.stringify(this.userData)); // } // Tool.log(""); // Tool.log("保存用户数据"); // Tool.log(this.userData); EventManager.sendEvent(GameEventName.UserData.UserData_UpdateUserData, this.userData); } /** * 读取 * @param 使用范例 this.readData(); * @param 设计目的 读取用户数据 * @param 可能问题 保存错误数据后,读取错误 */ private read (): void { let string = ""; if (cc.sys.platform == cc.sys.DESKTOP_BROWSER) { string = window.sessionStorage.getItem("UserInfo"); } else { string = cc.sys.localStorage.getItem("UserInfo"); } let userDataConfig: _IUserDataConfig = JsonResources.getResources(_EGameJsonRes.UserData); let userData: _IUserData = userDataConfig.userData; this.userData = Tool.dataAllCover({}, userDataConfig.userData); if (string != null && string != "") { userData = JSON.parse(string) as _IUserData; this.userData = Tool.dataSupplementCover(userData, this.userData); // Tool.log(""); // Tool.log("读取用户数据"); // Tool.log(this.userData); } EventManager.sendEvent(GameEventName.UserData.UserData_ReadUserData, _EGameBehavior.InitLoad); } /**设置用户数据响应方法 */ private onSetUserData (data: Object): void { this.userData = Tool.dataSupplementCover(this.userData, data); this.save(); } /**获得用户数据响应方法 */ private onGetUserData (callback: Function): void { callback(Tool.dataAllCover({}, this.userData)); } _destroy () { this.userData = null; super._destroy(); } }