colorBlock_iaa/assets/Script/GameManager.ts
2025-10-17 18:08:59 +08:00

596 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import Utils from "./module/Pay/Utils";
import { MiniGameManager } from "./Sdk/MiniGameManager";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";
const { ccclass, property } = cc._decorator;
@ccclass
export default class GameManager extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property
text: string = 'hello';
static _instance: GameManager = null;
@property({ type: [cc.Prefab], tooltip: "方块数组" })
Block_Array: Array<cc.Prefab> = [];
@property({ type: [cc.Prefab], tooltip: "墙壁数组" })
Wall_Prefab: Array<cc.Prefab> = [];
@property({ type: [cc.SpriteAtlas], tooltip: "方块颜色" })
Block_Color: Array<cc.SpriteAtlas> = [];
particleEffects: cc.ParticleAsset[];
// @property({type: [cc.ParticleSystem], tooltip:"粒子数组"})
// particleEffects : Array<cc.ParticleSystem> = [];
load1: boolean = false;
load2: boolean = false;
load3: boolean = false;
load4: boolean = false;
load5: boolean = false;
load6: boolean = false;
scheduleCallback: any;
timeNumber: number;
nowTime: number;
// LIFE-CYCLE CALLBACKS:
/** 游戏入口初始化 */
onLoad() {
window.initMgr();
this.timeNumber = 1;
this.startTimeCutDown();
cc.fx.GameConfig.init(true);
cc.fx.GameConfig.GM_INFO.gameState = false;
this.readMusicConfig();
this.load1 = this.load2 = this.load3 = this.load4 = this.load5 = this.load6 = false;
setTimeout(() => {
this.getSetting();
this.readUserData();
this.getShareInfo();
}, 100);
if (GameManager._instance == null) {
GameManager._instance = this;
cc.game.addPersistRootNode(this.node);
}
else {
return;
}
// 检测微信小游戏切到后台
if (cc.sys.platform === cc.sys.WECHAT_GAME) {
//@ts-ignore
wx.onHide(() => {
this.onHide();
});
// 检测微信小游戏回到前台
//@ts-ignore
wx.onShow(() => {
this.onShow();
});
}
}
start() {
setTimeout(() => {
const path = 'prefab/block';
const path2 = 'prefab/wall';
cc.resources.loadDir(path, cc.Prefab, (err, assets: cc.Prefab[]) => {
if (err) {
cc.director.loadScene("LoadScene");
return;
}
// 将加载的 Prefab 赋值给 Block_Array
this.Block_Array = assets;
this.setSort();
this.load1 = true;
});
cc.resources.loadDir(path2, cc.Prefab, (err, assets: cc.Prefab[]) => {
if (err) {
cc.director.loadScene("LoadScene");
return;
}
// 将加载的 Prefab 赋值给 Block_Array
this.Wall_Prefab = assets;
this.load2 = true;
this.setWallPrefabSort();
});
}, 100);
}
onHide() {
cc.audioEngine.stopMusic();
cc.game.pause();
}
onShow() {
cc.audioEngine.resumeMusic();
cc.game.resume();
}
//#region 给加载好的墙壁资源排序
/** 给加载好的墙壁资源排序,防止乱序 */
setWallPrefabSort() {
const order = ['down', 'downleft', 'downright', 'left', 'leftdown', 'leftup', 'right', 'rightdown', 'rightup', 'up', 'upleft', 'upright'];
this.Wall_Prefab.sort((a, b) => {
const indexA = order.indexOf(a.name);
const indexB = order.indexOf(b.name);
if (indexA === -1) return 1;
if (indexB === -1) return -1;
return indexA - indexB;
});
}
/** 给加载好的方块资源排序,防止乱序 */
setSort() {
this.Block_Array.sort((a, b) => {
// 从名称中提取数字部分
const numberA = parseInt(a.name.match(/\d+/)?.[0] || '0', 10);
const numberB = parseInt(b.name.match(/\d+/)?.[0] || '0', 10);
return numberA - numberB;
});
}
//#region 开始游戏
/** 开始游戏,执行逻辑 */
startGame() {
// 加载成功后进入 HomeScene
cc.assetManager.loadBundle('shop', (err, bundle) => {
if (err) {
console.error('加载 shop 失败:', err);
} else {
// 加载成功后进入 HomeScene
cc.assetManager.loadBundle('music', (err, bundle) => {
if (err) {
console.error('加载 music bundle 失败:', err);
// 加载失败时仍尝试进入 HomeScene
cc.director.loadScene("HomeScene");
} else {
}
cc.director.loadScene("HomeScene");
});
}
});
// 加载 music bundle
}
//#region 微信登录,以及读取用户信息
/** 微信登录,以及读取用户信息 */
readUserData(retryCount = 0) {
// this.load3 = true;
// this.load4 = true;
// this.load5 = true;
// this.load6 = true;
// let levelInfo = cc.fx.StorageMessage.getStorage("level");
// //如果本地缓存没有关卡信息,默认为服务器信息为主
// if (levelInfo == undefined || levelInfo == "" || levelInfo == null) {
// // this.getUserDataToServer(data.data);
// const timestamp = Date.now();
// cc.fx.GameConfig.GM_INFO.level = 0;
// let levelInfo = { "level": cc.fx.GameConfig.GM_INFO.level, "timestamp": timestamp };
// cc.fx.StorageMessage.setStorage("level", levelInfo);
// cc.fx.GameConfig.GM_INFO.first = true;
// // this.oldReadData(retryCount);
// }
// else {
// cc.fx.GameConfig.GM_INFO.level = levelInfo.level;
// }
// cc.fx.GameTool.getHealth(null);
//@ts-ignore
if (typeof wx !== 'undefined' && wx !== null) {
MiniGameSdk.API.shushu_Init();
this.nowTime = Date.now();
// 最大重试次数
const MAX_RETRIES = 30;
// 延迟时间数组,按照 1 秒 3 次、2 秒 5 次、5 秒 6 次、15 秒 5 次的规则生成
const delays = [
...Array(3).fill(2000),
...Array(5).fill(3000),
...Array(6).fill(5000),
...Array(5).fill(15000)
];
//cc.fx.GameConfig.GM_INFO.shushu_DistinctId
const attemptUserInfo = () => {
Utils.getUserInfo((data) => {
if (data.code == 1) { // 假设返回数据中有 success 字段表示成功
console.log("登錄", data);
if (data.data.openid) {
cc.fx.GameConfig.GM_INFO.openid = data.data.openid;
cc.fx.StorageMessage.setStorage("openid", cc.fx.GameConfig.GM_INFO.openid);
}
if (data.data._id) {
cc.fx.GameConfig.GM_INFO.uid = data.data._id;
cc.fx.StorageMessage.setStorage("uid", data.data._id);
}
if (data.data.onlyId) {
cc.fx.GameConfig.GM_INFO.userId = data.data.onlyId;
}
if (data.data.shareLv) {
console.log("分享数据", data.data.shareLv);
if (data.data.shareLv.length > 0) {
cc.fx.GameConfig.GM_INFO.helpLevel = data.data.shareLv[0].lv;
}
}
if (data.data.username) {
cc.fx.GameConfig.GM_INFO.username = data.data.username;
}
if (data.data.useravatar) {
cc.fx.GameConfig.GM_INFO.useravatarIcon = data.data.useravatar;
if (cc.fx.GameConfig.GM_INFO.useravatarIcon.length < 10)
cc.fx.GameConfig.GM_INFO.useravatarIcon = "icon_" + cc.fx.GameConfig.GM_INFO.useravatarIcon
}
if (data.data.useravatarIcon) {
cc.fx.GameConfig.GM_INFO.useravaterkuang = data.data.useravatarIcon;
cc.fx.GameConfig.GM_INFO.useravaterkuang = "kuang_" + (parseInt(cc.fx.GameConfig.GM_INFO.useravaterkuang) + 1);
}
// this.setUserPower(data);
// this.setmonth(data);
// this.setRevive(data);
let levelInfo = cc.fx.StorageMessage.getStorage("level");
//如果本地缓存没有关卡信息,默认为服务器信息为主
if (levelInfo == undefined || levelInfo == "" || levelInfo == null) {
this.getUserDataToServer(data.data);
// this.oldReadData(retryCount);
}
//新的读取数据设置方法,以本地为主
else {
this.getUserDataToLocal(data.data);
// this.newReadData();
}
cc.fx.GameTool.getHealth((data) => {
this.load5 = true;
});
this.load6 = true;
}
else {
if (retryCount < MAX_RETRIES && retryCount < delays.length) {
const delay = delays[retryCount];
console.error(`获取用户信息失败,第 ${retryCount + 1} 次重试,将在 ${delay / 1000} 秒后重试`);
setTimeout(() => {
retryCount++;
attemptUserInfo();
}, delay);
} else {
console.error('获取用户信息失败,达到最大重试次数,退出游戏');
// 退出游戏
cc.game.end();
}
}
});
};
attemptUserInfo();
}
else {
this.load3 = true;
this.load4 = true;
this.load5 = true;
this.load6 = true;
cc.fx.GameTool.getHealth(null);
}
// 存储用户数据
}
//#region 读取音乐配置
/** 读取音乐配置 */
readMusicConfig() {
let audioInfo = cc.fx.StorageMessage.getStorage("music");
if (audioInfo == undefined || audioInfo == "" || audioInfo == null) {
audioInfo = {
"musicOpen": true, //音乐
"effectOpen": true, //音效
"vibrateOpen": true, //震动
}
cc.fx.StorageMessage.setStorage("music", audioInfo);
}
else {
cc.fx.GameConfig.GM_INFO.musicOpen = audioInfo.musicOpen;
cc.fx.GameConfig.GM_INFO.effectOpen = audioInfo.effectOpen;
cc.fx.GameConfig.GM_INFO.vibrateOpen = audioInfo.vibrateOpen;
}
}
//#region 老用户,读取数据
/** 老用户,有本地缓存数据,与服务器数据做比对,哪边关卡等级高以哪边为主 */
getUserDataToLocal(data) {
const timestamp = Date.now();
let levelInfo = cc.fx.StorageMessage.getStorage("level");
let coinInfo = cc.fx.StorageMessage.getStorage("coin");
let propInfo = {
"freezeAmount": 0,
"hammerAmount": 0,
"magicAmount": 0,
"timestamp": timestamp,
}
cc.fx.GameConfig.GM_INFO.freezeAmount = propInfo.freezeAmount;
cc.fx.GameConfig.GM_INFO.hammerAmount = propInfo.hammerAmount;
cc.fx.GameConfig.GM_INFO.magicAmount = propInfo.magicAmount;
cc.fx.GameConfig.GM_INFO.level = data.levelAmount;
//// cc.fx.GameConfig.GM_INFO.coin = data.coinAmount;
cc.fx.StorageMessage.setStorage("prop", propInfo);
console.log("____________存储道具信息", propInfo);
if (data.levelAmount == null || data.levelAmount == undefined) {
data.levelAmount = 0;
}
if (data.coinAmount == null || data.coinAmount == undefined) {
data.coinAmount = 0;
}
if (levelInfo.level > data.levelAmount) {
cc.fx.GameConfig.GM_INFO.level = levelInfo.level;
//// cc.fx.GameConfig.GM_INFO.coin = coinInfo.coin;
// cc.fx.GameConfig.GM_INFO.freezeAmount = propInfo.freezeAmount;
// cc.fx.GameConfig.GM_INFO.hammerAmount = propInfo.hammerAmount;
// cc.fx.GameConfig.GM_INFO.magicAmount = propInfo.magicAmount;
const timestamp = Date.now();
//// if (coinInfo.coin != data.coinAmount) {
// if (coinInfo == undefined || coinInfo.coin == null) {
// //// let coinInfo = { "coin": cc.fx.GameConfig.GM_INFO.coin, "timestamp": timestamp };
// cc.fx.StorageMessage.setStorage("coin", coinInfo);
// }
// else {
// cc.fx.GameTool.setUserCoin((data) => {
// });
// }
// }
if (levelInfo.level != data.levelAmount) {
if (levelInfo.level == null || levelInfo == undefined) {
let levelInfo = { "level": cc.fx.GameConfig.GM_INFO.level, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("level", levelInfo);
}
else {
cc.fx.GameTool.setUserLevel((data) => {
});
}
}
// if (propInfo.freezeAmount != data.freezeAmount || propInfo.hammerAmount != data.hammerAmount || propInfo.magicAmount != data.magicAmount) {
// cc.fx.GameTool.setUserProp(0, 0, (data) => {
// })
// }
this.load3 = true;
this.load4 = true;
} else {
if (data.levelAmount == null || data.levelAmount == undefined) {
data.levelAmount = cc.fx.GameConfig.GM_INFO.level;
cc.fx.GameTool.setUserLevel((data) => {
});
}
//// if (data.coinAmount == null || data.coinAmount == undefined) {
// data.coinAmount = cc.fx.GameConfig.GM_INFO.coin;
// cc.fx.GameTool.setUserCoin((data) => {
// });
// }
const timestamp = Date.now();
let levelInfo = { "level": data.levelAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("level", levelInfo);
let coinInfo = { "coin": data.coinAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("coin", coinInfo);
// let propInfo = {
// "freezeAmount": data.freezeAmount,
// "hammerAmount": data.hammerAmount,
// "magicAmount": data.magicAmount,
// "timestamp": timestamp,
// }
// cc.fx.GameConfig.GM_INFO.freezeAmount = data.freezeAmount;
// cc.fx.GameConfig.GM_INFO.hammerAmount = data.hammerAmount;
// cc.fx.GameConfig.GM_INFO.magicAmount = data.magicAmount;
cc.fx.GameConfig.GM_INFO.level = data.levelAmount;
//// cc.fx.GameConfig.GM_INFO.coin = data.coinAmount;
// cc.fx.StorageMessage.setStorage("prop", propInfo);
this.load3 = true;
this.load4 = true;
}
}
//#region 新用户,读取数据
/** 本地没信息,新用户,或者清缓存用户 */
getUserDataToServer(data) {
const timestamp = Date.now();
if (data) {
if (data.isFirst == true) {
cc.fx.GameConfig.GM_INFO.first = true;
// if (data.register_time) {
// const time = data.register_time;
// let share = cc.fx.GameTool.isFromShareByScene();
// MiniGameSdk.API.shushu_userSet(time, share);
// }
}
else {
}
this.load3 = true;
this.load4 = true;
if (data.levelAmount == null || data.levelAmount == undefined) {
data.levelAmount = cc.fx.GameConfig.GM_INFO.level;
cc.fx.GameTool.setUserLevel((data) => {
});
}
//// if (data.coinAmount == null || data.coinAmount == undefined) {
// data.coinAmount = cc.fx.GameConfig.GM_INFO.coin;
// cc.fx.GameTool.setUserCoin((data) => {
// });
// }
let levelInfo = { "level": data.levelAmount, "timestamp": timestamp };
cc.fx.StorageMessage.setStorage("level", levelInfo);
//// let coinInfo = { "coin": data.coinAmount, "timestamp": timestamp };
//// cc.fx.StorageMessage.setStorage("coin", coinInfo);
let propInfo = {
"freezeAmount": 0,
"hammerAmount": 0,
"magicAmount": 0,
"timestamp": timestamp,
}
cc.fx.GameConfig.GM_INFO.freezeAmount = propInfo.freezeAmount;
cc.fx.GameConfig.GM_INFO.hammerAmount = propInfo.hammerAmount;
cc.fx.GameConfig.GM_INFO.magicAmount = propInfo.magicAmount;
cc.fx.GameConfig.GM_INFO.level = data.levelAmount;
//// cc.fx.GameConfig.GM_INFO.coin = data.coinAmount;
cc.fx.StorageMessage.setStorage("prop", propInfo);
console.log("____________存储道具信息", propInfo);
}
}
/** 倒计时保证进度在1秒内不进入游戏 */
startTimeCutDown() {
this.scheduleCallback = function () {
if (this.timeNumber <= 0) {
this.stopTimeCutDown();
}
else {
this.timeNumber -= 1;
}
}.bind(this);
this.schedule(this.scheduleCallback, 1);
}
/** 停止定时器 */
stopTimeCutDown() {
if (this.scheduleCallback) {
this.unschedule(this.scheduleCallback);
}
}
//#region 设置无限体力信息
/** 设置无限体力信息 */
setUserPower(data) {
// let nowTime = Math.floor(Date.now() / 1000);
// let powerTime = cc.fx.StorageMessage.getStorage("userPowerTime");
// //本地没缓存
// if (powerTime == "undifend" || powerTime == null || powerTime == "" || powerTime == 0) {
// //本地没缓存,但是服务器有缓存,判断服务器的无限体力时间是否过期
// if (data.data.userPowerTime && data.data.userPowerTime != 0) {
// powerTime = data.data.userPowerTime;
// if (powerTime > nowTime) {
// cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
// cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
// }
// else {
// cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
// cc.fx.StorageMessage.setStorage("userPowerTime", 0);
// }
// }
// //本地没缓存,服务器也没缓存
// else {
// powerTime = 0;
// cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
// cc.fx.StorageMessage.setStorage("userPowerTime", 0);
// }
// }
// //本地有缓存
// else {
// //本地有缓存,且服务器有缓存
// if (data.data.userPowerTime && data.data.userPowerTime != 0) {
// //服务器缓存大于本地缓存,以服务器缓存为主
// if (data.data.userPowerTime > powerTime) {
// powerTime = data.data.userPowerTime;
// if (powerTime > nowTime) {
// cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
// cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
// }
// else {
// cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
// cc.fx.StorageMessage.setStorage("userPowerTime", 0);
// }
// }
// //服务器缓存小于本地缓存,以本地缓存为主
// else {
// if (powerTime > nowTime) {
// cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
// cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
// }
// else {
// cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
// cc.fx.StorageMessage.setStorage("userPowerTime", 0);
// }
// }
// }
// //本地有缓存,服务器没缓存
// else {
// if (powerTime > nowTime) {
// cc.fx.GameConfig.GM_INFO.userPowerTime = powerTime;
// cc.fx.StorageMessage.setStorage("userPowerTime", powerTime);
// }
// else {
// cc.fx.GameConfig.GM_INFO.userPowerTime = 0;
// cc.fx.StorageMessage.setStorage("userPowerTime", 0);
// }
// }
// }
}
//#region 设置月卡信息
/** 设置月卡信息 */
setmonth(data) {
//如果给的时间戳大于当前时间hpmax=7,否则等于5
let nowTime = Math.floor(Date.now() / 1000);
if (data.data.monthCardTime > nowTime) {
cc.fx.GameConfig.GM_INFO.hp_Max = 7;
cc.fx.GameConfig.GM_INFO.doubleCoin = 2;
} else {
cc.fx.GameConfig.GM_INFO.hp_Max = 3;
cc.fx.GameConfig.GM_INFO.doubleCoin = 1;
}
//本地储存当前服务器时间
let dateStr = new Date(data.data.monthCardTime);
cc.fx.StorageMessage.setStorage("mCardDate", dateStr);
}
//#region 复活购买次数初始化
/** 复活购买次数初始化 */
setRevive(data) {
cc.fx.GameConfig.GM_INFO.revive = data.data.rebornGiftCount;
}
//#region 获取有没有分享信息
/** 获取有没有分享信息 */
getShareInfo() {
// 检查微信小游戏启动参数
if (cc.sys.platform === cc.sys.WECHAT_GAME) {
//@ts-ignore
const launchOptions = wx.getLaunchOptionsSync();
const query = launchOptions.query;
if (query.level && query.uid) {
const level = parseInt(query.level, 10);
const uid = query.uid;
cc.fx.GameConfig.GM_INFO.otherUid = uid;
cc.fx.GameConfig.GM_INFO.otherLevel = level;
// 可以在这里处理关卡信息和 UID
}
}
}
//#region 获取是否授权
/** 获取是否授权 */
getSetting() {
MiniGameSdk.API.getWechatUserInfo((res) => {
})
}
/** 主循环,判断是否各项加载完成进入游戏 */
update(dt) {
if (this.load1 && this.load2 && this.load3 && this.load4 && this.load5 && this.load6 == true && this.timeNumber <= 0) {
this.load1 = this.load2 = false;
MiniGameSdk.API.shushu_Login();
MiniGameSdk.API.yinli_Init();
MiniGameSdk.API.yinli_Login();
if (cc.fx.GameConfig.GM_INFO.first == true) {
const time = Date.now();
let share = cc.fx.GameTool.isFromShareByScene();
MiniGameSdk.API.shushu_userSet(time, share);
}
this.startGame();
}
}
}