import { defineStore } from "pinia"; const defaultUser = { id: "", nickName: "", avatar: "../static/user-icon.png", trio: 0, // 大于1表示完成了新手引导 lvlName: "", }; const getLvlName = (rankLvl, rankList = []) => { if (!rankList) return; let lvlName = ""; rankList.some((r, index) => { lvlName = rankList[index].name; if (r.rank_id === rankLvl) { lvlName = rankList[index].name; return true; } return false; }); return lvlName; }; const getLvlNameByScore = (score, rankList = []) => { if (!rankList) return; let lvlName = ""; rankList.some((r, index) => { if (r.upgrade_scores && r.upgrade_scores < score) { lvlName = rankList[index].name; return true; } return false; }); return lvlName; }; const getLvlImage = (rankLvl, rankList = []) => { if (!rankList) return; let lvlImage = ""; rankList.some((r, index) => { if (r.rank_id === rankLvl) { lvlImage = rankList[index].icoin; return true; } return false; }); return lvlImage; }; const getLvlImageByScore = (score, rankList = []) => { if (!rankList) return; let lvlImage = ""; rankList.some((r, index) => { if (r.upgrade_scores && r.upgrade_scores < score) { lvlImage = rankList[index].icoin; return true; } return false; }); return lvlImage; }; // 定义游戏相关的 store export default defineStore("store", { // 状态 state: () => ({ user: defaultUser, device: { deviceId: "", deviceName: "", }, config: {}, rankData: { rank: [], ringRank: [], }, online: false, game: { roomID: "", inBattle: false, roomNumber: "", // 当前房间号,供 Header 展示房号胶囊 }, }), // 计算属性 getters: { getUsername: (state) => { return state.user.username; }, }, // 方法 actions: { getLvlNameByScore(score) { return getLvlNameByScore(score, this.config.randInfos); }, getLvlName(rankLvl) { return getLvlName(rankLvl, this.config.randInfos); }, getLvlImage(rankLvl) { return getLvlImage(rankLvl, this.config.randInfos); }, updateRank(data = {}) { this.rankData = { ...(data || {}) }; }, updateOnline(online) { this.online = online; }, async updateUser(user = {}) { this.user = { ...defaultUser, ...user }; this.user.lvlName = getLvlNameByScore(this.user.scores, this.config.randInfos) this.user.lvlImage = getLvlImageByScore( this.user.scores, this.config.randInfos ); }, updateDevice(deviceId, deviceName) { this.device.deviceId = deviceId; this.device.deviceName = deviceName; }, async updateConfig(config) { this.config = config; if (this.user.scores !== undefined) { this.user.lvlName = getLvlName( this.user.rankLvl, this.config.randInfos ); } this.user.lvlImage = getLvlImage( this.user.rankLvl, this.config.randInfos ); }, updateGame(inBattle = false, roomID = "") { this.game.roomID = roomID; this.game.inBattle = inBattle; }, /** 更新当前房间号,供 Header 组件展示房号胶囊 */ updateRoomNumber(number) { this.game.roomNumber = number; }, }, // 开启数据持久化 persist: { enabled: true, strategies: [ { storage: uni.getStorageSync, paths: ["user", "device", "config"], // 只持久化用户信息 }, ], }, });