ElasticSearch学习35_Loading "Gruntfile.js" tasks...ERROR

在ElasticSearch 5.6.2版本中安装Head插件时遇到"Loading "Gruntfile.js" tasks...ERROR"的报错,原因是Gruntfile.js文件存在语法错误。通过检查并修改Gruntfile.js,特别是新增的hostname: '*'配置,发现并修复了不合法的字符,成功解决问题,插件启动正常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

再ES5.0以上的版本中,安装head插件比较麻烦,中途遇到这个报错:

C:\ELK\elasticsearch-5.6.2\head>grunt server
Loading "Gruntfile.js" tasks...ERROR
>> SyntaxError: Invalid or unexpected token
Warning: Task "server" not found. Use --force to continue.


Aborted due to warnings.

因为对Gruntfile.js文件进行过修改,修改内容如下:

connect: {
        server: {
                options: {
                        hostname: '*',
                        port: 9100,
                        base: '.',
                        keepalive: true
                }
        }
}

hostname: '*',是新加的,故去查看它是否出问题,尤其是中英文符号,结果发现果然有错误,解决后重新启动,正常。


// ====== 改进的环境修复代码 ====== (function() { // 1. 检测是否在原生平台 if (cc.sys.isNative) { try { console.log('Applying environment fix for', cc.sys.os); // 2. 获取全局对象的更可靠方法 const getGlobalObject = () => { // 尝试 Cocos Creator 的全局对象 if (typeof cc !== 'undefined' && cc.game && cc.game.globalObject) { return cc.game.globalObject; } // Node.js 环境 if (typeof global !== 'undefined') return global; // 浏览器环境 if (typeof window !== 'undefined') return window; // Web Worker 环境 if (typeof self !== 'undefined') return self; // 终极回退 return Function('return this')() || {}; }; const globalObj = getGlobalObject(); // 3. 修复关键全局变量 if (typeof global === 'undefined') { global = globalObj; console.log('Fixed global'); } if (typeof self === 'undefined') { self = globalObj; console.log('Fixed self'); } // 4. 确保全局对象链完整 if (typeof globalThis === 'undefined') { globalThis = globalObj; } // 5. 验证修复结果 console.log('Environment verification:'); console.log('typeof global:', typeof global); console.log('typeof self:', typeof self); console.log('self === global:', self === global); // 6. 特殊修复:确保全局对象上有 self 属性 if (globalObj && typeof globalObj.self === 'undefined') { Object.defineProperty(globalObj, 'self', { value: globalObj, writable: false, configurable: false, enumerable: false }); console.log('Added self to global object'); } } catch (e) { console.error('Environment fix failed:', e); } } else { console.log('Skipping environment fix for non-native platform'); } })(); // ====== 环境修复结束 ====== // 在环境修复后立即验证 setTimeout(() => { console.log('Environment verification after fix:'); console.log('self defined:', typeof self !== 'undefined'); console.log('global defined:', typeof global !== 'undefined'); console.log('self === global:', self === global); console.log('globalThis === self:', globalThis === self); // 尝试访问典型全局属性 try { console.log('self.setTimeout test:', typeof self.setTimeout); } catch (e) { console.error('Global access failed:', e); } }, 100); // 兼容 JSB 环境:确保 self 存在 if (typeof self === 'undefined') { self = globalThis || global || window || {}; console.warn('Fallback self initialization'); } cc.game.onStart = function() { // 1. 初始化游戏设置 cc.view.enableRetina(true); cc.view.resizeWithBrowserSize(true); // 2. 调整设计分辨率和适配策略 cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL); // 3. 加载重力引擎 SDK(核心位置) loadGravityEngineSDK(); // 4. 加载启动场景 cc.assetManager.loadBundle('main', (err) => { if (err) return console.error('Bundle load failed:', err); cc.director.loadScene('start'); }); }; function loadGravityEngineSDK() { const primaryPath = 'src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js'; const fallbackPath = 'assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js'; cc.assetManager.loadScript(primaryPath, (err) => { if (err) { console.error('Failed to load gravityengine SDK (primary):', err); // 尝试备用路径 console.log('Trying fallback path:', fallbackPath); cc.assetManager.loadScript(fallbackPath, (altErr) => { if (altErr) { console.error('Fallback load failed:', altErr); handleSDKLoadFailure(); } else { console.log('GravityEngine SDK loaded from fallback'); initGravityEngine(); } }); } else { console.log('GravityEngine SDK loaded successfully'); initGravityEngine(); } }); } function initGravityEngine() { // 确保 SDK 已加载 if (typeof GravityEngine === 'undefined') { console.error('GravityEngine SDK not available after loading!'); return; } // 初始化 SDK GravityEngine.init({ appId: 'YOUR_APP_ID', enableLog: true }); console.log('GravityEngine initialized'); } function handleSDKLoadFailure() { // 降级处理:禁用相关功能或显示提示 console.warn('SDK load failed, disabling analytics features'); window.trackEvent = () => {}; // 空函数降级 } cc.game.run(); var i; Object.defineProperty(exports, "__esModule", { value: true }); var r_Const_Common = require("Const_Common"); var r_GravityPlatform = require("GravityPlatform"); var r_YpNetMag = require("YpNetMag"); var r_EvenType = require("EvenType"); var r_PlayerDataManager = require("PlayerDataManager"); var r_ExcelLoader = require("ExcelLoader"); var r_GameDataManager = require("GameDataManager"); var r_GameGlobalVariable = require("GameGlobalVariable"); var r_UIConfig_Game = require("UIConfig_Game"); var r_UIConfig_Home = require("UIConfig_Home"); var r_BundleConfig = require("BundleConfig"); var r_GameConfig = require("GameConfig"); var r_AudioManager = require("AudioManager"); var r_EventManager = require("EventManager"); var r_HttpManager = require("HttpManager"); var r_LogManager = require("LogManager"); var r_ResLoader = require("ResLoader"); var r_UIManager = require("UIManager"); var r_UIView = require("UIView"); var _decorator = cc._decorator; var _ccclass = _decorator.ccclass; var _property = _decorator.property; var def_UI_Entry = function (e) { function _ctor() { var t = null !== e && e.apply(this, arguments) || this; t.progress_loading = null; return t; } __extends(_ctor, e); _ctor.prototype.onLoad = function () { cc.director.getCollisionManager().enabled = true; }; _ctor.prototype._show = function () { return __awaiter(this, undefined, Promise, function () { var e; var t = this; return __generator(this, function () { this.progress_loading.progress = 0; if (cc.sys.isBrowser) { YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", { gameChannelList: { h5: { platformType: "h5", describe: "默认 H5 渠道", version: "1.0.0" }, tt: { platformType: "tt", appId: "tt09297f94961f881b02", describe: "默认 TT 渠道", version: "1.0.0" }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff", describe: "默认 WX 渠道", version: "1.0.0" } } }); YPSDK.login(); } e = cc.tween(this).delay(10).call(function () { console.error("10s后,仍然未登录成功,直接进入游戏"); t.startLoadGame(); }).start(); YPSDK.setLoginCallBack(function (o) { return __awaiter(t, undefined, undefined, function () { return __generator(this, function () { if (o) { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); e.stop(); this.startLoadGame(); } return [2]; }); }); }); return [2]; }); }); }; _ctor.prototype.startLoadGame = function () { var e = []; e.push(this._loadGameConfig); e.push(this._loadRemoteConfig); e.push(this._loadExcelData); e.push(this._loadUserData); e.push(this._loadCommonBundle); e.push(this._loadMainBundle); this._completeTasks(e, this._loadGame); cc.sys.platform == cc.sys.WECHAT_GAME && mg.showShareMenu({ menus: ["shareAppMessage", "shareTimeline"] }); }; _ctor.prototype._loadExcelData = function () { return new Promise(function (e) { var t = new Date().getTime(); r_ExcelLoader.ExcelLoader.loadAll().then(function () { console.log("游戏数据表加载成功", new Date().getTime() - t); e(true); }); }); }; _ctor.prototype._loadGame = function () { cc.sys.platform == cc.sys.WECHAT_GAME && r_LogManager.LogMgr.info("开始游戏!" + mg.getChannel()); this._close(); if (r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(r_Const_Common.GuideName.战斗背包) != 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.onInitWhiteName(); }; _ctor.prototype._completeTasks = function (e, t) { var o = this; var n = 0; var i = 0; var a = Promise.resolve(); e.forEach(function (t) { a = a.then(function () { return t(); }).then(function () { n++; o._setProgress(n / e.length); }).catch(function () { i++; }); }); return a.then(function () { 0 == i && t.call(o); }); }; _ctor.prototype._loadGameConfig = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; var n; return __generator(this, function (i) { switch (i.label) { case 0: e = new Date().getTime(); return [4, r_ResLoader.default.loadRes("resources", "config/GameConfig", cc.JsonAsset)]; case 1: if (n = i.sent()) { r_GameConfig.default.appConfig = n.json; console.log("Load game config success:", r_GameConfig.default.appConfig); n.decRef(); t(true); console.log("游戏本地配置加载成功", new Date().getTime() - e); } else { console.log("Load game config failure"); o(false); } return [2]; } }); }); }); }; _ctor.prototype._loadRemoteConfig = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; var n; var i; var a; return __generator(this, function (r) { switch (r.label) { case 0: e = new Date().getTime(); if (n = r_GameConfig.default.appConfig.RemoteUrl) { i = cc.path.join(n, "ADConfig.json"); return [4, r_ResLoader.default.loadRemote(i, { ext: ".json" })]; } else { return [3, 2]; } case 1: if ((a = r.sent()) && a.json) { r_GravityPlatform.default.videoId = a.json.ADUnitId[0]; r_GameConfig.default.adConfig = a.json; console.log("Load remote config success:", r_GameConfig.default.adConfig); t(true); console.log("远程配置加载成功", new Date().getTime() - e); } else { console.log("Load remote config failure:", i); o(false); } return [3, 3]; case 2: console.log("Load remote config failure: RemoteUrl is null"); o(false); r.label = 3; case 3: return [2]; } }); }); }); }; _ctor.prototype._loadCommonBundle = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function () { e = new Date().getTime(); r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common).then(function (n) { console.log("Loaded main bundle", n); if (n) { t(true); console.log("Common分包下载", new Date().getTime() - e); } else { o(false); } }); return [2]; }); }); }); }; _ctor.prototype._loadMainBundle = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function () { e = new Date().getTime(); r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle).then(function (n) { console.log("Loaded main bundle", n); if (n) { t(true); console.log("Home分包下载", new Date().getTime() - e); } else { o(false); } }); return [2]; }); }); }); }; _ctor.prototype._yp_sdk_init = function () { var e = this; var t = r_GameConfig.default.appConfig.Version; var o = { gameChannelList: { h5: { platformType: "h5", describe: "默认 H5 渠道", version: t }, tt: { platformType: "tt", appId: "tt09297f94961f881b02", describe: "默认 TT 渠道", version: t }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff", describe: "默认 WX 渠道", version: t } } }; return new Promise(function (t, n) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function () { e = new Date().getTime(); YPSDK.init(r_GameConfig.default.appConfig.ServerID, r_GameConfig.default.appConfig.ServerUrl, o).then(function () { t(true); console.log("游品服务器初始化", new Date().getTime() - e); }).catch(function () { n(false); }); return [2]; }); }); }); }; _ctor.prototype._yp_sdk_login = function () { var e = this; return new Promise(function (t, o) { return __awaiter(e, undefined, undefined, function () { return __generator(this, function () { YPSDK.login().then(function () { t(true); }).catch(function () { o(false); }); return [2]; }); }); }); }; _ctor.prototype.onInitWhiteName = function () { return __awaiter(this, undefined, undefined, function () { var e; return __generator(this, function () { e = YPSDK.platformUrl + "/User/GetCfgData?userId=" + YPSDK.Platform.loginData.userUid + "&keyId=NoVideo"; console.log("初始化白名单", YPSDK.platformUrl, YPSDK.Platform.loginData.userUid, e); r_HttpManager.HttpMgr.requestData(function (e) { r_LogManager.LogMgr.debug("---后台请求白名单数据-->>>>>>res------", e); e && e.data && e.data.keyData && "true" == e.data.keyData && (r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true); }, e); return [2]; }); }); }; _ctor.prototype._loadUserData = function () { var e = this; return new Promise(function (t) { return __awaiter(e, undefined, undefined, function () { var e; return __generator(this, function (o) { switch (o.label) { case 0: o.trys.push([0, 2,, 3]); console.error("初始化数据"); r_AudioManager.AudioMgr.init(); r_GameGlobalVariable.GameGlobalVariable.initPeiZhi(); YPSDK.Common.curChannelData.platformType != YPSDK.GamePlatformType.WX && YPSDK.Common.curChannelData.platformType != YPSDK.GamePlatformType.TT || r_YpNetMag.YpNetMag.failSever(function () { r_YpNetMag.YpNetMag.isFail = true; t(true); console.error("数据读取失败"); }); return [4, r_YpNetMag.YpNetMag.initServer(YPSDK.Platform.loginData)]; case 1: o.sent(); return [3, 3]; case 2: e = o.sent(); r_LogManager.LogMgr.error("load user data error:", e); return [3, 3]; case 3: t(true); return [2]; } }); }); }); }; _ctor.prototype._setProgress = function (e) { e = Math.max(0, Math.min(1, e)); this.progress_loading.progress = e; }; __decorate([_property(cc.ProgressBar)], _ctor.prototype, "progress_loading", undefined); return __decorate([_ccclass], _ctor); }(r_UIView.default); exports.default = def_UI_Entry;这个是我的entry代码 结合上述所有问题 给我修改成最终版本
07-15
// ====== 环境修复与全局对象安全 ====== (function() { // 确保全局对象存在 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(); // 修复全局变量 if (typeof global === 'undefined') global = globalObj; if (typeof self === 'undefined') self = globalObj; if (typeof globalThis === 'undefined') globalThis = globalObj; // 确保require函数存在(关键修复) if (typeof globalObj.require === 'undefined') { globalObj.require = function(module) { // 简单实现require功能 if (globalObj.__modules && globalObj.__modules[module]) { return globalObj.__modules[module]; } console.warn(`[RequireFallback] Module '${module}' not found`); return {}; }; console.log('[EnvFix] Created fallback require function'); } })(); // ====== 引擎初始化保护系统 ====== 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 { await loadScript(path); console.log('[SDK] Loaded from:', path); initGravityEngine(); return; } catch (e) { console.warn('[SDK] Load failed:', path, e.message); } } console.error('[SDK] All paths failed'); handleSDKLoadFailure(); } function loadScript(path) { return new Promise((resolve, reject) => { // 优先使用Cocos的加载系统 if (cc.assetManager?.loadScript) { cc.assetManager.loadScript(path, (err) => { if (err) { 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() { if (typeof GravityEngine !== 'function') { 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(gameMainEntry); } else { setTimeout(gameMainEntry, 1000); } 我的代码你已经给我修改过了 依旧出现这个错误
07-16
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值