// ====== 环境修复与全局对象安全 ======
(function() {
// 安全获取全局对象的函数(支持严格模式和所有环境)
const getGlobalObject = () => {
// 1. 优先使用现代标准 globalThis
if (typeof globalThis !== 'undefined') return globalThis;
// 2. 处理严格模式限制
try {
const globalFromFn = Function('return this')();
if (globalFromFn) return globalFromFn;
} catch (e) {
console.warn('[EnvFix] Function constructor blocked in strict mode');
}
// 3. 环境特定对象
if (typeof global !== 'undefined') return global; // Node.js
if (typeof window !== 'undefined') return window; // 浏览器
if (typeof self !== 'undefined') return self; // Web Worker
// 4. Cocos Creator 原生环境特殊处理
if (typeof cc !== 'undefined' && cc.sys && cc.sys.__globalAdapter) {
return cc.sys.__globalAdapter;
}
// 5. 最后手段:创建新的全局对象
console.error('[EnvFix] Unable to determine global object, creating new');
return {};
};
const globalObj = getGlobalObject();
// 修复关键全局变量(使用 Object.defineProperty 防止覆盖)
const defineGlobal = (name, value) => {
if (typeof globalObj[name] === 'undefined') {
Object.defineProperty(globalObj, name, {
value,
writable: true,
configurable: true,
enumerable: true
});
console.log(`[EnvFix] Defined global: ${name}`);
}
};
// 定义关键全局对象
defineGlobal('global', globalObj);
defineGlobal('self', globalObj);
defineGlobal('globalThis', globalObj);
defineGlobal('window', globalObj);
// 原生平台特殊处理
if (cc && cc.sys && cc.sys.isNative) {
// 确保 XMLHttpRequest 存在
if (typeof XMLHttpRequest === 'undefined') {
defineGlobal('XMLHttpRequest', function() {
return cc.loader.getXMLHttpRequest();
});
}
// 确保 document 对象存在
if (typeof document === 'undefined') {
defineGlobal('document', {
createElement: () => ({ appendChild: () => {} }),
head: { appendChild: () => {} },
body: { appendChild: () => {} }
});
}
// 确保 location 对象存在
if (typeof location === 'undefined') {
defineGlobal('location', {
href: 'file://',
protocol: 'file:',
hostname: 'localhost',
host: 'localhost',
origin: 'file://'
});
}
console.log('[EnvFix] Native environment patched');
}
// 确保 require 函数存在
if (typeof globalObj.require === 'undefined') {
defineGlobal('require', function(module) {
if (globalObj.__modules && globalObj.__modules[module]) {
return globalObj.__modules[module];
}
console.warn(`[RequireFallback] Module '${module}' not found`);
return {};
});
}
})();
// ====== 引擎初始化保护系统 ======
const EngineReady = (function() {
let _promise = null;
let _resolve = null;
let _isReady = false;
let _checkInterval = null;
const safeCheckEngine = () => {
// 引擎已初始化
if (cc && cc.game && cc.game._isEngineInited) {
return true;
}
// 尝试监听初始化事件
if (cc && cc.game && cc.game.once) {
const eventName = cc.game.EVENT_ENGINE_INITED || 'engine-inited';
cc.game.once(eventName, () => {
_resolve && _resolve();
_isReady = true;
_checkInterval && clearInterval(_checkInterval);
});
return true;
}
return false;
};
return {
get isReady() { return _isReady; },
get promise() { return _promise; },
init() {
if (!_promise) {
_promise = new Promise(resolve => {
_resolve = () => {
_isReady = true;
resolve();
_checkInterval && clearInterval(_checkInterval);
};
// 首次检查
if (safeCheckEngine()) return;
// 轮询检查
_checkInterval = setInterval(() => {
safeCheckEngine() && _resolve();
}, 100);
});
}
return _promise;
},
safeAccess(callback) {
if (_isReady) {
try {
return callback();
} catch (e) {
console.error('[EngineSafe] Error:', e);
}
}
return _promise.then(callback).catch(e => {
console.error('[EngineSafe] Async error:', e);
});
}
};
})();
EngineReady.init();
// ====== 游戏主入口 ======
async function gameMainEntry() {
try {
console.log('[Main] Waiting for engine initialization...');
await EngineReady.promise;
console.log('[Main] Engine ready');
// 基本引擎配置
EngineReady.safeAccess(() => {
if (cc.view) {
cc.view.enableRetina(true);
cc.view.resizeWithBrowserSize(true);
cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL);
}
});
// 加载SDK
await loadGravityEngineSDK();
// 加载启动场景
await loadStartScene();
} catch (error) {
console.error('[Main] Initialization failed:', error);
try {
cc.director.loadScene('start');
} catch (fallbackError) {
displayErrorFallback('启动失败\n请重启应用');
}
}
}
// 错误显示后备方案
function displayErrorFallback(message) {
try {
const errorDiv = document.createElement('div');
errorDiv.style.cssText = `
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
background: black;
color: white;
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
font: 24px Arial, sans-serif;
text-align: center;
white-space: pre-line;
padding: 20px;
`;
errorDiv.textContent = message;
document.body.appendChild(errorDiv);
} catch (e) {
console.error('[Fallback] Display failed:', e);
}
}
// ====== SDK加载器增强版 ======
async function loadGravityEngineSDK() {
// 使用相对路径解决加载问题
const sdkPaths = [
'./assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'_plugs/lib/gravityengine.mg.cocoscreator.min.js',
'lib/gravityengine.mg.cocoscreator.min.js'
];
for (const path of sdkPaths) {
try {
// 关键修复:在加载 SDK 前确保全局对象完整
ensureGlobalEnvironment();
// JSB 特殊处理:使用 require 加载
if (cc.sys.isNative && cc.sys.__globalAdapter?.require) {
cc.sys.__globalAdapter.require(path);
console.log('[SDK] Native require loaded:', path);
} else {
await loadScript(path);
console.log('[SDK] Loaded from:', path);
}
// 关键修复:加载后再次检查全局对象
ensureGlobalEnvironment();
initGravityEngine();
return;
} catch (e) {
console.warn('[SDK] Load failed:', path, e.message);
}
}
console.error('[SDK] All paths failed');
handleSDKLoadFailure();
}
function ensureGlobalEnvironment() {
// 获取全局对象
const getGlobalObject = () => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof global !== 'undefined') return global;
if (typeof window !== 'undefined') return window;
if (typeof self !== 'undefined') return self;
return Function('return this')() || {};
};
const globalObj = getGlobalObject();
// 确保 self 在所有环境中都存在
if (typeof self === 'undefined') {
console.warn('[GlobalFix] self is undefined, patching...');
Object.defineProperty(globalObj, 'self', {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
// 确保其他关键全局对象存在
const requiredGlobals = ['window', 'global', 'globalThis', 'document', 'location'];
requiredGlobals.forEach(name => {
if (typeof globalObj[name] === 'undefined') {
console.warn(`[GlobalFix] ${name} is undefined, patching...`);
Object.defineProperty(globalObj, name, {
value: globalObj,
writable: true,
configurable: true,
enumerable: true
});
}
});
// 原生平台特殊处理
if (cc && cc.sys && cc.sys.isNative) {
// 确保 location 对象存在
if (typeof location === 'undefined') {
Object.defineProperty(globalObj, 'location', {
value: {
href: 'file://',
protocol: 'file:',
hostname: 'localhost'
},
writable: false,
configurable: false,
enumerable: true
});
}
}
}
function loadScript(path) {
return new Promise((resolve, reject) => {
// 优先使用 Cocos 的加载系统
if (cc.assetManager?.loadScript) {
cc.assetManager.loadScript(path, (err) => {
if (err) {
// 原生平台特殊处理
if (cc.sys.isNative) {
console.warn('[SDK] Using native fallback for script loading');
try {
// 原生平台直接执行脚本
const jsb = cc.sys.__globalAdapter;
if (jsb && jsb.require) {
jsb.require(path);
return resolve();
}
} catch (nativeError) {
console.error('[SDK] Native require failed:', nativeError);
}
}
reject(err);
} else {
resolve();
}
});
return;
}
// 后备方案:直接创建 script 标签
try {
const script = document.createElement('script');
script.src = path;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load ${path}`));
document.head.appendChild(script);
console.warn('[SDK] Using DOM fallback for script loading');
} catch (e) {
reject(e);
}
});
}
function initGravityEngine() {
let GravityEngine = null;
// 1. 尝试标准方式获取
if (typeof GravityEngine === 'function') {
console.log('[SDK] GravityEngine found in local scope');
}
// 2. 尝试从全局对象中查找
else if (typeof window.GravityEngine === 'function') {
GravityEngine = window.GravityEngine;
console.warn('[SDK] Found GravityEngine in window object');
}
// 3. 尝试从其他全局对象中查找
else if (typeof global.GravityEngine === 'function') {
GravityEngine = global.GravityEngine;
console.warn('[SDK] Found GravityEngine in global object');
}
// 4. 尝试从 self 对象中查找
else if (typeof self.GravityEngine === 'function') {
GravityEngine = self.GravityEngine;
console.warn('[SDK] Found GravityEngine in self object');
}
// 5. 最后尝试从 globalThis 中查找
else if (typeof globalThis.GravityEngine === 'function') {
GravityEngine = globalThis.GravityEngine;
console.warn('[SDK] Found GravityEngine in globalThis object');
}
else {
console.error('[SDK] GravityEngine not found');
return;
}
try {
// 使用您的 AppID 624768904
GravityEngine.init({
appId: '624768904',
enableLog: true
});
console.log('[SDK] GravityEngine initialized with AppID 624768904');
} catch (e) {
console.error('[SDK] Init failed:', e);
}
}
function handleSDKLoadFailure() {
console.warn('[SDK] Using fallback analytics');
window.GravityEngine = {
init: () => console.warn('SDK unavailable'),
trackEvent: () => {}
};
}
// ====== 场景加载器 ======
async function loadStartScene() {
try {
// 加载主资源包
await new Promise((resolve) => {
if (!cc.assetManager?.loadBundle) {
console.warn('[Scene] AssetManager unavailable');
return resolve();
}
cc.assetManager.loadBundle('main', (err) => {
if (err) console.error('[Scene] Bundle load error:', err);
resolve();
});
});
// 加载场景
if (cc.director?.loadScene) {
cc.director.loadScene('start');
} else {
throw new Error('Director unavailable');
}
} catch (error) {
console.error('[Scene] Load failed:', error);
try {
cc.director.loadScene('start');
} catch (e) {
throw new Error('Fallback scene load failed');
}
}
}
// ====== UI_Entry组件 ======
const { ccclass, property } = cc._decorator;
@ccclass
export default class UI_Entry extends cc.Component {
@property(cc.ProgressBar)
progress_loading = null;
loginTimeoutHandler = null;
onLoad() {
EngineReady.safeAccess(() => {
try {
cc.director.getCollisionManager().enabled = true;
this._show();
} catch (e) {
console.error('[UI] onLoad error:', e);
this.startLoadGame();
}
}).catch(e => {
console.error('[UI] Engine access error:', e);
this.startLoadGame();
});
}
onDestroy() {
this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler);
}
async _show() {
this.progress_loading.progress = 0;
// 平台SDK初始化
if (cc.sys.isBrowser) {
try {
await this.initYPSDK();
} catch (e) {
console.error('[YPSDK] Init failed:', e);
this.startLoadGame();
}
} else {
this.startLoadGame();
}
// 登录超时保护
this.setLoginTimeout();
}
setLoginTimeout() {
if (cc.tween) {
this.loginTimeoutHandler = cc.tween(this)
.delay(10)
.call(() => {
console.warn('[Login] Timeout after 10s');
this.startLoadGame();
})
.start();
} else {
setTimeout(() => this.startLoadGame(), 10000);
}
}
async initYPSDK() {
if (typeof YPSDK === 'undefined') {
console.warn('[YPSDK] SDK unavailable');
return;
}
const config = {
gameChannelList: {
h5: { platformType: "h5", version: "1.0.0" },
tt: { platformType: "tt", appId: "tt09297f94961f881b02" },
wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff" }
}
};
await YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config);
await YPSDK.login();
if (YPSDK.setLoginCallBack) {
YPSDK.setLoginCallBack(success => {
if (!success) return;
// 取消超时
this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler);
// 初始化分析SDK
if (r_GravityPlatform.default?.GA_Init) {
r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId);
}
this.startLoadGame();
});
} else {
this.startLoadGame();
}
}
startLoadGame() {
const tasks = [
this._loadGameConfig,
this._loadRemoteConfig,
this._loadExcelData,
this._loadUserData,
this._loadCommonBundle,
this._loadMainBundle
].map(fn => fn.bind(this));
this.executeTasks(tasks, () => this._loadGame());
}
executeTasks(tasks, finalCallback) {
let completed = 0;
const total = tasks.length;
const runTask = async (index) => {
if (index >= total) {
finalCallback();
return;
}
try {
await tasks[index]();
completed++;
this._setProgress(completed / total);
runTask(index + 1);
} catch (e) {
console.error(`[Task ${index}] Failed:`, e);
completed++;
this._setProgress(completed / total);
runTask(index + 1); // 继续执行后续任务
}
};
runTask(0);
}
async _loadExcelData() {
if (!r_ExcelLoader?.ExcelLoader?.loadAll) {
console.warn('[Data] ExcelLoader unavailable');
return;
}
await r_ExcelLoader.ExcelLoader.loadAll();
console.log('[Data] Excel loaded');
}
async _loadGameConfig() {
if (!r_ResLoader.default?.loadRes) {
console.warn('[Config] ResLoader unavailable');
return;
}
const jsonAsset = await r_ResLoader.default.loadRes(
"resources",
"config/GameConfig",
cc.JsonAsset
);
if (jsonAsset && r_GameConfig.default) {
r_GameConfig.default.appConfig = jsonAsset.json;
jsonAsset.decRef && jsonAsset.decRef();
console.log('[Config] Game config loaded');
}
}
async _loadRemoteConfig() {
if (!r_GameConfig.default?.appConfig?.RemoteUrl) {
console.warn('[Config] RemoteUrl not set');
return;
}
const remoteUrl = r_GameConfig.default.appConfig.RemoteUrl;
const remotePath = cc.path.join(remoteUrl, "ADConfig.json");
try {
const remoteConfig = await r_ResLoader.default.loadRemote(remotePath, { ext: ".json" });
if (remoteConfig?.json && r_GravityPlatform.default) {
r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0];
r_GameConfig.default.adConfig = remoteConfig.json;
console.log('[Config] Remote config loaded');
}
} catch (e) {
console.error('[Config] Remote load failed:', e);
}
}
async _loadCommonBundle() {
if (!r_ResLoader.default?.loadBundle) {
console.warn('[Bundle] ResLoader unavailable');
return;
}
try {
await r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common);
console.log('[Bundle] Common loaded');
} catch (e) {
console.error('[Bundle] Common load failed:', e);
}
}
async _loadMainBundle() {
if (!r_ResLoader.default?.loadBundle) {
console.warn('[Bundle] ResLoader unavailable');
return;
}
try {
await r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle);
console.log('[Bundle] Main loaded');
} catch (e) {
console.error('[Bundle] Main load failed:', e);
}
}
async _loadUserData() {
try {
// 音频初始化
r_AudioManager.AudioMgr?.init();
// 全局配置
r_GameGlobalVariable.GameGlobalVariable?.initPeiZhi();
// 网络检测
if (YPSDK?.Common?.curChannelData) {
const platformType = YPSDK.Common.curChannelData.platformType;
if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) {
r_YpNetMag.YpNetMag?.failSever(() => {
r_YpNetMag.YpNetMag.isFail = true;
});
}
}
// 用户数据初始化
if (YPSDK?.Platform?.loginData) {
await r_YpNetMag.YpNetMag?.initServer(YPSDK.Platform.loginData);
}
} catch (e) {
console.error('[User] Load failed:', e);
}
}
_loadGame() {
try {
const guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(
r_Const_Common.GuideName.战斗背包
);
if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) {
// 新玩家流程
r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex?.(
r_Const_Common.GuideName.战斗背包,
r_Const_Common.GameBagGuideIndex.引导初始1
);
r_GameDataManager.GameDataMgr?.ClearGameBagData();
r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1;
r_UIManager.default?.open(
r_BundleConfig.BundleNames.Game,
r_UIConfig_Game.UIView_Game.UI_GameView
);
} else {
// 老玩家流程
r_EventManager.EventMgr?.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true);
r_UIManager.default?.open(
r_BundleConfig.BundleNames.Home,
r_UIConfig_Home.UIView_Home.UI_Hall
);
}
// 白名单检查
this.checkWhiteList();
} catch (e) {
console.error('[Game] Load failed:', e);
try {
cc.director.loadScene('start');
} catch (sceneError) {
console.error('[Game] Scene load failed:', sceneError);
}
}
}
async checkWhiteList() {
try {
if (!YPSDK?.Platform?.loginData || !YPSDK.platformUrl) return;
const url = `${YPSDK.platformUrl}/User/GetCfgData?userId=${YPSDK.Platform.loginData.userUid}&keyId=NoVideo`;
if (r_HttpManager.HttpMgr?.requestData) {
r_HttpManager.HttpMgr.requestData(res => {
if (res?.data?.keyData === "true") {
r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true;
}
}, url);
}
} catch (e) {
console.error('[WhiteList] Check failed:', e);
}
}
_setProgress(progress) {
if (!this.progress_loading) return;
this.progress_loading.progress = Math.max(0, Math.min(1, progress));
}
}
// ====== 启动游戏 ======
if (cc?.game?.run) {
cc.game.run(() => {
// 确保环境修复完成
ensureGlobalEnvironment();
gameMainEntry();
});
} else {
setTimeout(() => {
ensureGlobalEnvironment();
gameMainEntry();
}, 1000);
}
针对上述问题 给我修改后的完整代码
最新发布