Js_window.setInterval & window.setTimeout

本文介绍了如何使用JavaScript的setTimeout和setInterval函数实现网页中随机数的自动变化显示,通过简单的代码示例展示了这两种函数的区别及应用。

[setTimeout]

setTimeout(表达式,延时时间) 在执行时,是在载入后延迟指定时间后,去执行一次表达式,记住,次数是一次

用setTimeout实现的自动变化显示随机数的效果:

<html>

<head>

<script>

window.onload=sett;

function sett()

{

document.body.innerHTML=Math.random();

setTimeout("sett()",500);

}

</script>

</head>

<body>

</body>

</html>

 

[setInterval]

setInterval(表达式,交互时间) 则不一样,它从载入后,每隔指定的时间就执行一次表达式

用setInterval实现的自动变化显示随机数的效果:

<html>

<head>

<script>

function sett()

{

document.body.innerHTML=Math.random();

}

setInterval("sett();", 500);

</script>

</head>

<body>

</body>

</html> 

var LogFloatWindow = (function () { function LogFloatWindow(y) { this.x = 0; this.y = y || device.height * 0.5; this.workThread = null; this.storage = $storages.create(&#39;floatLogWindow&#39;); this.onStart = null; this.onStop = null; } LogFloatWindow.prototype.init = function () { var _this = this; this.floatyLogW = $floaty.rawWindow( &#39;&lt;card id=&quot;root&quot; h=&quot;150&quot; cardBackgroundColor=&quot;#b3000000&quot; cardElevation=&quot;0&quot; cardCornerRadius=&quot;0&quot; gravity=&quot;center_vertical&quot;&gt;\n &lt;vertical id=&quot;layout&quot; marginLeft=&quot;22&quot;&gt;\n &lt;horizontal w=&quot;*&quot; margin=&quot;5&quot;&gt;\n &lt;horizontal h=&quot;auto&quot; w=&quot;0&quot; layout_weight=&quot;1&quot;&gt;\n &lt;text id=&quot;title&quot; text=&quot;&quot; textSize=&quot;13dp&quot; textColor=&quot;#FFD700&quot; textStyle=&quot;bold&quot; maxLines=&quot;1&quot; ellipsize=&quot;end&quot; style=&quot;Widget/AppCompat.Button.Borderless&quot; /&gt;\n &lt;text id=&quot;label&quot; text=&quot;&quot; textSize=&quot;13dp&quot; textColor=&quot;#1E90FF&quot; textStyle=&quot;bold&quot; maxLines=&quot;1&quot; ellipsize=&quot;end&quot; style=&quot;Widget/AppCompat.Button.Borderless&quot; marginLeft=&quot;10&quot; /&gt;\n &lt;/horizontal&gt;\n &lt;Chronometer id=&quot;runTime&quot; textSize=&quot;13dp&quot; textColor=&quot;#03D96A&quot; style=&quot;Widget/AppCompat.Button.Borderless&quot; textStyle=&quot;bold&quot; /&gt;\n &lt;/horizontal&gt;\n &lt;button gravity=&quot;center_horizontal&quot; textColor=&quot;#DC143C&quot; bg=&quot;#FFF5EE&quot; h=&quot;1&quot; padding=&quot;0&quot; margin=&quot;0&quot; textStyle=&quot;bold&quot; /&gt;\n &lt;console id=&quot;console&quot; w=&quot;*&quot; h=&quot;*&quot; padding=&quot;5&quot; /&gt;\n &lt;/vertical&gt;\n &lt;/card&gt;&#39; ); this.controller = floaty.rawWindow( &#39;&lt;vertical&gt;\n &lt;vertical h=&quot;150&quot; id=&quot;main&quot;&gt;\n &lt;text layout_weight=&quot;5&quot; id=&quot;start&quot; textStyle=&quot;bold&quot; gravity=&quot;center&quot; w=&quot;22dp&quot; text=&quot;\u542F\u52A8&quot; textColor=&quot;#333333&quot; bg=&quot;#00a86b&quot; /&gt;\n &lt;text layout_weight=&quot;5&quot; id=&quot;hideLog&quot; textStyle=&quot;bold&quot; gravity=&quot;center&quot; w=&quot;22dp&quot; text=&quot;\u65E5\u5FD7&quot; textColor=&quot;#333333&quot; bg=&quot;#FF8E12&quot; /&gt;\n &lt;text layout_weight=&quot;5&quot; id=&quot;stop&quot; textStyle=&quot;bold&quot; gravity=&quot;center&quot; w=&quot;22dp&quot; text=&quot;\u7ED3\u675F&quot; textColor=&quot;#333333&quot; bg=&quot;#ee4d2d&quot; /&gt;\n &lt;/vertical&gt;\n &lt;/vertical&gt;&#39; ); ui.post(function () { setTimeout(function () { if (_this.floatyLogW &amp;&amp; _this.controller) { try { _this.logButton = _this.controller.hideLog; _this.startButton = _this.controller.start; _this.stopButton = _this.controller.stop; _this.runTimeView = _this.floatyLogW.runTime; if (_this.floatyLogW.main) { _this.floatyLogW.main.getRootView().setAlpha(0.8); } _this.floatyLogW.setTouchable(false); _this.runTimeView.setFormat(&#39;运行时长 %s &#39;); _this.runTimeView.setBase(android.os.SystemClock.elapsedRealtime()); var floatConsole = _this.floatyLogW.console; floatConsole.setConsole(runtime.console); floatConsole.setInputEnabled(false); floatConsole.setColor(&#39;V&#39;, &#39;#ffff00&#39;); floatConsole.setColor(&#39;I&#39;, &#39;#ffffff&#39;); floatConsole.setColor(&#39;D&#39;, &#39;#ffff00&#39;); floatConsole.setColor(&#39;W&#39;, &#39;#673ab7&#39;); floatConsole.setColor(&#39;E&#39;, &#39;#ff0000&#39;); floatConsole.setTextSize(13); _this.floatyLogW.setSize(-1, -2); var storedX = _this.storage.get(&#39;floatLogWindowX&#39;, _this.x); var storedY = _this.storage.get(&#39;floatLogWindowY&#39;, _this.y); _this.floatyLogW.setPosition(storedX, storedY); _this.controller.setPosition(storedX, storedY); _this.logButton.setText(&#39;隐藏&#39;); _this.logButton.attr(&#39;background&#39;, &#39;#d1c7b7&#39;); if (_this.startButton) { _this.startButton.setOnClickListener(new java.lang.Object({ onClick: function () { _this.handleStart(_this); } })); } if (_this.stopButton) { _this.stopButton.setOnClickListener(new java.lang.Object({ onClick: function () { _this.handleStop(_this); } })); } if (_this.logButton) { _this.logButton.setOnClickListener(new java.lang.Object({ onClick: function () { _this.handleLog(_this); } })); } } catch (error) { console.error(&quot;初始化悬浮窗时出错:&quot;, error); } } }, 300); }); }; LogFloatWindow.getInstance = function () { if (!LogFloatWindow.instance) { LogFloatWindow.instance = new LogFloatWindow(); } return LogFloatWindow.instance; }; LogFloatWindow.prototype.handleStop = function (_this) { $app.launchPackage(context.getPackageName()); toast(&#39;停止本次任务&#39;); if (_this.workThread) { _this.workThread.interrupt(); } _this.floatyLogW.close(); _this.controller.close(); $threads.shutDownAll(); }; LogFloatWindow.prototype.handleLog = function (_this) { var x = _this.storage.get(&#39;floatLogWindowX&#39;, 0); var y = _this.storage.get(&#39;floatLogWindowY&#39;, device.height * 0.5); ui.post(function () { if (_this.logButton.attr(&#39;text&#39;) == &#39;隐藏&#39;) { _this.floatyLogW.setPosition(3000, 3000); _this.logButton.attr(&#39;text&#39;, &#39;日志&#39;); _this.logButton.attr(&#39;background&#39;, &#39;#FF8E12&#39;); } else { _this.logButton.setText(&#39;隐藏&#39;); _this.logButton.attr(&#39;background&#39;, &#39;#d1c7b7&#39;); _this.floatyLogW.setPosition(x, y); } }); }; LogFloatWindow.prototype.handleStart = function (_this) { toast(&#39;开始本次任务&#39;); if (!_this.workThread || !_this.workThread.isAlive()) { if (_this.controller) _this.toggleStatus(true); _this.workThread = threads.start(function () { try { _this.info(&#39;任务开始&#39;); _this.onStart &amp;&amp; _this.onStart(); if (_this.controller) _this.toggleStatus(false); _this.info(&#39;任务完成&#39;); } catch (e) { var info = $debug.getStackTrace(e); if (info.includes(&#39;com.stardust.autojs.runtime.exception.ScriptInterruptedException&#39;)) { _this.info(&#39;停止任务&#39;); } else { _this.error(&#39;任务报错: &#39; + e); _this.error(&#39;程序运行失败: &#39; + info); } _this.toggleStatus(false); } }); } else { _this.onStop &amp;&amp; _this.onStop(); _this.toggleStatus(false); _this.workThread &amp;&amp; _this.workThread.interrupt(); } }; LogFloatWindow.prototype.dateFormat = function (date, fmt_str) { return new java.text.SimpleDateFormat(fmt_str).format(date || new Date()); }; LogFloatWindow.prototype.info = function (msg) { console.info(&#39;[&#39;.concat(this.dateFormat(new Date(), &#39;HH:mm:ss&#39;), &#39;]&#39;).concat(msg)); }; LogFloatWindow.prototype.error = function (msg) { console.error(&#39;[&#39;.concat(this.dateFormat(new Date(), &#39;HH:mm:ss&#39;), &#39;]&#39;).concat(msg)); }; LogFloatWindow.prototype.setFloatyTitle = function (title) { ui.run(function () { if (this.floatyLogW &amp;&amp; this.floatyLogW.title) { this.floatyLogW.title.attr(&#39;text&#39;, title); } }); }; LogFloatWindow.prototype.setFloatySubTitle = function (label) { ui.run(function () { if (this.floatyLogW &amp;&amp; this.floatyLogW.label) { this.floatyLogW.label.attr(&#39;text&#39;, label); } }); }; LogFloatWindow.prototype.toggleStatus = function (enabled) { $ui.post(function () { if (this.floatyLogW &amp;&amp; this.controller &amp;&amp; this.runTimeView &amp;&amp; this.startButton) { if (enabled) { this.runTimeView.setBase(android.os.SystemClock.elapsedRealtime()); this.runTimeView.start(); this.startButton.setText(&#39;停止&#39;); this.startButton.attr(&#39;background&#39;, &#39;#05a7f4&#39;); } else { this.runTimeView.stop(); this.startButton.setText(&#39;启动&#39;); this.startButton.attr(&#39;background&#39;, &#39;#00a86b&#39;); } } }); }; return LogFloatWindow; })(); var logWindow = LogFloatWindow.getInstance(); logWindow.init(); logWindow.setFloatyTitle(&quot;任务日志&quot;); logWindow.setFloatySubTitle(&quot;运行状态&quot;); logWindow.onStart = function () { logWindow.info(&quot;任务已启动&quot;); for (let i = 0; i &lt; 5; i++) { logWindow.info(&quot;执行第 &quot; + (i + 1) + &quot; 次任务&quot;); threads.sleep(1000); // 模拟任务延迟 } }; logWindow.handleStart(logWindow); setTimeout(function () { logWindow.handleStop(logWindow); }, 3000000); 检查以上代码是哪出错了
05-07
import { reactive, nextTick } from &#39;vue&#39;; import View from &#39;./AmiProgressbar.vue&#39;; function assign(target, source) { for (let index = 1, key, src; index &lt; arguments.length; ++index) { src = arguments[index]; for (key in src) { if (Object.prototype.hasOwnProperty.call(src, key)) { target[key] = src[key]; } } } return target; } const options = { color: &#39;#5E7CE0&#39;, failedColor: &#39;#874b4b&#39;, thickness: &#39;6px&#39;, transition: { speed: &#39;0.2s&#39;, opacity: &#39;0.6s&#39;, termination: 300, }, autoRevert: true, location: &#39;top&#39;, inverse: false, }; export default { install: (app) =&gt; { const DEFAULT_OPTION = { canSuccess: true, show: false, color: &#39;#A0E6FF&#39;, position: &#39;fixed&#39;, failedColor: &#39;red&#39;, successLinearGradient: &#39;linear-gradient(to right, #A0E6FF , #5E7CE0)&#39;, failedLinearGradient: &#39;linear-gradient(to right, #FA9841 , #FACC41)&#39;, thickness: &#39;2px&#39;, transition: { speed: &#39;0.2s&#39;, opacity: &#39;0.6s&#39;, termination: 300, }, autoRevert: true, location: &#39;top&#39;, inverse: false, autoFinish: true, }; const progressOptions = assign(DEFAULT_OPTION, options); const RADON_LOADING_BAR = reactive({ percent: 0, options: progressOptions, }); app.provide(&#39;RADON_LOADING_BAR&#39;, RADON_LOADING_BAR); let Progress = { state: { tFailColor: &#39;&#39;, tColor: &#39;&#39;, timer: null, cut: 0, }, start(time) { if (!time) time = 3000; RADON_LOADING_BAR.percent = 0; RADON_LOADING_BAR.options.show = true; RADON_LOADING_BAR.options.canSuccess = true; this.state.cut = 10000 / Math.floor(time); clearInterval(this.state.timer); this.state.timer = setInterval(() =&gt; { const arr = new Uint8Array(1); const cryptoMethod = window.crypto || window.webkitCrypto || window.mozCrypto || window.oCrypto || window.msCrypto; const randomNum = cryptoMethod.getRandomValues(arr)[0]/256; this.increase(this.state.cut * randomNum); if ( RADON_LOADING_BAR.percent &gt; 95 &amp;&amp; RADON_LOADING_BAR.options.autoFinish ) { this.finish(); } }, 100); }, set(num) { RADON_LOADING_BAR.options.show = true; RADON_LOADING_BAR.options.canSuccess = true; RADON_LOADING_BAR.percent = Math.floor(num); }, get() { return Math.floor(RADON_LOADING_BAR.percent); }, increase(num) { RADON_LOADING_BAR.percent = Math.min( 99, RADON_LOADING_BAR.percent + Math.floor(num) ); }, decrease(num) { RADON_LOADING_BAR.percent = RADON_LOADING_BAR.percent - Math.floor(num); }, hide() { clearInterval(this.state.timer); this.state.timer = null; setTimeout(() =&gt; { RADON_LOADING_BAR.options.show = false; nextTick(() =&gt; { setTimeout(() =&gt; { RADON_LOADING_BAR.percent = 0; }, 100); if (RADON_LOADING_BAR.options.autoRevert) { setTimeout(() =&gt; { this.revert(); }, 300); } }); }, RADON_LOADING_BAR.options.transition.termination); }, pause() { clearInterval(this.state.timer); }, finish() { RADON_LOADING_BAR.percent = 100; this.hide(); }, fail() { RADON_LOADING_BAR.options.canSuccess = false; RADON_LOADING_BAR.percent = 100; this.hide(); }, setFailColor(color) { RADON_LOADING_BAR.options.failedColor = color; }, setColor(color) { RADON_LOADING_BAR.options.color = color; }, setLocation(loc) { RADON_LOADING_BAR.options.location = loc; }, setTransition(transition) { RADON_LOADING_BAR.options.transition = transition; }, tempFailColor(color) { this.state.tFailColor = RADON_LOADING_BAR.options.failedColor; RADON_LOADING_BAR.options.failedColor = color; }, tempColor(color) { this.state.tColor = RADON_LOADING_BAR.options.color; RADON_LOADING_BAR.options.color = color; }, tempLocation(loc) { this.state.tLocation = RADON_LOADING_BAR.options.location; RADON_LOADING_BAR.options.location = loc; }, tempTransition(transition) { this.state.tTransition = RADON_LOADING_BAR.options.transition; RADON_LOADING_BAR.options.transition = transition; }, revertColor() { RADON_LOADING_BAR.options.color = this.state.tColor; this.state.tColor = &#39;&#39;; }, revertFailColor() { RADON_LOADING_BAR.options.failedColor = this.state.tFailColor; this.state.tFailColor = &#39;&#39;; }, revertLocation() { RADON_LOADING_BAR.options.location = this.state.tLocation; this.state.tLocation = &#39;&#39;; }, revertTransition() { RADON_LOADING_BAR.options.transition = this.state.tTransition; this.state.tTransition = {}; }, revert() { if (RADON_LOADING_BAR.options.autoRevert) { if (this.state.tColor) { this.revertColor(); } if (this.state.tFailColor) { this.revertFailColor(); } if (this.state.tLocation) { this.revertLocation(); } if ( this.state.tTransition &amp;&amp; (this.state.tTransition.speed !== undefined || this.state.tTransition.opacity !== undefined) ) { this.revertTransition(); } } }, }; app.component(&#39;vue-progress-bar&#39;, View); app.config.globalProperties.$Progress = Progress; }, }; 将这份文件改为ts的形式
最新发布
09-24
// ====== 环境修复代码(确保全局对象安全) ====== (function() { if (cc &amp;&amp; cc.sys &amp;&amp; cc.sys.isNative) { try { console.log(&#39;[EnvFix] Applying environment patches for&#39;, cc.sys.os); // 可靠获取全局对象的多平台兼容方案 const getGlobalObject = () =&gt; { // 优先级1: Cocos Creator 的全局对象 if (typeof cc !== &#39;undefined&#39; &amp;&amp; cc.game &amp;&amp; cc.game.globalObject) { return cc.game.globalObject; } // 优先级2: Node.js 环境 if (typeof global !== &#39;undefined&#39;) return global; // 优先级3: 浏览器环境 if (typeof window !== &#39;undefined&#39;) return window; // 优先级4: Web Worker 环境 if (typeof self !== &#39;undefined&#39;) return self; // 终极回退方案 return Function(&#39;return this&#39;)() || {}; }; const globalObj = getGlobalObject(); // 修复关键全局变量缺失问题 if (typeof global === &#39;undefined&#39;) global = globalObj; if (typeof self === &#39;undefined&#39;) self = globalObj; if (typeof globalThis === &#39;undefined&#39;) globalThis = globalObj; // 确保全局对象上有 self 属性 if (globalObj &amp;&amp; typeof globalObj.self === &#39;undefined&#39;) { Object.defineProperty(globalObj, &#39;self&#39;, { value: globalObj, writable: false, configurable: false, enumerable: false }); console.log(&#39;[EnvFix] Added self to global object&#39;); } // 验证修复结果 console.log(&#39;[EnvFix] Verification:&#39;, { global: typeof global, self: typeof self, globalThis: typeof globalThis, equality: self === global &amp;&amp; global === globalThis }); } catch (e) { console.error(&#39;[EnvFix] Failed:&#39;, e); } } else { console.log(&#39;[EnvFix] Skipping for non-native platform&#39;); } })(); // ====== 改进的引擎初始化保护系统 ====== const EngineReady = (function() { let _promise = null; let _resolve = null; let _isReady = false; let _checkInterval = null; return { get isReady() { return _isReady; }, get promise() { return _promise; }, init() { if (!_promise) { _promise = new Promise(resolve =&gt; { _resolve = () =&gt; { _isReady = true; resolve(); if (_checkInterval) { clearInterval(_checkInterval); _checkInterval = null; } }; // 安全检查:确保cc.game存在 const safeCheckEngine = () =&gt; { // 如果引擎已经初始化 if (cc &amp;&amp; cc.game &amp;&amp; cc.game._isEngineInited) { _resolve(); return true; } // 尝试监听引擎初始化事件 if (cc &amp;&amp; cc.game &amp;&amp; cc.game.once) { // 使用更安全的方式访问事件常量 const eventName = (cc.game &amp;&amp; cc.game.EVENT_ENGINE_INITED) || (cc.Game &amp;&amp; cc.Game.EVENT_ENGINE_INITED) || &#39;engine-inited&#39;; cc.game.once(eventName, _resolve); return true; } return false; }; // 首次尝试检查 if (safeCheckEngine()) { return; } // 如果首次检查失败,设置轮询检查 _checkInterval = setInterval(() =&gt; { if (safeCheckEngine()) { clearInterval(_checkInterval); _checkInterval = null; } }, 100); }); } return _promise; }, // 安全访问引擎API的包装器 safeAccess(callback) { if (_isReady) { try { return callback(); } catch (e) { console.error(&#39;[EngineSafe] Callback error:&#39;, e); } } return _promise.then(callback).catch(e =&gt; { console.error(&#39;[EngineSafe] Async callback error:&#39;, e); }); } }; })(); // 初始化但不立即等待 EngineReady.init(); // ====== 游戏主入口 ====== async function gameMainEntry() { try { console.log(&#39;[Main] Waiting for engine initialization...&#39;); // 安全等待引擎初始化 await EngineReady.promise; console.log(&#39;[Main] Engine fully initialized&#39;); // 安全初始化游戏设置 EngineReady.safeAccess(() =&gt; { 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(&#39;[Main] Game initialization failed:&#39;, error); // 尝试恢复基本功能 try { // 直接尝试加载场景 if (cc.director &amp;&amp; cc.director.loadScene) { cc.director.loadScene(&#39;start&#39;); } } catch (fallbackError) { console.error(&#39;[Main] Fallback scene load failed:&#39;, fallbackError); // 最终后备方案 displayErrorFallback(&#39;Initialization Failed\nPlease Restart&#39;); } } } // 错误显示后备方案 function displayErrorFallback(message) { try { // 尝试使用DOM创建错误显示 const errorDiv = document.createElement(&#39;div&#39;); errorDiv.style.position = &#39;fixed&#39;; errorDiv.style.top = &#39;0&#39;; errorDiv.style.left = &#39;0&#39;; errorDiv.style.width = &#39;100%&#39;; errorDiv.style.height = &#39;100%&#39;; errorDiv.style.backgroundColor = &#39;black&#39;; errorDiv.style.color = &#39;white&#39;; errorDiv.style.display = &#39;flex&#39;; errorDiv.style.justifyContent = &#39;center&#39;; errorDiv.style.alignItems = &#39;center&#39;; errorDiv.style.zIndex = &#39;9999&#39;; errorDiv.style.fontFamily = &#39;Arial, sans-serif&#39;; errorDiv.style.fontSize = &#39;24px&#39;; errorDiv.style.textAlign = &#39;center&#39;; errorDiv.style.whiteSpace = &#39;pre-line&#39;; errorDiv.textContent = message; document.body.appendChild(errorDiv); } catch (domError) { console.error(&#39;[Fallback] Failed to create error display:&#39;, domError); } } // ====== SDK 加载器 ====== async function loadGravityEngineSDK() { const sdkPaths = [ &#39;src/assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js&#39;, &#39;assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js&#39;, &#39;lib/gravityengine.mg.cocoscreator.min.js&#39; // 额外后备路径 ]; let sdkLoaded = false; for (const path of sdkPaths) { try { console.log(`[SDK] Attempting to load from: ${path}`); await new Promise((resolve, reject) =&gt; { if (cc &amp;&amp; cc.assetManager &amp;&amp; cc.assetManager.loadScript) { cc.assetManager.loadScript(path, (err) =&gt; { if (err) { console.warn(`[SDK] Load failed: ${err.message}`); reject(err); } else { resolve(); } }); } else { console.warn(&#39;[SDK] cc.assetManager not available&#39;); reject(&#39;Asset manager not available&#39;); } }); console.log(&#39;[SDK] GravityEngine loaded successfully&#39;); sdkLoaded = true; initGravityEngine(); break; } catch (err) { // 继续尝试下一个路径 } } if (!sdkLoaded) { console.error(&#39;[SDK] All load attempts failed&#39;); handleSDKLoadFailure(); } } function initGravityEngine() { if (typeof GravityEngine === &#39;undefined&#39;) { console.error(&#39;[SDK] GravityEngine not defined after loading&#39;); return; } try { GravityEngine.init({ appId: &#39;YOUR_APP_ID&#39;, // 替换为实际AppID enableLog: true }); console.log(&#39;[SDK] GravityEngine initialized&#39;); } catch (e) { console.error(&#39;[SDK] Initialization failed:&#39;, e); } } function handleSDKLoadFailure() { console.warn(&#39;[SDK] Disabling analytics features&#39;); // 创建空函数降级 window.trackEvent = window.trackEvent || function() {}; window.GravityEngine = window.GravityEngine || { init: () =&gt; console.warn(&#39;SDK not available&#39;), trackEvent: () =&gt; {} }; } // ====== 场景加载器 ====== async function loadStartScene() { try { // 尝试加载主资源包 await new Promise((resolve, reject) =&gt; { if (cc &amp;&amp; cc.assetManager &amp;&amp; cc.assetManager.loadBundle) { cc.assetManager.loadBundle(&#39;main&#39;, (err) =&gt; { if (err) { console.error(&#39;[Scene] Bundle load failed:&#39;, err); reject(err); } else { console.log(&#39;[Scene] Main bundle loaded&#39;); resolve(); } }); } else { console.warn(&#39;[Scene] Asset manager not available, skipping bundle load&#39;); resolve(); // 继续执行 } }); // 加载启动场景 if (cc.director &amp;&amp; cc.director.loadScene) { cc.director.loadScene(&#39;start&#39;); } else { throw new Error(&#39;Director not available&#39;); } } catch (error) { console.error(&#39;[Scene] Failed to load main bundle:&#39;, error); // 后备方案:直接加载场景 try { console.log(&#39;[Scene] Trying direct scene load&#39;); if (cc.director &amp;&amp; cc.director.loadScene) { cc.director.loadScene(&#39;start&#39;); } else { throw new Error(&#39;Director not available&#39;); } } catch (directError) { console.error(&#39;[Scene] Direct scene load failed:&#39;, directError); throw directError; // 传递给上层处理 } } } // ====== UI_Entry 组件 ====== var _decorator = cc._decorator; var _ccclass = _decorator.ccclass; var _property = _decorator.property; // 导入依赖模块 const r_Const_Common = require(&quot;Const_Common&quot;); const r_GravityPlatform = require(&quot;GravityPlatform&quot;); const r_YpNetMag = require(&quot;YpNetMag&quot;); const r_EvenType = require(&quot;EvenType&quot;); const r_PlayerDataManager = require(&quot;PlayerDataManager&quot;); const r_ExcelLoader = require(&quot;ExcelLoader&quot;); const r_GameDataManager = require(&quot;GameDataManager&quot;); const r_GameGlobalVariable = require(&quot;GameGlobalVariable&quot;); const r_UIConfig_Game = require(&quot;UIConfig_Game&quot;); const r_UIConfig_Home = require(&quot;UIConfig_Home&quot;); const r_BundleConfig = require(&quot;BundleConfig&quot;); const r_GameConfig = require(&quot;GameConfig&quot;); const r_AudioManager = require(&quot;AudioManager&quot;); const r_EventManager = require(&quot;EventManager&quot;); const r_HttpManager = require(&quot;HttpManager&quot;); const r_LogManager = require(&quot;LogManager&quot;); const r_ResLoader = require(&quot;ResLoader&quot;); const r_UIManager = require(&quot;UIManager&quot;); const r_UIView = require(&quot;UIView&quot;); var def_UI_Entry = (function (_super) { __extends(def_UI_Entry, _super); function def_UI_Entry() { var _this = _super !== null &amp;&amp; _super.apply(this, arguments) || this; _this.progress_loading = null; _this.loginTimeoutHandler = null; return _this; } // 组件生命周期:加载 def_UI_Entry.prototype.onLoad = function () { var _this = this; EngineReady.safeAccess(function () { try { if (cc.director &amp;&amp; cc.director.getCollisionManager) { cc.director.getCollisionManager().enabled = true; } console.log(&#39;[UI] Collision manager enabled&#39;); _this._show(); } catch (e) { console.error(&#39;[UI] onLoad error:&#39;, e); _this.startLoadGame(); // 直接开始加载游戏 } }).catch(function (err) { console.error(&#39;[UI] Engine access error:&#39;, err); _this.startLoadGame(); }); }; // 组件生命周期:销毁 def_UI_Entry.prototype.onDestroy = function () { if (this.loginTimeoutHandler) { cc.Tween.stop(this.loginTimeoutHandler); this.loginTimeoutHandler = null; console.log(&#39;[UI] Login timeout handler cleared&#39;); } }; // 显示UI并初始化平台SDK def_UI_Entry.prototype._show = function () { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { this.progress_loading.progress = 0; console.log(&#39;[UI] Showing UI_Entry&#39;); // 平台特定的SDK初始化 if (cc.sys &amp;&amp; cc.sys.isBrowser) { this.initYPSDK().catch(function (err) { console.error(&#39;[UI] YPSDK init failed:&#39;, err); _this.startLoadGame(); }); } else { this.startLoadGame(); } // 设置登录超时保护(10秒) if (cc &amp;&amp; cc.tween) { this.loginTimeoutHandler = cc.tween(this) .delay(10) .call(function () { console.warn(&#39;[UI] Login timeout after 10s, proceeding without SDK&#39;); _this.startLoadGame(); }) .start(); } else { console.warn(&#39;[UI] cc.tween not available, using setTimeout&#39;); setTimeout(() =&gt; { console.warn(&#39;[UI] Login timeout after 10s, proceeding without SDK&#39;); this.startLoadGame(); }, 10000); } return [2]; }); }); }; // 初始化游品SDK def_UI_Entry.prototype.initYPSDK = function () { return __awaiter(this, void 0, void 0, function () { var config; var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: if (typeof YPSDK === &#39;undefined&#39;) { console.warn(&#39;[YPSDK] YPSDK not available&#39;); return [2]; } config = { gameChannelList: { h5: { platformType: &quot;h5&quot;, describe: &quot;默认 H5 渠道&quot;, version: &quot;1.0.0&quot; }, tt: { platformType: &quot;tt&quot;, appId: &quot;tt09297f94961f881b02&quot;, describe: &quot;默认 TT 渠道&quot;, version: &quot;1.0.0&quot; }, wx: { platformType: &quot;wx&quot;, appId: &quot;wx6baaaa27ab5186ff&quot;, describe: &quot;默认 WX 渠道&quot;, version: &quot;1.0.0&quot; } } }; return [4, YPSDK.init(39, &quot;https://platform-shop-dev.hanyougame.com&quot;, config)]; case 1: _a.sent(); return [4, YPSDK.login()]; case 2: _a.sent(); // 设置登录回调 if (YPSDK.setLoginCallBack) { YPSDK.setLoginCallBack(function (success) { if (success) { // 取消超时处理 if (_this.loginTimeoutHandler) { if (cc &amp;&amp; cc.Tween &amp;&amp; cc.Tween.stop) { cc.Tween.stop(_this.loginTimeoutHandler); } _this.loginTimeoutHandler = null; } // 初始化重力引擎 if (r_GravityPlatform.default &amp;&amp; typeof r_GravityPlatform.default.GA_Init === &#39;function&#39;) { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); } _this.startLoadGame(); } }); } else { console.warn(&#39;[YPSDK] setLoginCallBack not available&#39;); } return [2]; } }); }); }; // 开始加载游戏资源 def_UI_Entry.prototype.startLoadGame = function () { var tasks = [ this._loadGameConfig.bind(this), this._loadRemoteConfig.bind(this), this._loadExcelData.bind(this), this._loadUserData.bind(this), this._loadCommonBundle.bind(this), this._loadMainBundle.bind(this) ]; this.executeTasksWithProgress(tasks, this._loadGame.bind(this)); // 微信平台特殊处理 if (cc.sys &amp;&amp; cc.sys.platform === cc.sys.WECHAT_GAME &amp;&amp; typeof mg !== &#39;undefined&#39;) { try { mg.showShareMenu({ menus: [&quot;shareAppMessage&quot;, &quot;shareTimeline&quot;] }); } catch (e) { console.warn(&#39;[WeChat] Share menu setup failed:&#39;, e); } } }; // 带进度监控的任务执行器 def_UI_Entry.prototype.executeTasksWithProgress = function (tasks, finalCallback) { var _this = this; var completed = 0; var failed = 0; var executeNext = function (index) { if (index &gt;= tasks.length) { if (failed === 0) { finalCallback(); } else { console.warn(&quot;[Tasks] Completed with &quot; + failed + &quot; failures&quot;); finalCallback(); // 即使有失败也继续 } return; } tasks[index]() .then(function () { completed++; _this._setProgress(completed / tasks.length); executeNext(index + 1); }) .catch(function (err) { console.error(&quot;[Task] #&quot; + index + &quot; failed:&quot;, err); failed++; _this._setProgress((completed + 0.5) / tasks.length); // 部分进度 executeNext(index + 1); }); }; executeNext(0); }; // 加载Excel数据 def_UI_Entry.prototype._loadExcelData = function () { return new Promise(function (resolve, reject) { if (r_ExcelLoader &amp;&amp; r_ExcelLoader.ExcelLoader &amp;&amp; r_ExcelLoader.ExcelLoader.loadAll) { r_ExcelLoader.ExcelLoader.loadAll() .then(function () { console.log(&#39;[Data] Excel data loaded&#39;); resolve(); }) .catch(function (err) { console.error(&#39;[Data] Excel load failed:&#39;, err); reject(err); }); } else { console.warn(&#39;[Data] ExcelLoader not available&#39;); resolve(); // 非关键任务继续 } }); }; // 加载游戏配置 def_UI_Entry.prototype._loadGameConfig = function () { return __awaiter(this, void 0, void 0, function () { var jsonAsset; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!r_ResLoader || !r_ResLoader.default || !r_ResLoader.default.loadRes) { console.warn(&#39;[Config] ResLoader not available&#39;); return [2, Promise.resolve()]; } return [4, r_ResLoader.default.loadRes(&quot;resources&quot;, &quot;config/GameConfig&quot;, cc.JsonAsset)]; case 1: jsonAsset = _a.sent(); if (jsonAsset &amp;&amp; r_GameConfig &amp;&amp; r_GameConfig.default) { r_GameConfig.default.appConfig = jsonAsset.json; console.log(&#39;[Config] Game config loaded&#39;); if (jsonAsset.decRef) { jsonAsset.decRef(); // 释放引用 } return [2, Promise.resolve()]; } else { console.error(&#39;[Config] Game config not found&#39;); return [2, Promise.resolve()]; // 非关键错误继续 } } }); }); }; // 加载远程配置 def_UI_Entry.prototype._loadRemoteConfig = function () { return __awaiter(this, void 0, void 0, function () { var remoteUrl, remotePath, remoteConfig; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!r_GameConfig || !r_GameConfig.default || !r_GameConfig.default.appConfig || !r_GameConfig.default.appConfig.RemoteUrl) { console.warn(&#39;[Config] RemoteUrl not configured&#39;); return [2, Promise.resolve()]; } remoteUrl = r_GameConfig.default.appConfig.RemoteUrl; remotePath = cc.path.join(remoteUrl, &quot;ADConfig.json&quot;); return [4, r_ResLoader.default.loadRemote(remotePath, { ext: &quot;.json&quot; })]; case 1: remoteConfig = _a.sent(); if (remoteConfig &amp;&amp; remoteConfig.json &amp;&amp; r_GravityPlatform &amp;&amp; r_GravityPlatform.default) { r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0]; if (r_GameConfig &amp;&amp; r_GameConfig.default) { r_GameConfig.default.adConfig = remoteConfig.json; } console.log(&#39;[Config] Remote config loaded&#39;); return [2, Promise.resolve()]; } else { console.error(&#39;[Config] Remote config load failed&#39;); return [2, Promise.resolve()]; // 非关键错误,继续执行 } } }); }); }; // 加载公共资源包 def_UI_Entry.prototype._loadCommonBundle = function () { return new Promise(function (resolve, reject) { if (!r_ResLoader || !r_ResLoader.default || !r_ResLoader.default.loadBundle) { console.warn(&#39;[Bundle] ResLoader not available&#39;); resolve(); return; } r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common) .then(function (bundle) { if (bundle) { console.log(&#39;[Bundle] Common bundle loaded&#39;); resolve(); } else { console.warn(&#39;[Bundle] Common bundle not loaded&#39;); resolve(); // 非关键错误继续 } }) .catch(err =&gt; { console.error(&#39;[Bundle] Common bundle load failed:&#39;, err); resolve(); // 非关键错误继续 }); }); }; // 加载主游戏包 def_UI_Entry.prototype._loadMainBundle = function () { return new Promise(function (resolve, reject) { if (!r_ResLoader || !r_ResLoader.default || !r_ResLoader.default.loadBundle) { console.warn(&#39;[Bundle] ResLoader not available&#39;); resolve(); return; } r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle) .then(function (bundle) { if (bundle) { console.log(&#39;[Bundle] Main game bundle loaded&#39;); resolve(); } else { console.warn(&#39;[Bundle] Main game bundle not loaded&#39;); resolve(); // 非关键错误继续 } }) .catch(err =&gt; { console.error(&#39;[Bundle] Main game bundle load failed:&#39;, err); resolve(); // 非关键错误继续 }); }); }; // 加载用户数据 def_UI_Entry.prototype._loadUserData = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { try { if (r_AudioManager &amp;&amp; r_AudioManager.AudioMgr &amp;&amp; r_AudioManager.AudioMgr.init) { r_AudioManager.AudioMgr.init(); } if (r_GameGlobalVariable &amp;&amp; r_GameGlobalVariable.GameGlobalVariable &amp;&amp; r_GameGlobalVariable.GameGlobalVariable.initPeiZhi) { r_GameGlobalVariable.GameGlobalVariable.initPeiZhi(); } if (YPSDK &amp;&amp; YPSDK.Common &amp;&amp; YPSDK.Common.curChannelData &amp;&amp; r_YpNetMag &amp;&amp; r_YpNetMag.YpNetMag &amp;&amp; r_YpNetMag.YpNetMag.failSever) { var platformType = YPSDK.Common.curChannelData.platformType; if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) { r_YpNetMag.YpNetMag.failSever(function () { if (r_YpNetMag.YpNetMag) { r_YpNetMag.YpNetMag.isFail = true; } console.warn(&#39;[Network] Server connection failed&#39;); }); } } if (YPSDK &amp;&amp; YPSDK.Platform &amp;&amp; YPSDK.Platform.loginData &amp;&amp; r_YpNetMag &amp;&amp; r_YpNetMag.YpNetMag &amp;&amp; r_YpNetMag.YpNetMag.initServer) { return [2, r_YpNetMag.YpNetMag.initServer(YPSDK.Platform.loginData)]; } else { console.warn(&#39;[User] No login data, skipping user init&#39;); return [2, Promise.resolve()]; } } catch (err) { console.error(&#39;[User] Load user data failed:&#39;, err); return [2, Promise.resolve()]; // 非关键错误 } return [2]; }); }); }; // 初始化游戏主逻辑 def_UI_Entry.prototype._loadGame = function () { try { // 安全访问玩家数据管理器 if (!r_PlayerDataManager || !r_PlayerDataManager.PlayerDataMgr) { throw new Error(&#39;PlayerDataManager not available&#39;); } // 获取引导状态 var guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName(r_Const_Common.GuideName.战斗背包); if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) { // 新玩家流程 if (r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex) { r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex( r_Const_Common.GuideName.战斗背包, r_Const_Common.GameBagGuideIndex.引导初始1 ); } if (r_GameDataManager &amp;&amp; r_GameDataManager.GameDataMgr &amp;&amp; r_GameDataManager.GameDataMgr.ClearGameBagData) { r_GameDataManager.GameDataMgr.ClearGameBagData(); } if (r_GameGlobalVariable &amp;&amp; r_GameGlobalVariable.GameGlobalVariable) { r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1; } // 打开游戏场景 if (r_UIManager &amp;&amp; r_UIManager.default &amp;&amp; r_UIManager.default.open) { r_UIManager.default.open( r_BundleConfig.BundleNames.Game, r_UIConfig_Game.UIView_Game.UI_GameView ); } else { console.warn(&#39;[Game] UIManager not available, loading start scene&#39;); cc.director.loadScene(&#39;start&#39;); } } else { // 老玩家流程 if (r_EventManager &amp;&amp; r_EventManager.EventMgr &amp;&amp; r_EventManager.EventMgr.dispatchEvent) { r_EventManager.EventMgr.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true); } if (r_UIManager &amp;&amp; r_UIManager.default &amp;&amp; r_UIManager.default.open) { r_UIManager.default.open( r_BundleConfig.BundleNames.Home, r_UIConfig_Home.UIView_Home.UI_Hall ); } else { console.warn(&#39;[Game] UIManager not available, loading start scene&#39;); cc.director.loadScene(&#39;start&#39;); } } // 初始化白名单 this.onInitWhiteName(); } catch (error) { console.error(&#39;[Game] Load game failed:&#39;, error); // 尝试直接进入游戏场景 try { if (cc.director &amp;&amp; cc.director.loadScene) { cc.director.loadScene(&#39;start&#39;); } } catch (sceneError) { console.error(&#39;[Game] Fallback scene load failed:&#39;, sceneError); } } }; // 初始化白名单 def_UI_Entry.prototype.onInitWhiteName = function () { return __awaiter(this, void 0, void 0, function () { var url; return __generator(this, function (_a) { try { if (!YPSDK || !YPSDK.Platform || !YPSDK.Platform.loginData || !YPSDK.platformUrl) { console.warn(&#39;[WhiteList] YPSDK not initialized, skipping&#39;); return [2]; } url = YPSDK.platformUrl + &quot;/User/GetCfgData?userId=&quot; + YPSDK.Platform.loginData.userUid + &quot;&amp;keyId=NoVideo&quot;; console.log(&#39;[WhiteList] Checking:&#39;, url); if (r_HttpManager &amp;&amp; r_HttpManager.HttpMgr &amp;&amp; r_HttpManager.HttpMgr.requestData) { r_HttpManager.HttpMgr.requestData(function (response) { if (response &amp;&amp; response.data &amp;&amp; response.data.keyData === &quot;true&quot; &amp;&amp; r_PlayerDataManager &amp;&amp; r_PlayerDataManager.PlayerDataMgr) { r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true; console.log(&#39;[WhiteList] User is in white list&#39;); } }, url); } else { console.warn(&#39;[WhiteList] HttpManager not available&#39;); } } catch (err) { console.error(&#39;[WhiteList] Init failed:&#39;, err); } return [2]; }); }); }; // 设置进度条 def_UI_Entry.prototype._setProgress = function (progress) { if (!this.progress_loading || !this.progress_loading.progress) { return; } progress = Math.max(0, Math.min(1, progress)); this.progress_loading.progress = progress; }; // 属性装饰器 __decorate([ _property(cc.ProgressBar) ], def_UI_Entry.prototype, &quot;progress_loading&quot;, void 0); // 类装饰器 def_UI_Entry = __decorate([ _ccclass ], def_UI_Entry); return def_UI_Entry; }(r_UIView.default)); exports.default = def_UI_Entry; // ====== 启动游戏 ====== if (cc &amp;&amp; cc.game &amp;&amp; cc.game.run) { cc.game.run(gameMainEntry); } else { console.error(&#39;[Main] cc.game.run not available, using fallback start&#39;); setTimeout(gameMainEntry, 1000); } 这是我的代码 你根据前面的情况给我整体修改一下,最后给我完整的代码方便我进行复制
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值