From e4241ad217bfa16323cbec4bc43ba9f30a65d524 Mon Sep 17 00:00:00 2001 From: dgflash Date: Sat, 13 Dec 2025 23:32:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=89=80=E6=9C=89=E2=80=9C=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E2=80=98=E7=BB=9F=E4=B8=80=E6=A0=87=E5=87=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets/core/Oops.ts | 36 +-- assets/core/Root.ts | 67 ++--- assets/core/common/audio/AudioEffect.ts | 13 +- assets/core/common/audio/AudioEffectPool.ts | 56 ++--- assets/core/common/audio/AudioEnum.ts | 4 +- assets/core/common/audio/AudioManager.ts | 43 ++-- assets/core/common/audio/AudioMusic.ts | 22 +- assets/core/common/audio/IAudio.ts | 2 +- assets/core/common/event/EventDispatcher.ts | 10 +- assets/core/common/event/EventMessage.ts | 10 +- assets/core/common/event/MessageManager.ts | 68 ++--- assets/core/common/loader/ResLoader.ts | 81 +++--- assets/core/common/loader/ZipLoader.ts | 36 +-- assets/core/common/log/Logger.ts | 84 +++---- assets/core/common/random/RandomManager.ts | 34 +-- assets/core/common/random/SeedRandom.ts | 4 +- assets/core/common/storage/StorageManager.ts | 38 +-- .../common/storage/StorageSecurityCrypto.ts | 2 +- .../common/storage/StorageSecuritySimple.ts | 8 +- assets/core/common/timer/Timer.ts | 16 +- assets/core/common/timer/TimerManager.ts | 44 ++-- assets/core/game/GameManager.ts | 7 +- assets/core/gui/Gui.ts | 12 +- assets/core/gui/GuiEnum.ts | 2 +- assets/core/gui/layer/LayerDialog.ts | 20 +- assets/core/gui/layer/LayerEnum.ts | 30 +-- assets/core/gui/layer/LayerGame.ts | 42 ++-- assets/core/gui/layer/LayerGameElement.ts | 9 +- assets/core/gui/layer/LayerHelper.ts | 7 +- assets/core/gui/layer/LayerManager.ts | 116 ++++----- assets/core/gui/layer/LayerNotify.ts | 20 +- assets/core/gui/layer/LayerPopup.ts | 23 +- assets/core/gui/layer/LayerUI.ts | 27 +- assets/core/gui/layer/LayerUIElement.ts | 27 +- assets/core/gui/layer/UIConfig.ts | 4 +- assets/core/gui/prompt/LoadingIndicator.ts | 10 +- assets/core/gui/prompt/Notify.ts | 8 +- assets/core/utils/ArrayUtil.ts | 14 +- assets/core/utils/CameraUtil.ts | 5 +- assets/core/utils/DeviceUtil.ts | 70 ++++-- assets/core/utils/EncryptUtil.ts | 2 +- assets/core/utils/ImageUtil.ts | 10 +- assets/core/utils/JsonUtil.ts | 22 +- assets/core/utils/LayerUtil.ts | 4 +- assets/core/utils/MathUtil.ts | 6 +- assets/core/utils/ObjectUtil.ts | 4 +- assets/core/utils/PhysicsUtil.ts | 6 +- assets/core/utils/PlatformUtil.ts | 5 +- assets/core/utils/RotateUtil.ts | 15 +- assets/core/utils/StringUtil.ts | 40 +-- assets/core/utils/TimeUtils.ts | 26 +- assets/core/utils/Vec3Util.ts | 36 +-- assets/core/utils/ViewUtil.ts | 23 +- assets/libs/animator-effect/2d/Ambilight.ts | 5 +- assets/libs/animator-effect/2d/FlashSpine.ts | 16 +- assets/libs/animator-effect/2d/FlashSprite.ts | 15 +- .../2d/SpineFinishedRelease.ts | 8 +- .../libs/animator-effect/Effect2DFollow3D.ts | 15 +- .../animator-effect/EffectDelayRelease.ts | 2 +- assets/libs/animator-effect/EffectEvent.ts | 4 +- .../animator-effect/EffectFinishedRelease.ts | 28 +-- .../libs/animator-effect/EffectSingleCase.ts | 33 +-- assets/libs/animator-move/MoveRigidBody.ts | 46 ++-- assets/libs/animator-move/MoveTo.ts | 22 +- assets/libs/animator-move/MoveTranslate.ts | 8 +- assets/libs/animator/AnimatorAnimation.ts | 12 +- assets/libs/animator/AnimatorCustomization.ts | 13 +- assets/libs/animator/AnimatorDragonBones.ts | 11 +- assets/libs/animator/AnimatorSkeletal.ts | 10 +- assets/libs/animator/AnimatorSpine.ts | 35 +-- .../libs/animator/AnimatorSpineSecondary.ts | 15 +- assets/libs/animator/core/AnimatorBase.ts | 52 ++-- .../libs/animator/core/AnimatorCondition.ts | 58 +++-- .../libs/animator/core/AnimatorController.ts | 42 ++-- assets/libs/animator/core/AnimatorParams.ts | 65 ++--- assets/libs/animator/core/AnimatorState.ts | 44 ++-- .../libs/animator/core/AnimatorStateLogic.ts | 6 +- .../libs/animator/core/AnimatorTransition.ts | 23 +- assets/libs/behavior-tree/BTreeNode.ts | 4 +- assets/libs/behavior-tree/BehaviorTree.ts | 4 +- assets/libs/behavior-tree/BranchNode.ts | 4 +- assets/libs/behavior-tree/Decorator.ts | 6 +- assets/libs/behavior-tree/IControl.ts | 4 +- assets/libs/behavior-tree/Selector.ts | 6 +- assets/libs/behavior-tree/Sequence.ts | 4 +- assets/libs/behavior-tree/index.ts | 2 +- assets/libs/camera/FreeFlightCamera.ts | 139 +++++++---- assets/libs/camera/OrbitCamera.ts | 125 +++++----- assets/libs/collection/AsyncQueue.ts | 56 ++--- assets/libs/collection/Collection.ts | 8 +- assets/libs/ecs/ECS.ts | 55 ++-- assets/libs/ecs/ECSComp.ts | 14 +- assets/libs/ecs/ECSEntity.ts | 57 ++--- assets/libs/ecs/ECSGroup.ts | 12 +- assets/libs/ecs/ECSMask.ts | 8 +- assets/libs/ecs/ECSMatcher.ts | 53 ++-- assets/libs/ecs/ECSModel.ts | 12 +- assets/libs/ecs/ECSSystem.ts | 68 ++--- assets/libs/extension/ArrayExt.ts | 70 +++--- assets/libs/extension/DateExt.ts | 12 +- assets/libs/extension/DirectorExt.ts | 12 +- assets/libs/extension/NodeDragExt.ts | 35 +-- assets/libs/extension/NodeExt.ts | 150 +++++------ assets/libs/gui/button/ButtonEffect.ts | 23 +- assets/libs/gui/button/ButtonSimple.ts | 17 +- assets/libs/gui/button/ButtonTouchLong.ts | 19 +- assets/libs/gui/button/UIButton.ts | 19 +- assets/libs/gui/label/LabelChange.ts | 40 +-- assets/libs/gui/label/LabelNumber.ts | 18 +- assets/libs/gui/label/LabelTime.ts | 64 ++--- assets/libs/gui/language/Language.ts | 34 +-- assets/libs/gui/language/LanguageData.ts | 30 +-- assets/libs/gui/language/LanguageLabel.ts | 39 +-- assets/libs/gui/language/LanguagePack.ts | 48 ++-- assets/libs/gui/language/LanguageSpine.ts | 28 +-- assets/libs/gui/language/LanguageSprite.ts | 31 +-- assets/libs/gui/window/PromptBase.ts | 26 +- assets/libs/gui/window/PromptSkip.ts | 23 +- assets/libs/model-view/JsonOb.ts | 36 +-- assets/libs/model-view/StringFormat.ts | 76 +++--- assets/libs/model-view/VMBase.ts | 24 +- assets/libs/model-view/VMCompsEdit.ts | 132 +++++----- assets/libs/model-view/VMCustom.ts | 42 ++-- assets/libs/model-view/VMEnv.ts | 4 +- assets/libs/model-view/VMEvent.ts | 92 +++---- assets/libs/model-view/VMLabel.ts | 59 ++--- assets/libs/model-view/VMModify.ts | 84 ++++--- assets/libs/model-view/VMParent.ts | 21 +- assets/libs/model-view/VMProgress.ts | 26 +- assets/libs/model-view/VMState.ts | 235 +++++++++--------- assets/libs/model-view/ViewModel.ts | 96 ++++--- assets/libs/model-view/ui/BhvButtonGroup.ts | 67 ++--- assets/libs/model-view/ui/BhvFrameIndex.ts | 22 +- assets/libs/model-view/ui/BhvRollNumber.ts | 116 ++++----- assets/libs/model-view/ui/BhvSwitchPage.ts | 31 +-- assets/libs/network/HttpRequest.ts | 78 +++--- assets/libs/network/NetInterface.ts | 26 +- assets/libs/network/NetManager.ts | 32 +-- assets/libs/network/NetNode.ts | 150 +++++------ assets/libs/network/NetProtocolPako.ts | 24 +- assets/libs/network/WebSock.ts | 22 +- assets/libs/render-texture/RtToModel.ts | 4 +- assets/libs/render-texture/RtToSprite.ts | 31 +-- assets/module/common/CCBusiness.ts | 8 +- assets/module/common/CCEntity.ts | 45 ++-- assets/module/common/CCView.ts | 20 +- assets/module/common/CCViewVM.ts | 20 +- assets/module/common/GameCollision.ts | 53 ++-- assets/module/common/GameComponent.ts | 63 ++--- assets/module/common/GameStorage.ts | 6 +- assets/module/config/BuildTimeConstants.ts | 2 +- assets/module/config/Config.ts | 8 +- assets/module/config/GameConfig.ts | 22 +- assets/module/config/GameQueryConfig.ts | 40 +-- 154 files changed, 2673 insertions(+), 2441 deletions(-) diff --git a/assets/core/Oops.ts b/assets/core/Oops.ts index efc67e5..a976593 100644 --- a/assets/core/Oops.ts +++ b/assets/core/Oops.ts @@ -4,25 +4,25 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-21 15:19:56 */ -import { DEBUG } from "cc/env"; -import { EffectSingleCase } from "../libs/animator-effect/EffectSingleCase"; -import { ecs } from "../libs/ecs/ECS"; -import { ECSRootSystem } from "../libs/ecs/ECSSystem"; -import { LanguageManager } from "../libs/gui/language/Language"; -import { VM } from "../libs/model-view/ViewModel"; -import { Config } from "../module/config/Config"; -import { AudioManager } from "./common/audio/AudioManager"; -import { MessageManager } from "./common/event/MessageManager"; -import { ResLoader } from "./common/loader/ResLoader"; -import { Logger } from "./common/log/Logger"; -import { RandomManager } from "./common/random/RandomManager"; -import { StorageManager } from "./common/storage/StorageManager"; -import { TimerManager } from "./common/timer/TimerManager"; -import { GameManager } from "./game/GameManager"; -import { LayerManager } from "./gui/layer/LayerManager"; +import { DEBUG } from 'cc/env'; +import { EffectSingleCase } from '../libs/animator-effect/EffectSingleCase'; +import { ecs } from '../libs/ecs/ECS'; +import type { ECSRootSystem } from '../libs/ecs/ECSSystem'; +import { LanguageManager } from '../libs/gui/language/Language'; +import { VM } from '../libs/model-view/ViewModel'; +import { Config } from '../module/config/Config'; +import type { AudioManager } from './common/audio/AudioManager'; +import type { MessageManager } from './common/event/MessageManager'; +import type { ResLoader } from './common/loader/ResLoader'; +import { Logger } from './common/log/Logger'; +import { RandomManager } from './common/random/RandomManager'; +import type { StorageManager } from './common/storage/StorageManager'; +import type { TimerManager } from './common/timer/TimerManager'; +import type { GameManager } from './game/GameManager'; +import type { LayerManager } from './gui/layer/LayerManager'; /** 框架版本号 */ -export var version: string = "2.1.0.20251026"; +export var version = '2.1.0.20251026'; /** 框架核心模块访问入口 */ export class oops { @@ -65,4 +65,4 @@ export class oops { if (DEBUG) { //@ts-ignore window.oops = oops; -} \ No newline at end of file +} diff --git a/assets/core/Root.ts b/assets/core/Root.ts index d5d3c3c..ed30277 100644 --- a/assets/core/Root.ts +++ b/assets/core/Root.ts @@ -4,19 +4,20 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-28 10:02:57 */ -import { _decorator, Component, director, Game, game, JsonAsset, Node, profiler, resources, screen, sys } from "cc"; -import { GameConfig } from "../module/config/GameConfig"; -import { GameQueryConfig } from "../module/config/GameQueryConfig"; -import { oops, version } from "./Oops"; -import { AudioManager } from "./common/audio/AudioManager"; -import { EventMessage } from "./common/event/EventMessage"; -import { message } from "./common/event/MessageManager"; -import { resLoader } from "./common/loader/ResLoader"; -import { IStorageSecurity, StorageManager } from "./common/storage/StorageManager"; -import { StorageSecuritySimple } from "./common/storage/StorageSecuritySimple"; -import { TimerManager } from "./common/timer/TimerManager"; -import { GameManager } from "./game/GameManager"; -import { LayerManager } from "./gui/layer/LayerManager"; +import { _decorator, Component, director, Game, game, JsonAsset, Node, profiler, resources, screen, sys } from 'cc'; +import { GameConfig } from '../module/config/GameConfig'; +import { GameQueryConfig } from '../module/config/GameQueryConfig'; +import { oops, version } from './Oops'; +import { AudioManager } from './common/audio/AudioManager'; +import { EventMessage } from './common/event/EventMessage'; +import { message } from './common/event/MessageManager'; +import { resLoader } from './common/loader/ResLoader'; +import type { IStorageSecurity } from './common/storage/StorageManager'; +import { StorageManager } from './common/storage/StorageManager'; +import { StorageSecuritySimple } from './common/storage/StorageSecuritySimple'; +import { TimerManager } from './common/timer/TimerManager'; +import { GameManager } from './game/GameManager'; +import { LayerManager } from './gui/layer/LayerManager'; const { property } = _decorator; @@ -25,19 +26,19 @@ export class Root extends Component { /** 游戏层节点 */ @property({ type: Node, - tooltip: "游戏层" + tooltip: '游戏层' }) - game: Node = null!; // 可使用多摄像机自定义二维或三维游戏场景 + game: Node = null!; // 可使用多摄像机自定义二维或三维游戏场景 /** 界面层节点 */ @property({ type: Node, - tooltip: "界面层" + tooltip: '界面层' }) - gui: Node = null!; + gui: Node = null!; /** 框架常驻节点 */ - private persist: Node = null! + private persist: Node = null!; onLoad() { console.log(`Oops Framework ${version}`); @@ -50,7 +51,7 @@ export class Root extends Component { private initModule() { // 创建持久根节点 - this.persist = new Node("OopsFrameworkPersistNode"); + this.persist = new Node('OopsFrameworkPersistNode'); director.addPersistRootNode(this.persist); // Web平台查询参数管理 @@ -68,7 +69,7 @@ export class Root extends Component { } private async loadConfig() { - const config_name = "config"; + const config_name = 'config'; resources.load(config_name, JsonAsset, (err, config) => { if (err) { this.loadConfig().then(); @@ -79,7 +80,7 @@ export class Root extends Component { // 本地存储模块 oops.storage = new StorageManager(); - let security: IStorageSecurity = new StorageSecuritySimple(); // new StorageSecurityCrypto(); + const security: IStorageSecurity = new StorageSecuritySimple(); // new StorageSecurityCrypto(); security.key = oops.config.game.localDataKey; security.iv = oops.config.game.localDataIv; oops.storage.init(security); @@ -145,33 +146,33 @@ export class Root extends Component { // 游戏尺寸修改事件 if (!sys.isMobile) { - screen.on("window-resize", () => { + screen.on('window-resize', () => { oops.message.dispatchEvent(EventMessage.GAME_RESIZE); }, this); - screen.on("fullscreen-change", () => { + screen.on('fullscreen-change', () => { oops.message.dispatchEvent(EventMessage.GAME_FULL_SCREEN); }, this); } - screen.on("orientation-change", () => { + screen.on('orientation-change', () => { oops.message.dispatchEvent(EventMessage.GAME_ORIENTATION); }, this); } private onShow() { - oops.timer.load(); // 处理回到游戏时减去逝去时间 - oops.audio.resumeAll(); // 恢复所有暂停的音乐播放 - director.resume(); // 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生 - game.resume(); // 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效 + oops.timer.load(); // 处理回到游戏时减去逝去时间 + oops.audio.resumeAll(); // 恢复所有暂停的音乐播放 + director.resume(); // 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生 + game.resume(); // 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效 oops.message.dispatchEvent(EventMessage.GAME_SHOW); } private onHide() { - oops.timer.save(); // 处理切到后台后记录切出时间 - oops.audio.pauseAll(); // 暂停所有音乐播放 - director.pause(); // 暂停正在运行的场景,该暂停只会停止游戏逻辑执行,但是不会停止渲染和 UI 响应。 如果想要更彻底得暂停游戏,包含渲染,音频和事件 - game.pause(); // 暂停游戏主循环。包含:游戏逻辑、渲染、输入事件派发(Web 和小游戏平台除外) + oops.timer.save(); // 处理切到后台后记录切出时间 + oops.audio.pauseAll(); // 暂停所有音乐播放 + director.pause(); // 暂停正在运行的场景,该暂停只会停止游戏逻辑执行,但是不会停止渲染和 UI 响应。 如果想要更彻底得暂停游戏,包含渲染,音频和事件 + game.pause(); // 暂停游戏主循环。包含:游戏逻辑、渲染、输入事件派发(Web 和小游戏平台除外) oops.message.dispatchEvent(EventMessage.GAME_HIDE); } -} \ No newline at end of file +} diff --git a/assets/core/common/audio/AudioEffect.ts b/assets/core/common/audio/AudioEffect.ts index 354539a..24271d6 100644 --- a/assets/core/common/audio/AudioEffect.ts +++ b/assets/core/common/audio/AudioEffect.ts @@ -4,8 +4,9 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 10:22:36 */ -import { AudioClip, AudioSource, _decorator } from 'cc'; -import { IAudioParams } from './IAudio'; +import type { AudioClip } from 'cc'; +import { AudioSource, _decorator } from 'cc'; +import type { IAudioParams } from './IAudio'; const { ccclass } = _decorator; /** 游戏音效 */ @@ -14,11 +15,11 @@ export class AudioEffect extends AudioSource { /** 唯一编号 */ key: string = null!; /** 音效编号 */ - aeid: number = -1; + aeid = -1; /** 音效果资源路径 */ - path: string | AudioClip = null! + path: string | AudioClip = null!; /** 音效参数 */ - params: IAudioParams = null! + params: IAudioParams = null!; /** 背景音乐播放完成回调 */ onComplete: Function | null = null; @@ -36,4 +37,4 @@ export class AudioEffect extends AudioSource { this.path = null!; this.params = null!; } -} \ No newline at end of file +} diff --git a/assets/core/common/audio/AudioEffectPool.ts b/assets/core/common/audio/AudioEffectPool.ts index b3a4055..ac2f82e 100644 --- a/assets/core/common/audio/AudioEffectPool.ts +++ b/assets/core/common/audio/AudioEffectPool.ts @@ -1,9 +1,9 @@ -import { AudioClip, Node, NodePool } from "cc"; -import { oops } from "../../Oops"; -import { resLoader } from "../loader/ResLoader"; -import { AudioEffect } from "./AudioEffect"; -import { AudioEffectType } from "./AudioEnum"; -import { IAudioData, IAudioParams } from "./IAudio"; +import { AudioClip, Node, NodePool } from 'cc'; +import { oops } from '../../Oops'; +import { resLoader } from '../loader/ResLoader'; +import { AudioEffect } from './AudioEffect'; +import { AudioEffectType } from './AudioEnum'; +import type { IAudioData, IAudioParams } from './IAudio'; /** 音乐效缓冲编号最大值 */ const AE_ID_MAX = 30000; @@ -21,7 +21,7 @@ export class AudioEffectPool { /** 外网远程资源记录(地址、音效对象) */ private res_remote: Map = new Map(); - private _aeId: number = 0; + private _aeId = 0; /** 获取请求唯一编号 */ private getAeId() { if (this._aeId == AE_ID_MAX) this._aeId = 1; @@ -31,7 +31,7 @@ export class AudioEffectPool { /** * 注册音效类型 - * @param type + * @param type */ register(type: string) { this.data[type] = { switch: true, volume: 1 }; @@ -43,7 +43,7 @@ export class AudioEffectPool { * @returns 音效开关 */ getSwitch(type: string = AudioEffectType.Effect) { - let iad = this.data[type]; + const iad = this.data[type]; if (iad == null) console.error(`类型为【${type}】的音效配置不存在`); return iad.switch; } @@ -53,7 +53,7 @@ export class AudioEffectPool { * @param value 音效开关 */ setSwitch(value: boolean, type: string = AudioEffectType.Effect) { - let iad = this.data[type]; + const iad = this.data[type]; if (iad == null) console.error(`类型为【${type}】的音效配置不存在`); iad.switch = value; @@ -66,7 +66,7 @@ export class AudioEffectPool { * @returns 音效音量 */ getVolume(type: string = AudioEffectType.Effect) { - let iad = this.data[type]; + const iad = this.data[type]; if (iad == null) console.error(`类型为【${type}】的音效配置不存在`); return iad.volume; } @@ -77,18 +77,18 @@ export class AudioEffectPool { * @param type 音效类型 */ setVolume(value: number, type: string = AudioEffectType.Effect) { - let iad = this.data[type]; + const iad = this.data[type]; if (iad == null) console.error(`类型为【${type}】的音效配置不存在`); iad.volume = value; - this.effects.forEach(ac => ac.volume = value); + this.effects.forEach((ac) => ac.volume = value); } /** * 加载与播放音效 * @param path 音效资源地址与音效资源 * @param params 音效附加参数 - * @returns + * @returns */ async loadAndPlay(path: string | AudioClip, params?: IAudioParams): Promise { return new Promise(async (resolve, reject) => { @@ -98,7 +98,7 @@ export class AudioEffectPool { bundle: resLoader.defaultBundleName, loop: false, destroy: false - } + }; } else { if (params.type == null) params.type = AudioEffectType.Effect; @@ -107,7 +107,7 @@ export class AudioEffectPool { if (params.type == null) params.destroy = false; } - let iad = this.data[params.type!]; + const iad = this.data[params.type!]; if (iad == null) console.error(`类型为【${params.type!}】的音效配置不存在`); if (!iad.switch) { @@ -117,7 +117,7 @@ export class AudioEffectPool { if (params.volume == null) params.volume = iad.volume; - let bundle = params.bundle!; + const bundle = params.bundle!; let key: string = null!; let clip: AudioClip | undefined; // 通过预制自动加载的音效资源(音效内存跟随预制体的内存一并释放) @@ -126,7 +126,7 @@ export class AudioEffectPool { clip = path; } // 非引擎管理的远程资源加载 - else if (path.indexOf("http") == 0) { + else if (path.indexOf('http') == 0) { key = `${params.type}_${path}`; clip = this.res_remote.get(path); if (clip == null) { @@ -160,14 +160,14 @@ export class AudioEffectPool { } // 获取音效果播放器播放音乐 - let aeid: number = -1; + let aeid = -1; let ae: AudioEffect; let node: Node = null!; if (this.pool.size() == 0) { aeid = this.getAeId(); - key += "_" + aeid; + key += '_' + aeid; - node = new Node("AudioEffect"); + node = new Node('AudioEffect'); ae = node.addComponent(AudioEffect); ae.key = key; ae.aeid = aeid; @@ -217,7 +217,7 @@ export class AudioEffectPool { * @param ae loadAndPlay 方法返回的音效播放器对象 */ put(ae: AudioEffect) { - let effect = this.effects.get(ae.key); + const effect = this.effects.get(ae.key); if (effect && effect.clip) { effect.reset(); @@ -228,7 +228,7 @@ export class AudioEffectPool { /** 停止播放所有音效 */ stop() { - this.effects.forEach(ae => { + this.effects.forEach((ae) => { ae.stop(); this.onAudioEffectPlayComplete(ae); }); @@ -237,12 +237,12 @@ export class AudioEffectPool { /** 恢复所有音效 */ play() { - this.effects.forEach(ae => ae.play()); + this.effects.forEach((ae) => ae.play()); } /** 暂停所有音效 */ pause() { - this.effects.forEach(ae => { + this.effects.forEach((ae) => { ae.pause(); this.onAudioEffectPlayComplete(ae); }); @@ -266,14 +266,14 @@ export class AudioEffectPool { this.pool.clear(); // 释放正在播放的音效对象 - this.effects.forEach(ae => ae.node.destroy()); + this.effects.forEach((ae) => ae.node.destroy()); this.effects.clear(); } /** 释放各个资源包中的音效资源 */ releaseRes() { this.res_project.forEach((paths: string[], bundleName: string) => { - paths.forEach(path => resLoader.release(path, bundleName)); + paths.forEach((path) => resLoader.release(path, bundleName)); }); } @@ -284,4 +284,4 @@ export class AudioEffectPool { }); this.res_remote.clear(); } -} \ No newline at end of file +} diff --git a/assets/core/common/audio/AudioEnum.ts b/assets/core/common/audio/AudioEnum.ts index 15974b0..7aabfa3 100644 --- a/assets/core/common/audio/AudioEnum.ts +++ b/assets/core/common/audio/AudioEnum.ts @@ -1,7 +1,7 @@ /** 音乐音效默认类型 */ export enum AudioEffectType { /** 背景音乐 */ - Music = "music", + Music = 'music', /** 音乐音效 */ - Effect = "effect", + Effect = 'effect', } diff --git a/assets/core/common/audio/AudioManager.ts b/assets/core/common/audio/AudioManager.ts index 865e34c..bb8cd38 100644 --- a/assets/core/common/audio/AudioManager.ts +++ b/assets/core/common/audio/AudioManager.ts @@ -1,11 +1,12 @@ -import { AudioClip, Component } from "cc"; -import { oops } from "../../Oops"; -import { AudioEffect } from "./AudioEffect"; -import { AudioEffectPool } from "./AudioEffectPool"; -import { AudioEffectType } from "./AudioEnum"; -import { AudioMusic } from "./AudioMusic"; -import { IAudioData, IAudioParams } from "./IAudio"; -import { GameStorage } from "db://oops-framework/module/common/GameStorage"; +import type { AudioClip } from 'cc'; +import { Component } from 'cc'; +import { oops } from '../../Oops'; +import type { AudioEffect } from './AudioEffect'; +import { AudioEffectPool } from './AudioEffectPool'; +import { AudioEffectType } from './AudioEnum'; +import { AudioMusic } from './AudioMusic'; +import type { IAudioData, IAudioParams } from './IAudio'; +import { GameStorage } from 'db://oops-framework/module/common/GameStorage'; /** * 音频管理 @@ -98,21 +99,21 @@ export class AudioManager extends Component { if (typeof value === 'string') { this.data[value] = { switch: true, volume: 1 }; switch (value) { - case AudioEffectType.Music: - //@ts-ignore - this.music.data = this.data; - this.music.setSwitch(true); - this.music.setVolume(1); - break; - default: - //@ts-ignore - this.effect.data = this.data; - this.effect.setSwitch(true, value); - this.effect.setVolume(1, value); - break; + case AudioEffectType.Music: + //@ts-ignore + this.music.data = this.data; + this.music.setSwitch(true); + this.music.setVolume(1); + break; + default: + //@ts-ignore + this.effect.data = this.data; + this.effect.setSwitch(true, value); + this.effect.setVolume(1, value); + break; } } } this.save(); } -} \ No newline at end of file +} diff --git a/assets/core/common/audio/AudioMusic.ts b/assets/core/common/audio/AudioMusic.ts index 3c8b140..27f06e5 100644 --- a/assets/core/common/audio/AudioMusic.ts +++ b/assets/core/common/audio/AudioMusic.ts @@ -8,10 +8,10 @@ import { AudioClip, Node } from 'cc'; import { resLoader } from '../loader/ResLoader'; import { AudioEffect } from './AudioEffect'; import { AudioEffectType } from './AudioEnum'; -import { IAudioData, IAudioParams } from './IAudio'; +import type { IAudioData, IAudioParams } from './IAudio'; -/** - * 背景音乐 +/** + * 背景音乐 * 1、播放一个新背景音乐时,先加载音乐资源,然后停止正在播放的背景资源同时释放当前背景音乐资源,最后播放新的背景音乐 * 2、背景音乐循环播放时,不会触发播放完成事件 */ @@ -19,8 +19,8 @@ export class AudioMusic extends Node { /** 音效配置数据 */ private data: { [node: string]: IAudioData } = null!; - private _progress: number = 0; - private _isLoading: boolean = false; + private _progress = 0; + private _isLoading = false; private _nextPath: string = null!; private _nextParams: IAudioParams = null!; private _ae: AudioEffect = null!; @@ -75,7 +75,7 @@ export class AudioMusic extends Node { constructor() { super(); - this.name = "AudioMusic"; + this.name = 'AudioMusic'; this._ae = this.addComponent(AudioEffect); this._ae.onComplete = this.onAudioEffectPlayComplete.bind(this); } @@ -91,7 +91,7 @@ export class AudioMusic extends Node { * @param params 背景音乐资源播放参数 */ async loadAndPlay(path: string, params?: IAudioParams) { - if (!this.getSwitch()) return; // 禁止播放音乐 + if (!this.getSwitch()) return; // 禁止播放音乐 // 下一个加载的背景音乐资源 if (this._isLoading) { @@ -106,19 +106,19 @@ export class AudioMusic extends Node { bundle: resLoader.defaultBundleName, loop: true, volume: this.getVolume() - } + }; } else { if (params.type == null) params.type = AudioEffectType.Music; if (params.bundle == null) params.bundle = resLoader.defaultBundleName; if (params.loop == null) params.loop = true; - if (params.volume == null) params.volume = this.getVolume() + if (params.volume == null) params.volume = this.getVolume(); } this._isLoading = true; let clip: AudioClip = null!; - if (path.indexOf("http") == 0) { + if (path.indexOf('http') == 0) { const extension = path.split('.').pop(); clip = await resLoader.loadRemote(path, { ext: `.${extension}` }); } @@ -176,4 +176,4 @@ export class AudioMusic extends Node { this._ae.clip = null; } } -} \ No newline at end of file +} diff --git a/assets/core/common/audio/IAudio.ts b/assets/core/common/audio/IAudio.ts index b423ef1..83d058e 100644 --- a/assets/core/common/audio/IAudio.ts +++ b/assets/core/common/audio/IAudio.ts @@ -18,4 +18,4 @@ export interface IAudioData { switch: boolean; /** 音量 */ volume: number; -} \ No newline at end of file +} diff --git a/assets/core/common/event/EventDispatcher.ts b/assets/core/common/event/EventDispatcher.ts index b7edeec..d3b1b96 100644 --- a/assets/core/common/event/EventDispatcher.ts +++ b/assets/core/common/event/EventDispatcher.ts @@ -4,8 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 10:57:01 */ -import { ListenerFunc } from "./EventMessage"; -import { MessageEventData } from "./MessageManager"; +import type { ListenerFunc } from './EventMessage'; +import { MessageEventData } from './MessageManager'; /* 事件对象基类,继承该类将拥有发送和接送事件的能力 */ export class EventDispatcher { @@ -34,8 +34,8 @@ export class EventDispatcher { } } - /** - * 触发全局事件 + /** + * 触发全局事件 * @param event 事件名 * @param args 事件参数 */ @@ -55,4 +55,4 @@ export class EventDispatcher { } this._msg = null; } -} \ No newline at end of file +} diff --git a/assets/core/common/event/EventMessage.ts b/assets/core/common/event/EventMessage.ts index 0a77c91..1336070 100644 --- a/assets/core/common/event/EventMessage.ts +++ b/assets/core/common/event/EventMessage.ts @@ -15,13 +15,13 @@ export type ListenerFunc = (event: string, ...args: any) => void /** 框架内部全局事件 */ export enum EventMessage { /** 游戏从后台进入事件 */ - GAME_SHOW = "onGameShow", + GAME_SHOW = 'onGameShow', /** 游戏切到后台事件 */ - GAME_HIDE = "onGameHide", + GAME_HIDE = 'onGameHide', /** 游戏画笔尺寸变化事件 */ - GAME_RESIZE = "onGameResize", + GAME_RESIZE = 'onGameResize', /** 游戏全屏事件 */ - GAME_FULL_SCREEN = "onGameFullScreen", + GAME_FULL_SCREEN = 'onGameFullScreen', /** 游戏旋转屏幕事件 */ - GAME_ORIENTATION = "onGameOrientation" + GAME_ORIENTATION = 'onGameOrientation' } diff --git a/assets/core/common/event/MessageManager.ts b/assets/core/common/event/MessageManager.ts index ff1988b..a1f9bf1 100644 --- a/assets/core/common/event/MessageManager.ts +++ b/assets/core/common/event/MessageManager.ts @@ -1,10 +1,10 @@ -import { log, warn } from "cc"; -import { ListenerFunc } from "./EventMessage"; +import { log, warn } from 'cc'; +import type { ListenerFunc } from './EventMessage'; class EventData { - public event!: string; - public listener!: ListenerFunc; - public object: any; + event!: string; + listener!: ListenerFunc; + object: any; } /** 批量注册、移除全局事件对象 */ @@ -23,7 +23,7 @@ export class MessageEventData { eds = []; this.events.set(event, eds); } - let ed: EventData = new EventData(); + const ed: EventData = new EventData(); ed.event = event; ed.listener = listener; ed.object = object; @@ -37,17 +37,17 @@ export class MessageEventData { * @param event 事件名 */ off(event: string) { - let eds = this.events.get(event); + const eds = this.events.get(event); if (!eds) return; - for (let eb of eds) { + for (const eb of eds) { message.off(event, eb.listener, eb.object); } this.events.delete(event); } - /** - * 触发全局事件 + /** + * 触发全局事件 * @param event 事件名 * @param args 事件参数 */ @@ -58,28 +58,28 @@ export class MessageEventData { /** 清除所有的全局事件监听 */ clear() { const keys = Array.from(this.events.keys()); - for (let event of keys) { - this.off(event) + for (const event of keys) { + this.off(event); } } } -/** +/** * 全局消息管理 * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037894&doc_id=2873565 - * @example + * @example // 注册持续监听的全局事件 export class RoleViewComp extends Component{ onLoad(){ // 监听全局事件 oops.message.on(GameEvent.GameServerConnected, this.onHandler, this); } - + protected onDestroy() { // 对象释放时取消注册的全局事件 oops.message.off(GameEvent.GameServerConnected, this.onHandler, this); } - + private onHandler(event: string, args: any) { switch (event) { case GameEvent.GameServerConnected: @@ -95,7 +95,7 @@ export class RoleViewComp extends Component{ // 监听一次事件,事件响应后,该监听自动移除 oops.message.once(GameEvent.GameServerConnected, this.onHandler, this); } - + private onHandler(event: string, args: any) { switch (event) { case GameEvent.GameServerConnected: @@ -126,16 +126,16 @@ export class MessageManager { this.events.set(event, eds); } - let length = eds.length; + const length = eds.length; for (let i = 0; i < length; i++) { - let bin = eds[i]; + const bin = eds[i]; if (bin.listener == listener && bin.object == object) { warn(`名为【${event}】的事件重复注册侦听器`); } } - let data: EventData = new EventData(); + const data: EventData = new EventData(); data.event = event; data.listener = listener; data.object = object; @@ -153,7 +153,7 @@ export class MessageManager { this.off(event, _listener, object); _listener = null; listener.call(object, $event, $args); - } + }; this.on(event, _listener, object); } @@ -164,16 +164,16 @@ export class MessageManager { * @param object 侦听函数绑定的作用域对象 */ off(event: string, listener: Function, object: object) { - let eds = this.events.get(event); + const eds = this.events.get(event); if (!eds) { log(`名为【${event}】的事件不存在`); return; } - let length = eds.length; + const length = eds.length; for (let i = 0; i < length; i++) { - let bin: EventData = eds[i]; + const bin: EventData = eds[i]; if (bin.listener == listener && bin.object == object) { eds.splice(i, 1); break; @@ -185,16 +185,16 @@ export class MessageManager { } } - /** - * 触发全局事件 + /** + * 触发全局事件 * @param event 事件名 * @param args 事件参数 */ dispatchEvent(event: string, ...args: any) { - let list = this.events.get(event); + const list = this.events.get(event); if (list != null) { - let eds: Array = list.concat(); - let length = eds.length; + const eds: Array = list.concat(); + const length = eds.length; for (let i = 0; i < length; i++) { const ed = eds[i]; ed.listener.call(ed.object, event, ...args); @@ -202,7 +202,7 @@ export class MessageManager { } } - /** + /** * 触发全局事件,支持同步与异步处理 * @param event 事件名 * @param args 事件参数 @@ -218,10 +218,10 @@ export class MessageManager { */ dispatchEventAsync(event: string, ...args: any): Promise { return new Promise(async (resolve, reject) => { - let list = this.events.get(event); + const list = this.events.get(event); if (list != null) { - let eds: Array = list.concat(); - let length = eds.length; + const eds: Array = list.concat(); + const length = eds.length; for (let i = 0; i < length; i++) { const ed = eds[i]; await Promise.resolve(ed.listener.call(ed.object, event, ...args)); @@ -232,4 +232,4 @@ export class MessageManager { } } -export const message = new MessageManager(); \ No newline at end of file +export const message = new MessageManager(); diff --git a/assets/core/common/loader/ResLoader.ts b/assets/core/common/loader/ResLoader.ts index 67f7c1d..bf4cffc 100644 --- a/assets/core/common/loader/ResLoader.ts +++ b/assets/core/common/loader/ResLoader.ts @@ -1,4 +1,5 @@ -import { __private, AnimationClip, Asset, AssetManager, assetManager, AudioClip, Font, ImageAsset, js, JsonAsset, Material, Mesh, Prefab, resources, sp, SpriteFrame, Texture2D } from "cc"; +import type { __private, AssetManager } from 'cc'; +import { AnimationClip, Asset, assetManager, AudioClip, Font, ImageAsset, js, JsonAsset, Material, Mesh, Prefab, resources, sp, SpriteFrame, Texture2D } from 'cc'; export type AssetType = __private.__types_globals__Constructor | null; export type Paths = string | string[]; @@ -23,18 +24,18 @@ interface ILoadResArgs { preload?: boolean; } -/** +/** * 游戏资源管理 * 1、加载默认resources文件夹中资源 * 2、加载默认bundle远程资源 * 3、主动传递bundle名时,优先加载传递bundle名资源包中的资源 - * + * * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037901&doc_id=2873565 */ export class ResLoader { //#region 资源配置数据 /** 全局默认加载的资源包名 */ - defaultBundleName: string = "resources"; + defaultBundleName = 'resources'; /** 下载时的最大并发数 - 项目设置 -> 项目数据 -> 资源下载并发数,设置默认值;初始值为15 */ get maxConcurrency(): number { @@ -79,10 +80,10 @@ export class ResLoader { var data = await oops.res.loadRemote(this.url, opt); const texture = new Texture2D(); texture.image = data; - + const spriteFrame = new SpriteFrame(); spriteFrame.texture = texture; - + var sprite = this.sprite.addComponent(Sprite); sprite.spriteFrame = spriteFrame; */ @@ -133,7 +134,7 @@ export class ResLoader { * @param bundleName 资源地址 */ removeBundle(bundleName: string) { - let bundle = assetManager.bundles.get(bundleName); + const bundle = assetManager.bundles.get(bundleName); if (bundle) { bundle.releaseAll(); assetManager.removeBundle(bundle); @@ -165,16 +166,16 @@ export class ResLoader { onProgress?: ProgressCallback ) { return new Promise((resolve, reject) => { - let onComplete = (err: Error | null, data: AssetManager.RequestItem) => { + const onComplete = (err: Error | null, data: AssetManager.RequestItem) => { if (err) { resolve(null!); return; } resolve(data); - } + }; let args: ILoadResArgs | null = null; - if (typeof paths === "string" || paths instanceof Array) { + if (typeof paths === 'string' || paths instanceof Array) { args = this.parseLoadResArgs(paths, type, onProgress, onComplete); args.bundle = bundleName; } @@ -211,7 +212,7 @@ export class ResLoader { onComplete?: CompleteCallback, ) { let args: ILoadResArgs | null = null; - if (typeof dir === "string") { + if (typeof dir === 'string') { args = this.parseLoadResArgs(dir, type, onProgress, onComplete); args.bundle = bundleName; } @@ -236,16 +237,16 @@ export class ResLoader { */ load(bundleName: string, paths: Paths | AssetType, type?: AssetType) { return new Promise((resolve, reject) => { - let onComplete = (err: Error | null, data: T) => { + const onComplete = (err: Error | null, data: T) => { if (err) { resolve(null!); return; } resolve(data); - } + }; let args: ILoadResArgs | null = null; - if (typeof paths === "string" || paths instanceof Array) { + if (typeof paths === 'string' || paths instanceof Array) { args = this.parseLoadResArgs(paths, type, onComplete); args.bundle = bundleName; } @@ -266,7 +267,7 @@ export class ResLoader { */ loadAny(bundleName: string | string[], paths: string[] | ProgressCallback, onProgress?: ProgressCallback | CompleteCallback, onComplete?: CompleteCallback): void { let args: ILoadResArgs | null = null; - if (typeof bundleName === "string" && paths instanceof Array) { + if (typeof bundleName === 'string' && paths instanceof Array) { args = this.parseLoadResArgs(paths, onProgress, onComplete); args.bundle = bundleName; } @@ -289,7 +290,7 @@ export class ResLoader { var onProgressCallback = (finished: number, total: number, item: any) => { console.log("资源加载进度", finished, total); } - + // 加载完成事件 var onCompleteCallback = () => { console.log("资源加载完成"); @@ -312,7 +313,7 @@ export class ResLoader { onComplete?: CompleteCallback, ) { let args: ILoadResArgs | null = null; - if (typeof dir === "string") { + if (typeof dir === 'string') { args = this.parseLoadResArgs(dir, type, onProgress, onComplete); args.bundle = bundleName; } @@ -351,14 +352,14 @@ export class ResLoader { const bundle: AssetManager.Bundle | null = assetManager.getBundle(bundleName); if (bundle) { - var infos = bundle.getDirWithPath(path); + const infos = bundle.getDirWithPath(path); if (infos) { infos.map((info) => { this.releasePrefabtDepsRecursively(info.uuid); }); } - if (path == "" && bundleName != "resources") { + if (path == '' && bundleName != 'resources') { assetManager.removeBundle(bundle); } } @@ -368,11 +369,11 @@ export class ResLoader { * 获取资源路径 * @param bundleName 资源包名 * @param uuid 资源唯一编号 - * @returns + * @returns */ getAssetPath(bundleName: string, uuid: string): string { - let b = this.getBundle(bundleName)!; - let info = b.getAssetInfo(uuid)!; + const b = this.getBundle(bundleName)!; + const info = b.getAssetInfo(uuid)!; //@ts-ignore return info.path; } @@ -406,13 +407,13 @@ export class ResLoader { * @param bundleName 远程资源包名 */ get(path: string, type?: AssetType, bundleName: string = this.defaultBundleName): T | null { - var bundle: AssetManager.Bundle = assetManager.getBundle(bundleName)!; + const bundle: AssetManager.Bundle = assetManager.getBundle(bundleName)!; return bundle.get(path, type); } //#endregion private parseLoadResArgs(paths: Paths, type?: AssetType | ProgressCallback | CompleteCallback, onProgress?: AssetType | ProgressCallback | CompleteCallback, onComplete?: ProgressCallback | CompleteCallback) { - let pathsOut: any = paths; + const pathsOut: any = paths; let typeOut: any = type; let onProgressOut: any = onProgress; let onCompleteOut: any = onComplete; @@ -476,53 +477,53 @@ export class ResLoader { dump() { assetManager.assets.forEach((value: Asset, key: string) => { console.log(`引用数量:${value.refCount}`, assetManager.assets.get(key)); - }) + }); console.log(`当前资源总数:${assetManager.assets.count}`); } private debugLogReleasedAsset(bundleName: string, asset: Asset) { if (asset.refCount == 0) { - let path = this.getAssetPath(bundleName, asset.uuid); - let content: string = ""; + const path = this.getAssetPath(bundleName, asset.uuid); + let content = ''; if (asset instanceof JsonAsset) { - content = "【释放资源】Json【路径】" + path; + content = '【释放资源】Json【路径】' + path; } else if (asset instanceof Prefab) { - content = "【释放资源】Prefab【路径】" + path; + content = '【释放资源】Prefab【路径】' + path; } else if (asset instanceof SpriteFrame) { - content = "【释放资源】SpriteFrame【路径】" + path; + content = '【释放资源】SpriteFrame【路径】' + path; } else if (asset instanceof Texture2D) { - content = "【释放资源】Texture2D【路径】" + path; + content = '【释放资源】Texture2D【路径】' + path; } else if (asset instanceof ImageAsset) { - content = "【释放资源】ImageAsset【路径】" + path; + content = '【释放资源】ImageAsset【路径】' + path; } else if (asset instanceof AudioClip) { - content = "【释放资源】AudioClip【路径】" + path; + content = '【释放资源】AudioClip【路径】' + path; } else if (asset instanceof AnimationClip) { - content = "【释放资源】AnimationClip【路径】" + path; + content = '【释放资源】AnimationClip【路径】' + path; } else if (asset instanceof Font) { - content = "【释放资源】Font【路径】" + path; + content = '【释放资源】Font【路径】' + path; } else if (asset instanceof Material) { - content = "【释放资源】Material【路径】" + path; + content = '【释放资源】Material【路径】' + path; } else if (asset instanceof Mesh) { - content = "【释放资源】Mesh【路径】" + path; + content = '【释放资源】Mesh【路径】' + path; } else if (asset instanceof sp.SkeletonData) { - content = "【释放资源】Spine【路径】" + path; + content = '【释放资源】Spine【路径】' + path; } else { - content = "【释放资源】未知【路径】" + path; + content = '【释放资源】未知【路径】' + path; } console.log(content); } } } -export const resLoader = new ResLoader(); \ No newline at end of file +export const resLoader = new ResLoader(); diff --git a/assets/core/common/loader/ZipLoader.ts b/assets/core/common/loader/ZipLoader.ts index 6a7a11c..ca93697 100644 --- a/assets/core/common/loader/ZipLoader.ts +++ b/assets/core/common/loader/ZipLoader.ts @@ -1,7 +1,7 @@ -import { BufferAsset, SpriteFrame, Texture2D } from "cc"; -import { resLoader } from "./ResLoader"; +import { BufferAsset, SpriteFrame, Texture2D } from 'cc'; +import { resLoader } from './ResLoader'; -/** +/** * 加载Zip资源 * 注: * 1. 使用此功能需要教程项目中项目资源目录libs/jszip目录拷贝到自己的项目中 @@ -13,13 +13,13 @@ export class ZipLoader { /** * 加载ZIP资源包 - * @param url - * @returns + * @param url + * @returns */ static load(url: string): Promise { return new Promise(async (resolve, reject) => { - let asset = await resLoader.load(url, BufferAsset); - var zip = await JSZip.loadAsync(asset.buffer()); + const asset = await resLoader.load(url, BufferAsset); + const zip = await JSZip.loadAsync(asset.buffer()); this.zips.set(url, zip); resolve(zip); }); @@ -27,34 +27,34 @@ export class ZipLoader { static getJson(zipName: string, path: string): Promise { return new Promise(async (resolve, reject) => { - var zip = this.zips.get(zipName); + const zip = this.zips.get(zipName); if (zip == null) { console.error(`名为【${zipName}】的资源包不存在`); resolve(null); return; } - var file = zip.file(path); - var json = JSON.parse(await file.async("text")); + const file = zip.file(path); + const json = JSON.parse(await file.async('text')); resolve(json); }); } static getSpriteFrame(zipName: string, path: string): Promise { return new Promise(async (resolve, reject) => { - var zip = this.zips.get(zipName); + const zip = this.zips.get(zipName); if (zip == null) { console.error(`名为【${zipName}】的资源包不存在`); resolve(null!); return; } - var file = zip.file(path); - var buf = await file.async("base64"); - var img = new Image(); + const file = zip.file(path); + const buf = await file.async('base64'); + const img = new Image(); img.src = 'data:image/png;base64,' + buf; img.onload = () => { - var texture = new Texture2D(); + const texture = new Texture2D(); texture.reset({ width: img.width, height: img.height @@ -62,11 +62,11 @@ export class ZipLoader { texture.uploadData(img, 0, 0); texture.loaded = true; - var sf = new SpriteFrame(); + const sf = new SpriteFrame(); sf.texture = texture; resolve(sf); - } + }; }); } @@ -81,4 +81,4 @@ export class ZipLoader { }); } } -} \ No newline at end of file +} diff --git a/assets/core/common/log/Logger.ts b/assets/core/common/log/Logger.ts index a12dd34..2654c00 100644 --- a/assets/core/common/log/Logger.ts +++ b/assets/core/common/log/Logger.ts @@ -1,4 +1,4 @@ -import { log } from "cc"; +import { log } from 'cc'; /** 日志类型 */ export enum LogType { @@ -16,21 +16,21 @@ export enum LogType { Trace = 32, } -var names = { - "1": "网络日志", - "2": "数据日志", - "4": "业务日志", - "8": "视图日志", - "16": "配置日志", - "32": "标准日志", -} +const names = { + '1': '网络日志', + '2': '数据日志', + '4': '业务日志', + '8': '视图日志', + '16': '配置日志', + '32': '标准日志', +}; export interface ILoggerConsole { trace(content: string, color: string): void; } -/** - * 日志管理 +/** + * 日志管理 * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037904&doc_id=2873565 * @example oops.log.trace("默认标准日志"); @@ -50,7 +50,7 @@ export class Logger { return this._instance; } - private tags: number = 0; + private tags = 0; private lc: ILoggerConsole = null!; /** 设置界面日志控制台 */ @@ -68,7 +68,7 @@ export class Logger { LogType.Trace; } - /** + /** * 设置显示的日志类型,默认值为不显示任何类型日志 * @example oops.log.setTags(LogType.View|LogType.Business) @@ -89,7 +89,7 @@ oops.log.start(); ... oops.log.end(); */ - start(describe: string = "Time"): void { + start(describe = 'Time'): void { console.time(describe); } @@ -103,7 +103,7 @@ oops.log.start(); ... oops.log.end(); */ - end(describe: string = "Time"): void { + end(describe = 'Time'): void { console.timeEnd(describe); } @@ -126,7 +126,7 @@ oops.log.table(object); * 打印标准日志 * @param msg 日志消息 */ - trace(msg: any, color: string = "#000000ff") { + trace(msg: any, color = '#000000ff') { this.print(LogType.Trace, msg, color); } @@ -173,27 +173,27 @@ oops.log.table(object); // 橙色 private orange(tag: LogType, msg: any, describe?: string) { - this.print(tag, msg, "#ee7700", describe) + this.print(tag, msg, '#ee7700', describe); } // 紫色 private violet(tag: LogType, msg: any, describe?: string) { - this.print(tag, msg, "#800080", describe) + this.print(tag, msg, '#800080', describe); } // 蓝色 private blue(tag: LogType, msg: any, describe?: string) { - this.print(tag, msg, "#3a5fcd", describe) + this.print(tag, msg, '#3a5fcd', describe); } // 绿色 private green(tag: LogType, msg: any, describe?: string) { - this.print(tag, msg, "#008000", describe) + this.print(tag, msg, '#008000', describe); } // 灰色 private gray(tag: LogType, msg: any, describe?: string) { - this.print(tag, msg, "#808080", describe) + this.print(tag, msg, '#808080', describe); } private isOpen(tag: LogType): boolean { @@ -216,12 +216,12 @@ oops.log.table(object); const type = names[tag]; if (this.lc == null) { const backLog = console.log || log; - color = "color:" + color + ";"; + color = 'color:' + color + ';'; if (describe) { - backLog.call(null, "%c%s%s%s:%s%o", color, this.getDateString(), '[' + type + ']', this.stack(5), describe, msg); + backLog.call(null, '%c%s%s%s:%s%o', color, this.getDateString(), '[' + type + ']', this.stack(5), describe, msg); } else { - backLog.call(null, "%c%s%s%s:%o", color, this.getDateString(), '[' + type + ']', this.stack(5), msg); + backLog.call(null, '%c%s%s%s:%o', color, this.getDateString(), '[' + type + ']', this.stack(5), msg); } } else { @@ -231,11 +231,11 @@ oops.log.table(object); private stack(index: number): string { const e = new Error(); - const lines = e.stack!.split("\n"); + const lines = e.stack!.split('\n'); const result: Array = []; lines.forEach((line) => { line = line.substring(7); - var lineBreak = line.split(" "); + const lineBreak = line.split(' '); if (lineBreak.length < 2) { result.push(lineBreak[0]); } @@ -248,16 +248,16 @@ oops.log.table(object); let splitList: Array = []; if (index < result.length - 1) { let value: string; - for (let a in result[index]) { - splitList = a.split("."); + for (const a in result[index]) { + splitList = a.split('.'); if (splitList.length == 2) { list = splitList.concat(); } else { value = result[index][a]; - const start = value!.lastIndexOf("/"); - const end = value!.lastIndexOf("."); + const start = value!.lastIndexOf('/'); + const end = value!.lastIndexOf('.'); if (start > -1 && end > -1) { const r = value!.substring(start + 1, end); list.push(r); @@ -270,29 +270,29 @@ oops.log.table(object); } if (list.length == 1) { - return "[" + list[0] + ".ts]"; + return '[' + list[0] + '.ts]'; } else if (list.length == 2) { - return "[" + list[0] + ".ts->" + list[1] + "]"; + return '[' + list[0] + '.ts->' + list[1] + ']'; } - return ""; + return ''; } private getDateString(): string { - let d = new Date(); + const d = new Date(); let str = d.getHours().toString(); - let timeStr = ""; - timeStr += (str.length == 1 ? "0" + str : str) + ":"; + let timeStr = ''; + timeStr += (str.length == 1 ? '0' + str : str) + ':'; str = d.getMinutes().toString(); - timeStr += (str.length == 1 ? "0" + str : str) + ":"; + timeStr += (str.length == 1 ? '0' + str : str) + ':'; str = d.getSeconds().toString(); - timeStr += (str.length == 1 ? "0" + str : str) + ":"; + timeStr += (str.length == 1 ? '0' + str : str) + ':'; str = d.getMilliseconds().toString(); - if (str.length == 1) str = "00" + str; - if (str.length == 2) str = "0" + str; + if (str.length == 1) str = '00' + str; + if (str.length == 2) str = '0' + str; timeStr += str; - timeStr = "[" + timeStr + "]"; + timeStr = '[' + timeStr + ']'; return timeStr; } -} \ No newline at end of file +} diff --git a/assets/core/common/random/RandomManager.ts b/assets/core/common/random/RandomManager.ts index 0653ce8..f0bb8a8 100644 --- a/assets/core/common/random/RandomManager.ts +++ b/assets/core/common/random/RandomManager.ts @@ -1,7 +1,7 @@ /** 引擎 utils.ts 中有一些基础数学方法 */ -/** - * 随机管理 +/** + * 随机管理 * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037911&doc_id=2873565 */ export class RandomManager { @@ -31,7 +31,7 @@ export class RandomManager { * @param min 最小值 * @param max 最大值 */ - getRandomFloat(min: number = 0, max: number = 1): number { + getRandomFloat(min = 0, max = 1): number { return this.getRandom() * (max - min) + min; } @@ -43,7 +43,7 @@ export class RandomManager { * @example var min = 1; var max = 10; - // [min,max) 得到一个两数之间的随机整数,这个值不小于min(如果min不是整数的话,得到一个向上取整的 min),并且小于(但不等于)max + // [min,max) 得到一个两数之间的随机整数,这个值不小于min(如果min不是整数的话,得到一个向上取整的 min),并且小于(但不等于)max RandomManager.instance.getRandomInt(min, max, 1); // [min,max] 得到一个两数之间的随机整数,包括两个数在内,这个值比min大(如果min不是整数,那就不小于比min大的整数),但小于(但不等于)max @@ -52,16 +52,16 @@ export class RandomManager { // (min,max) 得到一个两数之间的随机整数 RandomManager.instance.getRandomInt(min, max, 3); */ - getRandomInt(min: number, max: number, type: number = 2): number { + getRandomInt(min: number, max: number, type = 2): number { min = Math.ceil(min); max = Math.floor(max); switch (type) { - case 1: // [min,max) 得到一个两数之间的随机整数,这个值不小于min(如果min不是整数的话,得到一个向上取整的 min),并且小于(但不等于)max - return Math.floor(this.getRandom() * (max - min)) + min; - case 2: // [min,max] 得到一个两数之间的随机整数,包括两个数在内,这个值比min大(如果min不是整数,那就不小于比min大的整数),但小于(但不等于)max - return Math.floor(this.getRandom() * (max - min + 1)) + min; - case 3: // (min,max) 得到一个两数之间的随机整数 - return Math.floor(this.getRandom() * (max - min - 1)) + min + 1; + case 1: // [min,max) 得到一个两数之间的随机整数,这个值不小于min(如果min不是整数的话,得到一个向上取整的 min),并且小于(但不等于)max + return Math.floor(this.getRandom() * (max - min)) + min; + case 2: // [min,max] 得到一个两数之间的随机整数,包括两个数在内,这个值比min大(如果min不是整数,那就不小于比min大的整数),但小于(但不等于)max + return Math.floor(this.getRandom() * (max - min + 1)) + min; + case 3: // (min,max) 得到一个两数之间的随机整数 + return Math.floor(this.getRandom() * (max - min - 1)) + min + 1; } return 0; } @@ -76,9 +76,9 @@ export class RandomManager { console.log("随机的数字", a); */ getRandomByMinMaxList(min: number, max: number, n: number): Array { - var result: Array = []; + const result: Array = []; for (let i = 0; i < n; i++) { - result.push(this.getRandomInt(min, max)) + result.push(this.getRandomInt(min, max)); } return result; } @@ -94,10 +94,10 @@ export class RandomManager { console.log("随机的对象", r); */ getRandomByObjectList(objects: Array, n: number): Array { - var temp: Array = objects.slice(); - var result: Array = []; + const temp: Array = objects.slice(); + const result: Array = []; for (let i = 0; i < n; i++) { - let index = this.getRandomInt(0, temp.length, 1); + const index = this.getRandomInt(0, temp.length, 1); result.push(temp.splice(index, 1)[0]); } return result; @@ -127,4 +127,4 @@ export class RandomManager { } return result; } -} \ No newline at end of file +} diff --git a/assets/core/common/random/SeedRandom.ts b/assets/core/common/random/SeedRandom.ts index 2669a47..12ec3dc 100644 --- a/assets/core/common/random/SeedRandom.ts +++ b/assets/core/common/random/SeedRandom.ts @@ -1,4 +1,4 @@ -import { RandomManager } from "./RandomManager"; +import { RandomManager } from './RandomManager'; /** 伪随机 */ export class SeedRandom { @@ -20,4 +20,4 @@ export class SeedRandom { this.rm = null!; this.sr = null!; } -} \ No newline at end of file +} diff --git a/assets/core/common/storage/StorageManager.ts b/assets/core/common/storage/StorageManager.ts index dec4ea2..27878d7 100644 --- a/assets/core/common/storage/StorageManager.ts +++ b/assets/core/common/storage/StorageManager.ts @@ -1,5 +1,5 @@ -import { sys } from "cc"; -import { PREVIEW } from "cc/env"; +import { sys } from 'cc'; +import { PREVIEW } from 'cc/env'; export interface IStorageSecurity { key: string; @@ -10,8 +10,8 @@ export interface IStorageSecurity { encryptKey(str: string): string; } -/** - * 本地存储 +/** + * 本地存储 * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037957&doc_id=2873565 */ export class StorageManager { @@ -31,7 +31,7 @@ export class StorageManager { /** * 设置用户唯一标识 - * @param id + * @param id */ setUser(id: string) { this.id = id; @@ -41,25 +41,25 @@ export class StorageManager { * 存储本地数据 * @param key 存储key * @param value 存储值 - * @returns + * @returns */ set(key: string, value: any) { let keywords = this.getKey(key); if (null == key) { - console.error("存储的key不能为空"); + console.error('存储的key不能为空'); return; } if (this.encrypted) { keywords = this.iss.encryptKey(keywords); } if (null == value) { - console.warn("存储的值为空,则直接移除该存储"); + console.warn('存储的值为空,则直接移除该存储'); this.remove(key); return; } if (typeof value === 'function') { - console.error("储存的值不能为方法"); + console.error('储存的值不能为方法'); return; } if (typeof value === 'object') { @@ -72,7 +72,7 @@ export class StorageManager { } } else if (typeof value === 'number') { - value = value + ""; + value = value + ''; } else if (typeof value === 'boolean') { value = String(value); @@ -88,11 +88,11 @@ export class StorageManager { * 获取指定关键字的数据 * @param key 获取的关键字 * @param defaultValue 获取的默认值 - * @returns + * @returns */ - get(key: string, defaultValue: any = ""): string { + get(key: string, defaultValue: any = ''): string { if (null == key) { - console.error("存储的key不能为空"); + console.error('存储的key不能为空'); return null!; } @@ -114,9 +114,9 @@ export class StorageManager { } /** 获取指定关键字的数值 */ - getNumber(key: string, defaultValue: number = 0): number { + getNumber(key: string, defaultValue = 0): number { const r = this.get(key); - if (r == "0") { + if (r == '0') { return Number(r); } return Number(r) || defaultValue; @@ -137,11 +137,11 @@ export class StorageManager { /** * 删除指定关键字的数据 * @param key 需要移除的关键字 - * @returns + * @returns */ remove(key: string) { if (null == key) { - console.error("存储的key不能为空"); + console.error('存储的key不能为空'); return; } @@ -160,9 +160,9 @@ export class StorageManager { /** 获取数据分组关键字 */ private getKey(key: string): string { - if (this.id == null || this.id == "") { + if (this.id == null || this.id == '') { return key; } return `${this.id}_${key}`; } -} \ No newline at end of file +} diff --git a/assets/core/common/storage/StorageSecurityCrypto.ts b/assets/core/common/storage/StorageSecurityCrypto.ts index 1a10202..266e0f4 100644 --- a/assets/core/common/storage/StorageSecurityCrypto.ts +++ b/assets/core/common/storage/StorageSecurityCrypto.ts @@ -31,4 +31,4 @@ // encryptKey(str: string): string { // return EncryptUtil.md5(str); // } -// } \ No newline at end of file +// } diff --git a/assets/core/common/storage/StorageSecuritySimple.ts b/assets/core/common/storage/StorageSecuritySimple.ts index 2cfd2cc..573e184 100644 --- a/assets/core/common/storage/StorageSecuritySimple.ts +++ b/assets/core/common/storage/StorageSecuritySimple.ts @@ -1,4 +1,4 @@ -import { IStorageSecurity } from './StorageManager'; +import type { IStorageSecurity } from './StorageManager'; /** * 本地存储加密 @@ -27,7 +27,7 @@ export class StorageSecuritySimple implements IStorageSecurity { encrypt(data: string): string { let encryptedText = ''; for (let i = 0; i < data.length; i++) { - let charCode = data.charCodeAt(i); + const charCode = data.charCodeAt(i); encryptedText += String.fromCharCode(charCode + this.secretkey.length); } return encryptedText; @@ -37,7 +37,7 @@ export class StorageSecuritySimple implements IStorageSecurity { decrypt(encryptedData: string): string { let decryptedText = ''; for (let i = 0; i < encryptedData.length; i++) { - let charCode = encryptedData.charCodeAt(i); + const charCode = encryptedData.charCodeAt(i); decryptedText += String.fromCharCode(charCode - this.secretkey.length); } return decryptedText; @@ -46,4 +46,4 @@ export class StorageSecuritySimple implements IStorageSecurity { encryptKey(str: string): string { return this.encrypt(str); } -} \ No newline at end of file +} diff --git a/assets/core/common/timer/Timer.ts b/assets/core/common/timer/Timer.ts index 9b162da..6d3601b 100644 --- a/assets/core/common/timer/Timer.ts +++ b/assets/core/common/timer/Timer.ts @@ -5,8 +5,8 @@ * @LastEditTime: 2023-01-19 14:28:05 */ -/** - * 定时触发组件 +/** + * 定时触发组件 * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037964&doc_id=2873565 * @example export class Test extends Component { @@ -23,20 +23,20 @@ export class Timer { callback: Function | null = null; - private _elapsedTime: number = 0; + private _elapsedTime = 0; get elapsedTime(): number { return this._elapsedTime; } - private _step: number = -1; + private _step = -1; /** 触发间隔时间(秒) */ get step(): number { return this._step; } set step(step: number) { - this._step = step; // 每次修改时间 - this._elapsedTime = 0; // 逝去时间 + this._step = step; // 每次修改时间 + this._elapsedTime = 0; // 逝去时间 } get progress(): number { @@ -47,7 +47,7 @@ export class Timer { * 定时触发组件 * @param step 触发间隔时间(秒) */ - constructor(step: number = 0) { + constructor(step = 0) { this.step = step; } @@ -72,4 +72,4 @@ export class Timer { this._elapsedTime = 0; this.step = -1; } -} \ No newline at end of file +} diff --git a/assets/core/common/timer/TimerManager.ts b/assets/core/common/timer/TimerManager.ts index 21b09f1..e28562d 100644 --- a/assets/core/common/timer/TimerManager.ts +++ b/assets/core/common/timer/TimerManager.ts @@ -4,9 +4,9 @@ * @LastEditors: dgflash * @LastEditTime: 2023-01-19 14:37:19 */ -import { Component, game } from "cc"; -import { StringUtil } from "../../utils/StringUtil"; -import { Timer } from "./Timer"; +import { Component, game } from 'cc'; +import { StringUtil } from '../../utils/StringUtil'; +import { Timer } from './Timer'; interface ITimer { /** 倒计时编号 */ @@ -36,15 +36,15 @@ export class TimerManager extends Component { /** 服务器初始时间 */ private date_s_start: Date = new Date(); /** 服务器时间后修正时间 */ - private polymeric_s: number = 0; + private polymeric_s = 0; /** 客户端时间 */ private date_c: Date = new Date(); /** 后台管理倒计时完成事件 */ protected update(dt: number) { - for (let key in this.times) { - let data = this.times[key]; - let timer = data.timer; + for (const key in this.times) { + const data = this.times[key]; + const timer = data.timer; if (timer.update(dt)) { if (data.object[data.field] > 0) { data.object[data.field]--; @@ -53,9 +53,9 @@ export class TimerManager extends Component { if (data.object[data.field] == 0) { this.onTimerComplete(data); } - // 触发每秒回调事件 + // 触发每秒回调事件 else if (data.onSeconds) { - data.onSeconds.forEach(fn => fn.call(data.object)); + data.onSeconds.forEach((fn) => fn.call(data.object)); } } } @@ -64,7 +64,7 @@ export class TimerManager extends Component { /** 触发倒计时完成事件 */ private onTimerComplete(data: ITimer) { - if (data.onCompletes) data.onCompletes.forEach(fn => fn.call(data.target, data.object)); + if (data.onCompletes) data.onCompletes.forEach((fn) => fn.call(data.target, data.object)); delete this.times[data.id]; } @@ -79,12 +79,12 @@ export class TimerManager extends Component { * @example export class Test extends Component { private timeId!: string; - + start() { // 在指定对象上注册一个倒计时的回调管理器 this.timeId = oops.timer.register(this, "countDown", this, this.onSecond, this.onComplete); } - + private onSecond() { console.log("每秒触发一次"); } @@ -98,7 +98,7 @@ export class TimerManager extends Component { const timer = new Timer(); timer.step = 1; - let data: ITimer = { + const data: ITimer = { id: StringUtil.guid(), timer: timer, object: object, @@ -122,15 +122,15 @@ export class TimerManager extends Component { * @param onComplete 倒计时完成事件 */ addCallback(id: string, onSecond?: Function, onComplete?: Function) { - let data = this.times[id]; + const data = this.times[id]; if (data) { if (onSecond) data.onSeconds.push(onSecond); if (onComplete) data.onCompletes.push(onComplete); } } - /** - * 在指定对象上注销一个倒计时的回调管理器 + /** + * 在指定对象上注销一个倒计时的回调管理器 * @param id 时间对象唯一表示 * @example export class Test extends Component { @@ -188,17 +188,17 @@ export class TimerManager extends Component { /** 游戏最小化时记录时间数据 */ save(): void { - for (let key in this.times) { - let data: ITimer = this.times[key]; + for (const key in this.times) { + const data: ITimer = this.times[key]; data.startTime = this.getTime(); } } /** 游戏最大化时恢复时间数据 */ load(): void { - for (let key in this.times) { - let data = this.times[key]; - let interval = Math.floor((this.getTime() - (data.startTime || this.getTime())) / 1000); + for (const key in this.times) { + const data = this.times[key]; + const interval = Math.floor((this.getTime() - (data.startTime || this.getTime())) / 1000); data.object[data.field] = data.object[data.field] - interval; if (data.object[data.field] <= 0) { data.object[data.field] = 0; @@ -206,4 +206,4 @@ export class TimerManager extends Component { } } } -} \ No newline at end of file +} diff --git a/assets/core/game/GameManager.ts b/assets/core/game/GameManager.ts index 9ad8917..effa818 100644 --- a/assets/core/game/GameManager.ts +++ b/assets/core/game/GameManager.ts @@ -4,7 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 12:09:55 */ -import { Node, director } from 'cc'; +import type { Node } from 'cc'; +import { director } from 'cc'; import { GameComponent } from '../../module/common/GameComponent'; import { resLoader } from '../common/loader/ResLoader'; import { ViewUtil } from '../utils/ViewUtil'; @@ -34,7 +35,7 @@ export class GameManager { */ open(parent: Node | GameComponent, prefabPath: string, params?: ElementParams): Promise { return new Promise(async (resolve, reject) => { - let bundleName: string = null! + let bundleName: string = null!; if (params && params.bundle) { bundleName = params.bundle; } @@ -73,4 +74,4 @@ export class GameManager { //@ts-ignore return director.globalGameTimeScale; } -} \ No newline at end of file +} diff --git a/assets/core/gui/Gui.ts b/assets/core/gui/Gui.ts index 7afdd97..b126489 100644 --- a/assets/core/gui/Gui.ts +++ b/assets/core/gui/Gui.ts @@ -1,7 +1,7 @@ -import { UIConfigMap } from "./layer/LayerEnum"; -import { UIConfig } from "./layer/UIConfig"; +import type { UIConfigMap } from './layer/LayerEnum'; +import type { UIConfig } from './layer/UIConfig'; -var configs: UIConfigMap = {}; +const configs: UIConfigMap = {}; export namespace gui { /** 注册界面组件 */ @@ -16,7 +16,7 @@ export namespace gui { /** 框架内部使用方法 */ export namespace internal { /** 界面唯一标记变量名 */ - export const GUI_KEY = "OOPS_GUI_KEY"; + export const GUI_KEY = 'OOPS_GUI_KEY'; /** 获取界面唯一关键字 */ export function getKey(ctor: any) { @@ -30,7 +30,7 @@ export namespace gui { /** 获取界面组件配置 */ export function setConfig(key: string, config: UIConfig) { - let c = getConfig(key); + const c = getConfig(key); if (c == null) { configs[key] = config; } @@ -46,4 +46,4 @@ export namespace gui { } } } -} \ No newline at end of file +} diff --git a/assets/core/gui/GuiEnum.ts b/assets/core/gui/GuiEnum.ts index 45ef620..7e86ff6 100644 --- a/assets/core/gui/GuiEnum.ts +++ b/assets/core/gui/GuiEnum.ts @@ -6,4 +6,4 @@ export enum PromptResType { Wait = 'common/prefab/wait', /** 遮罩层 */ Mask = 'common/prefab/mask', -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerDialog.ts b/assets/core/gui/layer/LayerDialog.ts index f9b9ed0..9c73e01 100644 --- a/assets/core/gui/layer/LayerDialog.ts +++ b/assets/core/gui/layer/LayerDialog.ts @@ -4,10 +4,10 @@ * @LastEditors: dgflash * @LastEditTime: 2023-07-24 17:14:57 */ -import { Node } from "cc"; -import { LayerPopUp } from "./LayerPopup"; -import { UIParam, UIState } from "./LayerUIElement"; -import { UIConfig } from "./UIConfig"; +import type { Node } from 'cc'; +import { LayerPopUp } from './LayerPopup'; +import type { UIParam, UIState } from './LayerUIElement'; +import type { UIConfig } from './UIConfig'; /** 模式弹窗数据 */ type DialogParam = { @@ -28,8 +28,8 @@ export class LayerDialog extends LayerPopUp { /** 当前打开的界面 */ private current: Node = null!; - /** - * 添加模式窗口 + /** + * 添加模式窗口 * 1. 同时添加多个模式窗口时,第一个之后的窗口会先队列起来,在第一个关闭后在加载与显示第二个;同时方法返回节点保持只返回当前显示的界面节点 */ add(uiid: string, config: UIConfig, params?: UIParam): Promise { @@ -49,8 +49,8 @@ export class LayerDialog extends LayerPopUp { /** 显示模式弹窗 */ private showDialog(uiid: string, config: UIConfig, param?: UIParam): Promise { return new Promise(async (resolve, reject) => { - let state = this.initUIConfig(uiid, config, param); - let node = await this.load(state); + const state = this.initUIConfig(uiid, config, param); + const node = await this.load(state); resolve(node); }); } @@ -68,8 +68,8 @@ export class LayerDialog extends LayerPopUp { private next() { if (this.params.length > 0) { - let param = this.params.shift()!; + const param = this.params.shift()!; this.showDialog(param.uiid, param.config, param.params); } } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerEnum.ts b/assets/core/gui/layer/LayerEnum.ts index 9879f98..0152d3c 100644 --- a/assets/core/gui/layer/LayerEnum.ts +++ b/assets/core/gui/layer/LayerEnum.ts @@ -1,4 +1,4 @@ -import { UIConfig } from "./UIConfig"; +import type { UIConfig } from './UIConfig'; /** 界面编号 */ export type Uiid = number | string | UIConfig | Function; @@ -18,37 +18,37 @@ export enum ScreenAdapterType { /** 自定义层类型 */ export enum LayerCustomType { /** 二维游戏层 */ - Game = "LayerGame", + Game = 'LayerGame', /** 消息提示层 */ - Notify = "LayerNotify", + Notify = 'LayerNotify', /** 新手引导层 */ - Guide = "LayerGuide" + Guide = 'LayerGuide' } /** 界面层类型 */ export enum LayerType { /** 主界面层 */ - UI = "LayerUI", + UI = 'LayerUI', /** 弹窗层 */ - PopUp = "LayerPopUp", + PopUp = 'LayerPopUp', /** 模式窗口层 */ - Dialog = "LayerDialog", + Dialog = 'LayerDialog', /** 系统触发模式窗口层 */ - System = "LayerSystem", + System = 'LayerSystem', } /** 界面层组件类型 */ export enum LayerTypeCls { /** 主界面层 */ - UI = "UI", + UI = 'UI', /** 弹窗层 */ - PopUp = "PopUp", + PopUp = 'PopUp', /** 模式窗口层 */ - Dialog = "Dialog", + Dialog = 'Dialog', /** 消息提示层 */ - Notify = "Notify", + Notify = 'Notify', /** 游戏层 */ - Game = "Game", + Game = 'Game', /** 自定义节点层 */ - Node = "Node" -} \ No newline at end of file + Node = 'Node' +} diff --git a/assets/core/gui/layer/LayerGame.ts b/assets/core/gui/layer/LayerGame.ts index 3b4425c..41e688e 100644 --- a/assets/core/gui/layer/LayerGame.ts +++ b/assets/core/gui/layer/LayerGame.ts @@ -4,13 +4,13 @@ * @LastEditors: dgflash * @LastEditTime: 2025-08-15 10:06:47 */ -import { Node, NodePool, Vec3, warn } from "cc"; -import { resLoader } from "../../common/loader/ResLoader"; -import { ViewUtil } from "../../utils/ViewUtil"; -import { LayerCustomType } from "./LayerEnum"; -import { GameElementParams, LayerGameElement } from "./LayerGameElement"; -import { LayerHelper } from "./LayerHelper"; -import { GameElementConfig } from "./UIConfig"; +import { Node, NodePool, Vec3, warn } from 'cc'; +import { resLoader } from '../../common/loader/ResLoader'; +import { ViewUtil } from '../../utils/ViewUtil'; +import { LayerCustomType } from './LayerEnum'; +import { GameElementParams, LayerGameElement } from './LayerGameElement'; +import { LayerHelper } from './LayerHelper'; +import type { GameElementConfig } from './UIConfig'; /* 二维游戏层 */ export class LayerGame extends Node { @@ -29,13 +29,13 @@ export class LayerGame extends Node { */ add(prefab: string, config: GameElementConfig = {}): Promise { return new Promise(async (resolve, reject) => { - let params = this.setParams(prefab, config, false); - let node = await ViewUtil.createPrefabNodeAsync(prefab, params.config.bundle); + const params = this.setParams(prefab, config, false); + const node = await ViewUtil.createPrefabNodeAsync(prefab, params.config.bundle); if (node) { // 设置自定义属性 this.setNode(node, config); - let lge = node.addComponent(LayerGameElement); + const lge = node.addComponent(LayerGameElement); lge.params = params; params.nodes.push(node); } @@ -50,7 +50,7 @@ export class LayerGame extends Node { */ addPool(prefab: string, config: GameElementConfig = {}): Promise { return new Promise(async (resolve, reject) => { - let params = this.setParams(prefab, config, true); + const params = this.setParams(prefab, config, true); let node: Node = null!; if (params.pool.size() > 0) { node = params.pool.get()!; @@ -63,7 +63,7 @@ export class LayerGame extends Node { // 设置自定义属性 this.setNode(node, config); - let lge = node.getComponent(LayerGameElement)!; + const lge = node.getComponent(LayerGameElement)!; lge.params = params; resolve(node); @@ -72,9 +72,9 @@ export class LayerGame extends Node { /** 清理池数据 */ clearPool(node: Node) { - let lge = node.getComponent(LayerGameElement)!; + const lge = node.getComponent(LayerGameElement)!; if (lge) { - let params = this.elements.get(lge.params.uiid); + const params = this.elements.get(lge.params.uiid); if (params) params.pool.clear(); } } @@ -84,14 +84,14 @@ export class LayerGame extends Node { * @param node 游戏元素节点 */ remove(node: Node) { - let lge = node.getComponent(LayerGameElement)!; + const lge = node.getComponent(LayerGameElement)!; if (lge) { if (lge.params.pool) { lge.params.pool.put(node); } else { - let nodes = lge.params.nodes; - let index = nodes.indexOf(node); + const nodes = lge.params.nodes; + const index = nodes.indexOf(node); if (index != -1) { nodes.splice(index, 1); if (nodes.length == 0) { @@ -103,14 +103,14 @@ export class LayerGame extends Node { } } else { - warn(`当前删除游戏元素的 Node 不是通过框架添加的`); + warn('当前删除游戏元素的 Node 不是通过框架添加的'); } } /** 设置元素参数 */ private setParams(prefab: string, config: GameElementConfig, pool: boolean) { - let bundleName = config.bundle ? config.bundle : resLoader.defaultBundleName; - let uuid = bundleName + "_" + prefab; + const bundleName = config.bundle ? config.bundle : resLoader.defaultBundleName; + const uuid = bundleName + '_' + prefab; let params = this.elements.get(uuid); if (params == null) { config.prefab = prefab; @@ -137,4 +137,4 @@ export class LayerGame extends Node { node.parent = config.parent ? config.parent : this; if (config.siblingIndex != null) node.setSiblingIndex(config.siblingIndex); } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerGameElement.ts b/assets/core/gui/layer/LayerGameElement.ts index 32938aa..f6155b1 100644 --- a/assets/core/gui/layer/LayerGameElement.ts +++ b/assets/core/gui/layer/LayerGameElement.ts @@ -1,5 +1,6 @@ -import { _decorator, Component, Node, NodePool } from "cc"; -import { GameElementConfig } from "./UIConfig"; +import type { Node, NodePool } from 'cc'; +import { _decorator, Component } from 'cc'; +import type { GameElementConfig } from './UIConfig'; const { ccclass } = _decorator; @@ -19,9 +20,9 @@ export class GameElementParams { /** 游戏元素唯一编号 */ uiid: string = null!; /** 游戏元素配置 */ - config: GameElementConfig = null! + config: GameElementConfig = null!; /** 同类游戏元素集合 */ nodes: Node[] = null!; /** 同类游戏元素对象池 */ pool: NodePool = null!; -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerHelper.ts b/assets/core/gui/layer/LayerHelper.ts index 05c71b5..25b69fe 100644 --- a/assets/core/gui/layer/LayerHelper.ts +++ b/assets/core/gui/layer/LayerHelper.ts @@ -1,5 +1,6 @@ -import { Layers } from "cc"; -import { Node, Widget } from "cc"; +import { Layers } from 'cc'; +import type { Node } from 'cc'; +import { Widget } from 'cc'; /** 界面层辅助工具 */ export class LayerHelper { @@ -17,4 +18,4 @@ export class LayerHelper { node.layer = Layers.Enum.UI_2D; return widget; } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerManager.ts b/assets/core/gui/layer/LayerManager.ts index 6720350..d526942 100644 --- a/assets/core/gui/layer/LayerManager.ts +++ b/assets/core/gui/layer/LayerManager.ts @@ -1,15 +1,17 @@ -import { Camera, Node, ResolutionPolicy, SafeArea, screen, view, warn } from "cc"; -import { oops } from "../../Oops"; -import { gui } from "../Gui"; -import { LayerDialog } from "./LayerDialog"; -import { LayerCustomType, LayerTypeCls, UIConfigMap, Uiid } from "./LayerEnum"; -import { LayerGame } from "./LayerGame"; -import { LayerHelper } from "./LayerHelper"; -import { LayerNotify } from "./LayerNotify"; -import { LayerPopUp } from "./LayerPopup"; -import { LayerUI } from "./LayerUI"; -import { LayerUIElement, UIParam } from "./LayerUIElement"; -import { UIConfig } from "./UIConfig"; +import { Camera, Node, ResolutionPolicy, SafeArea, screen, view, warn } from 'cc'; +import { oops } from '../../Oops'; +import { gui } from '../Gui'; +import { LayerDialog } from './LayerDialog'; +import type { UIConfigMap, Uiid } from './LayerEnum'; +import { LayerCustomType, LayerTypeCls } from './LayerEnum'; +import { LayerGame } from './LayerGame'; +import { LayerHelper } from './LayerHelper'; +import { LayerNotify } from './LayerNotify'; +import { LayerPopUp } from './LayerPopup'; +import { LayerUI } from './LayerUI'; +import type { UIParam } from './LayerUIElement'; +import { LayerUIElement } from './LayerUIElement'; +import type { UIConfig } from './UIConfig'; /** 界面层级管理器 */ export class LayerManager { @@ -23,11 +25,11 @@ export class LayerManager { guide!: Node; /** 窗口宽高比例 */ - windowAspectRatio: number = 0; + windowAspectRatio = 0; /** 设计宽高比例 */ - designAspectRatio: number = 0; + designAspectRatio = 0; /** 是否开启移动设备安全区域适配 */ - mobileSafeArea: boolean = false; + mobileSafeArea = false; /** 消息提示控制器,请使用show方法来显示 */ private notify!: LayerNotify; @@ -52,7 +54,7 @@ export class LayerManager { */ registerLayerCls(type: string, cls: any) { if (this.clsLayers.has(type)) { - console.error("已存在自定义界面层类型", type); + console.error('已存在自定义界面层类型', type); return; } this.clsLayers.set(type, cls); @@ -64,7 +66,7 @@ export class LayerManager { */ private initLayer(root: Node, config: any) { if (config == null) { - console.error("请升级到最新版本框架,界面层级管理修改为数据驱动。参考模板项目中的config.json配置文件"); + console.error('请升级到最新版本框架,界面层级管理修改为数据驱动。参考模板项目中的config.json配置文件'); return; } this.root = root; @@ -73,23 +75,23 @@ export class LayerManager { // 创建界面层 for (let i = 0; i < config.length; i++) { - let data = config[i]; + const data = config[i]; let layer: Node = null!; if (data.type == LayerTypeCls.Node) { switch (data.name) { - case LayerCustomType.Guide: - this.guide = this.create_node(data.name); - layer = this.guide; - break + case LayerCustomType.Guide: + this.guide = this.create_node(data.name); + layer = this.guide; + break; } } else { - let cls = this.clsLayers.get(data.type); + const cls = this.clsLayers.get(data.type); if (cls) { layer = new cls(data.name); } else { - console.error("未识别的界面层类型", data.type); + console.error('未识别的界面层类型', data.type); } } root.addChild(layer); @@ -110,24 +112,24 @@ export class LayerManager { this.windowAspectRatio = ws.width / ws.height; this.designAspectRatio = drs.width / drs.height; - let finalW: number = 0; - let finalH: number = 0; + let finalW = 0; + let finalH = 0; if (this.windowAspectRatio > this.designAspectRatio) { finalH = drs.height; finalW = finalH * ws.width / ws.height; - oops.log.logView("适配屏幕高度", "【横屏】"); + oops.log.logView('适配屏幕高度', '【横屏】'); } else { finalW = drs.width; finalH = finalW * ws.height / ws.width; - oops.log.logView("适配屏幕宽度", "【竖屏】"); + oops.log.logView('适配屏幕宽度', '【竖屏】'); } view.setDesignResolutionSize(finalW, finalH, ResolutionPolicy.UNKNOWN); if (this.mobileSafeArea) { this.root.addComponent(SafeArea); - oops.log.logView("开启移动设备安全区域适配"); + oops.log.logView('开启移动设备安全区域适配'); } } @@ -146,18 +148,18 @@ export class LayerManager { setOpenFailure(callback: Function) { this.uiLayers.forEach((layer: LayerUI) => { layer.onOpenFailure = callback; - }) + }); } /** * 渐隐飘过提示 * @param content 文本表示 * @param useI18n 是否使用多语言 - * @example + * @example * oops.gui.toast("提示内容"); */ - toast(content: string, useI18n: boolean = false) { - this.notify.toast(content, useI18n) + toast(content: string, useI18n = false) { + this.notify.toast(content, useI18n); } /** 打开等待提示 */ @@ -172,12 +174,12 @@ export class LayerManager { /** 获取界面信息 */ private getInfo(uiid: Uiid): { key: string; config: UIConfig } { - let key = ""; + let key = ''; let config: UIConfig = null!; // 界面配置 if (typeof uiid === 'object') { - key = uiid.bundle + "_" + uiid.prefab; + key = uiid.bundle + '_' + uiid.prefab; config = gui.internal.getConfig(key); if (config == null) { config = uiid; @@ -211,17 +213,17 @@ export class LayerManager { var comp = node.getComponent(LoadingViewComp) as ecs.Comp; } onRemoved:(node: Node | null, params: any) => { - + } }; oops.gui.open(UIID.Loading); */ open(uiid: Uiid, param?: UIParam): Promise { return new Promise(async (resolve, reject) => { - let info = this.getInfo(uiid); - let layer = this.uiLayers.get(info.config.layer); + const info = this.getInfo(uiid); + const layer = this.uiLayers.get(info.config.layer); if (layer) { - let node = await layer.add(info.key, info.config, param); + const node = await layer.add(info.key, info.config, param); resolve(node); } else { @@ -232,8 +234,8 @@ export class LayerManager { /** 显示指定界面 */ show(uiid: Uiid) { - let info = this.getInfo(uiid); - let layer = this.uiLayers.get(info.config.layer); + const info = this.getInfo(uiid); + const layer = this.uiLayers.get(info.config.layer); if (layer) { layer.show(info.config.prefab); } @@ -249,8 +251,8 @@ export class LayerManager { * oops.gui.remove(UIID.Loading); */ remove(uiid: Uiid) { - let info = this.getInfo(uiid); - let layer = this.uiLayers.get(info.config.layer); + const info = this.getInfo(uiid); + const layer = this.uiLayers.get(info.config.layer); if (layer) { layer.remove(info.config.prefab); } @@ -266,8 +268,8 @@ export class LayerManager { * oops.gui.removeCache(UIID.Loading); */ removeCache(uiid: Uiid) { - let info = this.getInfo(uiid); - let layer = this.uiLayers.get(info.config.layer); + const info = this.getInfo(uiid); + const layer = this.uiLayers.get(info.config.layer); if (layer) { layer.removeCache(info.config.prefab); } @@ -284,16 +286,16 @@ export class LayerManager { */ removeByNode(node: Node) { if (node instanceof Node) { - let comp = node.getComponent(LayerUIElement); + const comp = node.getComponent(LayerUIElement); if (comp && comp.state) { // 释放显示的界面 if (node.parent) { - let uiid = gui.internal.getConfig(comp.state.uiid); + const uiid = gui.internal.getConfig(comp.state.uiid); this.remove(uiid); } // 释放缓存中的界面 else { - let layer = this.uiLayers.get(comp.state.config.layer); + const layer = this.uiLayers.get(comp.state.config.layer); if (layer) { // @ts-ignore 注:不对外使用 layer.removeCache(comp.state.config.prefab); @@ -301,7 +303,7 @@ export class LayerManager { } } else { - warn(`当前删除的 Node 不是通过界面管理器添加的`); + warn('当前删除的 Node 不是通过界面管理器添加的'); node.destroy(); } } @@ -315,7 +317,7 @@ export class LayerManager { */ replace(removeUiId: Uiid, openUiid: Uiid, param?: UIParam): Promise { return new Promise(async (resolve, reject) => { - let node = await this.open(openUiid, param); + const node = await this.open(openUiid, param); this.remove(removeUiId); resolve(node); }); @@ -328,9 +330,9 @@ export class LayerManager { * oops.gui.has(UIID.Loading); */ has(uiid: Uiid): boolean { - let info = this.getInfo(uiid); + const info = this.getInfo(uiid); let result = false; - let layer = this.uiLayers.get(info.config.layer); + const layer = this.uiLayers.get(info.config.layer); if (layer) { result = layer.has(info.config.prefab); } @@ -348,9 +350,9 @@ export class LayerManager { * oops.gui.has(UIID.Loading); */ get(uiid: Uiid): Node { - let info = this.getInfo(uiid); + const info = this.getInfo(uiid); let result: Node = null!; - let layer = this.uiLayers.get(info.config.layer); + const layer = this.uiLayers.get(info.config.layer); if (layer) { result = layer.get(info.config.prefab); } @@ -366,10 +368,10 @@ export class LayerManager { * @example * oops.gui.clear(); */ - clear(isDestroy: boolean = true) { + clear(isDestroy = true) { this.uiLayers.forEach((layer: LayerUI) => { layer.clear(isDestroy); - }) + }); } private create_node(name: string) { @@ -377,4 +379,4 @@ export class LayerManager { LayerHelper.setFullScreen(node); return node; } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerNotify.ts b/assets/core/gui/layer/LayerNotify.ts index 3058597..1eda429 100644 --- a/assets/core/gui/layer/LayerNotify.ts +++ b/assets/core/gui/layer/LayerNotify.ts @@ -4,12 +4,12 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 13:44:12 */ -import { BlockInputEvents, Node, instantiate } from "cc"; -import { EDITOR } from "cc/env"; -import { ViewUtil } from "../../utils/ViewUtil"; -import { PromptResType } from "../GuiEnum"; -import { Notify } from "../prompt/Notify"; -import { LayerHelper } from "./LayerHelper"; +import { BlockInputEvents, Node, instantiate } from 'cc'; +import { EDITOR } from 'cc/env'; +import { ViewUtil } from '../../utils/ViewUtil'; +import { PromptResType } from '../GuiEnum'; +import { Notify } from '../prompt/Notify'; +import { LayerHelper } from './LayerHelper'; /* 滚动消息提示层 */ export class LayerNotify extends Node { @@ -74,9 +74,9 @@ export class LayerNotify extends Node { } this.notify.parent = this; - let childNode = instantiate(this.notifyItem); - let prompt = childNode.getChildByName("prompt")!; - let toastCom = prompt.getComponent(Notify)!; + const childNode = instantiate(this.notifyItem); + const prompt = childNode.getChildByName('prompt')!; + const toastCom = prompt.getComponent(Notify)!; childNode.parent = this.notify; toastCom.onComplete = () => { @@ -91,4 +91,4 @@ export class LayerNotify extends Node { this.notify.children[0].destroy(); } } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerPopup.ts b/assets/core/gui/layer/LayerPopup.ts index 6ac6d15..3f22385 100644 --- a/assets/core/gui/layer/LayerPopup.ts +++ b/assets/core/gui/layer/LayerPopup.ts @@ -3,12 +3,13 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 13:44:28 */ -import { BlockInputEvents, EventTouch, Node } from "cc"; -import { ViewUtil } from "../../utils/ViewUtil"; -import { PromptResType } from "../GuiEnum"; -import { LayerUI } from "./LayerUI"; -import { UIState } from "./LayerUIElement"; -import { UIConfig } from "./UIConfig"; +import type { EventTouch } from 'cc'; +import { BlockInputEvents, Node } from 'cc'; +import { ViewUtil } from '../../utils/ViewUtil'; +import { PromptResType } from '../GuiEnum'; +import { LayerUI } from './LayerUI'; +import type { UIState } from './LayerUIElement'; +import type { UIConfig } from './UIConfig'; /* 弹窗层,允许同时弹出多个窗口 */ export class LayerPopUp extends LayerUI { @@ -62,7 +63,7 @@ export class LayerPopUp extends LayerUI { if (this.mask == null) return; let flag = true; - for (let value of this.ui_nodes.values()) { + for (const value of this.ui_nodes.values()) { if (value.config.mask) { flag = false; break; @@ -97,7 +98,7 @@ export class LayerPopUp extends LayerUI { /** 关闭触摸非窗口区域关闭 */ protected closeVacancyRemove() { let flag = true; - for (let value of this.ui_nodes.values()) { + for (const value of this.ui_nodes.values()) { if (value.config.vacancy) { flag = false; break; @@ -112,7 +113,7 @@ export class LayerPopUp extends LayerUI { /** 触摸非窗口区域关闭 */ private onTouchEnd(event: EventTouch) { if (this.ui_nodes.size > 0) { - let vp = this.ui_nodes.array[this.ui_nodes.size - 1]; + const vp = this.ui_nodes.array[this.ui_nodes.size - 1]; if (vp.valid && vp.config.vacancy) { this.remove(vp.config.prefab); } @@ -120,7 +121,7 @@ export class LayerPopUp extends LayerUI { } clear(isDestroy: boolean) { - super.clear(isDestroy) + super.clear(isDestroy); this.closeBlack(); } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerUI.ts b/assets/core/gui/layer/LayerUI.ts index c56a585..7c271b6 100644 --- a/assets/core/gui/layer/LayerUI.ts +++ b/assets/core/gui/layer/LayerUI.ts @@ -1,11 +1,12 @@ -import { instantiate, Node, Prefab, SafeArea } from "cc"; -import { Collection } from "db://oops-framework/libs/collection/Collection"; -import { resLoader } from "../../common/loader/ResLoader"; -import { oops } from "../../Oops"; -import { Uiid } from "./LayerEnum"; -import { LayerHelper } from "./LayerHelper"; -import { LayerUIElement, UIParam, UIState } from "./LayerUIElement"; -import { UIConfig } from "./UIConfig"; +import { instantiate, Node, Prefab, SafeArea } from 'cc'; +import { Collection } from 'db://oops-framework/libs/collection/Collection'; +import { resLoader } from '../../common/loader/ResLoader'; +import { oops } from '../../Oops'; +import type { Uiid } from './LayerEnum'; +import { LayerHelper } from './LayerHelper'; +import type { UIParam } from './LayerUIElement'; +import { LayerUIElement, UIState } from './LayerUIElement'; +import type { UIConfig } from './UIConfig'; /** 界面层对象 */ export class LayerUI extends Node { @@ -54,7 +55,7 @@ export class LayerUI extends Node { } // 检查缓存中是否存界面 - let state = this.initUIConfig(uiid, config, params); + const state = this.initUIConfig(uiid, config, params); await this.load(state); resolve(state.node); }); @@ -89,7 +90,7 @@ export class LayerUI extends Node { return new Promise(async (resolve, reject) => { // 加载界面资源超时提示 if (state.node == null) { - let timerId = setTimeout(this.onLoadingTimeoutGui, oops.config.game.loadingTimeoutGui); + const timerId = setTimeout(this.onLoadingTimeoutGui, oops.config.game.loadingTimeoutGui); // 优先加载配置的指定资源包中资源,如果没配置则加载默认资源包资源 const res = await resLoader.load(state.config.bundle!, state.config.prefab, Prefab); @@ -127,7 +128,7 @@ export class LayerUI extends Node { const comp = state.node.getComponent(LayerUIElement)!; const r: boolean = await comp.add(); if (r) { - state.valid = true; // 标记界面为使用状态 + state.valid = true; // 标记界面为使用状态 if (!state.params.preload) { state.params.preload = false; state.node.parent = this; @@ -164,7 +165,7 @@ export class LayerUI extends Node { remove(prefabPath: string): void { const state = this.ui_nodes.get(prefabPath); if (state) { - let release: boolean = state.config.destroy!; + const release: boolean = state.config.destroy!; // 不释放界面,缓存起来待下次使用 if (release === false) this.ui_cache.set(state.config.prefab, state); @@ -231,4 +232,4 @@ export class LayerUI extends Node { }); } } -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/LayerUIElement.ts b/assets/core/gui/layer/LayerUIElement.ts index 4fede83..cfc12e0 100644 --- a/assets/core/gui/layer/LayerUIElement.ts +++ b/assets/core/gui/layer/LayerUIElement.ts @@ -4,13 +4,14 @@ * @LastEditors: dgflash * @LastEditTime: 2023-01-09 11:55:03 */ -import { Component, Node, _decorator } from "cc"; -import { oops } from "../../Oops"; -import { UIConfig } from "./UIConfig"; +import type { Node } from 'cc'; +import { Component, _decorator } from 'cc'; +import { oops } from '../../Oops'; +import type { UIConfig } from './UIConfig'; -const EventOnAdded: string = "onAdded"; -const EventOnBeforeRemove: string = "onBeforeRemove"; -const EventOnRemoved: string = "onRemoved"; +const EventOnAdded = 'onAdded'; +const EventOnBeforeRemove = 'onBeforeRemove'; +const EventOnRemoved = 'onRemoved'; const { ccclass } = _decorator; @@ -38,7 +39,7 @@ export class LayerUIElement extends Component { } // 触发外部窗口显示前的事件(辅助实现自定义动画逻辑) - if (typeof this.state.params.onAdded === "function") { + if (typeof this.state.params.onAdded === 'function') { this.state.params.onAdded(this.node, this.state.params.data); } @@ -53,7 +54,7 @@ export class LayerUIElement extends Component { this.applyComponentsFunction(this.node, EventOnBeforeRemove, this.state.params.data); // 通知外部对象窗口组件上移除之前的事件(关闭窗口前的关闭动画处理) - if (typeof this.state.params.onBeforeRemove === "function") { + if (typeof this.state.params.onBeforeRemove === 'function') { this.state.params.onBeforeRemove(this.node, this.onBeforeRemoveNext.bind(this, isDestroy)); } else { @@ -69,7 +70,7 @@ export class LayerUIElement extends Component { private onBeforeRemoveNext(isDestroy: boolean) { this.state.valid = false; - if (this.state.params && typeof this.state.params.onRemoved === "function") { + if (this.state.params && typeof this.state.params.onRemoved === 'function') { this.state.params.onRemoved(this.node, this.state.params.data); } @@ -118,7 +119,7 @@ export class UIState { /** 窗口事件 */ params: UIParam = null!; /** 是否在使用状态 */ - valid: boolean = true; + valid = true; /** 界面根节点 */ node: Node = null!; } @@ -138,9 +139,9 @@ export interface UIParam { */ onAdded?: (node: Node, params: any) => void, - /** + /** * 如果指定onBeforeRemoved,则next必须调用,否则节点不会被正常删除。 - * + * * 比如希望节点做一个FadeOut然后删除,则可以在`onBeforeRemoved`当中播放action动画,动画结束后调用next * @param node 当前界面节点 * @param next 回调方法 @@ -153,4 +154,4 @@ export interface UIParam { * @param params 外部传递参数 */ onRemoved?: (node: Node, params: any) => void -} \ No newline at end of file +} diff --git a/assets/core/gui/layer/UIConfig.ts b/assets/core/gui/layer/UIConfig.ts index 7babb75..4a7b239 100644 --- a/assets/core/gui/layer/UIConfig.ts +++ b/assets/core/gui/layer/UIConfig.ts @@ -1,6 +1,6 @@ -import { Node, Vec3 } from "cc"; +import type { Node, Vec3 } from 'cc'; -/** +/** * 界面配置结构体 * @help https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037986&doc_id=2873565 * @example diff --git a/assets/core/gui/prompt/LoadingIndicator.ts b/assets/core/gui/prompt/LoadingIndicator.ts index efeb511..b2c253f 100644 --- a/assets/core/gui/prompt/LoadingIndicator.ts +++ b/assets/core/gui/prompt/LoadingIndicator.ts @@ -4,23 +4,23 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 14:08:39 */ -import { Component, Node, _decorator } from "cc"; +import { Component, Node, _decorator } from 'cc'; const { ccclass, property } = _decorator; /** 加载延时提示动画 */ -@ccclass("LoadingIndicator") +@ccclass('LoadingIndicator') export class LoadingIndicator extends Component { @property(Node) private loading: Node | null = null; - private loading_rotate: number = 0; + private loading_rotate = 0; update(dt: number) { this.loading_rotate += dt * 220; - this.loading!.setRotationFromEuler(0, 0, -this.loading_rotate % 360) + this.loading!.setRotationFromEuler(0, 0, -this.loading_rotate % 360); if (this.loading_rotate > 360) { this.loading_rotate -= 360; } } -} \ No newline at end of file +} diff --git a/assets/core/gui/prompt/Notify.ts b/assets/core/gui/prompt/Notify.ts index c24b4c9..004bc4f 100644 --- a/assets/core/gui/prompt/Notify.ts +++ b/assets/core/gui/prompt/Notify.ts @@ -4,8 +4,8 @@ * @LastEditors: bansomin * @LastEditTime: 2025-01-02 10:47:47 */ -import { Animation, Component, Label, _decorator } from "cc"; -import { LanguageLabel } from "../../../libs/gui/language/LanguageLabel"; +import { Animation, Component, Label, _decorator } from 'cc'; +import { LanguageLabel } from '../../../libs/gui/language/LanguageLabel'; const { ccclass, property } = _decorator; @@ -38,7 +38,7 @@ export class Notify extends Component { * @param useI18n 设置为 true 时,使用多语言功能 msg 参数为多语言 key */ toast(msg: string, useI18n: boolean) { - let label = this.lab_content.getComponent(LanguageLabel)!; + const label = this.lab_content.getComponent(LanguageLabel)!; if (useI18n) { label.enabled = true; label.dataID = msg; @@ -48,4 +48,4 @@ export class Notify extends Component { this.lab_content.string = msg; } } -} \ No newline at end of file +} diff --git a/assets/core/utils/ArrayUtil.ts b/assets/core/utils/ArrayUtil.ts index cd26962..c463e48 100644 --- a/assets/core/utils/ArrayUtil.ts +++ b/assets/core/utils/ArrayUtil.ts @@ -31,10 +31,10 @@ export class ArrayUtil { /** * 复制二维数组 - * @param array 目标数组 + * @param array 目标数组 */ static copy2DArray(array: any[][]): any[][] { - let newArray: any[][] = []; + const newArray: any[][] = []; for (let i = 0; i < array.length; i++) { newArray.push(array[i].concat()); } @@ -48,8 +48,8 @@ export class ArrayUtil { static fisherYatesShuffle(array: any[]): any[] { let count = array.length; while (count) { - let index = Math.floor(Math.random() * count--); - let temp = array[count]; + const index = Math.floor(Math.random() * count--); + const temp = array[count]; array[count] = array[index]; array[index] = temp; } @@ -69,7 +69,7 @@ export class ArrayUtil { * @param array 目标数组 */ static flattening(array: any[]) { - for (; array.some(v => Array.isArray(v));) { // 判断 array 中是否有数组 + for (; array.some((v) => Array.isArray(v));) { // 判断 array 中是否有数组 array = [].concat.apply([], array); // 压扁数组 } return array; @@ -107,7 +107,7 @@ export class ArrayUtil { /** * 随机打乱数组 * @param array 目标数组 - * @example [1,2,3,4,5] --> [5, 1, 2, 3, 4] + * @example [1,2,3,4,5] --> [5, 1, 2, 3, 4] */ static shuffleArray(array: T[]): T[] { // 创建一个原数组的副本 @@ -127,7 +127,7 @@ export class ArrayUtil { * 获取连续数字数组, 范围在[start, end]之间 * @param start 开始数字 * @param end 结束数字 - * @example getNumsBetween(1, 10) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + * @example getNumsBetween(1, 10) => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */ static getNumsBetween(start: number, end: number): number[] { return Array.from({ length: end - start + 1 }, (_, i) => start + i); diff --git a/assets/core/utils/CameraUtil.ts b/assets/core/utils/CameraUtil.ts index f343053..8f826f4 100644 --- a/assets/core/utils/CameraUtil.ts +++ b/assets/core/utils/CameraUtil.ts @@ -4,7 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 14:50:16 */ -import { Camera, Vec3, view } from "cc"; +import type { Camera } from 'cc'; +import { Vec3, view } from 'cc'; /** 摄像机工具 */ export class CameraUtil { @@ -28,4 +29,4 @@ export class CameraUtil { && (viewPos.x <= viewportRect.width) && (viewPos.x >= 0) && (viewPos.y <= viewportRect.height) && (viewPos.y >= 0); } -} \ No newline at end of file +} diff --git a/assets/core/utils/DeviceUtil.ts b/assets/core/utils/DeviceUtil.ts index 02d4826..ed0712e 100644 --- a/assets/core/utils/DeviceUtil.ts +++ b/assets/core/utils/DeviceUtil.ts @@ -1,4 +1,4 @@ -import { sys } from "cc"; +import { sys } from 'cc'; /** 设备工具 */ export class DeviceUtil { @@ -8,53 +8,87 @@ export class DeviceUtil { } /** 当前平台 */ - static get platform() { return sys.platform; } + static get platform() { + return sys.platform; + } /** 当前操作系统 */ - static get os() { return sys.os; } + static get os() { + return sys.os; + } /** 是否为原生环境 */ - static get isNative() { return sys.isNative; } + static get isNative() { + return sys.isNative; + } /** 是否为浏览器环境 */ - static get isBrowser() { return sys.isBrowser; } + static get isBrowser() { + return sys.isBrowser; + } /** 是否为手机 */ - static get isMobile() { return sys.isMobile; } + static get isMobile() { + return sys.isMobile; + } /** 是否为安卓手机 */ - static get isAndroid() { return sys.platform === sys.Platform.ANDROID; } + static get isAndroid() { + return sys.platform === sys.Platform.ANDROID; + } /** 是否为苹果手机 */ - static get isIPhone() { return sys.platform === sys.Platform.IOS; } + static get isIPhone() { + return sys.platform === sys.Platform.IOS; + } /** 是否为手机浏览器 */ - static get isMobileBrowser() { return sys.platform === sys.Platform.MOBILE_BROWSER; } + static get isMobileBrowser() { + return sys.platform === sys.Platform.MOBILE_BROWSER; + } /** 是否为桌面浏览器 */ - static get isDesktopBrowser() { return sys.platform === sys.Platform.DESKTOP_BROWSER; } + static get isDesktopBrowser() { + return sys.platform === sys.Platform.DESKTOP_BROWSER; + } /** 是否为微信小游戏 */ - static get isWeChat() { return sys.platform === sys.Platform.WECHAT_GAME; } + static get isWeChat() { + return sys.platform === sys.Platform.WECHAT_GAME; + } /** 是否为字节小游戏 */ - static get isByteDance() { return sys.platform === sys.Platform.BYTEDANCE_MINI_GAME; } + static get isByteDance() { + return sys.platform === sys.Platform.BYTEDANCE_MINI_GAME; + } /** 是否为 vivo 小游戏 */ - static get isVivo() { return sys.platform === sys.Platform.VIVO_MINI_GAME; } + static get isVivo() { + return sys.platform === sys.Platform.VIVO_MINI_GAME; + } /** 是否为 OPPO 小游戏 */ - static get isOPPO() { return sys.platform === sys.Platform.OPPO_MINI_GAME; } + static get isOPPO() { + return sys.platform === sys.Platform.OPPO_MINI_GAME; + } /** 是否为小米小游戏 */ - static get isXiaomi() { return sys.platform === sys.Platform.XIAOMI_QUICK_GAME; } + static get isXiaomi() { + return sys.platform === sys.Platform.XIAOMI_QUICK_GAME; + } /** 是否为华为小游戏 */ - static get isHuawei() { return sys.platform === sys.Platform.HUAWEI_QUICK_GAME; } + static get isHuawei() { + return sys.platform === sys.Platform.HUAWEI_QUICK_GAME; + } /** 是否为支付宝小游戏 */ - static get isAlipay() { return sys.platform === sys.Platform.ALIPAY_MINI_GAME; } + static get isAlipay() { + return sys.platform === sys.Platform.ALIPAY_MINI_GAME; + } /** 是否为开源鸿蒙小游戏 */ - static get isOpenHarmony() { return sys.platform === sys.Platform.OPENHARMONY; } + static get isOpenHarmony() { + return sys.platform === sys.Platform.OPENHARMONY; + } } diff --git a/assets/core/utils/EncryptUtil.ts b/assets/core/utils/EncryptUtil.ts index 597aa1c..5b5a6ec 100644 --- a/assets/core/utils/EncryptUtil.ts +++ b/assets/core/utils/EncryptUtil.ts @@ -52,4 +52,4 @@ // // 将解密结果从WordArray转换为UTF-8字符串 // return decrypted.toString(Utf8); // } -// } \ No newline at end of file +// } diff --git a/assets/core/utils/ImageUtil.ts b/assets/core/utils/ImageUtil.ts index 839f7b9..2aa47fe 100644 --- a/assets/core/utils/ImageUtil.ts +++ b/assets/core/utils/ImageUtil.ts @@ -4,7 +4,7 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 14:49:42 */ -import { Color, Texture2D } from "cc"; +import { Color, Texture2D } from 'cc'; /** * 图像工具 @@ -42,7 +42,7 @@ cc.color(50, 100, 123, 255); * @param callback 完成回调 */ static imageToBase64(url: string, callback?: (dataURL: string) => void): Promise { - return new Promise(res => { + return new Promise((res) => { let extname = /\.png|\.jpg|\.jpeg/.exec(url)?.[0]; //@ts-ignore if (['.png', '.jpg', '.jpeg'].includes(extname)) { @@ -60,12 +60,12 @@ cc.color(50, 100, 123, 255); res(dataURL); image.remove(); canvas.remove(); - } + }; } else { console.warn('Not a jpg/jpeg or png resource!'); - callback && callback(""); - res(""); + callback && callback(''); + res(''); } }); } diff --git a/assets/core/utils/JsonUtil.ts b/assets/core/utils/JsonUtil.ts index 3e638d8..06b7fcd 100644 --- a/assets/core/utils/JsonUtil.ts +++ b/assets/core/utils/JsonUtil.ts @@ -5,14 +5,14 @@ * @LastEditTime: 2023-08-22 15:48:02 */ -import { JsonAsset } from "cc"; -import { ZipLoader } from "db://oops-framework/core/common/loader/ZipLoader"; -import { resLoader } from "../common/loader/ResLoader"; +import { JsonAsset } from 'cc'; +import { ZipLoader } from 'db://oops-framework/core/common/loader/ZipLoader'; +import { resLoader } from '../common/loader/ResLoader'; /** 资源路径 */ -const pathJson: string = "config/game/"; +const pathJson = 'config/game/'; /** 压缩包资源路径 */ -const pathZip: string = "config/game/game"; +const pathZip = 'config/game/game'; /** 数据缓存 */ const data: Map = new Map(); @@ -20,7 +20,7 @@ const data: Map = new Map(); /** JSON数据表工具 */ export class JsonUtil { /** 是否使用压缩包加载配置表 */ - static zip: boolean = false; + static zip = false; /** * 通知资源名从缓存中获取一个Json数据表 @@ -69,9 +69,9 @@ export class JsonUtil { static loadDir(): Promise { return new Promise(async (resolve, reject) => { if (this.zip) { - let zip = await ZipLoader.load(pathZip); - for (let key in zip.files) { - let name = key.replace(".json", ""); + const zip = await ZipLoader.load(pathZip); + for (const key in zip.files) { + const name = key.replace('.json', ''); data.set(name, ZipLoader.getJson(pathZip, `${name}.json`)); } ZipLoader.release(pathZip); @@ -84,7 +84,7 @@ export class JsonUtil { resolve(); } else { - assets.forEach(asset => { + assets.forEach((asset) => { data.set(asset.name, asset.json); }); resLoader.releaseDir(pathJson); @@ -107,4 +107,4 @@ export class JsonUtil { static clear() { data.clear(); } -} \ No newline at end of file +} diff --git a/assets/core/utils/LayerUtil.ts b/assets/core/utils/LayerUtil.ts index e6334d2..734363a 100644 --- a/assets/core/utils/LayerUtil.ts +++ b/assets/core/utils/LayerUtil.ts @@ -4,7 +4,7 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 12:05:38 */ -import { Node } from "cc"; +import type { Node } from 'cc'; /** 游戏摄像机层数据 */ export class LayerItem { @@ -58,7 +58,7 @@ export class LayerUtil { */ static setNodeLayer(item: LayerItem, node: Node): void { node.layer = item.mask; - node.children.forEach(n => { + node.children.forEach((n) => { n.layer = item.mask; LayerUtil.setNodeLayer(item, n); }); diff --git a/assets/core/utils/MathUtil.ts b/assets/core/utils/MathUtil.ts index de8e6ca..fafe6bf 100644 --- a/assets/core/utils/MathUtil.ts +++ b/assets/core/utils/MathUtil.ts @@ -13,7 +13,7 @@ export class MathUtil { /** * 获得随机方向 * @param x -1为左,1为右 - * @returns + * @returns */ static sign(x: number) { if (x > 0) { @@ -46,7 +46,7 @@ export class MathUtil { t = 1; } else if (t < 0) { - t = 0 + t = 0; } return numStart * (1 - t) + (numEnd * t); @@ -127,4 +127,4 @@ export class MathUtil { static probability(value: number) { return Math.random() < value; } -} \ No newline at end of file +} diff --git a/assets/core/utils/ObjectUtil.ts b/assets/core/utils/ObjectUtil.ts index b902147..5b1d86b 100644 --- a/assets/core/utils/ObjectUtil.ts +++ b/assets/core/utils/ObjectUtil.ts @@ -72,13 +72,13 @@ export class ObjectUtil { // 检查是否是特殊值 if (obj === Infinity || obj === -Infinity) return true; // 检测是否包含空格的字符串 - if (typeof obj === "string" && obj.trim() === "") return true; + if (typeof obj === 'string' && obj.trim() === '') return true; // 检查是否是无效的数字 if (Number.isNaN(obj)) return true; // 检查是否是空数组 if (Array.isArray(obj) && obj.length <= 0) return true; // 检查是否是空对象 - if (typeof (obj) == "object" && Object.keys(obj).length <= 0) return true; + if (typeof (obj) === 'object' && Object.keys(obj).length <= 0) return true; return false; } } diff --git a/assets/core/utils/PhysicsUtil.ts b/assets/core/utils/PhysicsUtil.ts index f8406ce..2b1438f 100644 --- a/assets/core/utils/PhysicsUtil.ts +++ b/assets/core/utils/PhysicsUtil.ts @@ -4,7 +4,7 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 14:40:28 */ -import { Node } from "cc"; +import type { Node } from 'cc'; /** 物理分组数据 */ export class GroupItem { @@ -49,9 +49,9 @@ export class PhysicsUtil { static setNodeLayer(item: GroupItem, node: Node) { node.layer = item.mask; - node.children.forEach(n => { + node.children.forEach((n) => { n.layer = item.mask; PhysicsUtil.setNodeLayer(item, n); }); } -} \ No newline at end of file +} diff --git a/assets/core/utils/PlatformUtil.ts b/assets/core/utils/PlatformUtil.ts index d9e2273..7e30a0d 100644 --- a/assets/core/utils/PlatformUtil.ts +++ b/assets/core/utils/PlatformUtil.ts @@ -3,7 +3,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 14:39:03 */ -import { __private, native, sys } from "cc"; +import type { __private } from 'cc'; +import { native, sys } from 'cc'; /** 平台数据 */ export class PlatformUtil { @@ -31,7 +32,7 @@ export class PlatformUtil { native.copyTextToClipboard(text); } else { - await navigator.clipboard.writeText(text) + await navigator.clipboard.writeText(text); } } } diff --git a/assets/core/utils/RotateUtil.ts b/assets/core/utils/RotateUtil.ts index 2691978..27fdb7d 100644 --- a/assets/core/utils/RotateUtil.ts +++ b/assets/core/utils/RotateUtil.ts @@ -4,8 +4,9 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 12:08:28 */ -import { Node, Quat, toRadian, Vec3 } from "cc"; -import { Vec3Util } from "./Vec3Util"; +import type { Node } from 'cc'; +import { Quat, toRadian, Vec3 } from 'cc'; +import { Vec3Util } from './Vec3Util'; /** 旋转工具 */ export class RotateUtil { @@ -34,8 +35,8 @@ export class RotateUtil { */ static rotateAroundTarget(lookAt: Node, target: Node, axis: Vec3, rad: number) { // 计算坐标 - const point_lookAt = lookAt.worldPosition; // 锚点坐标 - const point_target = target.worldPosition; // 目标坐标 + const point_lookAt = lookAt.worldPosition; // 锚点坐标 + const point_target = target.worldPosition; // 目标坐标 const quat = new Quat(); const vec3 = new Vec3(); @@ -62,8 +63,8 @@ export class RotateUtil { * @param angle 角度 */ static circularEdgePosition(center: Vec3, radius: number, angle: number): Vec3 { - const edge = Vec3Util.z.multiplyScalar(radius); // 距离圆心Z抽的距离 - const dir = Vec3Util.sub(edge, center); // 初始圆心与目标位置的方向 + const edge = Vec3Util.z.multiplyScalar(radius); // 距离圆心Z抽的距离 + const dir = Vec3Util.sub(edge, center); // 初始圆心与目标位置的方向 const vec3 = new Vec3(); const quat = new Quat(); @@ -76,4 +77,4 @@ export class RotateUtil { return vec3; } -} \ No newline at end of file +} diff --git a/assets/core/utils/StringUtil.ts b/assets/core/utils/StringUtil.ts index cfd43a1..eac0ed6 100644 --- a/assets/core/utils/StringUtil.ts +++ b/assets/core/utils/StringUtil.ts @@ -2,12 +2,12 @@ export class StringUtil { /** 获取一个唯一标识的字符串 */ static guid() { - let guid: string = ""; + let guid = ''; for (let i = 1; i <= 32; i++) { - let n = Math.floor(Math.random() * 16.0).toString(16); + const n = Math.floor(Math.random() * 16.0).toString(16); guid += n; if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) - guid += "-"; + guid += '-'; } return guid; } @@ -29,7 +29,7 @@ export class StringUtil { * @example * 12345 = 12.35K */ - static numberToThousand(value: number, fixed: number = 2): string { + static numberToThousand(value: number, fixed = 2): string { const k = 1000; const sizes = ['', 'K', 'M', 'G']; if (value < k) { @@ -49,7 +49,7 @@ export class StringUtil { * @example * 12345 = 1.23万 */ - static numberToTenThousand(value: number, fixed: number = 2): string { + static numberToTenThousand(value: number, fixed = 2): string { const k = 10000; const sizes = ['', '万', '亿', '万亿']; if (value < k) { @@ -66,10 +66,10 @@ export class StringUtil { * @param str 字符串 */ static stringToArray1(str: string) { - if (str == "") { + if (str == '') { return []; } - return str.split(","); + return str.split(','); } /** @@ -77,10 +77,10 @@ export class StringUtil { * @param str 字符串 */ static stringToArray2(str: string) { - if (str == "") { + if (str == '') { return []; } - return str.split("|"); + return str.split('|'); } /** @@ -88,10 +88,10 @@ export class StringUtil { * @param str 字符串 */ static stringToArray3(str: string) { - if (str == "") { + if (str == '') { return []; } - return str.split(":"); + return str.split(':'); } /** @@ -99,10 +99,10 @@ export class StringUtil { * @param str 字符串 */ static stringToArray4(str: string) { - if (str == "") { + if (str == '') { return []; } - return str.split(";"); + return str.split(';'); } /** @@ -111,14 +111,16 @@ export class StringUtil { * @param n 截取长度 * @param showdot 是否把截取的部分用省略号代替 */ - static sub(str: string, n: number, showdot: boolean = false) { + static sub(str: string, n: number, showdot = false) { const r = /[^\x00-\xff]/g; - if (str.replace(r, "mm").length <= n) { return str; } + if (str.replace(r, 'mm').length <= n) { + return str; + } const m = Math.floor(n / 2); for (let i = m; i < str.length; i++) { - if (str.substr(0, i).replace(r, "mm").length >= n) { + if (str.substr(0, i).replace(r, 'mm').length >= n) { if (showdot) { - return str.substr(0, i) + "..."; + return str.substr(0, i) + '...'; } else { return str.substr(0, i); @@ -177,8 +179,8 @@ export class StringUtil { args = rest; } - for (let i: number = 0; i < len; i++) { - str = str.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]); + for (let i = 0; i < len; i++) { + str = str.replace(new RegExp('\\{' + i + '\\}', 'g'), args[i]); } return str; diff --git a/assets/core/utils/TimeUtils.ts b/assets/core/utils/TimeUtils.ts index dfa57e1..d694830 100644 --- a/assets/core/utils/TimeUtils.ts +++ b/assets/core/utils/TimeUtils.ts @@ -4,16 +4,16 @@ export class TimeUtil { * 间隔天数 * @param time1 开始时间 * @param time2 结束时间 - * @returns + * @returns */ static daysBetween(time1: number | string | Date, time2: number | string | Date): number { if (time2 == undefined) { time2 = +new Date(); } - let startDate = new Date(time1).toLocaleDateString() - let endDate = new Date(time2).toLocaleDateString() - let startTime = new Date(startDate).getTime(); - let endTime = new Date(endDate).getTime(); + const startDate = new Date(time1).toLocaleDateString(); + const endDate = new Date(time2).toLocaleDateString(); + const startTime = new Date(startDate).getTime(); + const endTime = new Date(endDate).getTime(); return Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24); } @@ -32,24 +32,24 @@ export class TimeUtil { return new Promise((resolve) => { setTimeout(() => { resolve(); - }, ms) + }, ms); }); } /** 格式化字符串 */ static format(countDown: number) { - let result: string = ""; + let result = ''; let c: number = countDown; - let date: number = Math.floor(c / 86400); + const date: number = Math.floor(c / 86400); c = c - date * 86400; let hours: number = Math.floor(c / 3600); c = c - hours * 3600; - let minutes: number = Math.floor(c / 60); + const minutes: number = Math.floor(c / 60); c = c - minutes * 60; - let seconds: number = c; + const seconds: number = c; if (date == 0 && hours == 0 && minutes == 0 && seconds == 0) { - result = "00:00:00"; + result = '00:00:00'; } else { hours += date * 24; @@ -60,7 +60,7 @@ export class TimeUtil { /** 个位数的时间数据将字符串补位 */ private static coverString(value: number) { - if (value < 10) return "0" + value; + if (value < 10) return '0' + value; return value.toString(); } -} \ No newline at end of file +} diff --git a/assets/core/utils/Vec3Util.ts b/assets/core/utils/Vec3Util.ts index 9aeb5bd..a9dc503 100644 --- a/assets/core/utils/Vec3Util.ts +++ b/assets/core/utils/Vec3Util.ts @@ -1,5 +1,5 @@ -import {Mat4, Vec3} from "cc"; -import {MathUtil} from "./MathUtil"; +import { Mat4, Vec3 } from 'cc'; +import { MathUtil } from './MathUtil'; /** 向量工具 */ export class Vec3Util { @@ -175,7 +175,7 @@ export class Vec3Util { */ static direction(pos1: Vec3, pos2: Vec3): Vec3 { const outPos: Vec3 = new Vec3(); - Vec3.subtract(outPos, pos2, pos1) + Vec3.subtract(outPos, pos2, pos1); return outPos.normalize(); } @@ -207,12 +207,13 @@ export class Vec3Util { static slerp(from: Vec3, to: Vec3, t: number): Vec3 { if (t <= 0) { return from; - } else if (t >= 1) { + } + else if (t >= 1) { return to; } - var dir: Vec3 = this.rotateTo(from, to, (Vec3.angle(from, to) / Math.PI * 180) * t); - var lenght: number = to.length() * t + from.length() * (1 - t); + const dir: Vec3 = this.rotateTo(from, to, (Vec3.angle(from, to) / Math.PI * 180) * t); + const lenght: number = to.length() * t + from.length() * (1 - t); return (dir.normalize()).multiplyScalar(lenght); } @@ -229,7 +230,7 @@ export class Vec3Util { return to; } - const axis: Vec3 = new Vec3(); // 获得旋转轴 + const axis: Vec3 = new Vec3(); // 获得旋转轴 Vec3.cross(axis, from, to); axis.normalize(); @@ -254,12 +255,13 @@ export class Vec3Util { static bezierOne(t: number, posStart: Vec3, posEnd: Vec3): Vec3 { if (t > 1) { t = 1; - } else if (t < 0) { - t = 0 + } + else if (t < 0) { + t = 0; } - var pStart: Vec3 = posStart.clone(); - var pEnd: Vec3 = posEnd.clone(); + const pStart: Vec3 = posStart.clone(); + const pEnd: Vec3 = posEnd.clone(); return pStart.multiplyScalar(1 - t).add(pEnd.multiplyScalar(t)); } @@ -275,8 +277,9 @@ export class Vec3Util { static bezierTwo(t: number, posStart: Vec3, posCon: Vec3, posEnd: Vec3): Vec3 { if (t > 1) { t = 1; - } else if (t < 0) { - t = 0 + } + else if (t < 0) { + t = 0; } const n = (1 - t); @@ -307,8 +310,9 @@ export class Vec3Util { static bezierThree(t: number, posStart: Vec3, posCon1: Vec3, posCon2: Vec3, posEnd: Vec3): Vec3 { if (t > 1) { t = 1; - } else if (t < 0) { - t = 0 + } + else if (t < 0) { + t = 0; } const n = (1 - t); @@ -387,4 +391,4 @@ export class Vec3Util { return angle * sign; } -} \ No newline at end of file +} diff --git a/assets/core/utils/ViewUtil.ts b/assets/core/utils/ViewUtil.ts index 495959c..65156a0 100644 --- a/assets/core/utils/ViewUtil.ts +++ b/assets/core/utils/ViewUtil.ts @@ -4,8 +4,9 @@ * @LastEditors: dgflash * @LastEditTime: 2023-01-19 14:52:12 */ -import { Animation, AnimationClip, EventTouch, instantiate, Node, Prefab, Size, UITransform, v3, Vec3 } from "cc"; -import { resLoader } from "../common/loader/ResLoader"; +import type { EventTouch, Node, Vec3 } from 'cc'; +import { Animation, AnimationClip, instantiate, Prefab, Size, UITransform, v3 } from 'cc'; +import { resLoader } from '../common/loader/ResLoader'; /** 显示对象工具 */ export class ViewUtil { @@ -16,10 +17,10 @@ export class ViewUtil { * @param obj 绑定的js对象 (可选) */ static nodeTreeInfoLite(parent: Node, obj?: Map): Map | null { - let map: Map = obj || new Map(); - let items = parent.children; + const map: Map = obj || new Map(); + const items = parent.children; for (let i = 0; i < items.length; i++) { - let _node = items[i]; + const _node = items[i]; if (_node.name.length > 0) { if (map.has(_node.name)) console.error(`使用ViewUtil.nodeTreeInfoLite方法时发现重复的节点名称【${_node.name}】`); @@ -38,10 +39,10 @@ export class ViewUtil { * @param nodes 返回的数组(可选) */ static findNodes(reg: RegExp, parent: Node, nodes?: Array): Array { - let ns: Array = nodes || []; - let items = parent.children; + const ns: Array = nodes || []; + const items = parent.children; for (let i = 0; i < items.length; i++) { - let _name: string = items[i].name; + const _name: string = items[i].name; if (reg.test(_name)) { ns.push(items[i]); } @@ -125,7 +126,7 @@ export class ViewUtil { * @param onlyOne 是否唯一 * @param isDefaultClip 是否播放默认动画剪辑 */ - static addNodeAnimation(path: string, node: Node, onlyOne: boolean = true, isDefaultClip: boolean = false) { + static addNodeAnimation(path: string, node: Node, onlyOne = true, isDefaultClip = false) { if (!node || !node.isValid) { return; } @@ -159,9 +160,9 @@ export class ViewUtil { if (anim.getState(clip.name)) { anim.play(clip.name); - return + return; } anim.createState(clip, clip!.name); anim.play(clip!.name); } -} \ No newline at end of file +} diff --git a/assets/libs/animator-effect/2d/Ambilight.ts b/assets/libs/animator-effect/2d/Ambilight.ts index 24537dc..ba29296 100644 --- a/assets/libs/animator-effect/2d/Ambilight.ts +++ b/assets/libs/animator-effect/2d/Ambilight.ts @@ -1,12 +1,13 @@ -import { CCInteger, Component, Material, Sprite, _decorator } from 'cc'; +import type { Material } from 'cc'; +import { CCInteger, Component, Sprite, _decorator } from 'cc'; const { ccclass, property } = _decorator; @ccclass('Ambilight') /** 流光效果 */ export class Ambilight extends Component { @property - _max: number = 1; + _max = 1; @property(CCInteger) get max(): number { return this._max; diff --git a/assets/libs/animator-effect/2d/FlashSpine.ts b/assets/libs/animator-effect/2d/FlashSpine.ts index bb03de1..f746b22 100644 --- a/assets/libs/animator-effect/2d/FlashSpine.ts +++ b/assets/libs/animator-effect/2d/FlashSpine.ts @@ -3,9 +3,9 @@ const { ccclass, property } = _decorator; @ccclass('FlashSpine') export default class FlashSpine extends Component { - duration: number = 0.5; - _median: number = 0; - _time: number = 0; + duration = 0.5; + _median = 0; + _time = 0; _material: Material = null!; _skeleton: sp.Skeleton = null!; @@ -16,7 +16,7 @@ export default class FlashSpine extends Component { this._skeleton = this.node.getComponent(sp.Skeleton)!; this._material = this._skeleton.customMaterial!; // 设置材质对应的属性 - this._material.setProperty("u_rate", 1); + this._material.setProperty('u_rate', 1); } update(dt: number) { @@ -24,15 +24,15 @@ export default class FlashSpine extends Component { this._time -= dt; this._time = this._time < 0 ? 0 : this._time; - let rate = Math.abs(this._time - this._median) * 2 / this.duration; + const rate = Math.abs(this._time - this._median) * 2 / this.duration; - let mat = new Material(); + const mat = new Material(); mat.copy(this._material); this._skeleton.customMaterial = mat; - mat.setProperty("u_rate", rate); + mat.setProperty('u_rate', rate); } } - + clickFlash() { this._time = this.duration; } diff --git a/assets/libs/animator-effect/2d/FlashSprite.ts b/assets/libs/animator-effect/2d/FlashSprite.ts index 55116b2..7958758 100644 --- a/assets/libs/animator-effect/2d/FlashSprite.ts +++ b/assets/libs/animator-effect/2d/FlashSprite.ts @@ -1,11 +1,12 @@ -import { Component, Material, Sprite, _decorator } from 'cc'; +import type { Material } from 'cc'; +import { Component, Sprite, _decorator } from 'cc'; const { ccclass, property } = _decorator; @ccclass('FlashSprite') export default class FlashSprite extends Component { - duration: number = 0.5; - _median: number = 0; - _time: number = 0; + duration = 0.5; + _median = 0; + _time = 0; _material: Material = null!; @@ -14,7 +15,7 @@ export default class FlashSprite extends Component { // 获取材质 this._material = this.node.getComponent(Sprite)!.getMaterial(0)!; // 设置材质对应的属性 - this._material.setProperty("u_rate", 1); + this._material.setProperty('u_rate', 1); } update(dt: number) { @@ -22,8 +23,8 @@ export default class FlashSprite extends Component { this._time -= dt; this._time = this._time < 0 ? 0 : this._time; - let rate = Math.abs(this._time - this._median) * 2 / this.duration; - this._material.setProperty("u_rate", rate); + const rate = Math.abs(this._time - this._median) * 2 / this.duration; + this._material.setProperty('u_rate', rate); } } diff --git a/assets/libs/animator-effect/2d/SpineFinishedRelease.ts b/assets/libs/animator-effect/2d/SpineFinishedRelease.ts index e8b59a4..d21dae4 100644 --- a/assets/libs/animator-effect/2d/SpineFinishedRelease.ts +++ b/assets/libs/animator-effect/2d/SpineFinishedRelease.ts @@ -13,7 +13,7 @@ const { ccclass, property } = _decorator; @ccclass('SpineFinishedRelease') export class SpineFinishedRelease extends Component { @property - isDestroy: boolean = true; + isDestroy = true; private spine!: sp.Skeleton; private resPath: string = null!; @@ -31,15 +31,15 @@ export class SpineFinishedRelease extends Component { this.loadSkeletonData(); } else { - this.spine.setAnimation(0, "animation", false); + this.spine.setAnimation(0, 'animation', false); } } private async loadSkeletonData() { - let sd = await oops.res.load(this.resPath, sp.SkeletonData); + const sd = await oops.res.load(this.resPath, sp.SkeletonData); if (sd) { this.spine.skeletonData = sd; - this.spine.setAnimation(0, "animation", false); + this.spine.setAnimation(0, 'animation', false); } } diff --git a/assets/libs/animator-effect/Effect2DFollow3D.ts b/assets/libs/animator-effect/Effect2DFollow3D.ts index 06293cc..64cbbfd 100644 --- a/assets/libs/animator-effect/Effect2DFollow3D.ts +++ b/assets/libs/animator-effect/Effect2DFollow3D.ts @@ -5,26 +5,27 @@ * @LastEditTime: 2022-09-22 14:53:47 */ -import {_decorator, Camera, Component, Node, Vec3} from "cc"; -import {oops} from "../../core/Oops"; -import {MathUtil} from "../../core/utils/MathUtil"; +import type { Camera } from 'cc'; +import { _decorator, Component, Node, Vec3 } from 'cc'; +import { oops } from '../../core/Oops'; +import { MathUtil } from '../../core/utils/MathUtil'; const { ccclass, property } = _decorator; /** 2D节点跟随3D节点 */ -@ccclass("Effect2DFollow3D") +@ccclass('Effect2DFollow3D') export class Effect2DFollow3D extends Component { /** 3D世界节点 */ @property({ type: Node }) - node3d: Node = null!; + node3d: Node = null!; /** 2D界面界面 */ @property({ type: Node }) - nodeUi: Node = null!; + nodeUi: Node = null!; /** 距离 */ @property - distance: number = 10; + distance = 10; /** 3D摄像机 */ camera: Camera = null!; diff --git a/assets/libs/animator-effect/EffectDelayRelease.ts b/assets/libs/animator-effect/EffectDelayRelease.ts index 62582c6..a0ff0cc 100644 --- a/assets/libs/animator-effect/EffectDelayRelease.ts +++ b/assets/libs/animator-effect/EffectDelayRelease.ts @@ -14,7 +14,7 @@ const { ccclass, property } = _decorator; export class EffectDelayRelease extends Component { /** 延时释放时间(单位秒) */ @property - public delay: number = 1; + delay = 1; protected onEnable() { this.scheduleOnce(this.onDelay, this.delay); diff --git a/assets/libs/animator-effect/EffectEvent.ts b/assets/libs/animator-effect/EffectEvent.ts index 22a8d98..3f71611 100644 --- a/assets/libs/animator-effect/EffectEvent.ts +++ b/assets/libs/animator-effect/EffectEvent.ts @@ -1,5 +1,5 @@ /** 特效管理模块事件 */ export enum EffectEvent { /** 回收节点 */ - Put = "EffectEvent_Put" -} \ No newline at end of file + Put = 'EffectEvent_Put' +} diff --git a/assets/libs/animator-effect/EffectFinishedRelease.ts b/assets/libs/animator-effect/EffectFinishedRelease.ts index 434090a..14823b2 100644 --- a/assets/libs/animator-effect/EffectFinishedRelease.ts +++ b/assets/libs/animator-effect/EffectFinishedRelease.ts @@ -9,21 +9,21 @@ import { Animation, Component, ParticleSystem, _decorator, sp } from 'cc'; import { EffectEvent } from './EffectEvent'; import { message } from '../../core/common/event/MessageManager'; -const { ccclass, property } = _decorator; +const { ccclass } = _decorator; /** 动画播放完释放特效 - Animation、ParticleSystem */ @ccclass('EffectFinishedRelease') export class EffectFinishedRelease extends Component { /** 动画最大播放时间 */ - private maxDuration: number = 0; + private maxDuration = 0; protected onEnable() { // SPINE动画 - let spine = this.getComponent(sp.Skeleton); + const spine = this.getComponent(sp.Skeleton); if (spine) { // 播放第一个动画 - let json = (spine.skeletonData!.skeletonJson! as any).animations; - for (let name in json) { + const json = (spine.skeletonData!.skeletonJson! as any).animations; + for (const name in json) { spine.setCompleteListener(this.onRecovery.bind(this)); spine.setAnimation(0, name, false); break; @@ -31,14 +31,14 @@ export class EffectFinishedRelease extends Component { } else { // COCOS动画 - let anims: Animation[] = this.node.getComponentsInChildren(Animation); + const anims: Animation[] = this.node.getComponentsInChildren(Animation); if (anims.length > 0) { - anims.forEach(animator => { - let aniName = animator.defaultClip?.name; + anims.forEach((animator) => { + const aniName = animator.defaultClip?.name; if (aniName) { - let aniState = animator.getState(aniName); + const aniState = animator.getState(aniName); if (aniState) { - let duration = aniState.duration; + const duration = aniState.duration; this.maxDuration = duration > this.maxDuration ? duration : this.maxDuration; } } @@ -48,13 +48,13 @@ export class EffectFinishedRelease extends Component { } // 粒子动画 else if (ParticleSystem) { - let particles: ParticleSystem[] = this.node.getComponentsInChildren(ParticleSystem); - particles.forEach(particle => { + const particles: ParticleSystem[] = this.node.getComponentsInChildren(ParticleSystem); + particles.forEach((particle) => { particle.clear(); particle.stop(); - particle.play() + particle.play(); - let duration: number = particle.duration; + const duration: number = particle.duration; this.maxDuration = duration > this.maxDuration ? duration : this.maxDuration; }); this.scheduleOnce(this.onRecovery.bind(this), this.maxDuration); diff --git a/assets/libs/animator-effect/EffectSingleCase.ts b/assets/libs/animator-effect/EffectSingleCase.ts index 53c8d2c..ce94b05 100644 --- a/assets/libs/animator-effect/EffectSingleCase.ts +++ b/assets/libs/animator-effect/EffectSingleCase.ts @@ -4,7 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2023-03-06 14:40:34 */ -import { Animation, Node, NodePool, ParticleSystem, Prefab, sp, Vec3 } from 'cc'; +import type { Node, Vec3 } from 'cc'; +import { Animation, NodePool, ParticleSystem, Prefab, sp } from 'cc'; import { message } from '../../core/common/event/MessageManager'; import { resLoader } from '../../core/common/loader/ResLoader'; import { ViewUtil } from '../../core/utils/ViewUtil'; @@ -38,7 +39,7 @@ export class EffectSingleCase { return this._instance; } - private _speed: number = 1; + private _speed = 1; /** 全局动画播放速度 */ get speed(): number { return this._speed; @@ -70,7 +71,7 @@ export class EffectSingleCase { * @param path 预制资源路径 */ getCount(path: string): number { - var np = this.effects.get(path); + const np = this.effects.get(path); if (np) { return np.size(); } @@ -90,7 +91,7 @@ export class EffectSingleCase { await resLoader.load(bundleName, path, Prefab); for (let i = 0; i < count; i++) { - let node = ViewUtil.createPrefabNode(path, bundleName); + const node = ViewUtil.createPrefabNode(path, bundleName); //@ts-ignore node.res_path = path; np.put(node); @@ -107,7 +108,7 @@ export class EffectSingleCase { */ loadAndShow(path: string, parent?: Node, params?: IEffectParams): Promise { return new Promise(async (resolve, reject) => { - var np = this.effects.get(path); + const np = this.effects.get(path); if (np == undefined) { if (params && params.bundleName) { this.res.set(path, params.bundleName); @@ -135,16 +136,16 @@ export class EffectSingleCase { * @param params 显示参数 */ show(path: string, parent?: Node, params?: IEffectParams): Node { - var np = this.effects.get(path); + let np = this.effects.get(path); if (np == null) { np = new NodePool(); this.effects.set(path, np); } - var node: Node; + let node: Node; // 创建池中新显示对象 if (np.size() == 0) { - var bundleName = resLoader.defaultBundleName; + let bundleName = resLoader.defaultBundleName; if (params && params.bundleName) bundleName = params.bundleName; node = ViewUtil.createPrefabNode(path, bundleName); //@ts-ignore @@ -206,7 +207,7 @@ export class EffectSingleCase { if (np) np.clear(); } else { - this.effects.forEach(np => { + this.effects.forEach((np) => { np.clear(); }); this.effects.clear(); @@ -232,14 +233,14 @@ export class EffectSingleCase { this.res.forEach((bundleName: string, path: string) => { resLoader.release(path, bundleName); }); - this.res.clear() + this.res.clear(); } } /** 设置动画速度 */ private setSpeed(node: Node) { // SPINE动画 - let spine = node.getComponent(sp.Skeleton); + const spine = node.getComponent(sp.Skeleton); if (spine) { spine.timeScale = this.speed; } @@ -247,10 +248,10 @@ export class EffectSingleCase { // COCOS动画 const anims: Animation[] = node.getComponentsInChildren(Animation); if (anims.length > 0) { - anims.forEach(animator => { - let aniName = animator.defaultClip?.name; + anims.forEach((animator) => { + const aniName = animator.defaultClip?.name; if (aniName) { - let aniState = animator.getState(aniName); + const aniState = animator.getState(aniName); if (aniState) { aniState.speed = this.speed; } @@ -260,10 +261,10 @@ export class EffectSingleCase { // 粒子动画 else if (ParticleSystem) { const particles: ParticleSystem[] = node.getComponentsInChildren(ParticleSystem); - particles.forEach(particle => { + particles.forEach((particle) => { particle.simulationSpeed = this.speed; }); } } } -} \ No newline at end of file +} diff --git a/assets/libs/animator-move/MoveRigidBody.ts b/assets/libs/animator-move/MoveRigidBody.ts index bea6db3..f55d3ab 100644 --- a/assets/libs/animator-move/MoveRigidBody.ts +++ b/assets/libs/animator-move/MoveRigidBody.ts @@ -4,7 +4,7 @@ const { ccclass, property } = _decorator; const v3_0 = new Vec3(); const v3_1 = new Vec3(); -/** +/** * 物理方式移动 * 1. 施加线性数度 * 2. 施加阻尼 @@ -14,58 +14,60 @@ const v3_1 = new Vec3(); @ccclass('MoveRigidBody') export class MoveRigidBody extends Component { @property({ tooltip: '阻尼' }) - damping: number = 0.5; + damping = 0.5; @property({ tooltip: '重力' }) - gravity: number = -10; + gravity = -10; @property - private _speed: number = 5; + private _speed = 5; @property({ tooltip: '移动速度' }) - public get speed(): number { + get speed(): number { return this._speed; } - public set speed(value: number) { + set speed(value: number) { this._speed = value; this._curMaxSpeed = value * this.ratio; } @property - private _ratio: number = 1; + private _ratio = 1; @property({ tooltip: '速度比率' }) - public get ratio(): number { + get ratio(): number { return this._ratio; } - public set ratio(value: number) { + set ratio(value: number) { this._ratio = value; this._curMaxSpeed = this.speed * value; } private _rigidBody: RigidBody = null!; - private _grounded = true; // 是否着地 - private _curMaxSpeed: number = 0; // 当前最大速度 - private _prevAngleY: number = 0; // 之前的Y角度值 - private _stateX: number = 0; - private _stateZ: number = 0; + private _grounded = true; // 是否着地 + private _curMaxSpeed = 0; // 当前最大速度 + private _prevAngleY = 0; // 之前的Y角度值 + private _stateX = 0; + private _stateZ = 0; /** 是否着地 */ - get grounded() { return this._grounded; } + get grounded() { + return this._grounded; + } private _velocity: Vec3 = new Vec3(); /** 移动方向 */ - public get velocity(): Vec3 { + get velocity(): Vec3 { return this._velocity; } - public set velocity(value: Vec3) { + set velocity(value: Vec3) { this._velocity = value; - var x = value.x; - var z = value.z; + const x = value.x; + const z = value.z; if ((x > 0 && this._stateX < 0) || (x < 0 && this._stateX > 0) || (z > 0 && this._stateZ < 0) || (z < 0 && this._stateZ > 0)) { - this._rigidBody.clearVelocity(); // 当前跟之前方向不一致则清除速度,避免惯性太大 + this._rigidBody.clearVelocity(); // 当前跟之前方向不一致则清除速度,避免惯性太大 } this._stateX = x; @@ -81,7 +83,7 @@ export class MoveRigidBody extends Component { stop() { this._stateX = 0; this._stateZ = 0; - this._rigidBody.clearVelocity(); // 清除移动速度 + this._rigidBody.clearVelocity(); // 清除移动速度 } update(dt: number) { @@ -145,4 +147,4 @@ export class MoveRigidBody extends Component { this._rigidBody.setLinearVelocity(v3_1); } } -} \ No newline at end of file +} diff --git a/assets/libs/animator-move/MoveTo.ts b/assets/libs/animator-move/MoveTo.ts index 5addcf3..176fb9e 100644 --- a/assets/libs/animator-move/MoveTo.ts +++ b/assets/libs/animator-move/MoveTo.ts @@ -5,9 +5,9 @@ * @LastEditors: dgflash * @LastEditTime: 2023-01-19 14:59:50 */ -import { Component, Node, Vec3, _decorator } from "cc"; -import { Timer } from "../../core/common/timer/Timer"; -import { Vec3Util } from "../../core/utils/Vec3Util"; +import { Component, Node, Vec3, _decorator } from 'cc'; +import { Timer } from '../../core/common/timer/Timer'; +import { Vec3Util } from '../../core/utils/Vec3Util'; const { ccclass, property } = _decorator; @@ -19,14 +19,14 @@ export class MoveTo extends Component { /** 移动方向 */ velocity: Vec3 = Vec3Util.zero; /** 移动速度(每秒移动的像素距离) */ - speed: number = 0; + speed = 0; /** 是否计算将 Y 轴带入计算 */ - hasYAxis: boolean = true; + hasYAxis = true; /** 坐标标(默认本地坐标) */ ns: number = Node.NodeSpace.LOCAL; /** 偏移距离 */ - offset: number = 0; + offset = 0; /** 偏移向量 */ offsetVector: Vec3 | null = null; /** 移动开始 */ @@ -53,7 +53,7 @@ export class MoveTo extends Component { let end: Vec3; if (this.speed <= 0) { - console.error("移动速度必须要大于零"); + console.error('移动速度必须要大于零'); return; } @@ -80,11 +80,11 @@ export class MoveTo extends Component { if (this.hasYAxis == false) target.y = 0; // 移动方向与移动数度 - let start = this.ns == Node.NodeSpace.WORLD ? this.node.worldPosition : this.node.position; + const start = this.ns == Node.NodeSpace.WORLD ? this.node.worldPosition : this.node.position; this.velocity = Vec3Util.sub(target, start).normalize(); // 移动时间与目标偏位置计算 - let distance = Vec3.distance(start, target) - this.offset; + const distance = Vec3.distance(start, target) - this.offset; // 目标位置修改事件 this.onChange?.call(this); @@ -101,7 +101,7 @@ export class MoveTo extends Component { } if (this.speed > 0) { - let trans = Vec3Util.mul(this.velocity, this.speed * dt); + const trans = Vec3Util.mul(this.velocity, this.speed * dt); if (this.ns == Node.NodeSpace.WORLD) this.node.worldPosition = Vec3Util.add(this.node.worldPosition, trans); else @@ -137,4 +137,4 @@ export class MoveTo extends Component { this.timer.reset(); this.end = null; } -} \ No newline at end of file +} diff --git a/assets/libs/animator-move/MoveTranslate.ts b/assets/libs/animator-move/MoveTranslate.ts index 43fa98b..21e06e5 100644 --- a/assets/libs/animator-move/MoveTranslate.ts +++ b/assets/libs/animator-move/MoveTranslate.ts @@ -5,8 +5,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-07-25 11:52:23 */ -import { Component, Node, Vec3, _decorator } from "cc"; -import { Vec3Util } from "../../core/utils/Vec3Util"; +import { Component, Node, Vec3, _decorator } from 'cc'; +import { Vec3Util } from '../../core/utils/Vec3Util'; const { ccclass, property } = _decorator; @@ -16,7 +16,7 @@ export class MoveTranslate extends Component { /** 移动方向 */ velocity: Vec3 = Vec3Util.zero; /** 移动速度 */ - speed: number = 0; + speed = 0; private vector: Vec3 = new Vec3(); @@ -26,4 +26,4 @@ export class MoveTranslate extends Component { this.node.translate(this.vector, Node.NodeSpace.WORLD); } } -} \ No newline at end of file +} diff --git a/assets/libs/animator/AnimatorAnimation.ts b/assets/libs/animator/AnimatorAnimation.ts index 78185cc..2a6ccaa 100644 --- a/assets/libs/animator/AnimatorAnimation.ts +++ b/assets/libs/animator/AnimatorAnimation.ts @@ -1,10 +1,12 @@ -import { Animation, AnimationState, _decorator } from "cc"; -import AnimatorBase, { AnimationPlayer } from "./core/AnimatorBase"; -import { AnimatorStateLogic } from "./core/AnimatorStateLogic"; +import type { AnimationState } from 'cc'; +import { Animation, _decorator } from 'cc'; +import type { AnimationPlayer } from './core/AnimatorBase'; +import AnimatorBase from './core/AnimatorBase'; +import type { AnimatorStateLogic } from './core/AnimatorStateLogic'; const { ccclass, property, requireComponent, disallowMultiple, menu, help } = _decorator; -/** +/** * Cocos Animation状态机组件 */ @ccclass @@ -42,7 +44,7 @@ export default class AnimatorAnimation extends AnimatorBase { * - animationPlayer 自定义动画控制 * @override */ - public onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { + onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { if (this.PlayOnStart || this._hasInit) { return; } diff --git a/assets/libs/animator/AnimatorCustomization.ts b/assets/libs/animator/AnimatorCustomization.ts index 274c13d..d9b9fa4 100644 --- a/assets/libs/animator/AnimatorCustomization.ts +++ b/assets/libs/animator/AnimatorCustomization.ts @@ -1,10 +1,11 @@ -import { _decorator } from "cc"; -import AnimatorBase, { AnimationPlayer } from "./core/AnimatorBase"; -import { AnimatorStateLogic } from "./core/AnimatorStateLogic"; +import { _decorator } from 'cc'; +import type { AnimationPlayer } from './core/AnimatorBase'; +import AnimatorBase from './core/AnimatorBase'; +import type { AnimatorStateLogic } from './core/AnimatorStateLogic'; const { ccclass, property, disallowMultiple, menu, help } = _decorator; -/** +/** * 自定义动画控制的状态机组件 */ @ccclass @@ -14,7 +15,7 @@ const { ccclass, property, disallowMultiple, menu, help } = _decorator; export default class AnimatorCustomization extends AnimatorBase { /** 此组件必须主动调用onInit初始化 */ @property({ override: true, visible: false }) - PlayOnStart: boolean = false; + PlayOnStart = false; /** * 手动初始化状态机,可传入0-3个参数,类型如下 @@ -23,7 +24,7 @@ export default class AnimatorCustomization extends AnimatorBase { * - animationPlayer 自定义动画控制 * @override */ - public onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { + onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { if (this._hasInit) { return; } diff --git a/assets/libs/animator/AnimatorDragonBones.ts b/assets/libs/animator/AnimatorDragonBones.ts index 8c30222..5dcea46 100644 --- a/assets/libs/animator/AnimatorDragonBones.ts +++ b/assets/libs/animator/AnimatorDragonBones.ts @@ -1,10 +1,11 @@ -import { _decorator, dragonBones } from "cc"; -import AnimatorBase, { AnimationPlayer } from "./core/AnimatorBase"; -import { AnimatorStateLogic } from "./core/AnimatorStateLogic"; +import { _decorator, dragonBones } from 'cc'; +import type { AnimationPlayer } from './core/AnimatorBase'; +import AnimatorBase from './core/AnimatorBase'; +import type { AnimatorStateLogic } from './core/AnimatorStateLogic'; const { ccclass, property, requireComponent, disallowMultiple, menu, help } = _decorator; -/** +/** * DragonBones状态机组件 */ @ccclass @@ -37,7 +38,7 @@ export default class AnimatorDragonBones extends AnimatorBase { * - animationPlayer 自定义动画控制 * @override */ - public onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { + onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { if (this.PlayOnStart || this._hasInit) { return; } diff --git a/assets/libs/animator/AnimatorSkeletal.ts b/assets/libs/animator/AnimatorSkeletal.ts index 6466b95..4d7f6cc 100644 --- a/assets/libs/animator/AnimatorSkeletal.ts +++ b/assets/libs/animator/AnimatorSkeletal.ts @@ -18,12 +18,12 @@ const { ccclass, property, requireComponent, disallowMultiple, menu, help } = _d export class AnimatorSkeletal extends AnimatorAnimation { @property({ type: CCFloat, - tooltip: "动画切换过度时间" + tooltip: '动画切换过度时间' }) - private duration: number = 0.3; + private duration = 0.3; - private cross_duration: number = 0; // 防止切换动画时间少于间隔时间导致动画状态错乱的问题 - private current_time: number = 0; // 上一次切换状态时间 + private cross_duration = 0; // 防止切换动画时间少于间隔时间导致动画状态错乱的问题 + private current_time = 0; // 上一次切换状态时间 onLoad() { this.cross_duration = this.duration * 1000; @@ -56,6 +56,6 @@ export class AnimatorSkeletal extends AnimatorAnimation { this._wrapModeMap.set(this._animState, this._animState.wrapMode); } // this._animState.wrapMode = loop ? 2 : this._wrapModeMap.get(this._animState)!; - this._animState.wrapMode = loop ? 2 : 1; // 2为循环播放,1为单次播放 + this._animState.wrapMode = loop ? 2 : 1; // 2为循环播放,1为单次播放 } } diff --git a/assets/libs/animator/AnimatorSpine.ts b/assets/libs/animator/AnimatorSpine.ts index 0fd2fda..30503e1 100644 --- a/assets/libs/animator/AnimatorSpine.ts +++ b/assets/libs/animator/AnimatorSpine.ts @@ -1,11 +1,12 @@ -import { _decorator, sp } from "cc"; -import AnimatorSpineSecondary from "./AnimatorSpineSecondary"; -import AnimatorBase, { AnimationPlayer } from "./core/AnimatorBase"; -import { AnimatorStateLogic } from "./core/AnimatorStateLogic"; +import { _decorator, sp } from 'cc'; +import type AnimatorSpineSecondary from './AnimatorSpineSecondary'; +import type { AnimationPlayer } from './core/AnimatorBase'; +import AnimatorBase from './core/AnimatorBase'; +import type { AnimatorStateLogic } from './core/AnimatorStateLogic'; const { ccclass, property, requireComponent, disallowMultiple, menu, help } = _decorator; -/** +/** * Spine状态机组件(主状态机),trackIndex为0 */ @ccclass @@ -43,7 +44,7 @@ export default class AnimatorSpine extends AnimatorBase { * - animationPlayer 自定义动画控制 * @override */ - public onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { + onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { if (this.PlayOnStart || this._hasInit) { return; } @@ -62,13 +63,13 @@ export default class AnimatorSpine extends AnimatorBase { /** ---------- 后续扩展代码 开始 ---------- */ - public getBone(name: string): any { + getBone(name: string): any { const bone = this._spine.findBone(name); - return bone + return bone; } private onSpineEvent(trackEntry: any, event: any) { - const animationName = trackEntry.animation ? event.data.name : ""; + const animationName = trackEntry.animation ? event.data.name : ''; this._animationPlayer?.onFrameEventCallback(animationName, this); } @@ -76,8 +77,12 @@ export default class AnimatorSpine extends AnimatorBase { private onSpineComplete(entry: any) { entry.trackIndex === 0 && this.onAnimFinished(); - this._completeListenerMap.forEach((target, cb) => { target ? cb.call(target, entry) : cb(entry); }); - this._secondaryListenerMap.forEach((target, cb) => { entry.trackIndex === target.TrackIndex && cb.call(target, entry); }); + this._completeListenerMap.forEach((target, cb) => { + target ? cb.call(target, entry) : cb(entry); + }); + this._secondaryListenerMap.forEach((target, cb) => { + entry.trackIndex === target.TrackIndex && cb.call(target, entry); + }); } /** @@ -108,7 +113,7 @@ export default class AnimatorSpine extends AnimatorBase { /** * 注册次状态机动画结束的回调(状态机内部方法,不能由外部直接调用) */ - public addSecondaryListener(cb: (entry?: any) => void, target: AnimatorSpineSecondary) { + addSecondaryListener(cb: (entry?: any) => void, target: AnimatorSpineSecondary) { this._secondaryListenerMap.set(cb, target); } @@ -117,7 +122,7 @@ export default class AnimatorSpine extends AnimatorBase { * @param cb 回调 * @param target 调用回调的this对象 */ - public addCompleteListener(cb: (entry?: any) => void, target: any = null) { + addCompleteListener(cb: (entry?: any) => void, target: any = null) { if (this._completeListenerMap.has(cb)) { return; } @@ -128,14 +133,14 @@ export default class AnimatorSpine extends AnimatorBase { * 注销动画完成的监听 * @param cb 回调 */ - public removeCompleteListener(cb: (entry?: any) => void) { + removeCompleteListener(cb: (entry?: any) => void) { this._completeListenerMap.delete(cb); } /** * 清空动画完成的监听 */ - public clearCompleteListener() { + clearCompleteListener() { this._completeListenerMap.clear; } } diff --git a/assets/libs/animator/AnimatorSpineSecondary.ts b/assets/libs/animator/AnimatorSpineSecondary.ts index 60af756..15ab56a 100644 --- a/assets/libs/animator/AnimatorSpineSecondary.ts +++ b/assets/libs/animator/AnimatorSpineSecondary.ts @@ -1,11 +1,12 @@ -import { _decorator, sp } from "cc"; -import AnimatorSpine from "./AnimatorSpine"; -import AnimatorBase, { AnimationPlayer } from "./core/AnimatorBase"; -import { AnimatorStateLogic } from "./core/AnimatorStateLogic"; +import { _decorator, sp } from 'cc'; +import AnimatorSpine from './AnimatorSpine'; +import type { AnimationPlayer } from './core/AnimatorBase'; +import AnimatorBase from './core/AnimatorBase'; +import type { AnimatorStateLogic } from './core/AnimatorStateLogic'; const { ccclass, property, requireComponent, menu, help } = _decorator; -/** +/** * Spine状态机组件(次状态机),同一节点可添加多个,用于在不同track中播放动画,trackIndex必须大于0 */ @ccclass @@ -13,7 +14,7 @@ const { ccclass, property, requireComponent, menu, help } = _decorator; @menu('OopsFramework/Animator/AnimatorSpine (Spine 次状态机)') @help('https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12036279&doc_id=2873565') export default class AnimatorSpineSecondary extends AnimatorBase { - @property({ tooltip: '动画播放的trackIndex,必须大于0' }) TrackIndex: number = 1; + @property({ tooltip: '动画播放的trackIndex,必须大于0' }) TrackIndex = 1; /** 主状态机 */ private _main: AnimatorSpine = null!; @@ -42,7 +43,7 @@ export default class AnimatorSpineSecondary extends AnimatorBase { * - animationPlayer 自定义动画控制 * @override */ - public onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { + onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { if (this.PlayOnStart || this._hasInit) { return; } diff --git a/assets/libs/animator/core/AnimatorBase.ts b/assets/libs/animator/core/AnimatorBase.ts index d945d10..81a229e 100644 --- a/assets/libs/animator/core/AnimatorBase.ts +++ b/assets/libs/animator/core/AnimatorBase.ts @@ -1,7 +1,7 @@ import { Component, JsonAsset, _decorator } from 'cc'; -import AnimatorController from "./AnimatorController"; -import AnimatorState from "./AnimatorState"; -import { AnimatorStateLogic } from './AnimatorStateLogic'; +import AnimatorController from './AnimatorController'; +import type AnimatorState from './AnimatorState'; +import type { AnimatorStateLogic } from './AnimatorStateLogic'; const { ccclass, property, executionOrder, menu } = _decorator; @@ -36,16 +36,16 @@ export default class AnimatorBase extends Component { /** ---------- 后续扩展代码 结束 ---------- */ @property({ type: JsonAsset, tooltip: '状态机json文件' }) - AssetRawUrl: JsonAsset = null!; + AssetRawUrl: JsonAsset = null!; @property({ tooltip: '是否在start中自动启动状态机' }) - PlayOnStart: boolean = true; + PlayOnStart = true; @property({ tooltip: '是否在update中自动触发状态机逻辑更新' }) - AutoUpdate: boolean = true; + AutoUpdate = true; /** 是否初始化 */ - protected _hasInit: boolean = false; + protected _hasInit = false; /** 状态机控制 */ protected _ac: AnimatorController = null!; @@ -57,16 +57,16 @@ export default class AnimatorBase extends Component { protected _animationPlayer: AnimationPlayer = null!; /** 当前状态名 */ - public get curStateName(): string { + get curStateName(): string { return this._ac.curState.name; } /** 当前动画名 */ - public get curStateMotion(): string { + get curStateMotion(): string { return this._ac.curState.motion; } /** 获取指定状态 */ - public getState(name: string): AnimatorState | undefined { + getState(name: string): AnimatorState | undefined { return this._ac.states.get(name); } @@ -77,7 +77,7 @@ export default class AnimatorBase extends Component { * - animationPlayer 自定义动画控制 * @virtual */ - public onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { + onInit(...args: Array | ((fromState: string, toState: string) => void) | AnimationPlayer>) { } /** @@ -112,7 +112,7 @@ export default class AnimatorBase extends Component { // 更新动画状态逻辑 if (this._stateLogicMap) { - let curLogic = this._stateLogicMap.get(this._ac.curState.name); + const curLogic = this._stateLogicMap.get(this._ac.curState.name); curLogic && curLogic.onUpdate(); } @@ -129,7 +129,7 @@ export default class AnimatorBase extends Component { /** * 手动调用更新 */ - public manualUpdate() { + manualUpdate() { if (this._hasInit && !this.AutoUpdate) { this.updateAnimator(); } @@ -167,18 +167,18 @@ export default class AnimatorBase extends Component { protected scaleTime(scale: number) { } - /** + /** * 状态切换时的逻辑(状态机内部方法,不能由外部直接调用) */ - public onStateChange(fromState: AnimatorState, toState: AnimatorState) { + onStateChange(fromState: AnimatorState, toState: AnimatorState) { this.playAnimation(toState.motion, toState.loop); - let fromStateName = fromState ? fromState.name : ''; + const fromStateName = fromState ? fromState.name : ''; if (this._stateLogicMap) { - let fromLogic = this._stateLogicMap.get(fromStateName); + const fromLogic = this._stateLogicMap.get(fromStateName); fromLogic && fromLogic.onExit(); - let toLogic = this._stateLogicMap.get(toState.name); + const toLogic = this._stateLogicMap.get(toState.name); toLogic && toLogic.onEntry(); } @@ -188,49 +188,49 @@ export default class AnimatorBase extends Component { /** * 设置boolean类型参数的值 */ - public setBool(key: string, value: boolean) { + setBool(key: string, value: boolean) { this._ac.params.setBool(key, value); } /** * 获取boolean类型参数的值 */ - public getBool(key: string): boolean { + getBool(key: string): boolean { return this._ac.params.getBool(key) !== 0; } /** * 设置number类型参数的值 */ - public setNumber(key: string, value: number) { + setNumber(key: string, value: number) { this._ac.params.setNumber(key, value); } /** * 获取number类型参数的值 */ - public getNumber(key: string): number { + getNumber(key: string): number { return this._ac.params.getNumber(key); } /** * 设置trigger类型参数的值 */ - public setTrigger(key: string) { + setTrigger(key: string) { this._ac.params.setTrigger(key); } /** * 重置trigger类型参数的值 */ - public resetTrigger(key: string) { + resetTrigger(key: string) { this._ac.params.resetTrigger(key); } /** * 设置autoTrigger类型参数的值(autoTrigger类型参数不需要主动reset,每次状态机更新结束后会自动reset) */ - public autoTrigger(key: string) { + autoTrigger(key: string) { this._ac.params.autoTrigger(key); } @@ -238,7 +238,7 @@ export default class AnimatorBase extends Component { * 无视条件直接跳转状态 * @param 状态名 */ - public play(stateName: string) { + play(stateName: string) { if (!this._hasInit) { return; } diff --git a/assets/libs/animator/core/AnimatorCondition.ts b/assets/libs/animator/core/AnimatorCondition.ts index 7d86291..1e7fc9a 100644 --- a/assets/libs/animator/core/AnimatorCondition.ts +++ b/assets/libs/animator/core/AnimatorCondition.ts @@ -1,5 +1,5 @@ -import { error } from "cc"; -import AnimatorController from "./AnimatorController"; +import { error } from 'cc'; +import type AnimatorController from './AnimatorController'; /** 参数类型 */ export enum ParamType { @@ -26,9 +26,9 @@ export enum LogicType { export default class AnimatorCondition { private _ac: AnimatorController; /** 此条件对应的参数名 */ - private _param: string = ""; + private _param = ''; /** 此条件对应的值 */ - private _value: number = 0; + private _value = 0; /** 此条件与值比较的逻辑 */ private _logic: LogicType = LogicType.EQUAL; @@ -39,42 +39,46 @@ export default class AnimatorCondition { this._logic = data.logic; } - public getParamName() { + getParamName() { return this._param; } - public getParamType(): ParamType { + getParamType(): ParamType { return this._ac.params.getParamType(this._param); } /** 判断此条件是否满足 */ - public check(): boolean { - let type: ParamType = this.getParamType(); + check(): boolean { + const type: ParamType = this.getParamType(); if (type === ParamType.BOOLEAN) { return this._ac.params.getBool(this._param) === this._value; - } else if (type === ParamType.NUMBER) { - let value: number = this._ac.params.getNumber(this._param); + } + else if (type === ParamType.NUMBER) { + const value: number = this._ac.params.getNumber(this._param); switch (this._logic) { - case LogicType.EQUAL: - return value === this._value; - case LogicType.NOTEQUAL: - return value !== this._value; - case LogicType.GREATER: - return value > this._value; - case LogicType.LESS: - return value < this._value; - case LogicType.GREATER_EQUAL: - return value >= this._value; - case LogicType.LESS_EQUAL: - return value <= this._value; - default: - return false; + case LogicType.EQUAL: + return value === this._value; + case LogicType.NOTEQUAL: + return value !== this._value; + case LogicType.GREATER: + return value > this._value; + case LogicType.LESS: + return value < this._value; + case LogicType.GREATER_EQUAL: + return value >= this._value; + case LogicType.LESS_EQUAL: + return value <= this._value; + default: + return false; } - } else if (type === ParamType.AUTO_TRIGGER) { + } + else if (type === ParamType.AUTO_TRIGGER) { return this._ac.params.getAutoTrigger(this._param) !== 0; - } else if (type === ParamType.TRIGGER) { + } + else if (type === ParamType.TRIGGER) { return this._ac.params.getTrigger(this._param) !== 0; - } else { + } + else { error(`[AnimatorCondition.check] 错误的type: ${type}`); return false; } diff --git a/assets/libs/animator/core/AnimatorController.ts b/assets/libs/animator/core/AnimatorController.ts index bccec17..5d6c0a1 100644 --- a/assets/libs/animator/core/AnimatorController.ts +++ b/assets/libs/animator/core/AnimatorController.ts @@ -1,7 +1,7 @@ -import { error } from "cc"; -import AnimatorBase from "./AnimatorBase"; -import AnimatorParams from "./AnimatorParams"; -import AnimatorState from "./AnimatorState"; +import { error } from 'cc'; +import type AnimatorBase from './AnimatorBase'; +import AnimatorParams from './AnimatorParams'; +import AnimatorState from './AnimatorState'; /** * 状态机控制类 @@ -16,15 +16,21 @@ export default class AnimatorController { private _curState: AnimatorState = null!; /** 状态切换次数 */ - private _changeCount: number = 0; + private _changeCount = 0; /** 对应animComplete的状态 */ - public animCompleteState: AnimatorState = null!; + animCompleteState: AnimatorState = null!; /** 动画播放完毕的标记 */ - public animComplete: boolean = false; + animComplete = false; /** 当前运行的状态 */ - public get curState(): AnimatorState { return this._curState; } - public get params(): AnimatorParams { return this._params; } - public get states(): Map { return this._states } + get curState(): AnimatorState { + return this._curState; + } + get params(): AnimatorParams { + return this._params; + } + get states(): Map { + return this._states; + } constructor(player: AnimatorBase, json: any) { this._animator = player; @@ -39,14 +45,14 @@ export default class AnimatorController { */ private init(json: any) { if (json.states.length <= 0) { - error(`[AnimatorController.init] 状态机json错误`); + error('[AnimatorController.init] 状态机json错误'); return; } - let defaultState: string = json.defaultState; + const defaultState: string = json.defaultState; this._anyState = new AnimatorState(json.anyState, this); for (let i = 0; i < json.states.length; i++) { - let state: AnimatorState = new AnimatorState(json.states[i], this); + const state: AnimatorState = new AnimatorState(json.states[i], this); this._states.set(state.name, state); } this.changeState(defaultState); @@ -62,7 +68,7 @@ export default class AnimatorController { /** * 更新状态机逻辑 */ - public updateAnimator() { + updateAnimator() { // 重置计数 this._changeCount = 0; @@ -76,7 +82,7 @@ export default class AnimatorController { this.params.resetAllAutoTrigger(); } - public onAnimationComplete() { + onAnimationComplete() { this.animComplete = true; this.animCompleteState = this._curState; // cc.log(`animation complete: ${this._curState.name}`); @@ -86,7 +92,7 @@ export default class AnimatorController { * 无视条件直接跳转状态 * @param 状态名 */ - public play(stateName: string) { + play(stateName: string) { if (!this._states.has(stateName) || this._curState.name === stateName) { return; } @@ -99,7 +105,7 @@ export default class AnimatorController { /** * 切换动画状态 */ - public changeState(stateName: string) { + changeState(stateName: string) { this._changeCount++; if (this._changeCount > 1000) { error('[AnimatorController.changeState] error: 状态切换递归调用超过1000次,transition设置可能出错!'); @@ -107,7 +113,7 @@ export default class AnimatorController { } if (this._states.has(stateName) && (this._curState === null || this._curState.name !== stateName)) { - let oldState = this._curState; + const oldState = this._curState; this._curState = this._states.get(stateName)!; this._animator.onStateChange(oldState, this._curState); diff --git a/assets/libs/animator/core/AnimatorParams.ts b/assets/libs/animator/core/AnimatorParams.ts index c349540..d7841a7 100644 --- a/assets/libs/animator/core/AnimatorParams.ts +++ b/assets/libs/animator/core/AnimatorParams.ts @@ -1,4 +1,4 @@ -import { ParamType } from "./AnimatorCondition"; +import { ParamType } from './AnimatorCondition'; /** * 参数结构 @@ -16,7 +16,7 @@ export default class AnimatorParams { constructor(dataArr: any[]) { dataArr.forEach((data: any) => { - let param: Param = { + const param: Param = { type: data.type, value: data.init }; @@ -24,58 +24,59 @@ export default class AnimatorParams { }); } - public getParamType(key: string): ParamType { - let param: Param = this._paramMap.get(key)!; + getParamType(key: string): ParamType { + const param: Param = this._paramMap.get(key)!; if (param) { return param.type; - } else { + } + else { return null!; } } - public setNumber(key: string, value: number) { - let param: Param = this._paramMap.get(key)!; + setNumber(key: string, value: number) { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.NUMBER) { param.value = value; } } - public setBool(key: string, value: boolean) { - let param: Param = this._paramMap.get(key)!; + setBool(key: string, value: boolean) { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.BOOLEAN) { param.value = value ? 1 : 0; } } - public setTrigger(key: string) { - let param: Param = this._paramMap.get(key)!; + setTrigger(key: string) { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.TRIGGER) { param.value = 1; } } - public resetTrigger(key: string) { - let param: Param = this._paramMap.get(key)!; + resetTrigger(key: string) { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.TRIGGER) { param.value = 0; } } - public autoTrigger(key: string) { - let param: Param = this._paramMap.get(key)!; + autoTrigger(key: string) { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.AUTO_TRIGGER) { param.value = 1; } } - public resetAutoTrigger(key: string) { - let param: Param = this._paramMap.get(key)!; + resetAutoTrigger(key: string) { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.AUTO_TRIGGER) { param.value = 0; } } - public resetAllAutoTrigger() { + resetAllAutoTrigger() { this._paramMap.forEach((param: Param, key: string) => { if (param.type === ParamType.AUTO_TRIGGER) { param.value = 0; @@ -83,38 +84,42 @@ export default class AnimatorParams { }); } - public getNumber(key: string): number { - let param: Param = this._paramMap.get(key)!; + getNumber(key: string): number { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.NUMBER) { return param.value; - } else { + } + else { return 0; } } - public getBool(key: string): number { - let param: Param = this._paramMap.get(key)!; + getBool(key: string): number { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.BOOLEAN) { return param.value; - } else { + } + else { return 0; } } - public getTrigger(key: string): number { - let param: Param = this._paramMap.get(key)!; + getTrigger(key: string): number { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.TRIGGER) { return param.value; - } else { + } + else { return 0; } } - public getAutoTrigger(key: string): number { - let param: Param = this._paramMap.get(key)!; + getAutoTrigger(key: string): number { + const param: Param = this._paramMap.get(key)!; if (param && param.type === ParamType.AUTO_TRIGGER) { return param.value; - } else { + } + else { return 0; } } diff --git a/assets/libs/animator/core/AnimatorState.ts b/assets/libs/animator/core/AnimatorState.ts index 78e2944..e74960a 100644 --- a/assets/libs/animator/core/AnimatorState.ts +++ b/assets/libs/animator/core/AnimatorState.ts @@ -1,30 +1,42 @@ -import AnimatorController from "./AnimatorController"; -import AnimatorTransition from "./AnimatorTransition"; +import type AnimatorController from './AnimatorController'; +import AnimatorTransition from './AnimatorTransition'; /** * 状态管理类 */ export default class AnimatorState { - private _name: string = ""; - private _motion: string = ""; - private _loop: boolean = false; - private _speed: number = 1; - private _multi: string = ""; + private _name = ''; + private _motion = ''; + private _loop = false; + private _speed = 1; + private _multi = ''; private _transitions: AnimatorTransition[] = []; private _ac: AnimatorController = null!; /** 状态名 */ - public get name() { return this._name; } + get name() { + return this._name; + } /** 动画名 */ - public get motion() { return this._motion; } + get motion() { + return this._motion; + } /** 动画是否循环播放 */ - public get loop() { return this._loop; } + get loop() { + return this._loop; + } /** 动画播放速度的混合参数 */ - public get multi() { return this._multi; } + get multi() { + return this._multi; + } /** 动画播放速度 */ - public get speed() { return this._speed; } - public set speed(value: number) { this._speed = value; } + get speed() { + return this._speed; + } + set speed(value: number) { + this._speed = value; + } constructor(data: any, ac: AnimatorController) { this._name = data.state; @@ -36,7 +48,7 @@ export default class AnimatorState { this._ac = ac; for (let i = 0; i < data.transitions.length; i++) { - let transition: AnimatorTransition = new AnimatorTransition(data.transitions[i], ac); + const transition: AnimatorTransition = new AnimatorTransition(data.transitions[i], ac); transition.isValid() && this._transitions.push(transition); } } @@ -44,9 +56,9 @@ export default class AnimatorState { /** * 判断各个分支是否满足条件,满足则转换状态 */ - public checkAndTrans() { + checkAndTrans() { for (let i = 0; i < this._transitions.length; i++) { - let transition: AnimatorTransition = this._transitions[i]; + const transition: AnimatorTransition = this._transitions[i]; if (transition && transition.check()) { transition.doTrans(); return; diff --git a/assets/libs/animator/core/AnimatorStateLogic.ts b/assets/libs/animator/core/AnimatorStateLogic.ts index 53c31e5..8d2ebb9 100644 --- a/assets/libs/animator/core/AnimatorStateLogic.ts +++ b/assets/libs/animator/core/AnimatorStateLogic.ts @@ -6,20 +6,20 @@ export class AnimatorStateLogic { * 进入状态时调用 * @virtual */ - public onEntry() { + onEntry() { } /** * 每次状态机逻辑更新时调用 * @virtual */ - public onUpdate() { + onUpdate() { } /** * 离开状态时调用 * @virtual */ - public onExit() { + onExit() { } } diff --git a/assets/libs/animator/core/AnimatorTransition.ts b/assets/libs/animator/core/AnimatorTransition.ts index c91513d..dbcf817 100644 --- a/assets/libs/animator/core/AnimatorTransition.ts +++ b/assets/libs/animator/core/AnimatorTransition.ts @@ -1,12 +1,12 @@ -import AnimatorCondition, { ParamType } from "./AnimatorCondition"; -import AnimatorController from "./AnimatorController"; +import AnimatorCondition, { ParamType } from './AnimatorCondition'; +import type AnimatorController from './AnimatorController'; /** * 状态过渡类 */ export default class AnimatorTransition { - private _toStateName: string = ''; - private _hasExitTime: boolean = false; + private _toStateName = ''; + private _hasExitTime = false; private _conditions: AnimatorCondition[] = []; private _ac: AnimatorController = null!; @@ -15,7 +15,7 @@ export default class AnimatorTransition { this._hasExitTime = data.hasExitTime; this._ac = ac; for (let i = 0; i < data.conditions.length; i++) { - let condition: AnimatorCondition = new AnimatorCondition(data.conditions[i], ac); + const condition: AnimatorCondition = new AnimatorCondition(data.conditions[i], ac); this._conditions.push(condition); } } @@ -23,14 +23,14 @@ export default class AnimatorTransition { /** * 返回该transition是否有效,当未勾选hasExitTime以及没有添加任何condition时此transition无效并忽略 */ - public isValid(): boolean { + isValid(): boolean { return this._hasExitTime || this._conditions.length > 0; } /** * 判断是否满足所有转换条件 */ - public check(): boolean { + check(): boolean { if (this._toStateName === this._ac.curState.name) { return false; } @@ -50,18 +50,19 @@ export default class AnimatorTransition { /** * 转换状态 */ - public doTrans() { + doTrans() { // 满足条件时重置动画播完标记 if (this._hasExitTime) { this._ac.animComplete = false; } // 满足状态转换条件时重置trigger和autoTrigger for (let i = 0; i < this._conditions.length; i++) { - let type = this._conditions[i].getParamType(); - let name = this._conditions[i].getParamName(); + const type = this._conditions[i].getParamType(); + const name = this._conditions[i].getParamName(); if (type === ParamType.TRIGGER) { this._ac.params.resetTrigger(name); - } else if (type === ParamType.AUTO_TRIGGER) { + } + else if (type === ParamType.AUTO_TRIGGER) { this._ac.params.resetAutoTrigger(name); } } diff --git a/assets/libs/behavior-tree/BTreeNode.ts b/assets/libs/behavior-tree/BTreeNode.ts index 0932554..5fed36b 100644 --- a/assets/libs/behavior-tree/BTreeNode.ts +++ b/assets/libs/behavior-tree/BTreeNode.ts @@ -4,7 +4,7 @@ * @LastEditors: dgflash * @LastEditTime: 2022-07-20 14:04:44 */ -import { IControl } from './IControl'; +import type { IControl } from './IControl'; /** 行为树节点 */ export abstract class BTreeNode implements IControl { @@ -41,4 +41,4 @@ export abstract class BTreeNode implements IControl { fail() { this._control.fail(); } -} \ No newline at end of file +} diff --git a/assets/libs/behavior-tree/BehaviorTree.ts b/assets/libs/behavior-tree/BehaviorTree.ts index d7beb52..dad9e5c 100644 --- a/assets/libs/behavior-tree/BehaviorTree.ts +++ b/assets/libs/behavior-tree/BehaviorTree.ts @@ -1,5 +1,5 @@ import { BTreeNode } from './BTreeNode'; -import { IControl } from './IControl'; +import type { IControl } from './IControl'; let countUnnamed = 0; @@ -12,7 +12,7 @@ export class BehaviorTree implements IControl { /** 当前执行节点 */ private _current!: BTreeNode; /** 是否已开始执行 */ - private _started: boolean = false; + private _started = false; /** 外部参数对象 */ private _blackboard: any; diff --git a/assets/libs/behavior-tree/BranchNode.ts b/assets/libs/behavior-tree/BranchNode.ts index 58c39bf..5fbded8 100644 --- a/assets/libs/behavior-tree/BranchNode.ts +++ b/assets/libs/behavior-tree/BranchNode.ts @@ -30,7 +30,7 @@ export abstract class BranchNode extends BTreeNode { } run(blackboard?: any) { - if (this.children.length == 0) { // 没有子任务直接视为执行失败 + if (this.children.length == 0) { // 没有子任务直接视为执行失败 this._control.fail(); } else { @@ -46,7 +46,7 @@ export abstract class BranchNode extends BTreeNode { /** 执行当前节点逻辑 */ protected _run(blackboard?: any) { - var node = BehaviorTree.getNode(this.children[this._actualTask]); + const node = BehaviorTree.getNode(this.children[this._actualTask]); this._runningNode = node; node.setControl(this); node.start(this._blackboard); diff --git a/assets/libs/behavior-tree/Decorator.ts b/assets/libs/behavior-tree/Decorator.ts index 4e80744..f28f0dc 100644 --- a/assets/libs/behavior-tree/Decorator.ts +++ b/assets/libs/behavior-tree/Decorator.ts @@ -7,15 +7,15 @@ import { BehaviorTree } from './BehaviorTree'; import { BTreeNode } from './BTreeNode'; -/** - * 装饰器是条件语句只能附加在其他节点上并且定义所附加的节点是否执行 +/** + * 装饰器是条件语句只能附加在其他节点上并且定义所附加的节点是否执行 * 如果装饰器是true 它所在的子树会被执行,如果是false 所在的子树不会被执行 */ export class Decorator extends BTreeNode { node!: BTreeNode; constructor(node?: string | BTreeNode) { - super() + super(); if (node) this.node = BehaviorTree.getNode(node); diff --git a/assets/libs/behavior-tree/IControl.ts b/assets/libs/behavior-tree/IControl.ts index 5312536..641c7e1 100644 --- a/assets/libs/behavior-tree/IControl.ts +++ b/assets/libs/behavior-tree/IControl.ts @@ -14,7 +14,7 @@ export interface IControl { /** 处理行为逻辑 */ run(blackboard?: any): void; - + /** 正在处理中 */ running(blackboard?: any): void; -} \ No newline at end of file +} diff --git a/assets/libs/behavior-tree/Selector.ts b/assets/libs/behavior-tree/Selector.ts index b375609..6064113 100644 --- a/assets/libs/behavior-tree/Selector.ts +++ b/assets/libs/behavior-tree/Selector.ts @@ -6,18 +6,18 @@ */ import { BranchNode } from './BranchNode'; -/** +/** * 逻辑或关系 * 只要子节点有一个返回true,则停止执行其它子节点,并且Selector返回true。如果所有子节点都返回false,则Selector返回false。 */ export class Selector extends BranchNode { success() { - super.success() + super.success(); this._control.success(); } fail() { - super.fail() + super.fail(); this._actualTask += 1; if (this._actualTask < this.children.length) { diff --git a/assets/libs/behavior-tree/Sequence.ts b/assets/libs/behavior-tree/Sequence.ts index 05f33d9..61bbf63 100644 --- a/assets/libs/behavior-tree/Sequence.ts +++ b/assets/libs/behavior-tree/Sequence.ts @@ -5,9 +5,9 @@ * @LastEditTime: 2022-07-20 14:05:22 */ import { BranchNode } from './BranchNode'; -import { BTreeNode } from './BTreeNode'; +import type { BTreeNode } from './BTreeNode'; -/** +/** * 逻辑与关系 * 只要有一个子节点返回false,则停止执行其它子节点,并且Sequence返回false。如果所有子节点都返回true,则Sequence返回true。 */ diff --git a/assets/libs/behavior-tree/index.ts b/assets/libs/behavior-tree/index.ts index 8fa80fc..9f203e1 100644 --- a/assets/libs/behavior-tree/index.ts +++ b/assets/libs/behavior-tree/index.ts @@ -5,4 +5,4 @@ export * from './BTreeNode'; export * from './Priority'; export * from './Sequence'; export * from './Task'; -export * from './Selector'; \ No newline at end of file +export * from './Selector'; diff --git a/assets/libs/camera/FreeFlightCamera.ts b/assets/libs/camera/FreeFlightCamera.ts index afa19be..f0fa458 100644 --- a/assets/libs/camera/FreeFlightCamera.ts +++ b/assets/libs/camera/FreeFlightCamera.ts @@ -9,7 +9,8 @@ * 6、只支持PC上使用 */ -import { CCFloat, Component, EventKeyboard, EventMouse, EventTouch, game, Input, input, KeyCode, math, _decorator } from 'cc'; +import type { EventKeyboard, EventMouse, EventTouch } from 'cc'; +import { CCFloat, Component, game, Input, input, KeyCode, math, _decorator } from 'cc'; const { ccclass, property, menu } = _decorator; const { Vec2, Vec3, Quat } = math; @@ -28,41 +29,41 @@ const KEYCODE = { SHIFT: KeyCode.SHIFT_LEFT }; -@ccclass("FreeFlightCamera") +@ccclass('FreeFlightCamera') @menu('OopsFramework/Camera/FreeFlightCamera (自由飞行摄像机)') export class FreeFlightCamera extends Component { @property({ type: CCFloat, - tooltip: "移动速度" + tooltip: '移动速度' }) - public moveSpeed: number = 1; + moveSpeed = 1; @property({ type: CCFloat, - tooltip: "按Shift键后的速度" + tooltip: '按Shift键后的速度' }) - public moveSpeedShiftScale: number = 5; + moveSpeedShiftScale = 5; @property({ type: CCFloat, slide: true, range: [0.05, 0.5, 0.01], - tooltip: "移动后惯性效果" + tooltip: '移动后惯性效果' }) - public damp: number = 0.2; + damp = 0.2; @property({ type: CCFloat, - tooltip: "旋转速度" + tooltip: '旋转速度' }) - public rotateSpeed: number = 1; + rotateSpeed = 1; - public _euler = new Vec3(); - public _velocity = new Vec3(); - public _position = new Vec3(); - public _speedScale = 1; + _euler = new Vec3(); + _velocity = new Vec3(); + _position = new Vec3(); + _speedScale = 1; - public onLoad() { + onLoad() { input.on(Input.EventType.MOUSE_WHEEL, this.onMouseWheel, this); input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this); input.on(Input.EventType.KEY_UP, this.onKeyUp, this); @@ -74,7 +75,7 @@ export class FreeFlightCamera extends Component { Vec3.copy(this._position, this.node.position); } - public onDestroy() { + onDestroy() { input.off(Input.EventType.MOUSE_WHEEL, this.onMouseWheel, this); input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this); input.off(Input.EventType.KEY_UP, this.onKeyUp, this); @@ -83,45 +84,97 @@ export class FreeFlightCamera extends Component { input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this); } - public update(dt: number) { + update(dt: number) { // position Vec3.transformQuat(v3_1, this._velocity, this.node.rotation); Vec3.scaleAndAdd(this._position, this._position, v3_1, this.moveSpeed * this._speedScale); - Vec3.lerp(v3_1, this.node.position, this._position, dt / this.damp); // 向量线性插值产生位移惯性效果 + Vec3.lerp(v3_1, this.node.position, this._position, dt / this.damp); // 向量线性插值产生位移惯性效果 this.node.setPosition(v3_1); // rotation Quat.fromEuler(qt_1, this._euler.x, this._euler.y, this._euler.z); - Quat.slerp(qt_1, this.node.rotation, qt_1, dt / this.damp); // 四元素线性插值产生旋转惯性效果 + Quat.slerp(qt_1, this.node.rotation, qt_1, dt / this.damp); // 四元素线性插值产生旋转惯性效果 this.node.setRotation(qt_1); } - public onMouseWheel(event: EventMouse) { - const delta = -event.getScrollY() * this.moveSpeed * 0.1; // 向下滚动时增量为正 + onMouseWheel(event: EventMouse) { + const delta = -event.getScrollY() * this.moveSpeed * 0.1; // 向下滚动时增量为正 Vec3.transformQuat(v3_1, Vec3.UNIT_Z, this.node.rotation); Vec3.scaleAndAdd(this._position, this.node.position, v3_1, delta); } - public onKeyDown(event: EventKeyboard) { + onKeyDown(event: EventKeyboard) { const v = this._velocity; - if (event.keyCode === KEYCODE.SHIFT) { this._speedScale = this.moveSpeedShiftScale; } - else if (event.keyCode === KEYCODE.W) { if (v.z === 0) { v.z = -1; } } - else if (event.keyCode === KEYCODE.S) { if (v.z === 0) { v.z = 1; } } - else if (event.keyCode === KEYCODE.A) { if (v.x === 0) { v.x = -1; } } - else if (event.keyCode === KEYCODE.D) { if (v.x === 0) { v.x = 1; } } - else if (event.keyCode === KEYCODE.Q) { if (v.y === 0) { v.y = -1; } } - else if (event.keyCode === KEYCODE.E) { if (v.y === 0) { v.y = 1; } } + if (event.keyCode === KEYCODE.SHIFT) { + this._speedScale = this.moveSpeedShiftScale; + } + else if (event.keyCode === KEYCODE.W) { + if (v.z === 0) { + v.z = -1; + } + } + else if (event.keyCode === KEYCODE.S) { + if (v.z === 0) { + v.z = 1; + } + } + else if (event.keyCode === KEYCODE.A) { + if (v.x === 0) { + v.x = -1; + } + } + else if (event.keyCode === KEYCODE.D) { + if (v.x === 0) { + v.x = 1; + } + } + else if (event.keyCode === KEYCODE.Q) { + if (v.y === 0) { + v.y = -1; + } + } + else if (event.keyCode === KEYCODE.E) { + if (v.y === 0) { + v.y = 1; + } + } } - public onKeyUp(event: EventKeyboard) { + onKeyUp(event: EventKeyboard) { const v = this._velocity; - if (event.keyCode === KEYCODE.SHIFT) { this._speedScale = 1; } - else if (event.keyCode === KEYCODE.W) { if (v.z < 0) { v.z = 0; } } - else if (event.keyCode === KEYCODE.S) { if (v.z > 0) { v.z = 0; } } - else if (event.keyCode === KEYCODE.A) { if (v.x < 0) { v.x = 0; } } - else if (event.keyCode === KEYCODE.D) { if (v.x > 0) { v.x = 0; } } - else if (event.keyCode === KEYCODE.Q) { if (v.y < 0) { v.y = 0; } } - else if (event.keyCode === KEYCODE.E) { if (v.y > 0) { v.y = 0; } } + if (event.keyCode === KEYCODE.SHIFT) { + this._speedScale = 1; + } + else if (event.keyCode === KEYCODE.W) { + if (v.z < 0) { + v.z = 0; + } + } + else if (event.keyCode === KEYCODE.S) { + if (v.z > 0) { + v.z = 0; + } + } + else if (event.keyCode === KEYCODE.A) { + if (v.x < 0) { + v.x = 0; + } + } + else if (event.keyCode === KEYCODE.D) { + if (v.x > 0) { + v.x = 0; + } + } + else if (event.keyCode === KEYCODE.Q) { + if (v.y < 0) { + v.y = 0; + } + } + else if (event.keyCode === KEYCODE.E) { + if (v.y > 0) { + v.y = 0; + } + } } private onTouchStart(e: EventTouch) { @@ -130,12 +183,12 @@ export class FreeFlightCamera extends Component { private onTouchMove(e: EventTouch) { e.getStartLocation(v2_1); - if (v2_1.x > game.canvas!.width * 0.4) { // rotation + if (v2_1.x > game.canvas!.width * 0.4) { // rotation e.getDelta(v2_2); - this._euler.y -= v2_2.x * this.rotateSpeed * 0.1; // 上下旋转 - this._euler.x += v2_2.y * this.rotateSpeed * 0.1; // 左右旋转 + this._euler.y -= v2_2.x * this.rotateSpeed * 0.1; // 上下旋转 + this._euler.x += v2_2.y * this.rotateSpeed * 0.1; // 左右旋转 } - else { // position + else { // position e.getLocation(v2_2); Vec2.subtract(v2_2, v2_2, v2_1); this._velocity.x = v2_2.x * 0.01; @@ -149,9 +202,9 @@ export class FreeFlightCamera extends Component { } e.getStartLocation(v2_1); - if (v2_1.x < game.canvas!.width * 0.4) { // position + if (v2_1.x < game.canvas!.width * 0.4) { // position this._velocity.x = 0; this._velocity.z = 0; } } -} \ No newline at end of file +} diff --git a/assets/libs/camera/OrbitCamera.ts b/assets/libs/camera/OrbitCamera.ts index d20f5f8..df38b89 100644 --- a/assets/libs/camera/OrbitCamera.ts +++ b/assets/libs/camera/OrbitCamera.ts @@ -1,13 +1,14 @@ -import { _decorator, Component, EventMouse, EventTouch, input, Input, lerp, Node, Quat, Vec2, Vec3 } from 'cc'; +import type { EventMouse, EventTouch } from 'cc'; +import { _decorator, Component, input, Input, lerp, Node, Quat, Vec2, Vec3 } from 'cc'; import { EDITOR } from 'cc/env'; const { ccclass, property, menu } = _decorator; -let tempVec3 = new Vec3; -let tempVec3_2 = new Vec3; -let tempQuat = new Quat; +const tempVec3 = new Vec3; +const tempVec3_2 = new Vec3; +const tempQuat = new Quat; const DeltaFactor = 1 / 200; -/** +/** * 轨道摄影机 * 1、触摸自由旋转 * 2、镜头远近鼠标滚轮调节 @@ -17,71 +18,71 @@ const DeltaFactor = 1 / 200; @menu('OopsFramework/Camera/OrbitCamera (轨道摄影机)') export class OrbitCamera extends Component { @property({ - tooltip: "是否启动触摸控制" + tooltip: '是否启动触摸控制' }) - enableTouch = true; + enableTouch = true; @property({ - tooltip: "是否开启启用缩放半径(鼠标滚轮控制摄像机与目标距离)" + tooltip: '是否开启启用缩放半径(鼠标滚轮控制摄像机与目标距离)' }) - enableScaleRadius = false; + enableScaleRadius = false; @property({ - tooltip: "摄像机与目标的半径缩放速度", + tooltip: '摄像机与目标的半径缩放速度', visible: function () { //@ts-ignore return this.enableScaleRadius === true; } }) - radiusScaleSpeed = 1; + radiusScaleSpeed = 1; @property({ - tooltip: "摄像机与目标的半径最小值", + tooltip: '摄像机与目标的半径最小值', visible: function () { //@ts-ignore return this.enableScaleRadius === true; } }) - minRadius = 5; + minRadius = 5; @property({ - tooltip: "摄像机与目标的半径最大值", + tooltip: '摄像机与目标的半径最大值', visible: function () { //@ts-ignore return this.enableScaleRadius === true; } }) - maxRadius = 10; + maxRadius = 10; @property({ - tooltip: "自动旋转是否开启" + tooltip: '自动旋转是否开启' }) - autoRotate = false; + autoRotate = false; @property({ - tooltip: "自动旋转速度", + tooltip: '自动旋转速度', visible: function () { //@ts-ignore return this.autoRotate === true; } }) - autoRotateSpeed = 90; + autoRotateSpeed = 90; @property({ - tooltip: "旋转速度" + tooltip: '旋转速度' }) - rotateSpeed = 1; + rotateSpeed = 1; @property({ - tooltip: "跟随速度" + tooltip: '跟随速度' }) - followSpeed = 1; + followSpeed = 1; @property({ - tooltip: "X轴旋转范围(人物上下看的角度控制)" + tooltip: 'X轴旋转范围(人物上下看的角度控制)' }) - xRotationRange = new Vec2(5, 70); + xRotationRange = new Vec2(5, 70); @property private _targetRadius = 10; @property({ - tooltip: "摄像机与目标的距离(以玩家为中心环绕球半径)" + tooltip: '摄像机与目标的距离(以玩家为中心环绕球半径)' }) get radius(): number { return this._targetRadius; @@ -91,10 +92,10 @@ export class OrbitCamera extends Component { } @property - _target: Node = null!; + _target: Node = null!; @property({ type: Node, - tooltip: "跟随目标" + tooltip: '跟随目标' }) get target(): Node { return this._target; @@ -109,7 +110,7 @@ export class OrbitCamera extends Component { private _startRotation = new Vec3; @property({ type: Vec3, - tooltip: "目标旋转偏移量(初始旋转向量)" + tooltip: '目标旋转偏移量(初始旋转向量)' }) get targetRotation(): Vec3 { if (!EDITOR) { @@ -123,16 +124,16 @@ export class OrbitCamera extends Component { } @property({ - tooltip: "是否跟随目标 Y 轴旋转" + tooltip: '是否跟随目标 Y 轴旋转' }) - followTargetRotationY = false; + followTargetRotationY = false; - private _center = new Vec3; // 摄像机视口方向量 - private _targetCenter = new Vec3; // 摄像机中心点位置(目标位置) - private _touched = false; // 是否触摸屏幕 - private _targetRotation = new Vec3; // 目标旋转向量 - private _rotation = new Quat; // 摄像机旋转四元素 - private _radius = 10; // 当前玩家与目标半径距离 + private _center = new Vec3; // 摄像机视口方向量 + private _targetCenter = new Vec3; // 摄像机中心点位置(目标位置) + private _touched = false; // 是否触摸屏幕 + private _targetRotation = new Vec3; // 目标旋转向量 + private _rotation = new Quat; // 摄像机旋转四元素 + private _radius = 10; // 当前玩家与目标半径距离 start() { if (this.enableTouch) { @@ -157,7 +158,7 @@ export class OrbitCamera extends Component { this._radius = this.radius; - this.limitRotation() + this.limitRotation(); } /** 重置摄像机到初始位置 */ @@ -172,13 +173,13 @@ export class OrbitCamera extends Component { /** 限制 X 轴旋转(上下看) */ private limitRotation() { - let rotation = this._targetRotation; + const rotation = this._targetRotation; if (rotation.x < this.xRotationRange.x) { - rotation.x = this.xRotationRange.x + rotation.x = this.xRotationRange.x; } else if (rotation.x > this.xRotationRange.y) { - rotation.x = this.xRotationRange.y + rotation.x = this.xRotationRange.y; } rotation.z = 0; @@ -192,7 +193,7 @@ export class OrbitCamera extends Component { private onTouchMove(event: EventTouch) { if (!this._touched) return; - let delta = event.touch!.getDelta() + const delta = event.touch!.getDelta(); Quat.fromEuler(tempQuat, this._targetRotation.x, this._targetRotation.y, this._targetRotation.z); Quat.rotateX(tempQuat, tempQuat, -delta.y * DeltaFactor); @@ -208,8 +209,8 @@ export class OrbitCamera extends Component { //#endregion private onMouseWheel(event: EventMouse) { - let scrollY = event.getScrollY(); - this._targetRadius += this.radiusScaleSpeed * -Math.sign(scrollY); // 滚轮向前为负,滚轮向后为正 + const scrollY = event.getScrollY(); + this._targetRadius += this.radiusScaleSpeed * -Math.sign(scrollY); // 滚轮向前为负,滚轮向后为正 this._targetRadius = Math.min(this.maxRadius, Math.max(this.minRadius, this._targetRadius)); } @@ -228,23 +229,23 @@ export class OrbitCamera extends Component { if (this.followTargetRotationY) { targetRotation = tempVec3_2.set(targetRotation); Quat.toEuler(tempVec3, this.target.worldRotation); - targetRotation.y += tempVec3.y; // 运行时,只变化 Y 旋转 + targetRotation.y += tempVec3.y; // 运行时,只变化 Y 旋转 } } - Quat.fromEuler(tempQuat, targetRotation.x, targetRotation.y, targetRotation.z); // 获取目标对象的旋转四元素(人物面向与摄像机一至) + Quat.fromEuler(tempQuat, targetRotation.x, targetRotation.y, targetRotation.z); // 获取目标对象的旋转四元素(人物面向与摄像机一至) - Quat.slerp(this._rotation, this._rotation, tempQuat, dt * 7 * this.rotateSpeed); // 旋转线性插值(平滑摄像机视口旋转) - Vec3.lerp(this._center, this._center, this._targetCenter, dt * 5 * this.followSpeed); // 摄像机跟随位移线性插值(平滑摄像机节点位置移动) + Quat.slerp(this._rotation, this._rotation, tempQuat, dt * 7 * this.rotateSpeed); // 旋转线性插值(平滑摄像机视口旋转) + Vec3.lerp(this._center, this._center, this._targetCenter, dt * 5 * this.followSpeed); // 摄像机跟随位移线性插值(平滑摄像机节点位置移动) - this._radius = lerp(this._radius, this._targetRadius, dt * 5); // 摄像机与目标距离半径线性插值(镜头平滑前后移动) + this._radius = lerp(this._radius, this._targetRadius, dt * 5); // 摄像机与目标距离半径线性插值(镜头平滑前后移动) - Vec3.transformQuat(tempVec3, Vec3.FORWARD, this._rotation); // 计算摄像机旋转后的方向量 - Vec3.multiplyScalar(tempVec3, tempVec3, this._radius); // 计算摄像机与目标半径向量 - tempVec3.add(this._center); // 计算摄像机与目标偏移后的位置 + Vec3.transformQuat(tempVec3, Vec3.FORWARD, this._rotation); // 计算摄像机旋转后的方向量 + Vec3.multiplyScalar(tempVec3, tempVec3, this._radius); // 计算摄像机与目标半径向量 + tempVec3.add(this._center); // 计算摄像机与目标偏移后的位置 - this.node.position = tempVec3; // 设置摄像机位置 - this.node.lookAt(this._center); // 设置摄像机视口方向 + this.node.position = tempVec3; // 设置摄像机位置 + this.node.lookAt(this._center); // 设置摄像机视口方向 } /** 摄像机立即跟随到制定目标的位置 */ @@ -259,21 +260,21 @@ export class OrbitCamera extends Component { if (this.followTargetRotationY) { targetRotation = tempVec3_2.set(targetRotation); Quat.toEuler(tempVec3, this.target.worldRotation); - targetRotation.y += tempVec3.y; // 运行时,只变化 Y 旋转 + targetRotation.y += tempVec3.y; // 运行时,只变化 Y 旋转 } } - Quat.fromEuler(tempQuat, targetRotation.x, targetRotation.y, targetRotation.z); // 获取目标对象的旋转四元素(人物面向与摄像机一至) + Quat.fromEuler(tempQuat, targetRotation.x, targetRotation.y, targetRotation.z); // 获取目标对象的旋转四元素(人物面向与摄像机一至) this._rotation = tempQuat; this._center = this._targetCenter; this._radius = this._targetRadius; - Vec3.transformQuat(tempVec3, Vec3.FORWARD, this._rotation); // 计算摄像机旋转后的方向量 - Vec3.multiplyScalar(tempVec3, tempVec3, this._radius); // 计算摄像机与目标半径向量 - tempVec3.add(this._center); // 计算摄像机与目标偏移后的位置 + Vec3.transformQuat(tempVec3, Vec3.FORWARD, this._rotation); // 计算摄像机旋转后的方向量 + Vec3.multiplyScalar(tempVec3, tempVec3, this._radius); // 计算摄像机与目标半径向量 + tempVec3.add(this._center); // 计算摄像机与目标偏移后的位置 - this.node.position = tempVec3; // 设置摄像机位置 - this.node.lookAt(this._center); // 设置摄像机视口方向 + this.node.position = tempVec3; // 设置摄像机位置 + this.node.lookAt(this._center); // 设置摄像机视口方向 } -} \ No newline at end of file +} diff --git a/assets/libs/collection/AsyncQueue.ts b/assets/libs/collection/AsyncQueue.ts index 4c73af2..32dd15b 100644 --- a/assets/libs/collection/AsyncQueue.ts +++ b/assets/libs/collection/AsyncQueue.ts @@ -1,4 +1,4 @@ -import { log, warn } from "cc"; +import { log, warn } from 'cc'; export type NextFunction = (nextArgs?: any) => void; @@ -38,7 +38,7 @@ queue.play(); */ export class AsyncQueue { // 任务task的唯一标识 - private static _$uuid_count: number = 1; + private static _$uuid_count = 1; // 正在运行的任务 private _runningAsyncTask: AsyncTask | null = null; @@ -51,8 +51,8 @@ export class AsyncQueue { } // 正在执行的异步任务标识 - private _isProcessingTaskUUID: number = 0; - private _enable: boolean = true; + private _isProcessingTaskUUID = 0; + private _enable = true; /** 是否开启可用 */ get enable() { @@ -80,12 +80,12 @@ export class AsyncQueue { * @param params 参数 */ push(callback: AsyncCallback, params: any = null): number { - let uuid = AsyncQueue._$uuid_count++; + const uuid = AsyncQueue._$uuid_count++; this._queues.push({ uuid: uuid, callbacks: [callback], params: params - }) + }); return uuid; } @@ -93,15 +93,15 @@ export class AsyncQueue { * 添加多个任务,多个任务函数会同时执行 * @param params 参数据 * @param callbacks 回调 - * @returns + * @returns */ pushMulti(params: any, ...callbacks: AsyncCallback[]): number { - let uuid = AsyncQueue._$uuid_count++; + const uuid = AsyncQueue._$uuid_count++; this._queues.push({ uuid: uuid, callbacks: callbacks, params: params - }) + }); return uuid; } @@ -111,7 +111,7 @@ export class AsyncQueue { */ remove(uuid: number) { if (this._runningAsyncTask?.uuid === uuid) { - warn("正在执行的任务不可以移除"); + warn('正在执行的任务不可以移除'); return; } for (let i = 0; i < this._queues.length; i++) { @@ -178,31 +178,31 @@ export class AsyncQueue { return; } - let actionData: AsyncTask = this._queues.shift()!; + const actionData: AsyncTask = this._queues.shift()!; if (actionData) { this._runningAsyncTask = actionData; - let taskUUID: number = actionData.uuid; + const taskUUID: number = actionData.uuid; this._isProcessingTaskUUID = taskUUID; - let callbacks: Array = actionData.callbacks; + const callbacks: Array = actionData.callbacks; if (callbacks.length == 1) { - let nextFunc: NextFunction = (nextArgs: any = null) => { + const nextFunc: NextFunction = (nextArgs: any = null) => { this.next(taskUUID, nextArgs); - } + }; callbacks[0](nextFunc, actionData.params, args); } else { // 多个任务函数同时执行 let fnum: number = callbacks.length; - let nextArgsArr: any[] = []; - let nextFunc: NextFunction = (nextArgs: any = null) => { + const nextArgsArr: any[] = []; + const nextFunc: NextFunction = (nextArgs: any = null) => { --fnum; nextArgsArr.push(nextArgs || null); if (fnum === 0) { this.next(taskUUID, nextArgsArr); } - } - let knum = fnum; + }; + const knum = fnum; for (let i = 0; i < knum; i++) { callbacks[i](nextFunc, actionData.params, args); } @@ -223,16 +223,16 @@ export class AsyncQueue { * @param callback (可选参数)时间到了之后回调 */ yieldTime(time: number, callback: Function | null = null) { - let task = function (next: Function, params: any, args: any) { - let _t = setTimeout(() => { + const task = function (next: Function, params: any, args: any) { + const _t = setTimeout(() => { clearTimeout(_t); if (callback) { callback(); } next(args); }, time); - } - this.push(task, { des: "AsyncQueue.yieldTime" }); + }; + this.push(task, { des: 'AsyncQueue.yieldTime' }); } protected next(taskUUID: number, args: any = null) { @@ -250,18 +250,18 @@ export class AsyncQueue { /** * 返回一个执行函数,执行函数调用count次后,next将触发 - * @param count - * @param next + * @param count + * @param next * @return 返回一个匿名函数 */ static excuteTimes(count: number, next: Function | null = null): Function { let fnum: number = count; - let call = () => { + const call = () => { --fnum; if (fnum === 0) { next && next(); } - } + }; return call; } -} \ No newline at end of file +} diff --git a/assets/libs/collection/Collection.ts b/assets/libs/collection/Collection.ts index c446cf0..b0bd607 100644 --- a/assets/libs/collection/Collection.ts +++ b/assets/libs/collection/Collection.ts @@ -6,7 +6,7 @@ */ /** 支持Map与Array功能的集合对象 */ -export class Collection extends Map{ +export class Collection extends Map { private _array: V[] = []; /** 获取数组对象 */ @@ -21,8 +21,8 @@ export class Collection extends Map{ */ set(key: K, value: V) { if (this.has(key)) { - var old = this.get(key)!; - var index = this._array.indexOf(old); + const old = this.get(key)!; + const index = this._array.indexOf(old); this._array[index] = value; } else { @@ -50,4 +50,4 @@ export class Collection extends Map{ this._array.splice(0, this._array.length); super.clear(); } -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECS.ts b/assets/libs/ecs/ECS.ts index fbc2431..af7918a 100644 --- a/assets/libs/ecs/ECS.ts +++ b/assets/libs/ecs/ECS.ts @@ -1,15 +1,16 @@ -import { ECSComp } from "./ECSComp"; -import { ECSEntity } from "./ECSEntity"; -import { ECSMatcher } from "./ECSMatcher"; -import { CompCtor, CompType, ECSModel, EntityCtor } from "./ECSModel"; -import { ECSComblockSystem, ECSRootSystem, ECSSystem } from "./ECSSystem"; +import { ECSComp } from './ECSComp'; +import { ECSEntity } from './ECSEntity'; +import { ECSMatcher } from './ECSMatcher'; +import type { CompCtor, CompType, EntityCtor } from './ECSModel'; +import { ECSModel } from './ECSModel'; +import { ECSComblockSystem, ECSRootSystem, ECSSystem } from './ECSSystem'; -/** +/** * ECSEntity对象在destroy后,会回收到ECSModel.entityPool实体对象池中 * ECSComp对象从ECSEntity.remove后,数据组件会回收到ECSModel.compPools组件对象池中 */ -/** +/** * Entity-Component-System(实体-组件-系统)框架 * 文档:https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12033388&doc_id=2873565 */ @@ -122,15 +123,15 @@ export namespace ecs { @ecs.register('RoleView', false) export class RoleViewComp extends CCComp { onLoad(){ - + } } */ - export function register(name: string, canNew: boolean = true) { + export function register(name: string, canNew = true) { return function (ctor: any) { // 注册系统 if (ctor.s) { - var system = ECSModel.systems.get(name); + let system = ECSModel.systems.get(name); if (system == null) { system = new ecs.System(); ECSModel.systems.set(name, system); @@ -146,7 +147,7 @@ export namespace ecs { if (ctor.tid === -1) { ctor.tid = ECSModel.compTid++; ctor.compName = name; - ECSModel.compCtors.push(ctor); // 注册不同类型的组件 + ECSModel.compCtors.push(ctor); // 注册不同类型的组件 if (canNew) { ECSModel.compPools.set(ctor.tid, []); } @@ -156,7 +157,7 @@ export namespace ecs { throw new Error(`ECS 组件重复注册: ${name}.`); } } - } + }; } /** @@ -165,18 +166,18 @@ export namespace ecs { */ export function getEntity(ctor: EntityCtor): T { // 获取实体对象名 - var entityName = ECSModel.entityCtors.get(ctor); + const entityName = ECSModel.entityCtors.get(ctor); if (entityName == undefined) console.error(`${ctor.name} 实体没有注册`); // 获取实体对象池 - var entitys = ECSModel.entityPool.get(entityName!) || []; - var entity: any = entitys.pop(); + const entitys = ECSModel.entityPool.get(entityName!) || []; + let entity: any = entitys.pop(); // 缓存中没有同类实体,则创建一个新的 if (!entity) { entity = new ctor(); - entity.eid = ECSModel.eid++; // 实体唯一编号 + entity.eid = ECSModel.eid++; // 实体唯一编号 entity.name = entityName; } @@ -215,7 +216,7 @@ export namespace ecs { ECSModel.groups.forEach((group) => { group.clear(); }); - ECSModel.compAddOrRemove.forEach(callbackLst => { + ECSModel.compAddOrRemove.forEach((callbackLst) => { callbackLst.length = 0; }); ECSModel.eid2Entity.clear(); @@ -237,18 +238,18 @@ export namespace ecs { /** 创建实体 */ function createEntity(): E { - let entity = new Entity(); - entity.eid = ECSModel.eid++; // 实体id也是有限的资源 + const entity = new Entity(); + entity.eid = ECSModel.eid++; // 实体id也是有限的资源 ECSModel.eid2Entity.set(entity.eid, entity); return entity as E; } /** * 指定一个组件创建实体,返回组件对象。 - * @param ctor + * @param ctor */ function createEntityWithComp(ctor: CompCtor): T { - let entity = createEntity(); + const entity = createEntity(); return entity.add(ctor); } @@ -256,7 +257,7 @@ export namespace ecs { /** * 表示只关心这些组件的添加和删除动作。虽然实体可能有这些组件之外的组件,但是它们的添加和删除没有被关注,所以不会存在对关注之外的组件 * 进行添加操作引发Group重复添加实体。 - * @param args + * @param args * @example * ecs.allOf(AComponent, BComponent, CComponent); */ @@ -294,7 +295,7 @@ export namespace ecs { * @param args 组件类 * @example // 表示不包含组件A或者组件B - ecs.excludeOf(A, B); + ecs.excludeOf(A, B); */ export function excludeOf(...args: CompType[]) { return new ECSMatcher().excludeOf(...args); @@ -308,7 +309,7 @@ export namespace ecs { */ export function getSingleton(ctor: CompCtor) { if (!ECSModel.tid2comp.has(ctor.tid)) { - let comp = createEntityWithComp(ctor) as T; + const comp = createEntityWithComp(ctor) as T; ECSModel.tid2comp.set(ctor.tid, comp); } return ECSModel.tid2comp.get(ctor.tid) as T; @@ -316,14 +317,14 @@ export namespace ecs { /** * 注册单例组件 - 主要用于那些不能手动创建对象的组件 - * @param obj + * @param obj */ export function addSingleton(obj: IComp) { - let tid = (obj.constructor as CompCtor).tid; + const tid = (obj.constructor as CompCtor).tid; if (!ECSModel.tid2comp.has(tid)) { ECSModel.tid2comp.set(tid, obj); } } //#endregion -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSComp.ts b/assets/libs/ecs/ECSComp.ts index 41ead31..ddff445 100644 --- a/assets/libs/ecs/ECSComp.ts +++ b/assets/libs/ecs/ECSComp.ts @@ -4,16 +4,16 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-05 14:03:54 */ -import { ecs } from "./ECS"; -import { ECSEntity } from "./ECSEntity"; +import type { ecs } from './ECS'; +import type { ECSEntity } from './ECSEntity'; -/** +/** * 组件抽象类 * 注:建议组件里面只放数据可能在实际写代码会碰到一些比较麻烦的问题,如果是单纯对组件内的数据操作可以在组件里面写方法 */ export abstract class ECSComp implements ecs.IComp { /** 组件的类型编号,-1表示未给该组件分配编号 */ - static tid: number = -1; + static tid = -1; /** 组件名 */ static compName: string; @@ -21,15 +21,15 @@ export abstract class ECSComp implements ecs.IComp { * 是否可回收组件对象,默认情况下都是可回收的 * 注:如果该组件对象是由ecs系统外部创建的,则不可回收,需要用户自己手动进行回收 */ - canRecycle: boolean = true; + canRecycle = true; /** 拥有该组件的实体 */ ent!: ECSEntity; /** 组件的类型编号 */ - tid: number = -1; + tid = -1; /** * 组件被回收时会调用这个接口。可以在这里重置数据,或者解除引用 * 注:不要偷懒,除非你能确定并保证组件在复用时,里面的数据是先赋值然后再使用 */ abstract reset(): void; -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSEntity.ts b/assets/libs/ecs/ECSEntity.ts index e6c2d4f..ab6f960 100644 --- a/assets/libs/ecs/ECSEntity.ts +++ b/assets/libs/ecs/ECSEntity.ts @@ -1,6 +1,7 @@ -import { ecs } from "./ECS"; -import { ECSMask } from "./ECSMask"; -import { CompCtor, CompType, ECSModel } from "./ECSModel"; +import type { ecs } from './ECS'; +import { ECSMask } from './ECSMask'; +import type { CompCtor, CompType } from './ECSModel'; +import { ECSModel } from './ECSModel'; //#region 辅助方法 @@ -10,7 +11,7 @@ import { CompCtor, CompType, ECSModel } from "./ECSModel"; * @param componentTypeId 组件类型id */ function broadcastCompAddOrRemove(entity: ECSEntity, componentTypeId: number) { - let events = ECSModel.compAddOrRemove.get(componentTypeId); + const events = ECSModel.compAddOrRemove.get(componentTypeId); for (let i = events!.length - 1; i >= 0; i--) { events![i](entity); } @@ -29,16 +30,16 @@ function createComp(ctor: CompCtor): T { if (!cct) { throw Error(`没有找到该组件的构造函数,检查${ctor.compName}是否为不可构造的组件`); } - let comps = ECSModel.compPools.get(ctor.tid)!; - let component = comps.pop() || new (cct as CompCtor); + const comps = ECSModel.compPools.get(ctor.tid)!; + const component = comps.pop() || new (cct as CompCtor); return component as T; } /** * 销毁实体 - * + * * 缓存销毁的实体,下次新建实体时会优先从缓存中拿 - * @param entity + * @param entity */ function destroyEntity(entity: ECSEntity) { if (ECSModel.eid2Entity.has(entity.eid)) { @@ -60,11 +61,11 @@ function destroyEntity(entity: ECSEntity) { /** ECS实体对象 */ export class ECSEntity { /** 实体唯一标识,不要手动修改 */ - eid: number = -1; + eid = -1; /** 实体对象名 */ - name: string = ""; + name = ''; /** 实体是否有效 */ - isValid: boolean = true; + isValid = true; /** 组件过滤数据 */ private mask = new ECSMask(); /** 当前实体身上附加的组件构造函数 */ @@ -111,7 +112,7 @@ export class ECSEntity { * 移除子实体 * @param entity 被移除的实体对象 * @param isDestroy 被移除的实体是否释放,默认为释放 - * @returns + * @returns */ removeChild(entity: ECSEntity, isDestroy = true) { if (this.childs == null) return; @@ -123,20 +124,20 @@ export class ECSEntity { /** * 根据组件类动态创建组件,并通知关心的系统。如果实体存在了这个组件,那么会先删除之前的组件然后添加新的 - * + * * 注意:不要直接new Component,new来的Component不会从Component的缓存池拿缓存的数据 * @param componentTypeId 组件类 * @param isReAdd true-表示用户指定这个实体可能已经存在了该组件,那么再次add组件的时候会先移除该组件然后再添加一遍。false-表示不重复添加组件 */ add(obj: T): ECSEntity; add(ctor: CompType, isReAdd?: boolean): T; - add(ctor: CompType | T, isReAdd: boolean = false): T | ECSEntity { + add(ctor: CompType | T, isReAdd = false): T | ECSEntity { if (typeof ctor === 'function') { - let compTid = ctor.tid; + const compTid = ctor.tid; if (ctor.tid === -1) { throw Error(`【${this.name}】实体【${ctor.compName}】组件未注册`); } - if (this.compTid2Ctor.has(compTid)) { // 判断是否有该组件,如果有则先移除 + if (this.compTid2Ctor.has(compTid)) { // 判断是否有该组件,如果有则先移除 if (isReAdd) { this.remove(ctor); } @@ -170,8 +171,8 @@ export class ECSEntity { return comp; } else { - let tmpCtor = (ctor.constructor as CompCtor); - let compTid = tmpCtor.tid; + const tmpCtor = (ctor.constructor as CompCtor); + const compTid = tmpCtor.tid; // console.assert(compTid !== -1 || !compTid, '组件未注册!'); // console.assert(this.compTid2Ctor.has(compTid), '已存在该组件!'); if (compTid === -1 || compTid == null) throw Error(`【${this.name}】实体【${tmpCtor.name}】组件未注册`); @@ -196,10 +197,10 @@ export class ECSEntity { /** * 批量添加组件 * @param ctors 组件类 - * @returns + * @returns */ addComponents(...ctors: CompType[]) { - for (let ctor of ctors) { + for (const ctor of ctors) { this.add(ctor); } return this; @@ -221,7 +222,7 @@ export class ECSEntity { * @param ctor 组件类 */ has(ctor: CompType): boolean { - if (typeof ctor == "number") { + if (typeof ctor === 'number') { return this.mask.has(ctor); } else { @@ -236,16 +237,16 @@ export class ECSEntity { * 设置该参数为false,这样该组件对象会缓存在实体身上,下次重新添加组件时会将该组件对象添加回来,不会重新从组件缓存 * 池中拿一个组件来用。 */ - remove(ctor: CompType, isRecycle: boolean = true) { + remove(ctor: CompType, isRecycle = true) { let hasComp = false; //@ts-ignore - let componentTypeId = ctor.tid; + const componentTypeId = ctor.tid; //@ts-ignore - let compName = ctor.compName; + const compName = ctor.compName; if (this.mask.has(componentTypeId)) { hasComp = true; //@ts-ignore - let comp = this[ctor.compName]; + const comp = this[ctor.compName]; //@ts-ignore comp.ent = null; if (isRecycle) { @@ -258,7 +259,7 @@ export class ECSEntity { } } else { - this.compTid2Obj.set(componentTypeId, comp); // 用于缓存显示对象组件 + this.compTid2Obj.set(componentTypeId, comp); // 用于缓存显示对象组件 } } @@ -284,7 +285,7 @@ export class ECSEntity { // 移除模块上所有子模块 if (this.childs) { - this.childs.forEach(e => { + this.childs.forEach((e) => { this.removeChild(e); }); this.childs = null!; @@ -299,4 +300,4 @@ export class ECSEntity { private _remove(comp: CompType) { this.remove(comp, true); } -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSGroup.ts b/assets/libs/ecs/ECSGroup.ts index ac0c039..2c46f5b 100644 --- a/assets/libs/ecs/ECSGroup.ts +++ b/assets/libs/ecs/ECSGroup.ts @@ -4,8 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-05 14:21:54 */ -import { ecs } from "./ECS"; -import { ECSEntity } from "./ECSEntity"; +import type { ecs } from './ECS'; +import type { ECSEntity } from './ECSEntity'; export class ECSGroup { /** 实体筛选规则 */ @@ -27,7 +27,7 @@ export class ECSGroup { /** * 当前group中实体的数量 - * + * * 注:不要手动修改这个属性值。 * 注:其实可以通过this._matchEntities.size获得实体数量,但是需要封装get方法。为了减少一次方法的调用所以才直接创建一个count属性 */ @@ -46,7 +46,7 @@ export class ECSGroup { } onComponentAddOrRemove(entity: E) { - if (this.matcher.isMatch(entity)) { // Group只关心指定组件在实体身上的添加和删除动作。 + if (this.matcher.isMatch(entity)) { // Group只关心指定组件在实体身上的添加和删除动作。 this._matchEntities.set(entity.eid, entity); this._entitiesCache = null; this.count++; @@ -56,7 +56,7 @@ export class ECSGroup { this._removedEntities!.delete(entity.eid); } } - else if (this._matchEntities.has(entity.eid)) { // 如果Group中有这个实体,但是这个实体已经不满足匹配规则,则从Group中移除该实体 + else if (this._matchEntities.has(entity.eid)) { // 如果Group中有这个实体,但是这个实体已经不满足匹配规则,则从Group中移除该实体 this._matchEntities.delete(entity.eid); this._entitiesCache = null; this.count--; @@ -80,4 +80,4 @@ export class ECSGroup { this._enteredEntities?.clear(); this._removedEntities?.clear(); } -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSMask.ts b/assets/libs/ecs/ECSMask.ts index fca81b8..170f656 100644 --- a/assets/libs/ecs/ECSMask.ts +++ b/assets/libs/ecs/ECSMask.ts @@ -4,14 +4,14 @@ * @LastEditors: dgflash * @LastEditTime: 2022-05-24 11:09:49 */ -import { ECSModel } from "./ECSModel"; +import { ECSModel } from './ECSModel'; export class ECSMask { private mask: Uint32Array; - private size: number = 0; + private size = 0; constructor() { - let length = Math.ceil(ECSModel.compTid / 31); + const length = Math.ceil(ECSModel.compTid / 31); this.mask = new Uint32Array(length); this.size = length; } @@ -54,4 +54,4 @@ export class ECSMask { this.mask[i] = 0; } } -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSMatcher.ts b/assets/libs/ecs/ECSMatcher.ts index fb87062..b9e0a83 100644 --- a/assets/libs/ecs/ECSMatcher.ts +++ b/assets/libs/ecs/ECSMatcher.ts @@ -1,9 +1,10 @@ -import { ecs } from "./ECS"; -import { ECSEntity } from "./ECSEntity"; -import { ECSMask } from "./ECSMask"; -import { CompCtor, CompType, ECSModel } from "./ECSModel"; +import type { ecs } from './ECS'; +import type { ECSEntity } from './ECSEntity'; +import { ECSMask } from './ECSMask'; +import type { CompCtor, CompType } from './ECSModel'; +import { ECSModel } from './ECSModel'; -let macherId: number = 1; +let macherId = 1; /** * 筛选规则间是“与”的关系 @@ -12,17 +13,17 @@ let macherId: number = 1; export class ECSMatcher implements ecs.IMatcher { protected rules: BaseOf[] = []; protected _indices: number[] | null = null; - public isMatch!: (entity: ECSEntity) => boolean; - public mid: number = -1; + isMatch!: (entity: ECSEntity) => boolean; + mid = -1; private _key: string | null = null; - public get key(): string { + get key(): string { if (!this._key) { let s = ''; for (let i = 0; i < this.rules.length; i++) { - s += this.rules[i].getKey() + s += this.rules[i].getKey(); if (i < this.rules.length - 1) { - s += ' && ' + s += ' && '; } } this._key = s; @@ -69,15 +70,15 @@ export class ECSMatcher implements ecs.IMatcher { /** * 表示关注只拥有这些组件的实体 - * + * * 注意: * 不是特殊情况不建议使用onlyOf。因为onlyOf会监听所有组件的添加和删除事件。 * @param args 组件索引 */ onlyOf(...args: CompType[]): ECSMatcher { this.rules.push(new AllOf(...args)); - let otherTids: CompType[] = []; - for (let ctor of ECSModel.compCtors) { + const otherTids: CompType[] = []; + for (const ctor of ECSModel.compCtors) { if (args.indexOf(ctor) < 0) { otherTids.push(ctor); } @@ -89,7 +90,7 @@ export class ECSMatcher implements ecs.IMatcher { /** * 不包含指定的任意一个组件 - * @param args + * @param args */ excludeOf(...args: CompType[]) { this.rules.push(new ExcludeOf(...args)); @@ -118,7 +119,7 @@ export class ECSMatcher implements ecs.IMatcher { } private isMatchMore(entity: ECSEntity): boolean { - for (let rule of this.rules) { + for (const rule of this.rules) { if (!rule.isMatch(entity)) { return false; } @@ -127,9 +128,9 @@ export class ECSMatcher implements ecs.IMatcher { } clone(): ECSMatcher { - let newMatcher = new ECSMatcher(); + const newMatcher = new ECSMatcher(); newMatcher.mid = macherId++; - this.rules.forEach(rule => newMatcher.rules.push(rule)); + this.rules.forEach((rule) => newMatcher.rules.push(rule)); return newMatcher; } } @@ -141,9 +142,9 @@ abstract class BaseOf { constructor(...args: CompType[]) { let componentTypeId = -1; - let len = args.length; + const len = args.length; for (let i = 0; i < len; i++) { - if (typeof (args[i]) === "number") { + if (typeof (args[i]) === 'number') { componentTypeId = args[i] as number; } else { @@ -159,7 +160,9 @@ abstract class BaseOf { } } if (len > 1) { - this.indices.sort((a, b) => { return a - b; }); // 对组件类型id进行排序,这样关注相同组件的系统就能共用同一个group + this.indices.sort((a, b) => { + return a - b; + }); // 对组件类型id进行排序,这样关注相同组件的系统就能共用同一个group } } @@ -176,7 +179,7 @@ abstract class BaseOf { * 用于描述包含任意一个这些组件的实体 */ class AnyOf extends BaseOf { - public isMatch(entity: ECSEntity): boolean { + isMatch(entity: ECSEntity): boolean { // @ts-ignore return this.mask.or(entity.mask); } @@ -190,7 +193,7 @@ class AnyOf extends BaseOf { * 用于描述包含了“这些”组件的实体,这个实体除了包含这些组件还可以包含其他组件 */ class AllOf extends BaseOf { - public isMatch(entity: ECSEntity): boolean { + isMatch(entity: ECSEntity): boolean { // @ts-ignore return this.mask.and(entity.mask); } @@ -204,12 +207,12 @@ class AllOf extends BaseOf { * 不包含指定的任意一个组件 */ class ExcludeOf extends BaseOf { - public getKey(): string { + getKey(): string { return 'excludeOf:' + this.toString(); } - public isMatch(entity: ECSEntity): boolean { + isMatch(entity: ECSEntity): boolean { // @ts-ignore return !this.mask.or(entity.mask); } -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSModel.ts b/assets/libs/ecs/ECSModel.ts index 5d62a61..e03663e 100644 --- a/assets/libs/ecs/ECSModel.ts +++ b/assets/libs/ecs/ECSModel.ts @@ -4,9 +4,9 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-05 16:37:10 */ -import { ecs } from "./ECS"; -import { ECSEntity } from "./ECSEntity"; -import { ECSGroup } from "./ECSGroup"; +import type { ecs } from './ECS'; +import type { ECSEntity } from './ECSEntity'; +import { ECSGroup } from './ECSGroup'; type CompAddOrRemove = (entity: ecs.Entity) => void; @@ -55,7 +55,7 @@ export class ECSModel { /** * 缓存的group - * + * * key是组件的筛选规则,一个筛选规则对应一个group */ static groups: Map = new Map(); @@ -69,7 +69,7 @@ export class ECSModel { if (!group) { group = new ECSGroup(matcher); ECSModel.groups.set(matcher.mid, group); - let careComponentTypeIds = matcher.indices; + const careComponentTypeIds = matcher.indices; for (let i = 0; i < careComponentTypeIds.length; i++) { ECSModel.compAddOrRemove.get(careComponentTypeIds[i])!.push(group.onComponentAddOrRemove.bind(group)); } @@ -79,4 +79,4 @@ export class ECSModel { /** 系统组件 */ static systems: Map = new Map(); -} \ No newline at end of file +} diff --git a/assets/libs/ecs/ECSSystem.ts b/assets/libs/ecs/ECSSystem.ts index fdfb70f..f84c8bb 100644 --- a/assets/libs/ecs/ECSSystem.ts +++ b/assets/libs/ecs/ECSSystem.ts @@ -1,33 +1,33 @@ -import { ecs } from "./ECS"; -import { ECSEntity } from "./ECSEntity"; -import { ECSGroup } from "./ECSGroup"; -import { ECSModel } from "./ECSModel"; +import type { ecs } from './ECS'; +import type { ECSEntity } from './ECSEntity'; +import type { ECSGroup } from './ECSGroup'; +import { ECSModel } from './ECSModel'; /** 继承此类实现具体业务逻辑的系统 */ export abstract class ECSComblockSystem { - static s: boolean = true; + static s = true; protected group: ECSGroup; - protected dt: number = 0; + protected dt = 0; private enteredEntities: Map = null!; private removedEntities: Map = null!; - private hasEntityEnter: boolean = false; - private hasEntityRemove: boolean = false; - private hasUpdate: boolean = false; + private hasEntityEnter = false; + private hasEntityRemove = false; + private hasUpdate = false; private tmpExecute: ((dt: number) => void) | null = null; private execute!: (dt: number) => void; /** 构造函数 */ constructor() { - let hasOwnProperty = Object.hasOwnProperty; - let prototype = Object.getPrototypeOf(this); - let hasEntityEnter = hasOwnProperty.call(prototype, 'entityEnter'); - let hasEntityRemove = hasOwnProperty.call(prototype, 'entityRemove'); - let hasFirstUpdate = hasOwnProperty.call(prototype, 'firstUpdate'); - let hasUpdate = hasOwnProperty.call(prototype, 'update'); + const hasOwnProperty = Object.hasOwnProperty; + const prototype = Object.getPrototypeOf(this); + const hasEntityEnter = hasOwnProperty.call(prototype, 'entityEnter'); + const hasEntityRemove = hasOwnProperty.call(prototype, 'entityRemove'); + const hasFirstUpdate = hasOwnProperty.call(prototype, 'firstUpdate'); + const hasUpdate = hasOwnProperty.call(prototype, 'update'); this.hasEntityEnter = hasEntityEnter; this.hasEntityRemove = hasEntityRemove; @@ -69,8 +69,8 @@ export abstract class ECSComblockSystem { /** * 先执行entityEnter,最后执行firstUpdate - * @param dt - * @returns + * @param dt + * @returns */ private updateOnce(dt: number) { if (this.group.count === 0) { @@ -81,15 +81,15 @@ export abstract class ECSComblockSystem { // 处理刚进来的实体 if (this.enteredEntities.size > 0) { - var entities = this.enteredEntities.values(); - for (let entity of entities) { + const entities = this.enteredEntities.values(); + for (const entity of entities) { (this as unknown as ecs.IEntityEnterSystem).entityEnter(entity); } this.enteredEntities.clear(); } // 只执行firstUpdate - for (let entity of this.group.matchEntities) { + for (const entity of this.group.matchEntities) { (this as unknown as ecs.ISystemFirstUpdate).firstUpdate(entity); } @@ -100,8 +100,8 @@ export abstract class ECSComblockSystem { /** * 只执行update - * @param dt - * @returns + * @param dt + * @returns */ private execute0(dt: number): void { if (this.group.count === 0) return; @@ -110,7 +110,7 @@ export abstract class ECSComblockSystem { // 执行update if (this.hasUpdate) { - for (let entity of this.group.matchEntities) { + for (const entity of this.group.matchEntities) { (this as unknown as ecs.ISystemUpdate).update(entity); } } @@ -118,15 +118,15 @@ export abstract class ECSComblockSystem { /** * 先执行entityRemove,再执行entityEnter,最后执行update - * @param dt - * @returns + * @param dt + * @returns */ private execute1(dt: number): void { let entities; if (this.removedEntities.size > 0) { if (this.hasEntityRemove) { entities = this.removedEntities.values(); - for (let entity of entities) { + for (const entity of entities) { (this as unknown as ecs.IEntityRemoveSystem).entityRemove(entity); } } @@ -141,7 +141,7 @@ export abstract class ECSComblockSystem { if (this.enteredEntities!.size > 0) { if (this.hasEntityEnter) { entities = this.enteredEntities!.values(); - for (let entity of entities) { + for (const entity of entities) { (this as unknown as ecs.IEntityEnterSystem).entityEnter(entity); } } @@ -150,7 +150,7 @@ export abstract class ECSComblockSystem { // 执行update if (this.hasUpdate) { - for (let entity of this.group.matchEntities) { + for (const entity of this.group.matchEntities) { (this as unknown as ecs.ISystemUpdate).update(entity); } } @@ -158,7 +158,7 @@ export abstract class ECSComblockSystem { /** * 实体过滤规则 - * + * * 根据提供的组件过滤实体。 */ abstract filter(): ecs.IMatcher; @@ -167,7 +167,7 @@ export abstract class ECSComblockSystem { /** 根System,对游戏中的System遍历从这里开始,一个System组合中只能有一个RootSystem,可以有多个并行的RootSystem */ export class ECSRootSystem { private executeSystemFlows: ECSComblockSystem[] = []; - private systemCnt: number = 0; + private systemCnt = 0; add(system: ECSSystem | ECSComblockSystem) { if (system instanceof ECSSystem) { @@ -183,10 +183,10 @@ export class ECSRootSystem { init() { // 自动注册系统组件 - ECSModel.systems.forEach(sys => this.add(sys)); + ECSModel.systems.forEach((sys) => this.add(sys)); // 初始化组件 - this.executeSystemFlows.forEach(sys => sys.init()); + this.executeSystemFlows.forEach((sys) => sys.init()); } execute(dt: number) { @@ -197,7 +197,7 @@ export class ECSRootSystem { } clear() { - this.executeSystemFlows.forEach(sys => sys.onDestroy()); + this.executeSystemFlows.forEach((sys) => sys.onDestroy()); } } @@ -218,4 +218,4 @@ export class ECSSystem { } return this; } -} \ No newline at end of file +} diff --git a/assets/libs/extension/ArrayExt.ts b/assets/libs/extension/ArrayExt.ts index f8405a0..cdc1fd0 100644 --- a/assets/libs/extension/ArrayExt.ts +++ b/assets/libs/extension/ArrayExt.ts @@ -80,7 +80,7 @@ declare global { !Array.prototype.__cc_extended && Object.defineProperties(Array.prototype, { remove: { value: function (filter: any) { - if (typeof (filter) == 'function') { + if (typeof (filter) === 'function') { for (let i = this.length - 1; i > -1; --i) { filter(this[i], i, this) && this.splice(i, 1); } @@ -95,7 +95,7 @@ declare global { }, removeOne: { value: function (filter: any) { - if (typeof (filter) == 'function') { + if (typeof (filter) === 'function') { for (let i = 0; i < this.length; ++i) { if (filter(this[i], i, this)) { this.splice(i, 1); @@ -116,7 +116,7 @@ declare global { }, random: { value: function () { - let element = this[Math.floor(Math.random() * this.length)]; + const element = this[Math.floor(Math.random() * this.length)]; return element; } }, @@ -126,7 +126,7 @@ declare global { if (index < 0 || index >= length) { return null; } - let res = this[index]; + const res = this[index]; this[index] = this[length - 1]; this.length = length - 1; return res; @@ -161,16 +161,18 @@ declare global { function _max(a: number, b: number) { return a > b ? a : b; } - if (typeof (mapper) == 'function') { + if (typeof (mapper) === 'function') { let max = mapper(this[0], 0, this); for (let i = 1; i < this.length; ++i) { - let temp = mapper(this[i], i, this); + const temp = mapper(this[i], i, this); max = temp > max ? temp : max; } return max; } else { - return this.reduce(function (prev: any, cur: any) { return _max(prev, cur); }); + return this.reduce((prev: any, cur: any) => { + return _max(prev, cur); + }); } } }, @@ -182,27 +184,31 @@ declare global { function _min(a: number, b: number) { return a < b ? a : b; } - if (typeof (mapper) == 'function') { + if (typeof (mapper) === 'function') { let min = mapper(this[0], 0, this); for (let i = 1; i < this.length; ++i) { - let temp = mapper(this[i], i, this); + const temp = mapper(this[i], i, this); min = temp < min ? temp : min; } return min; } else { - return this.reduce(function (prev: any, cur: any) { return _min(prev, cur); }); + return this.reduce((prev: any, cur: any) => { + return _min(prev, cur); + }); } } }, distinct: { value: function () { - return this.filter(function (v: any, i: number, arr: any[]) { return arr.indexOf(v) === i; }); + return this.filter((v: any, i: number, arr: any[]) => { + return arr.indexOf(v) === i; + }); } }, filterIndex: { value: function (filter: any) { - let output = []; + const output = []; for (let i = 0; i < this.length; ++i) { if (filter(this[i], i, this)) { output.push(i); @@ -238,14 +244,14 @@ declare global { }, orderBy: { value: function () { - let mappers = []; + const mappers = []; for (let _i = 0; _i < arguments.length; _i++) { mappers[_i] = arguments[_i]; } - return this.slice().sort(function (a: any, b: any) { + return this.slice().sort((a: any, b: any) => { for (let i = 0; i < mappers.length; ++i) { - let va = mappers[i](a); - let vb = mappers[i](b); + const va = mappers[i](a); + const vb = mappers[i](b); if (va > vb) { return 1; } @@ -259,14 +265,14 @@ declare global { }, orderByDesc: { value: function () { - let mappers = []; + const mappers = []; for (let _i = 0; _i < arguments.length; _i++) { mappers[_i] = arguments[_i]; } - return this.slice().sort(function (a: any, b: any) { + return this.slice().sort((a: any, b: any) => { for (let i = 0; i < mappers.length; ++i) { - let va = mappers[i](a); - let vb = mappers[i](b); + const va = mappers[i](a); + const vb = mappers[i](b); if (va > vb) { return -1; } @@ -282,8 +288,8 @@ declare global { value: function (value: any, keyMapper: any) { let low = 0, high = this.length - 1; while (low <= high) { - let mid = ((high + low) / 2) | 0; - let midValue = keyMapper ? keyMapper(this[mid]) : this[mid]; + const mid = ((high + low) / 2) | 0; + const midValue = keyMapper ? keyMapper(this[mid]) : this[mid]; if (value === midValue) { return mid; } @@ -299,16 +305,16 @@ declare global { }, binaryInsert: { value: function (item: any, keyMapper: any, unique: any) { - if (typeof (keyMapper) == 'boolean') { + if (typeof (keyMapper) === 'boolean') { unique = keyMapper; keyMapper = undefined; } let low = 0, high = this.length - 1; let mid = NaN; - let itemValue = keyMapper ? keyMapper(item) : item; + const itemValue = keyMapper ? keyMapper(item) : item; while (low <= high) { mid = ((high + low) / 2) | 0; - let midValue = keyMapper ? keyMapper(this[mid]) : this[mid]; + const midValue = keyMapper ? keyMapper(this[mid]) : this[mid]; if (itemValue === midValue) { if (unique) { return mid; @@ -324,14 +330,16 @@ declare global { high = mid - 1; } } - let index = low > mid ? mid + 1 : mid; + const index = low > mid ? mid + 1 : mid; this.splice(index, 0, item); return index; } }, binaryDistinct: { value: function (keyMapper: any) { - return this.filter(function (v: any, i: number, arr: any[]) { return arr.binarySearch(v, keyMapper) === i; }); + return this.filter((v: any, i: number, arr: any[]) => { + return arr.binarySearch(v, keyMapper) === i; + }); } }, findLast: { @@ -356,16 +364,16 @@ declare global { }, groupBy: { value: function (grouper: any) { - let group = this.reduce(function (prev: any, next: any) { - let groupKey = grouper(next); + const group = this.reduce((prev: any, next: any) => { + const groupKey = grouper(next); if (!prev[groupKey]) { prev[groupKey] = []; } prev[groupKey].push(next); return prev; }, {}); - return Object.keys(group).map(function (key) { - let arr = group[key]; + return Object.keys(group).map((key) => { + const arr = group[key]; arr.key = key; return arr; }); diff --git a/assets/libs/extension/DateExt.ts b/assets/libs/extension/DateExt.ts index f4c437d..da5ad43 100644 --- a/assets/libs/extension/DateExt.ts +++ b/assets/libs/extension/DateExt.ts @@ -53,11 +53,11 @@ Date.prototype.format = function (format: string): string { Date.prototype.addTime = function (addMillis: number): Date { return new Date(this.getTime() + addMillis); -} +}; Date.prototype.range = function (d1: number | Date, d2: number | Date): boolean { - let t1: number = -1; - let t2: number = -1; + let t1 = -1; + let t2 = -1; if (d1 instanceof Date) t1 = d1.getTime(); else @@ -67,11 +67,11 @@ Date.prototype.range = function (d1: number | Date, d2: number | Date): boolean else t2 = d2; - let now = this.getTime(); + const now = this.getTime(); if (now >= t1 && now < t2) { return true; } return false; -} +}; -export { }; \ No newline at end of file +export { }; diff --git a/assets/libs/extension/DirectorExt.ts b/assets/libs/extension/DirectorExt.ts index 8d9ff0a..5da27d2 100644 --- a/assets/libs/extension/DirectorExt.ts +++ b/assets/libs/extension/DirectorExt.ts @@ -1,12 +1,12 @@ -import { Director, director, js } from "cc"; +import { Director, director, js } from 'cc'; /** 全局游戏时间缩放 */ //@ts-ignore -if (!Director.prototype["__$cc-director-speed-extension$__"]) { +if (!Director.prototype['__$cc-director-speed-extension$__']) { //@ts-ignore - Director.prototype["__$cc-director-speed-extension$__"] = true; + Director.prototype['__$cc-director-speed-extension$__'] = true; - let oldTick = director.tick.bind(director); + const oldTick = director.tick.bind(director); director.tick = function (dt) { dt *= director.globalGameTimeScale; oldTick(dt); @@ -17,10 +17,10 @@ if (!Director.prototype["__$cc-director-speed-extension$__"]) { }); } -declare module "cc" { +declare module 'cc' { interface Director { globalGameTimeScale: number; } } -// director.globalGameTimeScale = 0.5; \ No newline at end of file +// director.globalGameTimeScale = 0.5; diff --git a/assets/libs/extension/NodeDragExt.ts b/assets/libs/extension/NodeDragExt.ts index b723e3b..938a9fb 100644 --- a/assets/libs/extension/NodeDragExt.ts +++ b/assets/libs/extension/NodeDragExt.ts @@ -1,17 +1,18 @@ -import { EventTouch, Node, Vec2, js, v3 } from "cc"; +import type { EventTouch } from 'cc'; +import { Node, Vec2, js, v3 } from 'cc'; /** 节点拖拽功能 */ //@ts-ignore -if (!Node.prototype["__$NodeDragExt$__"]) { +if (!Node.prototype['__$NodeDragExt$__']) { //@ts-ignore - Node.prototype["__$NodeDragExt$__"] = true; + Node.prototype['__$NodeDragExt$__'] = true; - let _DragEvent = { - DRAG_START: "drag_start", - DRAG_MOVE: "drag_move", - DRAG_END: "drag_end" - } + const _DragEvent = { + DRAG_START: 'drag_start', + DRAG_MOVE: 'drag_move', + DRAG_END: 'drag_end' + }; js.mixin(Node, { DragEvent: _DragEvent @@ -45,14 +46,14 @@ if (!Node.prototype["__$NodeDragExt$__"]) { // DEV && console.log(`NodeDragExt -> onTouchBegin_0 ${this.name}`); // event.preventSwallow = true; - let pos = event.getUILocation(); + const pos = event.getUILocation(); this._dragStartPoint.set(pos); this._dragTesting = true; }, onTouchMove_0: function (event: EventTouch) { if (!this._dragging && this._draggable && this._dragTesting) { - let sensitivity = 10; - let pos = event.getUILocation(); + const sensitivity = 10; + const pos = event.getUILocation(); if (Math.abs(this._dragStartPoint.x - pos.x) < sensitivity && Math.abs(this._dragStartPoint.y - pos.y) < sensitivity) { return; @@ -65,10 +66,10 @@ if (!Node.prototype["__$NodeDragExt$__"]) { } if (this._dragging) { - let delta = event.getUIDelta(); + const delta = event.getUIDelta(); // /** 这里除以 世界缩放,在有缩放的时候拖拽不至于很怪 */ // this.position = this.position.add(v3(delta.x / this.worldScale.x, delta.y / this.worldScale.y, 0)); - let newPos = v3(delta.x, delta.y, 0).add(this.position); + const newPos = v3(delta.x, delta.y, 0).add(this.position); this.position = newPos; this.emit(Node.DragEvent.DRAG_MOVE, event); } @@ -127,7 +128,7 @@ if (!Node.prototype["__$NodeDragExt$__"]) { }); // 如果 node 设置 node.draggable = true, 则启用 拖拽 - Object.defineProperty(Node.prototype, "draggable", { + Object.defineProperty(Node.prototype, 'draggable', { get: function () { return this._draggable; }, @@ -141,7 +142,7 @@ if (!Node.prototype["__$NodeDragExt$__"]) { configurable: true }); - Object.defineProperty(Node.prototype, "dragTesting", { + Object.defineProperty(Node.prototype, 'dragTesting', { get: function () { return this._dragTesting; }, @@ -156,7 +157,7 @@ if (!Node.prototype["__$NodeDragExt$__"]) { //---------------- Node 添加 拖拽属性 ---------------- } -declare module "cc" { +declare module 'cc' { // 这里使用 interface 进行扩展,如果使用 class 则会与现有的 d.ts 有冲突 export interface Node { /** 是否启动拖拽 - true为启动 */ @@ -180,4 +181,4 @@ declare module "cc" { static DRAG_END: string; } } -} \ No newline at end of file +} diff --git a/assets/libs/extension/NodeExt.ts b/assets/libs/extension/NodeExt.ts index 3110124..fe04051 100644 --- a/assets/libs/extension/NodeExt.ts +++ b/assets/libs/extension/NodeExt.ts @@ -1,10 +1,10 @@ -import { Button, Canvas, Color, EditBox, Graphics, Label, Layout, Mask, Node, PageView, ProgressBar, RichText, ScrollView, Size, Slider, Sprite, Toggle, UIOpacity, UIRenderer, UITransform, Widget, v3 } from "cc"; -import { EDITOR_NOT_IN_PREVIEW } from "cc/env"; +import { Button, Canvas, Color, EditBox, Graphics, Label, Layout, Mask, Node, PageView, ProgressBar, RichText, ScrollView, Size, Slider, Sprite, Toggle, UIOpacity, UIRenderer, UITransform, Widget, v3 } from 'cc'; +import { EDITOR_NOT_IN_PREVIEW } from 'cc/env'; // ========= 扩展 cc 提示声明 ========= /** 扩展节点属性 */ -declare module "cc" { +declare module 'cc' { interface Node { uiGraphics: Graphics, uiLabel: Label, @@ -60,119 +60,119 @@ declare module "cc" { } if (!EDITOR_NOT_IN_PREVIEW) { - Object.defineProperty(Node.prototype, "uiGraphics", { + Object.defineProperty(Node.prototype, 'uiGraphics', { get: function () { return this.getComponent(Graphics)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiLabel", { + Object.defineProperty(Node.prototype, 'uiLabel', { get: function () { return this.getComponent(Label)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiRichText", { + Object.defineProperty(Node.prototype, 'uiRichText', { get: function () { return this.getComponent(RichText)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiSprite", { + Object.defineProperty(Node.prototype, 'uiSprite', { get: function () { return this.getComponent(Sprite)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiButton", { + Object.defineProperty(Node.prototype, 'uiButton', { get: function () { return this.getComponent(Button)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiCanvas", { + Object.defineProperty(Node.prototype, 'uiCanvas', { get: function () { return this.getComponent(Canvas)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiEditBox", { + Object.defineProperty(Node.prototype, 'uiEditBox', { get: function () { return this.getComponent(EditBox)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiLayout", { + Object.defineProperty(Node.prototype, 'uiLayout', { get: function () { return this.getComponent(Layout)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiPageView", { + Object.defineProperty(Node.prototype, 'uiPageView', { get: function () { return this.getComponent(PageView)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiProgressBar", { + Object.defineProperty(Node.prototype, 'uiProgressBar', { get: function () { return this.getComponent(ProgressBar)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiScrollView", { + Object.defineProperty(Node.prototype, 'uiScrollView', { get: function () { return this.getComponent(ScrollView)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiSlider", { + Object.defineProperty(Node.prototype, 'uiSlider', { get: function () { return this.getComponent(Slider)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiToggle", { + Object.defineProperty(Node.prototype, 'uiToggle', { get: function () { return this.getComponent(Toggle)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiWidget", { + Object.defineProperty(Node.prototype, 'uiWidget', { get: function () { return this.getComponent(Widget)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiOpacity", { + Object.defineProperty(Node.prototype, 'uiOpacity', { get: function () { return this.getComponent(UIOpacity)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiTransform", { + Object.defineProperty(Node.prototype, 'uiTransform', { get: function () { return this.getComponent(UITransform)!; }, set: function (value) { } }); - Object.defineProperty(Node.prototype, "uiMask", { + Object.defineProperty(Node.prototype, 'uiMask', { get: function () { return this.getComponent(Mask)!; }, @@ -180,92 +180,92 @@ if (!EDITOR_NOT_IN_PREVIEW) { }); /** 获取、设置节点的 X 坐标 */ - Object.defineProperty(Node.prototype, "x", { + Object.defineProperty(Node.prototype, 'x', { get: function () { - let self: Node = this; + const self: Node = this; return self.position.x; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.setPosition(value, self.position.y); } }); /** 获取、设置节点的 Y 坐标 */ - Object.defineProperty(Node.prototype, "y", { + Object.defineProperty(Node.prototype, 'y', { get: function () { - let self: Node = this; + const self: Node = this; return self.position.y; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.setPosition(self.position.x, value); } }); /** 获取、设置节点的 Z 坐标 */ - Object.defineProperty(Node.prototype, "z", { + Object.defineProperty(Node.prototype, 'z', { get: function () { - let self: Node = this; + const self: Node = this; return self.position.z; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.setPosition(self.position.x, self.position.y, value); } }); /** 获取、设置节点的宽度 */ - Object.defineProperty(Node.prototype, "w", { + Object.defineProperty(Node.prototype, 'w', { configurable: true, get: function () { - let self: Node = this; + const self: Node = this; return self.getComponent(UITransform)?.width ?? 0; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; (self.getComponent(UITransform) || self.addComponent(UITransform)).width = value; } }); /** 获取、设置节点的高度 */ - Object.defineProperty(Node.prototype, "h", { + Object.defineProperty(Node.prototype, 'h', { configurable: true, get: function () { - let self: Node = this; + const self: Node = this; return self.getComponent(UITransform)?.height ?? 0; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; (self.getComponent(UITransform) || self.addComponent(UITransform)).height = value; } }); /** 获取、设置节点的尺寸 */ - Object.defineProperty(Node.prototype, "size", { + Object.defineProperty(Node.prototype, 'size', { get: function () { - let self: Node = this; - let uiTransform = self.getComponent(UITransform)!; + const self: Node = this; + const uiTransform = self.getComponent(UITransform)!; return new Size(uiTransform.width, uiTransform.height); }, set: function (value: Size) { - let self: Node = this; - let uiTransform = self.getComponent(UITransform) || self.addComponent(UITransform); + const self: Node = this; + const uiTransform = self.getComponent(UITransform) || self.addComponent(UITransform); uiTransform.width = value.width; uiTransform.height = value.height; } }); /** 获取、设置节点的透明度 */ - Object.defineProperty(Node.prototype, "opacity", { + Object.defineProperty(Node.prototype, 'opacity', { get: function () { - let self: Node = this; - let op = self.getComponent(UIOpacity); + const self: Node = this; + const op = self.getComponent(UIOpacity); if (op != null) { return op.opacity; } - let render = self.getComponent(UIRenderer); + const render = self.getComponent(UIRenderer); if (render) { return render.color.a; } @@ -274,14 +274,14 @@ if (!EDITOR_NOT_IN_PREVIEW) { }, set: function (value: number) { - let self: Node = this; - let op = self.getComponent(UIOpacity); + const self: Node = this; + const op = self.getComponent(UIOpacity); if (op != null) { op.opacity = value; return; } - let render = self.getComponent(UIRenderer); + const render = self.getComponent(UIRenderer); if (render) { // 直接通过 color.a 设置透明度会有bug,没能直接生效,需要激活节点才生效 // (render.color.a as any) = value; @@ -293,7 +293,7 @@ if (!EDITOR_NOT_IN_PREVIEW) { else { this.$__color__.a = value; } - render.color = this.$__color__; // 设置 color 对象则可以立刻生效 + render.color = this.$__color__; // 设置 color 对象则可以立刻生效 } else { self.addComponent(UIOpacity).opacity = value; @@ -302,109 +302,109 @@ if (!EDITOR_NOT_IN_PREVIEW) { }); /** 获取、设置节点的颜色 */ - Object.defineProperty(Node.prototype, "color", { + Object.defineProperty(Node.prototype, 'color', { get: function () { - let self: Node = this; + const self: Node = this; return self.getComponent(UIRenderer)?.color; }, set: function (value: Color) { - let self: Node = this; - let render = self.getComponent(UIRenderer); + const self: Node = this; + const render = self.getComponent(UIRenderer); render && (render.color = value); } }); /** 获取、设置节点的 X 缩放系数 */ - Object.defineProperty(Node.prototype, "scale_x", { + Object.defineProperty(Node.prototype, 'scale_x', { get: function () { - let self: Node = this; + const self: Node = this; return self.scale.x; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.scale = v3(value, self.scale.y, self.scale.z); } }); /** 获取、设置节点的 Y 缩放系数 */ - Object.defineProperty(Node.prototype, "scale_y", { + Object.defineProperty(Node.prototype, 'scale_y', { get: function () { - let self: Node = this; + const self: Node = this; return self.scale.y; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.scale = v3(self.scale.x, value, self.scale.z); } }); /** 获取、设置节点的 Z 缩放系数 */ - Object.defineProperty(Node.prototype, "scale_z", { + Object.defineProperty(Node.prototype, 'scale_z', { get: function () { - let self: Node = this; + const self: Node = this; return self.scale.z; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.scale = v3(self.scale.x, self.scale.y, value); } }); /** 获取、设置节点的水平锚点 */ - Object.defineProperty(Node.prototype, "anchor_x", { + Object.defineProperty(Node.prototype, 'anchor_x', { get: function () { - let self: Node = this; + const self: Node = this; return self.getComponent(UITransform)?.anchorX ?? 0.5; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; (self.getComponent(UITransform) || self.addComponent(UITransform)).anchorX = value; } }); /** 获取、设置节点的垂直锚点 */ - Object.defineProperty(Node.prototype, "anchor_y", { + Object.defineProperty(Node.prototype, 'anchor_y', { get: function () { - let self: Node = this; + const self: Node = this; return self.getComponent(UITransform)?.anchorY ?? 0.5; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; (self.getComponent(UITransform) || self.addComponent(UITransform)).anchorY = value; } }); /** 获取、设置节点的 X 欧拉角 */ - Object.defineProperty(Node.prototype, "angle_x", { + Object.defineProperty(Node.prototype, 'angle_x', { get: function () { - let self: Node = this; + const self: Node = this; return self.eulerAngles.x; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.setRotationFromEuler(value, self.eulerAngles.y, self.eulerAngles.z); } }); /** 获取、设置节点的 Y 欧拉角 */ - Object.defineProperty(Node.prototype, "angle_y", { + Object.defineProperty(Node.prototype, 'angle_y', { get: function () { return this.eulerAngles.y; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.setRotationFromEuler(self.eulerAngles.x, value, self.eulerAngles.z); } }); /** 获取、设置节点的 Z 欧拉角 */ - Object.defineProperty(Node.prototype, "angle_z", { + Object.defineProperty(Node.prototype, 'angle_z', { get: function () { return this.eulerAngles.y; }, set: function (value: number) { - let self: Node = this; + const self: Node = this; self.setRotationFromEuler(self.eulerAngles.x, self.eulerAngles.y, value); } }); -} \ No newline at end of file +} diff --git a/assets/libs/gui/button/ButtonEffect.ts b/assets/libs/gui/button/ButtonEffect.ts index 710a5c3..7c1eeff 100644 --- a/assets/libs/gui/button/ButtonEffect.ts +++ b/assets/libs/gui/button/ButtonEffect.ts @@ -4,20 +4,21 @@ * @LastEditors: dgflash * @LastEditTime: 2023-02-09 10:54:28 */ -import { Animation, AnimationClip, EventTouch, Node, Sprite, _decorator } from "cc"; -import { oops } from "../../../core/Oops"; -import ButtonSimple from "./ButtonSimple"; +import type { EventTouch } from 'cc'; +import { Animation, AnimationClip, Node, Sprite, _decorator } from 'cc'; +import { oops } from '../../../core/Oops'; +import ButtonSimple from './ButtonSimple'; const { ccclass, property, menu } = _decorator; /** 有特效按钮 */ -@ccclass("ButtonEffect") +@ccclass('ButtonEffect') @menu('OopsFramework/Button/ButtonEffect (有特效按钮)') export default class ButtonEffect extends ButtonSimple { @property({ - tooltip: "是否开启" + tooltip: '是否开启' }) - disabledEffect: boolean = false; + disabledEffect = false; private anim!: Animation; @@ -34,8 +35,8 @@ export default class ButtonEffect extends ButtonSimple { onLoad() { this.anim = this.node.addComponent(Animation); - var ac_start: AnimationClip = oops.res.get("common/anim/button_scale_start", AnimationClip)!; - var ac_end: AnimationClip = oops.res.get("common/anim/button_scale_end", AnimationClip)!; + const ac_start: AnimationClip = oops.res.get('common/anim/button_scale_start', AnimationClip)!; + const ac_end: AnimationClip = oops.res.get('common/anim/button_scale_end', AnimationClip)!; this.anim.defaultClip = ac_start; this.anim.createState(ac_start, ac_start?.name); this.anim.createState(ac_end, ac_end?.name); @@ -47,13 +48,13 @@ export default class ButtonEffect extends ButtonSimple { protected onTouchtStart(event: EventTouch) { if (!this.disabledEffect) { - this.anim.play("button_scale_start"); + this.anim.play('button_scale_start'); } } protected onTouchEnd(event: EventTouch) { if (!this.disabledEffect) { - this.anim.play("button_scale_end"); + this.anim.play('button_scale_end'); } super.onTouchEnd(event); @@ -63,4 +64,4 @@ export default class ButtonEffect extends ButtonSimple { this.node.off(Node.EventType.TOUCH_START, this.onTouchtStart, this); super.onDestroy(); } -} \ No newline at end of file +} diff --git a/assets/libs/gui/button/ButtonSimple.ts b/assets/libs/gui/button/ButtonSimple.ts index a96b0b9..ae4cc86 100644 --- a/assets/libs/gui/button/ButtonSimple.ts +++ b/assets/libs/gui/button/ButtonSimple.ts @@ -1,24 +1,25 @@ -import { AudioClip, Component, EventTouch, Node, _decorator, game } from "cc"; -import { oops } from "../../../core/Oops"; +import type { EventTouch } from 'cc'; +import { AudioClip, Component, Node, _decorator, game } from 'cc'; +import { oops } from '../../../core/Oops'; const { ccclass, property, menu } = _decorator; /** 节点按钮 */ -@ccclass("ButtonSimple") +@ccclass('ButtonSimple') @menu('OopsFramework/Button/ButtonSimple (节点按钮)') export default class ButtonSimple extends Component { @property({ - tooltip: "是否只触发一次" + tooltip: '是否只触发一次' }) - private once: boolean = false; + private once = false; @property({ - tooltip: "每次触发间隔" + tooltip: '每次触发间隔' }) - private interval: number = 500; + private interval = 500; @property({ - tooltip: "触摸音效", + tooltip: '触摸音效', type: AudioClip }) private effect: AudioClip = null!; diff --git a/assets/libs/gui/button/ButtonTouchLong.ts b/assets/libs/gui/button/ButtonTouchLong.ts index 9018d0f..ea1640a 100644 --- a/assets/libs/gui/button/ButtonTouchLong.ts +++ b/assets/libs/gui/button/ButtonTouchLong.ts @@ -4,28 +4,29 @@ * @LastEditors: dgflash * @LastEditTime: 2022-04-14 18:15:42 */ -import { EventHandler, EventTouch, _decorator } from "cc"; -import ButtonEffect from "./ButtonEffect"; +import type { EventTouch } from 'cc'; +import { EventHandler, _decorator } from 'cc'; +import ButtonEffect from './ButtonEffect'; const { ccclass, property, menu } = _decorator; /** 长按按钮 */ -@ccclass("ButtonTouchLong") +@ccclass('ButtonTouchLong') @menu('OopsFramework/Button/ButtonTouchLong (长按按钮)') export class ButtonTouchLong extends ButtonEffect { @property({ - tooltip: "长按时间(秒)" + tooltip: '长按时间(秒)' }) - time: number = 1; + time = 1; @property({ type: [EventHandler], - tooltip: "长按时间(秒)" + tooltip: '长按时间(秒)' }) - clickEvents: EventHandler[] = []; + clickEvents: EventHandler[] = []; protected _passTime = 0; - protected _isTouchLong: boolean = true; + protected _isTouchLong = true; protected _event: EventTouch | null = null; onLoad() { @@ -64,7 +65,7 @@ export class ButtonTouchLong extends ButtonEffect { if (this._passTime >= this.time) { this._isTouchLong = true; - this.clickEvents.forEach(event => { + this.clickEvents.forEach((event) => { event.emit([event.customEventData]); // 长按触摸音效 this.playEffect(); diff --git a/assets/libs/gui/button/UIButton.ts b/assets/libs/gui/button/UIButton.ts index 9ec26c5..9b895ef 100644 --- a/assets/libs/gui/button/UIButton.ts +++ b/assets/libs/gui/button/UIButton.ts @@ -1,28 +1,29 @@ -import { AudioClip, Button, EventHandler, EventTouch, _decorator, game } from "cc"; -import { oops } from "../../../core/Oops"; +import type { EventTouch } from 'cc'; +import { AudioClip, Button, EventHandler, _decorator, game } from 'cc'; +import { oops } from '../../../core/Oops'; const { ccclass, property, menu } = _decorator; -/** +/** * 通用按钮 * 1、防连点 * 2、按钮点击触发音效 */ -@ccclass("UIButton") +@ccclass('UIButton') @menu('OopsFramework/Button/UIButton (通用按钮)') export default class UIButton extends Button { @property({ - tooltip: "每次触发间隔" + tooltip: '每次触发间隔' }) - private interval: number = 500; + private interval = 500; @property({ - tooltip: "是否只触发一次" + tooltip: '是否只触发一次' }) - private once: boolean = false; + private once = false; @property({ - tooltip: "触摸音效", + tooltip: '触摸音效', type: AudioClip }) private effect: AudioClip = null!; diff --git a/assets/libs/gui/label/LabelChange.ts b/assets/libs/gui/label/LabelChange.ts index 3d39b18..c53efd8 100644 --- a/assets/libs/gui/label/LabelChange.ts +++ b/assets/libs/gui/label/LabelChange.ts @@ -4,33 +4,33 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-11 10:00:51 */ -import { _decorator } from "cc"; -import LabelNumber from "./LabelNumber"; +import { _decorator } from 'cc'; +import LabelNumber from './LabelNumber'; const { ccclass, property, menu } = _decorator; /** 数值变化动画标签组件 */ -@ccclass("LabelChange") +@ccclass('LabelChange') @menu('OopsFramework/Label/LabelChange (数值变化动画标签)') export class LabelChange extends LabelNumber { @property - isInteger: boolean = false; + isInteger = false; - private duration: number = 0; // 持续时间 - private callback: Function | undefined; // 完成回调 - private isBegin: boolean = false; // 是否开始 - private speed: number = 0; // 变化速度 - private end: number = 0; // 最终值 + private duration = 0; // 持续时间 + private callback: Function | undefined; // 完成回调 + private isBegin = false; // 是否开始 + private speed = 0; // 变化速度 + private end = 0; // 最终值 - private _data: number = 0; + private _data = 0; /** * 变化到某值,如果从当前开始的begin传入null - * @param {number} duration - * @param {number} end + * @param {number} duration + * @param {number} end * @param {Function} [callback] */ - public changeTo(duration: number, end: number, callback?: Function) { + changeTo(duration: number, end: number, callback?: Function) { if (duration == 0) { if (callback) callback(); return; @@ -41,12 +41,12 @@ export class LabelChange extends LabelNumber { /** * 变化值,如果从当前开始的begin传入null - * @param {number} duration - * @param {number} value - * @param {Function} [callback] + * @param {number} duration + * @param {number} value + * @param {Function} [callback] * @memberof LabelChange */ - public changeBy(duration: number, value: number, callback?: Function) { + changeBy(duration: number, value: number, callback?: Function) { if (duration == 0) { if (callback) callback(); return; @@ -55,7 +55,7 @@ export class LabelChange extends LabelNumber { } /** 立刻停止 */ - public stop(excCallback: boolean = true) { + stop(excCallback = true) { this.num = this.end; this.isBegin = false; if (excCallback && this.callback) this.callback(); @@ -108,7 +108,7 @@ export class LabelChange extends LabelNumber { this.num = this.end; this.isBegin = false; if (this.callback) this.callback(); - } + } } } -} \ No newline at end of file +} diff --git a/assets/libs/gui/label/LabelNumber.ts b/assets/libs/gui/label/LabelNumber.ts index 117116b..7c22c9d 100644 --- a/assets/libs/gui/label/LabelNumber.ts +++ b/assets/libs/gui/label/LabelNumber.ts @@ -4,17 +4,17 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-11 10:27:04 */ -import {Label, _decorator, error} from "cc"; +import { Label, _decorator } from 'cc'; -const {ccclass, property, menu} = _decorator; +const { ccclass, property, menu } = _decorator; /** 只能显示数字的标签组件 */ -@ccclass("LabelNumber") +@ccclass('LabelNumber') @menu('OopsFramework/Label/LabelNumber (只显示数字的标签)') export default class LabelNumber extends Label { - @property({tooltip: "数字"}) - _num: number = 0; - @property({tooltip: "数字"}) + @property({ tooltip: '数字' }) + _num = 0; + @property({ tooltip: '数字' }) get num(): number { return this._num; } @@ -24,8 +24,8 @@ export default class LabelNumber extends Label { this.updateLabel(); } - @property({tooltip: "货币符号"}) - symbol: string = ""; + @property({ tooltip: '货币符号' }) + symbol = ''; start() { this.updateLabel(); @@ -35,4 +35,4 @@ export default class LabelNumber extends Label { protected updateLabel() { this.string = this.num.toString() + this.symbol; } -} \ No newline at end of file +} diff --git a/assets/libs/gui/label/LabelTime.ts b/assets/libs/gui/label/LabelTime.ts index d8b9b07..955dff2 100644 --- a/assets/libs/gui/label/LabelTime.ts +++ b/assets/libs/gui/label/LabelTime.ts @@ -1,43 +1,43 @@ -import { Label, _decorator } from "cc"; -import { EDITOR } from "cc/env"; -import { oops } from "../../../core/Oops"; -import { EventMessage } from "../../../core/common/event/EventMessage"; -import { TimeUtil } from "../../../core/utils/TimeUtils"; +import { Label, _decorator } from 'cc'; +import { EDITOR } from 'cc/env'; +import { oops } from '../../../core/Oops'; +import { EventMessage } from '../../../core/common/event/EventMessage'; +import { TimeUtil } from '../../../core/utils/TimeUtils'; const { ccclass, property, menu } = _decorator; /** 倒计时标签 */ -@ccclass("LabelTime") -@menu("OopsFramework/Label/LabelTime (倒计时标签)") +@ccclass('LabelTime') +@menu('OopsFramework/Label/LabelTime (倒计时标签)') export default class LabelTime extends Label { @property({ - tooltip: "到计时间总时间(单位秒)", + tooltip: '到计时间总时间(单位秒)', }) - countDown: number = 1000; + countDown = 1000; @property({ - tooltip: "天数数据格式化", + tooltip: '天数数据格式化', }) - dayFormat: string = "{0}天{1}小时"; + dayFormat = '{0}天{1}小时'; @property({ - tooltip: "时间格式化", + tooltip: '时间格式化', }) - timeFormat: string = "{0}:{1}:{2}"; + timeFormat = '{0}:{1}:{2}'; @property({ - tooltip: "时间是否有固定二位数据", + tooltip: '时间是否有固定二位数据', }) - zeroize: boolean = true; + zeroize = true; @property({ - tooltip: "游戏进入后台时间暂时", + tooltip: '游戏进入后台时间暂时', }) - paused: boolean = false; + paused = false; - private backStartTime: number = 0; // 进入后台开始时间 - private dateDisable!: boolean; // 时间能否由天数显示 - private result!: string; // 时间结果字符串 + private backStartTime = 0; // 进入后台开始时间 + private dateDisable!: boolean; // 时间能否由天数显示 + private result!: string; // 时间结果字符串 /** 每秒触发事件 */ onSecond: Function = null!; @@ -45,7 +45,7 @@ export default class LabelTime extends Label { onComplete: Function = null!; private replace(value: string, ...args: any): string { - return value.replace(/\{(\d+)\}/g, function (m, i) { + return value.replace(/\{(\d+)\}/g, (m, i) => { return args[i]; }); } @@ -53,35 +53,35 @@ export default class LabelTime extends Label { /** 格式化字符串 */ private format() { let c: number = this.countDown; - let date: number = Math.floor(c / 86400); + const date: number = Math.floor(c / 86400); c = c - date * 86400; let hours: number = Math.floor(c / 3600); c = c - hours * 3600; - let minutes: number = Math.floor(c / 60); + const minutes: number = Math.floor(c / 60); c = c - minutes * 60; - let seconds: number = c; + const seconds: number = c; this.dateDisable = this.dateDisable || false; if (date == 0 && hours == 0 && minutes == 0 && seconds == 0) { if (this.zeroize) { - this.result = this.replace(this.timeFormat, "00", "00", "00"); + this.result = this.replace(this.timeFormat, '00', '00', '00'); } else { - this.result = this.replace(this.timeFormat, "0", "0", "0"); + this.result = this.replace(this.timeFormat, '0', '0', '0'); } } else if (date > 0 && !this.dateDisable) { let dataFormat = this.dayFormat; - let index = dataFormat.indexOf("{1}"); + const index = dataFormat.indexOf('{1}'); if (hours == 0 && index > -1) { dataFormat = dataFormat.substring(0, index); } let df = dataFormat; - if (date > 1 && dataFormat.indexOf("days") < 0) { - df = df.replace("day", "days"); + if (date > 1 && dataFormat.indexOf('days') < 0) { + df = df.replace('day', 'days'); } if (date < 2) { - df = df.replace("days", "day"); + df = df.replace('days', 'day'); } if (this.zeroize) { @@ -105,7 +105,7 @@ export default class LabelTime extends Label { /** 个位数的时间数据将字符串补位 */ private coverString(value: number) { - if (value < 10) return "0" + value; + if (value < 10) return '0' + value; return value.toString(); } @@ -220,4 +220,4 @@ export default class LabelTime extends Label { timing_end() { this.unscheduleAllCallbacks(); } -} \ No newline at end of file +} diff --git a/assets/libs/gui/language/Language.ts b/assets/libs/gui/language/Language.ts index 88fea18..4e02ec3 100644 --- a/assets/libs/gui/language/Language.ts +++ b/assets/libs/gui/language/Language.ts @@ -1,13 +1,13 @@ -import { sys } from "cc"; -import { Logger } from "../../../core/common/log/Logger"; -import { LanguageData } from "./LanguageData"; -import { LanguagePack } from "./LanguagePack"; +import { sys } from 'cc'; +import { Logger } from '../../../core/common/log/Logger'; +import { LanguageData } from './LanguageData'; +import { LanguagePack } from './LanguagePack'; /** 多语言管理器 */ export class LanguageManager { - private _languages: Array = [sys.Language.CHINESE, sys.Language.ENGLISH]; // 支持的语言 - private _languagePack: LanguagePack = new LanguagePack(); // 语言包 - private _defaultLanguage: string = sys.Language.CHINESE; // 默认语言 + private _languages: Array = [sys.Language.CHINESE, sys.Language.ENGLISH]; // 支持的语言 + private _languagePack: LanguagePack = new LanguagePack(); // 语言包 + private _defaultLanguage: string = sys.Language.CHINESE; // 默认语言 /** 支持的多种语言列表 */ get languages(): string[] { @@ -43,8 +43,8 @@ export class LanguageManager { /** 获取下一个语种 */ getNextLang(): string { - let supportLangs = this.languages; - let index = supportLangs.indexOf(LanguageData.current); + const supportLangs = this.languages; + const index = supportLangs.indexOf(LanguageData.current); return supportLangs[(index + 1) % supportLangs.length]; } @@ -54,14 +54,14 @@ export class LanguageManager { * @param callback 多语言资源数据加载完成回调 */ setLanguage(language: string, callback?: Function) { - if (language == null || language == "") { + if (language == null || language == '') { language = this._defaultLanguage; } else { language = language.toLowerCase(); } - let index = this.languages.indexOf(language); + const index = this.languages.indexOf(language); if (index < 0) { console.log(`当前不支持【${language}】语言,将自动切换到【${this._defaultLanguage}】语言`); language = this._defaultLanguage; @@ -84,8 +84,8 @@ export class LanguageManager { /** * 根据data获取对应语种的字符 - * @param labId - * @param arr + * @param labId + * @param arr */ getLangByID(labId: string): string { return LanguageData.getLangByID(labId); @@ -94,8 +94,8 @@ export class LanguageManager { /** * 下载语言包素材资源 * 包括语言json配置和语言纹理包 - * @param lang - * @param callback + * @param lang + * @param callback */ loadLanguageAssets(lang: string, callback: Function) { lang = lang.toLowerCase(); @@ -104,10 +104,10 @@ export class LanguageManager { /** * 释放不需要的语言包资源 - * @param lang + * @param lang */ releaseLanguageAssets(lang: string) { lang = lang.toLowerCase(); this._languagePack.releaseLanguageAssets(lang); } -} \ No newline at end of file +} diff --git a/assets/libs/gui/language/LanguageData.ts b/assets/libs/gui/language/LanguageData.ts index 0e99f51..3bd8976 100644 --- a/assets/libs/gui/language/LanguageData.ts +++ b/assets/libs/gui/language/LanguageData.ts @@ -1,4 +1,4 @@ -import { TTFFont } from "cc"; +import type { TTFFont } from 'cc'; /* * @Author: dgflash @@ -10,42 +10,42 @@ import { TTFFont } from "cc"; /** 框架支持的语言数据类型 */ export enum LanguageDataType { /** Json格式配置 */ - Json = "Json", + Json = 'Json', /** Excel生成的Json配置 */ - Excel = "Excel", + Excel = 'Excel', } export class LanguageData { /** JSON资源目录 */ - static path_json: string = "language/json"; + static path_json = 'language/json'; /** 纹理资源目录 */ - static path_texture: string = "language/texture"; + static path_texture = 'language/texture'; /** SPINE资源目录 */ - static path_spine: string = "language/spine"; + static path_spine = 'language/spine'; /** 当前语言 */ - static current: string = ""; + static current = ''; /** 语言数据 */ static language: Map = new Map(); /** TTF字体 */ static font: TTFFont = null!; - /** - * 通过多语言关键字获取语言文本 - * + /** + * 通过多语言关键字获取语言文本 + * * 注: - * + * * 1、先获取language/json中的配置数据,如果没有者获取config/game/Language配置表中的多语言数据 - * + * * 2、config/game/Language配置表可选使用,不用时不创建同名配置表即可 - * + * * 3、config/game/Language配置表使用oops-plugin-excel-to-json插件生成,点击项目根目录下载update-oops-plugin-framework.bat或update-oops-plugin-framework.sh脚本下载插件 */ static getLangByID(labId: string): string { let content: string = null!; for (const [key, value] of this.language) { if (key == LanguageDataType.Excel) { - let lang = value[labId]; + const lang = value[labId]; if (lang) content = lang[this.current]; } else { @@ -61,4 +61,4 @@ export const LanguageType = [ 'LanguageLabel', 'LanguageSprite', 'LanguageSpine' -] \ No newline at end of file +]; diff --git a/assets/libs/gui/language/LanguageLabel.ts b/assets/libs/gui/language/LanguageLabel.ts index 51afb9a..7c76a42 100644 --- a/assets/libs/gui/language/LanguageLabel.ts +++ b/assets/libs/gui/language/LanguageLabel.ts @@ -1,30 +1,31 @@ -import { CCString, Component, Label, RichText, TTFFont, _decorator, warn } from "cc"; -import { EDITOR } from "cc/env"; -import { LanguageData } from "./LanguageData"; +import type { TTFFont } from 'cc'; +import { CCString, Component, Label, RichText, _decorator, warn } from 'cc'; +import { EDITOR } from 'cc/env'; +import { LanguageData } from './LanguageData'; const { ccclass, property, menu } = _decorator; -@ccclass("LangLabelParamsItem") +@ccclass('LangLabelParamsItem') export class LangLabelParamsItem { @property - key: string = ""; + key = ''; @property - value: string = ""; + value = ''; } /** 文本多语言 */ -@ccclass("LanguageLabel") +@ccclass('LanguageLabel') @menu('OopsFramework/Language/LanguageLabel (文本多语言)') export class LanguageLabel extends Component { @property({ type: LangLabelParamsItem, - displayName: "params" + displayName: 'params' }) private _params: Array = []; @property({ type: LangLabelParamsItem, - displayName: "params" + displayName: 'params' }) set params(value: Array) { this._params = value; @@ -37,10 +38,10 @@ export class LanguageLabel extends Component { } @property({ serializable: true }) - private _dataID: string = ""; + private _dataID = ''; @property({ type: CCString, serializable: true }) get dataID(): string { - return this._dataID || ""; + return this._dataID || ''; } set dataID(value: string) { this._dataID = value; @@ -53,11 +54,11 @@ export class LanguageLabel extends Component { let _string = LanguageData.getLangByID(this._dataID); if (_string && this._params.length > 0) { this._params.forEach((item: LangLabelParamsItem) => { - _string = _string.replace(`%{${item.key}}`, item.value) - }) + _string = _string.replace(`%{${item.key}}`, item.value); + }); } if (!_string) { - warn("[LanguageLabel] 未找到语言标识,使用dataID替换"); + warn('[LanguageLabel] 未找到语言标识,使用dataID替换'); _string = this._dataID; } return _string; @@ -69,7 +70,7 @@ export class LanguageLabel extends Component { } /** 初始字体尺寸 */ - initFontSize: number = 0; + initFontSize = 0; onLoad() { this._needUpdate = true; @@ -83,21 +84,21 @@ export class LanguageLabel extends Component { setVars(key: string, value: string) { let haskey = false; for (let i = 0; i < this._params.length; i++) { - let element: LangLabelParamsItem = this._params[i]; + const element: LangLabelParamsItem = this._params[i]; if (element.key === key) { element.value = value; haskey = true; } } if (!haskey) { - let ii = new LangLabelParamsItem(); + const ii = new LangLabelParamsItem(); ii.key = key; ii.value = value; this._params.push(ii); } this._needUpdate = true; } - private _needUpdate: boolean = false; + private _needUpdate = false; update() { if (this._needUpdate) { @@ -126,7 +127,7 @@ export class LanguageLabel extends Component { this.initFontSize = richtext.fontSize; } else { - warn("[LanguageLabel], 该节点没有cc.Label || cc.RichText组件"); + warn('[LanguageLabel], 该节点没有cc.Label || cc.RichText组件'); } } } diff --git a/assets/libs/gui/language/LanguagePack.ts b/assets/libs/gui/language/LanguagePack.ts index e092556..8702164 100644 --- a/assets/libs/gui/language/LanguagePack.ts +++ b/assets/libs/gui/language/LanguagePack.ts @@ -4,26 +4,26 @@ * @LastEditors: dgflash * @LastEditTime: 2023-08-22 16:34:28 */ -import { director, error, JsonAsset, TTFFont } from "cc"; -import { resLoader } from "../../../core/common/loader/ResLoader"; -import { Logger } from "../../../core/common/log/Logger"; -import { JsonUtil } from "../../../core/utils/JsonUtil"; -import { LanguageData, LanguageDataType, LanguageType } from "./LanguageData"; +import { director, error, JsonAsset, TTFFont } from 'cc'; +import { resLoader } from '../../../core/common/loader/ResLoader'; +import { Logger } from '../../../core/common/log/Logger'; +import { JsonUtil } from '../../../core/utils/JsonUtil'; +import { LanguageData, LanguageDataType, LanguageType } from './LanguageData'; export class LanguagePack { /** * 刷新语言文字 - * @param lang + * @param lang */ updateLanguage(lang: string) { - let rootNodes = director.getScene()!.children; + const rootNodes = director.getScene()!.children; for (let i = 0; i < rootNodes.length; ++i) { - LanguageType.forEach(type => { - let comps: any[] = rootNodes[i].getComponentsInChildren(type); + LanguageType.forEach((type) => { + const comps: any[] = rootNodes[i].getComponentsInChildren(type); for (let j = 0; j < comps.length; j++) { comps[j].language(); } - }) + }); } } @@ -44,10 +44,10 @@ export class LanguagePack { /** 多语言Excel配置表数据 */ private loadTable(lang: string): Promise { return new Promise(async (resolve, reject) => { - let json = await JsonUtil.load("Language"); + const json = await JsonUtil.load('Language'); if (json) { LanguageData.language.set(LanguageDataType.Excel, json); - Logger.instance.logConfig("config/game/Language", "下载语言包 table 资源"); + Logger.instance.logConfig('config/game/Language', '下载语言包 table 资源'); } resolve(); }); @@ -63,7 +63,7 @@ export class LanguagePack { resolve(); return; } - Logger.instance.logConfig(path, "下载语言包 textures 资源"); + Logger.instance.logConfig(path, '下载语言包 textures 资源'); resolve(); }); }); @@ -76,7 +76,7 @@ export class LanguagePack { const jsonAsset = await resLoader.load(path, JsonAsset); if (jsonAsset) { LanguageData.language.set(LanguageDataType.Json, jsonAsset.json); - Logger.instance.logConfig(path, "下载语言包 json 资源"); + Logger.instance.logConfig(path, '下载语言包 json 资源'); } else { resolve(); @@ -86,7 +86,7 @@ export class LanguagePack { const font = await resLoader.load(path, TTFFont); if (font) { LanguageData.font = font; - Logger.instance.logConfig(path, "下载语言包 ttf 资源"); + Logger.instance.logConfig(path, '下载语言包 ttf 资源'); } resolve(); }); @@ -102,32 +102,32 @@ export class LanguagePack { resolve(); return; } - Logger.instance.logConfig(path, "下载语言包 spine 资源"); + Logger.instance.logConfig(path, '下载语言包 spine 资源'); resolve(); - }) + }); }); } /** * 释放某个语言的语言包资源包括json - * @param lang + * @param lang */ releaseLanguageAssets(lang: string) { - let langTexture = `${LanguageData.path_texture}/${lang}`; + const langTexture = `${LanguageData.path_texture}/${lang}`; resLoader.releaseDir(langTexture); - let langJson = `${LanguageData.path_json}/${lang}`; - let json = resLoader.get(langJson, JsonAsset); + const langJson = `${LanguageData.path_json}/${lang}`; + const json = resLoader.get(langJson, JsonAsset); if (json) { json.decRef(); } - let font = resLoader.get(langJson, TTFFont); + const font = resLoader.get(langJson, TTFFont); if (font) { font.decRef(); } - let langSpine = `${LanguageData.path_spine}/${lang}`; + const langSpine = `${LanguageData.path_spine}/${lang}`; resLoader.release(langSpine); } -} \ No newline at end of file +} diff --git a/assets/libs/gui/language/LanguageSpine.ts b/assets/libs/gui/language/LanguageSpine.ts index 10f6c19..b4af2e0 100644 --- a/assets/libs/gui/language/LanguageSpine.ts +++ b/assets/libs/gui/language/LanguageSpine.ts @@ -4,22 +4,22 @@ * @LastEditors: dgflash * @LastEditTime: 2023-07-25 11:48:52 */ -import { CCString, Component, _decorator, sp } from "cc"; -import { EDITOR } from "cc/env"; -import { resLoader } from "../../../core/common/loader/ResLoader"; -import { LanguageData } from "./LanguageData"; +import { CCString, Component, _decorator, sp } from 'cc'; +import { EDITOR } from 'cc/env'; +import { resLoader } from '../../../core/common/loader/ResLoader'; +import { LanguageData } from './LanguageData'; const { ccclass, property, menu } = _decorator; /** Spine 动画多语言 */ -@ccclass("LanguageSpine") +@ccclass('LanguageSpine') @menu('OopsFramework/Language/LanguageSpine (Spine 动画多语言)') export class LanguageSpine extends Component { @property({ serializable: true }) - private _dataID: string = ""; + private _dataID = ''; @property({ type: CCString, serializable: true }) get dataID(): string { - return this._dataID || ""; + return this._dataID || ''; } set dataID(value: string) { this._dataID = value; @@ -29,10 +29,10 @@ export class LanguageSpine extends Component { } /** 默认动画名 */ - private _defaultAnimation: string = ""; + private _defaultAnimation = ''; onLoad() { - let spine: sp.Skeleton = this.getComponent(sp.Skeleton)!; + const spine: sp.Skeleton = this.getComponent(sp.Skeleton)!; this._defaultAnimation = spine.animation; } @@ -47,15 +47,15 @@ export class LanguageSpine extends Component { private updateSpine() { // 获取语言标记 - let path = `language/spine/${LanguageData.current}/${this.dataID}`; - let res: sp.SkeletonData | null = resLoader.get(path, sp.SkeletonData); + const path = `language/spine/${LanguageData.current}/${this.dataID}`; + const res: sp.SkeletonData | null = resLoader.get(path, sp.SkeletonData); if (res) { - let spine: sp.Skeleton = this.getComponent(sp.Skeleton)!; + const spine: sp.Skeleton = this.getComponent(sp.Skeleton)!; spine.skeletonData = res; spine.setAnimation(0, this._defaultAnimation, true); } else { - console.error("[LanguageSpine] 资源不存在 " + path); + console.error('[LanguageSpine] 资源不存在 ' + path); } } -} \ No newline at end of file +} diff --git a/assets/libs/gui/language/LanguageSprite.ts b/assets/libs/gui/language/LanguageSprite.ts index 50ce34d..2adba85 100644 --- a/assets/libs/gui/language/LanguageSprite.ts +++ b/assets/libs/gui/language/LanguageSprite.ts @@ -4,22 +4,23 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 10:04:57 */ -import { CCString, Component, Size, Sprite, SpriteFrame, UITransform, _decorator } from "cc"; -import { EDITOR } from "cc/env"; -import { resLoader } from "../../../core/common/loader/ResLoader"; -import { LanguageData } from "./LanguageData"; +import type { Size } from 'cc'; +import { CCString, Component, Sprite, SpriteFrame, UITransform, _decorator } from 'cc'; +import { EDITOR } from 'cc/env'; +import { resLoader } from '../../../core/common/loader/ResLoader'; +import { LanguageData } from './LanguageData'; const { ccclass, property, menu } = _decorator; /** 图片多语言 */ -@ccclass("LanguageSprite") +@ccclass('LanguageSprite') @menu('OopsFramework/Language/LanguageSprite (图片多语言)') export class LanguageSprite extends Component { @property({ serializable: true }) - private _dataID: string = ""; + private _dataID = ''; @property({ type: CCString, serializable: true }) get dataID(): string { - return this._dataID || ""; + return this._dataID || ''; } set dataID(value: string) { this._dataID = value; @@ -29,9 +30,9 @@ export class LanguageSprite extends Component { } @property({ - tooltip: "是否设置为图片原始资源大小" + tooltip: '是否设置为图片原始资源大小' }) - private isRawSize: boolean = true; + private isRawSize = true; start() { this.updateSprite(); @@ -44,21 +45,21 @@ export class LanguageSprite extends Component { private updateSprite() { // 获取语言标记 - let path = `language/texture/${LanguageData.current}/${this.dataID}/spriteFrame`; - let res: SpriteFrame | null = resLoader.get(path, SpriteFrame); + const path = `language/texture/${LanguageData.current}/${this.dataID}/spriteFrame`; + const res: SpriteFrame | null = resLoader.get(path, SpriteFrame); if (res) { - let spcomp: Sprite = this.getComponent(Sprite)!; + const spcomp: Sprite = this.getComponent(Sprite)!; spcomp.spriteFrame = res; /** 修改节点为原始图片资源大小 */ if (this.isRawSize) { //@ts-ignore - let rawSize = res._originalSize as Size; + const rawSize = res._originalSize as Size; spcomp.getComponent(UITransform)?.setContentSize(rawSize); } } else { - console.error("[LanguageSprite] 资源不存在 " + path); + console.error('[LanguageSprite] 资源不存在 ' + path); } } -} \ No newline at end of file +} diff --git a/assets/libs/gui/window/PromptBase.ts b/assets/libs/gui/window/PromptBase.ts index aa8cd46..e940ff5 100644 --- a/assets/libs/gui/window/PromptBase.ts +++ b/assets/libs/gui/window/PromptBase.ts @@ -1,17 +1,17 @@ -import { _decorator } from "cc"; -import { GameComponent } from "db://oops-framework/module/common/GameComponent"; -import { LanguageLabel } from "../language/LanguageLabel"; +import { _decorator } from 'cc'; +import { GameComponent } from 'db://oops-framework/module/common/GameComponent'; +import { LanguageLabel } from '../language/LanguageLabel'; const { ccclass, property } = _decorator; -/** +/** * 基础提示窗口 * 1. 自定义提示标题、按钮名 * 2. 自定义确认、取消事件回调 * 3. 自定义提示内容 * 4. 支持文本多语言 */ -@ccclass("PromptBase") +@ccclass('PromptBase') export class PromptBase extends GameComponent { /** 窗口标题多语言组件 */ @property(LanguageLabel) @@ -34,7 +34,7 @@ export class PromptBase extends GameComponent { /** * 窗口打开事件 - * @param params 参数 + * @param params 参数 * { * title: 标题 * content: 内容 @@ -49,11 +49,11 @@ export class PromptBase extends GameComponent { this.config = params; if (this.config == null) return false; - this.labTitle.dataID = this.config.title; // 窗口标题 - this.labContent.dataID = this.config.content; // 提示内容 - this.labOk.dataID = this.config.okWord; // 确定按钮文字 + this.labTitle.dataID = this.config.title; // 窗口标题 + this.labContent.dataID = this.config.content; // 提示内容 + this.labOk.dataID = this.config.okWord; // 确定按钮文字 if (this.labCancel) { - this.labCancel.dataID = this.config.cancelWord || ""; // 取消按钮文字 + this.labCancel.dataID = this.config.cancelWord || ''; // 取消按钮文字 this.labCancel.node.parent!.active = this.config.needCancel || false; } this.node.active = true; @@ -65,14 +65,14 @@ export class PromptBase extends GameComponent { } private btnOk() { - if (typeof this.config.onOk == "function") { + if (typeof this.config.onOk === 'function') { this.config.onOk(); } this.remove(); } private btnCancel() { - if (typeof this.config.onCancel == "function") { + if (typeof this.config.onCancel === 'function') { this.config.onCancel(); } this.remove(); @@ -86,4 +86,4 @@ export class PromptBase extends GameComponent { this.config = null!; super.onDestroy(); } -} \ No newline at end of file +} diff --git a/assets/libs/gui/window/PromptSkip.ts b/assets/libs/gui/window/PromptSkip.ts index 34d0d4a..cdeffc2 100644 --- a/assets/libs/gui/window/PromptSkip.ts +++ b/assets/libs/gui/window/PromptSkip.ts @@ -1,22 +1,23 @@ -import { _decorator, Toggle } from "cc"; -import { oops } from "db://oops-framework/core/Oops"; -import { GameStorage } from "db://oops-framework/module/common/GameStorage"; -import { PromptBase } from "./PromptBase"; +import type { Toggle } from 'cc'; +import { _decorator } from 'cc'; +import { oops } from 'db://oops-framework/core/Oops'; +import { GameStorage } from 'db://oops-framework/module/common/GameStorage'; +import { PromptBase } from './PromptBase'; -const { ccclass, property } = _decorator; +const { ccclass } = _decorator; /** 不同类型的提示窗口状态数据 */ -var content: any = null; +let content: any = null; /** 可设置指定时间内跳过提示 */ -@ccclass("PromptSkip") +@ccclass('PromptSkip') export class PromptSkip extends PromptBase { /** 是否可提示 */ static isPrompt(id: string): boolean { - if (content == null) content = oops.storage.getJson(GameStorage.PromptSkip, {}); // 第一次打开窗口从本地数据中获取窗口状态信息 + if (content == null) content = oops.storage.getJson(GameStorage.PromptSkip, {}); // 第一次打开窗口从本地数据中获取窗口状态信息 - let r = content[id]; - let c = oops.timer.getClientTime(); + const r = content[id]; + const c = oops.timer.getClientTime(); if (r == null || c > r) { return true; } @@ -44,4 +45,4 @@ export class PromptSkip extends PromptBase { } oops.storage.set(GameStorage.PromptSkip, JSON.stringify(content)); } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/JsonOb.ts b/assets/libs/model-view/JsonOb.ts index d902ffd..388d916 100644 --- a/assets/libs/model-view/JsonOb.ts +++ b/assets/libs/model-view/JsonOb.ts @@ -13,7 +13,7 @@ const OP = Object.prototype; const types = { obj: '[object Object]', array: '[object Array]' -} +}; const OAM = ['push', 'pop', 'shift', 'unshift', 'sort', 'reverse', 'splice']; /** @@ -38,7 +38,7 @@ export class JsonOb { // @ts-ignore 注:避免API生成工具报错 Object.keys(obj).forEach((key) => { - let self = this; + const self = this; // @ts-ignore let oldVal = obj[key]; let pathArray = path && path.slice(); @@ -64,7 +64,7 @@ export class JsonOb { self._callback(newVal, ov, pathArray); } } - }) + }); // @ts-ignore const o = obj[key]; @@ -76,33 +76,33 @@ export class JsonOb { /** * 对数组类型进行动态绑定 - * @param array - * @param path + * @param array + * @param path */ private overrideArrayProto(array: any, path: any) { - // 保存原始 Array 原型 - var originalProto = Array.prototype; - // 通过 Object.create 方法创建一个对象,该对象的原型是Array.prototype - var overrideProto = Object.create(Array.prototype); - var self = this; - var result; + // 保存原始 Array 原型 + const originalProto = Array.prototype; + // 通过 Object.create 方法创建一个对象,该对象的原型是Array.prototype + const overrideProto = Object.create(Array.prototype); + const self = this; + let result; - // 遍历要重写的数组方法 + // 遍历要重写的数组方法 OAM.forEach((method: any) => { Object.defineProperty(overrideProto, method, { value: function () { - var oldVal = this.slice(); - // 调用原始原型上的方法 + const oldVal = this.slice(); + // 调用原始原型上的方法 result = originalProto[method].apply(this, arguments); - // 继续监听新数组 + // 继续监听新数组 self.observe(this, path); self._callback(this, oldVal, path); return result; } - }) + }); }); - // 最后 让该数组实例的 __proto__ 属性指向 假的原型 overrideProto + // 最后 让该数组实例的 __proto__ 属性指向 假的原型 overrideProto array['__proto__'] = overrideProto; } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/StringFormat.ts b/assets/libs/model-view/StringFormat.ts index 5b24aae..2cde93d 100644 --- a/assets/libs/model-view/StringFormat.ts +++ b/assets/libs/model-view/StringFormat.ts @@ -1,4 +1,4 @@ -import { LanguageData } from "../gui/language/LanguageData"; +import { LanguageData } from '../gui/language/LanguageData'; /** * 数值格式化函数, 通过语义解析自动设置值的范围 @@ -8,37 +8,37 @@ class StringFormat { deal(value: number | string, format: string): string { if (format === '') return value as string; - format = format.toLowerCase().trim(); // 不区分大小 - let match_func = format.match(/^[a-z|A-Z]+/gi); // 匹配到 format 中的函数名 - let match_num = format.match(/\d+$/gi); // 匹配到 format 中的参数 - let func: string = ''; - let num: number = 0; + format = format.toLowerCase().trim(); // 不区分大小 + const match_func = format.match(/^[a-z|A-Z]+/gi); // 匹配到 format 中的函数名 + const match_num = format.match(/\d+$/gi); // 匹配到 format 中的参数 + let func = ''; + let num = 0; let res: number | string = ''; if (match_func) func = match_func[0]; if (match_num) num = parseInt(match_num[0]); - if (typeof value == 'number') { + if (typeof value === 'number') { switch (func) { - case 'int': res = this.int(value); break; - case 'fix': res = this.fix(value, num); break; - case 'kmbt': res = this.kmbt(value); break; - case 'per': res = this.per(value, num); break; - case 'sep': res = this.sep(value); break; + case 'int': res = this.int(value); break; + case 'fix': res = this.fix(value, num); break; + case 'kmbt': res = this.kmbt(value); break; + case 'per': res = this.per(value, num); break; + case 'sep': res = this.sep(value); break; - case 'stamp': res = this.time_stamp(value); break; - case 'ms': res = this.time_ms(value); break; - case 'hms': res = this.time_hms(value); break; - case 'hmss': res = this.time_hmss(value); break; + case 'stamp': res = this.time_stamp(value); break; + case 'ms': res = this.time_ms(value); break; + case 'hms': res = this.time_hms(value); break; + case 'hmss': res = this.time_hmss(value); break; - default: break; + default: break; } } else { switch (func) { - case 'limit': res = this.limit(value, num); break; - default: - break; + case 'limit': res = this.limit(value, num); break; + default: + break; } res = value; } @@ -48,8 +48,8 @@ class StringFormat { /** 将数字按分号显示 */ private sep(value: number) { - let num = Math.round(value).toString(); - return num.replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), "$1,"); + const num = Math.round(value).toString(); + return num.replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), '$1,'); } /** 将数字按分显示 00:00 显示 (分:秒) */ @@ -74,7 +74,7 @@ class StringFormat { /** [value:int] 将取值0~1 变成 1~100,可以指定修饰的小数位数 */ private per(value: number, fd: number) { - let r = value * 100; + const r = value * 100; return r.toFixed(fd); } @@ -85,7 +85,7 @@ class StringFormat { /** [value:fix2]数值转换为小数 */ private fix(value: number, fd: number) { - return value.toFixed(fd) + return value.toFixed(fd); } /** [value:limit3]字符串长度限制 */ @@ -100,25 +100,25 @@ class StringFormat { let units: string[] = null!; switch (LanguageData.current) { - case 'zh': - //10^4=万, 10^8=亿,10^12=兆,10^16=京, - counts = [10000, 100000000, 1000000000000, 10000000000000000]; - units = ['', '万', '亿', '兆', '京']; - break; - default: - counts = [1000, 1000000, 1000000000, 1000000000000]; - units = ['', 'K', 'M', 'B', 'T']; - break; + case 'zh': + //10^4=万, 10^8=亿,10^12=兆,10^16=京, + counts = [10000, 100000000, 1000000000000, 10000000000000000]; + units = ['', '万', '亿', '兆', '京']; + break; + default: + counts = [1000, 1000000, 1000000000, 1000000000000]; + units = ['', 'K', 'M', 'B', 'T']; + break; } return this.compressUnit(value, counts, units, 2); } /** 压缩任意单位的数字,后缀加上单位文字 */ - private compressUnit(value: any, valueArr: number[], unitArr: string[], fixNum: number = 2): string { - let counts = valueArr; - let units = unitArr; - let res: string = ""; + private compressUnit(value: any, valueArr: number[], unitArr: string[], fixNum = 2): string { + const counts = valueArr; + const units = unitArr; + let res = ''; let index: number; for (index = 0; index < counts.length; index++) { const e = counts[index]; @@ -137,4 +137,4 @@ class StringFormat { } /** 格式化处理函数 */ -export let StringFormatFunction = new StringFormat(); \ No newline at end of file +export const StringFormatFunction = new StringFormat(); diff --git a/assets/libs/model-view/VMBase.ts b/assets/libs/model-view/VMBase.ts index b1ba08d..6be9c07 100644 --- a/assets/libs/model-view/VMBase.ts +++ b/assets/libs/model-view/VMBase.ts @@ -8,7 +8,7 @@ import { VMEnv } from './VMEnv'; // 目前只是起到一个识别组件的作用,之后会抽象很多功能在这里面 // player.equips.* 可以自动根据所在父对象的位置设置顺序 -const DEBUG_WATCH_PATH: boolean = false; +const DEBUG_WATCH_PATH = false; const { ccclass, help } = _decorator; @@ -22,10 +22,10 @@ export class VMBase extends Component { VM = VM; /** watch 单路径 */ - watchPath: string = ''; + watchPath = ''; /** 是否启用模板多路径模式 */ - templateMode: boolean = false; + templateMode = false; /** watch 多路径 */ protected watchPathArr: string[] = []; @@ -40,12 +40,12 @@ export class VMBase extends Component { if (VMEnv.editor) return; // 提前拆分、并且解析路径 - let paths = this.watchPath.split('.'); + const paths = this.watchPath.split('.'); for (let i = 1; i < paths.length; i++) { const p = paths[i]; // 如果发现了路径使用了 * ,则自动去自己的父节点查找自己所在 index 值 if (p == '*') { - let index = this.node.parent!.children.findIndex(n => n === this.node); + let index = this.node.parent!.children.findIndex((n) => n === this.node); if (index <= 0) index = 0; paths[i] = index.toString(); break; @@ -56,16 +56,16 @@ export class VMBase extends Component { this.watchPath = paths.join('.'); // 提前进行路径数组 的 解析 - let pathArr = this.watchPathArr; + const pathArr = this.watchPathArr; if (pathArr.length >= 1) { for (let i = 0; i < pathArr.length; i++) { const path = pathArr[i]; - let paths = path.split('.'); + const paths = path.split('.'); for (let i = 1; i < paths.length; i++) { const p = paths[i]; if (p == '*') { - let index = this.node.parent!.children.findIndex(n => n === this.node); + let index = this.node.parent!.children.findIndex((n) => n === this.node); if (index <= 0) index = 0; paths[i] = index.toString(); break; @@ -79,7 +79,7 @@ export class VMBase extends Component { // 打印出所有绑定的路径,方便调试信息 if (DEBUG_WATCH_PATH && DEBUG) { - log('所有路径', this.watchPath ? [this.watchPath] : this.watchPathArr, '<<', this.node.parent!.name + '.' + this.node.name) + log('所有路径', this.watchPath ? [this.watchPath] : this.watchPathArr, '<<', this.node.parent!.name + '.' + this.node.name); } if (this.watchPath == '' && this.watchPathArr.join('') == '') { @@ -97,7 +97,7 @@ export class VMBase extends Component { this.VM.bindPath(this.watchPath, this.onValueChanged, this); } - this.onValueInit(); // 激活时,调用值初始化 + this.onValueInit(); // 激活时,调用值初始化 } onDisable() { @@ -112,10 +112,10 @@ export class VMBase extends Component { } // 多路径监听方式 - private setMultPathEvent(enabled: boolean = true) { + private setMultPathEvent(enabled = true) { if (VMEnv.editor) return; - let arr = this.watchPathArr; + const arr = this.watchPathArr; for (let i = 0; i < arr.length; i++) { const path = arr[i]; if (enabled) { diff --git a/assets/libs/model-view/VMCompsEdit.ts b/assets/libs/model-view/VMCompsEdit.ts index d8c6228..5a8bc83 100644 --- a/assets/libs/model-view/VMCompsEdit.ts +++ b/assets/libs/model-view/VMCompsEdit.ts @@ -1,5 +1,5 @@ -import { _decorator, CCString, Component, Enum, log, Node } from "cc"; -import { VMEnv } from "./VMEnv"; +import { _decorator, CCString, Component, Enum, log, Node } from 'cc'; +import { VMEnv } from './VMEnv'; const { ccclass, property, executeInEditMode, menu, help } = _decorator; @@ -22,12 +22,12 @@ export default class MVCompsEdit extends Component { @property({ type: [CCString] }) - findList: string[] = ["VMBase", "VMParent"]; + findList: string[] = ['VMBase', 'VMParent']; @property({ type: Enum(ACTION_MODE) }) - actionType: ACTION_MODE = ACTION_MODE.SEARCH_COMPONENT; + actionType: ACTION_MODE = ACTION_MODE.SEARCH_COMPONENT; @property({ tooltip: '勾选后,会自动查找 find list 中填写的组件', @@ -78,7 +78,7 @@ export default class MVCompsEdit extends Component { return this.actionType === ACTION_MODE.DELETE_COMPONENT; } }) - allowDelete: boolean = false; + allowDelete = false; @property({ tooltip: '勾选后,会批量删除 find list 中填写的组件', @@ -116,7 +116,7 @@ export default class MVCompsEdit extends Component { return this.actionType === ACTION_MODE.REPLACE_WATCH_PATH; } }) - targetPath: string = 'game'; + targetPath = 'game'; @property({ tooltip: '替换的路径,将匹配到的路径替换', @@ -125,7 +125,7 @@ export default class MVCompsEdit extends Component { return this.actionType === ACTION_MODE.REPLACE_WATCH_PATH; } }) - replacePath: string = '*'; + replacePath = '*'; @property({ @@ -135,7 +135,7 @@ export default class MVCompsEdit extends Component { return this.actionType === ACTION_MODE.SEARCH_COMPONENT; } }) - canCollectNodes: boolean = false; + canCollectNodes = false; @property({ type: [Node], @@ -143,51 +143,51 @@ export default class MVCompsEdit extends Component { tooltip: '收集到绑定了VM组件相关的节点,可以自己跳转过去', visible: function () { // @ts-ignore - return this.canCollectNodes && this.actionType === ACTION_MODE.SEARCH_COMPONENT + return this.canCollectNodes && this.actionType === ACTION_MODE.SEARCH_COMPONENT; } }) - collectNodes: Node[] = []; + collectNodes: Node[] = []; onLoad() { if (VMEnv.editor) return; - let path = this.getNodePath(this.node); + const path = this.getNodePath(this.node); console.error('you forget delete MVEditFinder,[path]', path); } setComponents(state: number) { - let array = this.findList; + const array = this.findList; let title = '搜索到当前节点下面的组件'; switch (state) { - case 0: title = '搜索到当前节点下面的组件'; break; - case 1: title = '激活以下节点的组件'; break; - case 2: title = '关闭以下节点的组件'; break; - case 3: title = '删除以下节点的组件'; break; - case 4: title = '替换以下节点的路径'; break; + case 0: title = '搜索到当前节点下面的组件'; break; + case 1: title = '激活以下节点的组件'; break; + case 2: title = '关闭以下节点的组件'; break; + case 3: title = '删除以下节点的组件'; break; + case 4: title = '替换以下节点的路径'; break; - default: - break; + default: + break; } - log(title) - log('______________________') + log(title); + log('______________________'); - array.forEach(name => { - this.searchComponent(name, state) - }) + array.forEach((name) => { + this.searchComponent(name, state); + }); - log('______________________') + log('______________________'); } /** - * - * @param className + * + * @param className * @param state 0-查找节点组件 1-激活节点组件 2-关闭节点组件 3-移除节点组件 */ - searchComponent(className: string, state: number = 0) { + searchComponent(className: string, state = 0) { /**收集节点清空 */ this.collectNodes = []; - let comps = this.node.getComponentsInChildren(className); + const comps = this.node.getComponentsInChildren(className); if (comps == null || comps.length < 1) return; log('[' + className + ']:'); comps.forEach((v: any) => { @@ -196,55 +196,55 @@ export default class MVCompsEdit extends Component { if (state <= 3) { //区分模板模式路径 if (v.templateMode === true) { - ext = v.watchPathArr ? ':[Path:' + v.watchPathArr.join('|') + ']' : '' + ext = v.watchPathArr ? ':[Path:' + v.watchPathArr.join('|') + ']' : ''; } else { - ext = v.watchPath ? ':[Path:' + v.watchPath + ']' : '' + ext = v.watchPath ? ':[Path:' + v.watchPath + ']' : ''; } } log(this.getNodePath(v.node) + ext); switch (state) { - case 0://寻找组件 - if (this.canCollectNodes) { - if (this.collectNodes.indexOf(v.node) === -1) { - this.collectNodes.push(v.node); - } + case 0://寻找组件 + if (this.canCollectNodes) { + if (this.collectNodes.indexOf(v.node) === -1) { + this.collectNodes.push(v.node); } - break; - case 1: // 激活组件 - v.enabled = true; - break; - case 2: // 关闭组件 - v.enabled = false; - break; - case 3: // 删除组件 - v.node.removeComponent(v); - break; - case 4: // 替换指定路径 - let targetPath = this.targetPath; - let replacePath = this.replacePath; - if (v.templateMode === true) { - for (let i = 0; i < v.watchPathArr.length; i++) { - const path = v.watchPathArr[i]; - v.watchPathArr[i] = this.replaceNodePath(path, targetPath, replacePath); - } - } - else { - v.watchPath = this.replaceNodePath(v.watchPath, targetPath, replacePath); + } + break; + case 1: // 激活组件 + v.enabled = true; + break; + case 2: // 关闭组件 + v.enabled = false; + break; + case 3: // 删除组件 + v.node.removeComponent(v); + break; + case 4: // 替换指定路径 + const targetPath = this.targetPath; + const replacePath = this.replacePath; + if (v.templateMode === true) { + for (let i = 0; i < v.watchPathArr.length; i++) { + const path = v.watchPathArr[i]; + v.watchPathArr[i] = this.replaceNodePath(path, targetPath, replacePath); } + } + else { + v.watchPath = this.replaceNodePath(v.watchPath, targetPath, replacePath); + } - default: - break; + default: + break; } }); } replaceNodePath(path: string, search: string, replace: string) { - let pathArr = path.split('.'); - let searchArr = search.split('.'); - let replaceArr = replace.split('.') + const pathArr = path.split('.'); + const searchArr = search.split('.'); + const replaceArr = replace.split('.'); let match = true; for (let i = 0; i < searchArr.length; i++) { @@ -261,7 +261,7 @@ export default class MVCompsEdit extends Component { for (let i = 0; i < replaceArr.length; i++) { pathArr[i] = replaceArr[i]; } - log(' 路径更新:', path, '>>>', pathArr.join('.')) + log(' 路径更新:', path, '>>>', pathArr.join('.')); } return pathArr.join('.'); @@ -269,9 +269,9 @@ export default class MVCompsEdit extends Component { getNodePath(node: Node) { let parent = node; - let array: string[] = []; + const array: string[] = []; while (parent) { - let p = parent.getParent(); + const p = parent.getParent(); if (p) { array.push(parent.name); parent = p; @@ -282,4 +282,4 @@ export default class MVCompsEdit extends Component { } return array.reverse().join('/'); } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMCustom.ts b/assets/libs/model-view/VMCustom.ts index 5db4230..0e1e5e8 100644 --- a/assets/libs/model-view/VMCustom.ts +++ b/assets/libs/model-view/VMCustom.ts @@ -30,22 +30,22 @@ export class VMCustom extends VMBase { @property({ tooltip: '激活controller,以开启双向绑定,否则只能接收消息', }) - controller: boolean = false; + controller = false; @property({ - tooltip: "监视对象路径" + tooltip: '监视对象路径' }) - watchPath: string = ""; + watchPath = ''; @property({ tooltip: '绑定组件的名字' }) - componentName: string = ""; + componentName = ''; @property({ tooltip: '组件上需要监听的属性' }) - componentProperty: string = ""; + componentProperty = ''; @property({ tooltip: '刷新间隔频率(只影响脏检查的频率)', @@ -56,7 +56,7 @@ export class VMCustom extends VMBase { return this.controller === true; } }) - refreshRate: number = 0.1; + refreshRate = 0.1; /** 计时器 */ private _timer = 0; @@ -65,7 +65,7 @@ export class VMCustom extends VMBase { private _watchComponent: any = null; /** 是否能监听组件的数据 */ - private _canWatchComponent: boolean = false; + private _canWatchComponent = false; /** 检查的值 */ private _oldValue: any = null; @@ -95,10 +95,10 @@ export class VMCustom extends VMBase { checkEditorComponent() { if (VMEnv.editor) return; - let checkArray = COMP_ARRAY_CHECK; + const checkArray = COMP_ARRAY_CHECK; for (let i = 0; i < checkArray.length; i++) { const params = checkArray[i]; - let comp = this.node.getComponent(params[0] as string); + const comp = this.node.getComponent(params[0] as string); if (comp) { if (this.componentName == '') this.componentName = params[0] as string; if (this.componentProperty == '') this.componentProperty = params[1] as string; @@ -111,9 +111,15 @@ export class VMCustom extends VMBase { checkComponentState() { this._canWatchComponent = false; - if (!this._watchComponent) { console.error('未设置需要监听的组件'); return; } - if (!this.componentProperty) { console.error('未设置需要监听的组件 的属性'); return; } - if (this.componentProperty in this._watchComponent === false) { console.error('需要监听的组件的属性不存在'); return; } + if (!this._watchComponent) { + console.error('未设置需要监听的组件'); return; + } + if (!this.componentProperty) { + console.error('未设置需要监听的组件 的属性'); return; + } + if (this.componentProperty in this._watchComponent === false) { + console.error('需要监听的组件的属性不存在'); return; + } this._canWatchComponent = true; } @@ -123,8 +129,8 @@ export class VMCustom extends VMBase { setComponentValue(value: any) { // 如果遇到 Toggle 组件就调用上面的方法解决 - if (this.componentName == "cc.Toggle") { - this.node.getComponent(Toggle)!.isChecked = value + if (this.componentName == 'cc.Toggle') { + this.node.getComponent(Toggle)!.isChecked = value; } else { this._watchComponent[this.componentProperty] = value; @@ -153,7 +159,7 @@ export class VMCustom extends VMBase { // 脏检查(组件是否存在,是否被激活) if (VMEnv.editor) return; - //if (this.templateMode == true) return; //todo 模板模式下不能计算 + //if (this.templateMode == true) return; //todo 模板模式下不能计算 if (!this.controller) return; if (!this._canWatchComponent || this._watchComponent['enabled'] === false) return; @@ -162,11 +168,11 @@ export class VMCustom extends VMBase { if (this._timer < this.refreshRate) return; this._timer = 0; - let oldValue = this._oldValue; - let newValue = this.getComponentValue(); + const oldValue = this._oldValue; + const newValue = this.getComponentValue(); if (this._oldValue === newValue) return; this._oldValue = this.getComponentValue(); this.onValueController(newValue, oldValue); } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMEnv.ts b/assets/libs/model-view/VMEnv.ts index c01816b..b06bf8e 100644 --- a/assets/libs/model-view/VMEnv.ts +++ b/assets/libs/model-view/VMEnv.ts @@ -1,4 +1,4 @@ -import { EDITOR_NOT_IN_PREVIEW } from "cc/env"; +import { EDITOR_NOT_IN_PREVIEW } from 'cc/env'; /** VM组件环境验证 */ export class VMEnv { @@ -6,4 +6,4 @@ export class VMEnv { static get editor() { return EDITOR_NOT_IN_PREVIEW; } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMEvent.ts b/assets/libs/model-view/VMEvent.ts index 4086d80..72e5c6d 100644 --- a/assets/libs/model-view/VMEvent.ts +++ b/assets/libs/model-view/VMEvent.ts @@ -3,23 +3,23 @@ import { VMBase } from './VMBase'; // +普通 label 更新数据的情况,label.string = xxx; // +frameIndex 插件,通过number 数值设置 BhvFrameIndex 来切换当前贴图 -// +spriteFrame 直接替换贴图的情况 , +// +spriteFrame 直接替换贴图的情况 , // 读取本地路径 data.spriteFrame = $res:/pic/com1 // 读取网页路径 data.spriteFrame = $url:http:xxxxxxxxxx.png -// +特殊条件控制 +// +特殊条件控制 // 比较条件:,如果传入值 > /< />= /<= /== 某值时,执行的action类型 const { ccclass, property, executeInEditMode, menu, help } = _decorator; enum FILTER_MODE { - "none", - "==", // 正常计算,比较 等于 - "!=", // 正常计算,比较 不等于 - ">", // 正常计算,比较> - ">=", // 正常计算,比较>= - "<", // 正常计算,比较< - "<=", // 正常计算,比较>= + 'none', + '==', // 正常计算,比较 等于 + '!=', // 正常计算,比较 不等于 + '>', // 正常计算,比较> + '>=', // 正常计算,比较>= + '<', // 正常计算,比较< + '<=', // 正常计算,比较>= } /** @@ -35,7 +35,7 @@ export default class VMEvent extends VMBase { @property({ tooltip: '使用模板模式,可以使用多路径监听' }) - templateMode: boolean = false; + templateMode = false; @property({ tooltip: '监听获取值的路径', @@ -44,12 +44,12 @@ export default class VMEvent extends VMBase { return this.templateMode === false; } }) - watchPath: string = ""; + watchPath = ''; @property({ tooltip: '触发一次后会自动关闭该事件' }) - triggerOnce: boolean = false; + triggerOnce = false; @property({ tooltip: '监听获取值的多条路径,这些值的改变都会通过这个函数回调,请使用 pathArr 区分获取的值 ', @@ -65,31 +65,31 @@ export default class VMEvent extends VMBase { tooltip: '过滤模式,会根据条件过滤掉时间的触发', type: Enum(FILTER_MODE) }) - filterMode: FILTER_MODE = FILTER_MODE.none; + filterMode: FILTER_MODE = FILTER_MODE.none; @property({ visible: function () { // @ts-ignore - return this.filterMode !== FILTER_MODE.none + return this.filterMode !== FILTER_MODE.none; } }) - compareValue: string = ''; + compareValue = ''; @property([EventHandler]) - changeEvents: EventHandler[] = []; + changeEvents: EventHandler[] = []; onValueInit() { } onValueChanged(newVar: any, oldVar: any, pathArr: any[]) { - let res = this.conditionCheck(newVar, this.compareValue); + const res = this.conditionCheck(newVar, this.compareValue); if (!res) return; if (Array.isArray(this.changeEvents)) { - this.changeEvents.forEach(v => { + this.changeEvents.forEach((v) => { v.emit([newVar, oldVar, pathArr]); - }) + }); } // 激活一次后,自动关闭组件 @@ -100,37 +100,37 @@ export default class VMEvent extends VMBase { /** 条件检查 */ private conditionCheck(a: any, b: any): boolean { - let cod = FILTER_MODE; + const cod = FILTER_MODE; switch (this.filterMode) { - case cod.none: - return true; - case cod["=="]: - if (a == b) return true; - break; - case cod["!="]: - if (a != b) return true; - break; - case cod["<"]: - if (a < b) return true; - break; - case cod[">"]: - if (a > b) return true; - break; - case cod[">="]: - if (a >= b) return true; - break; - case cod["<"]: - if (a < b) return true; - break; - case cod["<="]: - if (a <= b) return true; - break; + case cod.none: + return true; + case cod['==']: + if (a == b) return true; + break; + case cod['!=']: + if (a != b) return true; + break; + case cod['<']: + if (a < b) return true; + break; + case cod['>']: + if (a > b) return true; + break; + case cod['>=']: + if (a >= b) return true; + break; + case cod['<']: + if (a < b) return true; + break; + case cod['<=']: + if (a <= b) return true; + break; - default: - break; + default: + break; } return false; } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMLabel.ts b/assets/libs/model-view/VMLabel.ts index 9f5c1c6..4d3593f 100644 --- a/assets/libs/model-view/VMLabel.ts +++ b/assets/libs/model-view/VMLabel.ts @@ -1,4 +1,5 @@ -import { _decorator, CCString, error, Node } from 'cc'; +import type { Node } from 'cc'; +import { _decorator, CCString, error } from 'cc'; import { StringFormatFunction } from './StringFormat'; import { VMBase } from './VMBase'; import { VMEnv } from './VMEnv'; @@ -9,7 +10,7 @@ const LABEL_TYPE = { CC_LABEL: 'cc.Label', CC_RICH_TEXT: 'cc.RichText', CC_EDIT_BOX: 'cc.EditBox' -} +}; /** * [VM-Label] @@ -28,7 +29,7 @@ export default class VMLabel extends VMBase { * @param watchPath 监听数据路径 */ static bind(node: Node, watchPath: string | string[]) { - let label = node.addComponent(VMLabel); + const label = node.addComponent(VMLabel); if (watchPath instanceof Array) { label.templateMode = true; label.watchPathArr = watchPath; @@ -41,7 +42,7 @@ export default class VMLabel extends VMBase { @property({ tooltip: '是否启用模板代码,只能在运行时之前设置,\n将会动态解析模板语法 {{0}},并且自动设置监听的路径' }) - templateMode: boolean = false; + templateMode = false; @property({ visible() { @@ -49,7 +50,7 @@ export default class VMLabel extends VMBase { return this.templateMode === false; } }) - watchPath: string = ''; + watchPath = ''; @property({ readonly: true @@ -99,35 +100,35 @@ export default class VMLabel extends VMBase { /** 解析模板 获取初始格式化字符串格式的信息 */ parseTemplate() { - let regexAll = /\{\{(.+?)\}\}/g; // 匹配: 所有的{{value}} - let regex = /\{\{(.+?)\}\}/; // 匹配: {{value}} 中的 value - let res = this.originText!.match(regexAll); // 匹配结果数组 + const regexAll = /\{\{(.+?)\}\}/g; // 匹配: 所有的{{value}} + const regex = /\{\{(.+?)\}\}/; // 匹配: {{value}} 中的 value + const res = this.originText!.match(regexAll); // 匹配结果数组 if (res == null) return; for (let i = 0; i < res.length; i++) { const e = res[i]; - let arr = e.match(regex); - let matchName = arr![1]; + const arr = e.match(regex); + const matchName = arr![1]; // let paramIndex = parseInt(matchName) || 0; - let matchInfo = matchName.split(':')[1] || ''; + const matchInfo = matchName.split(':')[1] || ''; this.templateFormatArr[i] = matchInfo; } } /** 获取解析字符串模板后得到的值 */ getReplaceText() { - if (!this.originText) return ""; - let regexAll = /\{\{(.+?)\}\}/g; // 匹配: 所有的{{value}} - let regex = /\{\{(.+?)\}\}/; // 匹配: {{value}} 中的 value - let res = this.originText.match(regexAll); // 匹配结果数组 [{{value}},{{value}},{{value}}] - if (res == null) return ''; // 未匹配到文本 - let str = this.originText; // 原始字符串模板 "name:{{0}} 或 name:{{0:fix2}}" + if (!this.originText) return ''; + const regexAll = /\{\{(.+?)\}\}/g; // 匹配: 所有的{{value}} + const regex = /\{\{(.+?)\}\}/; // 匹配: {{value}} 中的 value + const res = this.originText.match(regexAll); // 匹配结果数组 [{{value}},{{value}},{{value}}] + if (res == null) return ''; // 未匹配到文本 + let str = this.originText; // 原始字符串模板 "name:{{0}} 或 name:{{0:fix2}}" for (let i = 0; i < res.length; i++) { const e = res[i]; let getValue; - let arr = e.match(regex); // 匹配到的数组 [{{value}}, value] - let indexNum = parseInt(arr![1] || '0') || 0; // 取出数组的 value 元素 转换成整数 - let format = this.templateFormatArr[i]; // 格式化字符 的 配置参数 + const arr = e.match(regex); // 匹配到的数组 [{{value}}, value] + const indexNum = parseInt(arr![1] || '0') || 0; // 取出数组的 value 元素 转换成整数 + const format = this.templateFormatArr[i]; // 格式化字符 的 配置参数 getValue = this.templateValueArr[indexNum]; str = str.replace(e, this.getValueFromFormat(getValue, format));//从路径缓存值获取数据 } @@ -146,7 +147,7 @@ export default class VMLabel extends VMBase { this.setLabelValue(this.VM.getValue(this.watchPath)); // } else { - let max = this.watchPathArr.length; + const max = this.watchPathArr.length; for (let i = 0; i < max; i++) { this.templateValueArr[i] = this.VM.getValue(this.watchPathArr[i], '?'); } @@ -160,30 +161,30 @@ export default class VMLabel extends VMBase { this.setLabelValue(n); } else { - let path = pathArr.join('.'); + const path = pathArr.join('.'); // 寻找缓存位置 - let index = this.watchPathArr.findIndex(v => v === path); + const index = this.watchPathArr.findIndex((v) => v === path); if (index >= 0) { //如果是所属的路径,就可以替换文本了 - this.templateValueArr[index] = n; // 缓存值 + this.templateValueArr[index] = n; // 缓存值 this.setLabelValue(this.getReplaceText()); // 重新解析文本 } } } setLabelValue(value: string) { - var component: any = this.getComponent(this.labelType); + const component: any = this.getComponent(this.labelType); component.string = value + ''; } getLabelValue(): string { - var component: any = this.getComponent(this.labelType); + const component: any = this.getComponent(this.labelType); return component.string; } private checkLabel() { - let checkArray = [ + const checkArray = [ 'cc.Label', 'cc.RichText', 'cc.EditBox', @@ -191,7 +192,7 @@ export default class VMLabel extends VMBase { for (let i = 0; i < checkArray.length; i++) { const e = checkArray[i]; - let comp = this.node.getComponent(e); + const comp = this.node.getComponent(e); if (comp) { this.labelType = e; return true; @@ -202,4 +203,4 @@ export default class VMLabel extends VMBase { return false; } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMModify.ts b/assets/libs/model-view/VMModify.ts index cd07d42..06eb2ac 100644 --- a/assets/libs/model-view/VMModify.ts +++ b/assets/libs/model-view/VMModify.ts @@ -20,14 +20,14 @@ enum CLAMP_MODE { @help('https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037642&doc_id=2873565') export default class VMModify extends VMBase { @property({ - tooltip: "监视对象路径" + tooltip: '监视对象路径' }) - watchPath: string = ""; + watchPath = ''; @property({ - tooltip: "是不启用取值范围限制" + tooltip: '是不启用取值范围限制' }) - valueClamp: boolean = false; + valueClamp = false; @property({ type: Enum(CLAMP_MODE), @@ -36,7 +36,7 @@ export default class VMModify extends VMBase { return this.valueClamp === true; } }) - valueClampMode: CLAMP_MODE = CLAMP_MODE.MIN_MAX; + valueClampMode: CLAMP_MODE = CLAMP_MODE.MIN_MAX; @property({ visible: function () { @@ -44,7 +44,7 @@ export default class VMModify extends VMBase { return this.valueClamp === true && this.valueClampMode !== CLAMP_MODE.MAX; } }) - valueMin: number = 0; + valueMin = 0; @property({ visible: function () { @@ -52,26 +52,26 @@ export default class VMModify extends VMBase { return this.valueClamp === true && this.valueClampMode !== CLAMP_MODE.MIN; } }) - valueMax: number = 1; + valueMax = 1; // 限制最终结果的取值范围 private clampValue(res: number): number { - let min = this.valueMin; - let max = this.valueMax; + const min = this.valueMin; + const max = this.valueMax; if (this.valueClamp == false) return res; switch (this.valueClampMode) { - case CLAMP_MODE.MIN_MAX: - if (res > max) res = max; - if (res < min) res = min; - break; - case CLAMP_MODE.MIN: - if (res < min) res = min; - break; - case CLAMP_MODE.MAX: - if (res > max) res = max; - break; - default: - break; + case CLAMP_MODE.MIN_MAX: + if (res > max) res = max; + if (res < min) res = min; + break; + case CLAMP_MODE.MIN: + if (res < min) res = min; + break; + case CLAMP_MODE.MAX: + if (res > max) res = max; + break; + default: + break; } return res; @@ -98,40 +98,48 @@ export default class VMModify extends VMBase { } /** 加 */ - vAdd(e: Event, data: string, int: boolean = false) { - let a = parseFloat(data); + vAdd(e: Event, data: string, int = false) { + const a = parseFloat(data); let res = this.VM.getValue(this.watchPath, 0) + a; - if (int) { res = Math.round(res) } + if (int) { + res = Math.round(res); + } this.VM.setValue(this.watchPath, this.clampValue(res)); } /** 减 */ - vSub(e: Event, data: string, int: boolean = false) { - let a = parseFloat(data); + vSub(e: Event, data: string, int = false) { + const a = parseFloat(data); let res = this.VM.getValue(this.watchPath, 0) - a; - if (int) { res = Math.round(res) } + if (int) { + res = Math.round(res); + } this.VM.setValue(this.watchPath, this.clampValue(res)); } /** 乘 */ - vMul(e: Event, data: string, int: boolean = false) { - let a = parseFloat(data); + vMul(e: Event, data: string, int = false) { + const a = parseFloat(data); let res = this.VM.getValue(this.watchPath, 0) * a; - if (int) { res = Math.round(res) } + if (int) { + res = Math.round(res); + } this.VM.setValue(this.watchPath, this.clampValue(res)); } /** 除 */ - vDiv(e: Event, data: string, int: boolean = false) { - let a = parseFloat(data); + vDiv(e: Event, data: string, int = false) { + const a = parseFloat(data); let res = this.VM.getValue(this.watchPath, 0) / a; - if (int) { res = Math.round(res) } + if (int) { + res = Math.round(res); + } this.VM.setValue(this.watchPath, this.clampValue(res)); } /** 字符串赋值 */ vString(e: Event, data: string) { - let a = data; + const a = data; this.VM.setValue(this.watchPath, a); } @@ -141,9 +149,11 @@ export default class VMModify extends VMBase { } /** 数字赋值 */ - vNumber(e: Event, data: string, int: boolean = false) { + vNumber(e: Event, data: string, int = false) { let a = parseFloat(data); - if (int) { a = Math.round(a) } + if (int) { + a = Math.round(a); + } this.VM.setValue(this.watchPath, this.clampValue(a)); } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMParent.ts b/assets/libs/model-view/VMParent.ts index abcd52f..c4b9b4e 100644 --- a/assets/libs/model-view/VMParent.ts +++ b/assets/libs/model-view/VMParent.ts @@ -1,4 +1,5 @@ -import { Component, _decorator } from 'cc'; +import type { Component } from 'cc'; +import { _decorator } from 'cc'; import { GameComponent } from '../../module/common/GameComponent'; import { VM } from './ViewModel'; import { VMBase } from './VMBase'; @@ -17,19 +18,19 @@ const { ccclass, help, executionOrder } = _decorator; @help('https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037729&doc_id=2873565') export default class VMParent extends GameComponent { /** 绑定的标签,可以通过这个tag 获取 当前的 vm 实例 */ - protected tag: string = '_temp'; + protected tag = '_temp'; /** 需要绑定的私有数据 */ protected data: any = {}; /** * [注意]不能直接覆盖此方法,如果需要覆盖。 - * 只能在该方法内部调用父类的实现 + * 只能在该方法内部调用父类的实现 * ```ts * onLoad(){ * super.onLoad(); * } - * ``` + * ``` */ onLoad() { if (this.data == null) return; @@ -39,7 +40,7 @@ export default class VMParent extends GameComponent { VM.add(this.data, this.tag); // log(VM['_mvs'],this.tag) //搜寻所有节点:找到 watch path - let comps = this.getVMComponents(); + const comps = this.getVMComponents(); // console.group(); for (let i = 0; i < comps.length; i++) { const comp = comps[i]; @@ -56,11 +57,11 @@ export default class VMParent extends GameComponent { private replaceVMPath(comp: Component, tag: string) { // @ts-ignore - let path: string = comp['watchPath']; + const path: string = comp['watchPath']; // @ts-ignore if (comp['templateMode'] == true) { // @ts-ignore - let pathArr: string[] = comp['watchPathArr']; + const pathArr: string[] = comp['watchPathArr']; if (pathArr) { for (let i = 0; i < pathArr.length; i++) { const path = pathArr[i]; @@ -82,13 +83,13 @@ export default class VMParent extends GameComponent { /** 未优化的遍历节点,获取VM 组件 */ private getVMComponents() { let comps = this.node.getComponentsInChildren(VMBase); - let parents = this.node.getComponentsInChildren(VMParent).filter(v => v.uuid !== this.uuid); // 过滤掉自己 + const parents = this.node.getComponentsInChildren(VMParent).filter((v) => v.uuid !== this.uuid); // 过滤掉自己 //过滤掉不能赋值的parent let filters: any[] = []; parents.forEach((node: Component) => { filters = filters.concat(node.getComponentsInChildren(VMBase)); - }) + }); comps = comps.filter((v) => filters.indexOf(v) < 0); return comps; @@ -112,4 +113,4 @@ export default class VMParent extends GameComponent { super.onDestroy(); } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMProgress.ts b/assets/libs/model-view/VMProgress.ts index 192477a..4679d5d 100644 --- a/assets/libs/model-view/VMProgress.ts +++ b/assets/libs/model-view/VMProgress.ts @@ -4,10 +4,10 @@ * @LastEditors: dgflash * @LastEditTime: 2022-08-11 15:43:34 */ -import { CCString, _decorator } from "cc"; -import { StringFormatFunction } from "./StringFormat"; -import { VMCustom } from "./VMCustom"; -import { VMEnv } from "./VMEnv"; +import { CCString, _decorator } from 'cc'; +import { StringFormatFunction } from './StringFormat'; +import { VMCustom } from './VMCustom'; +import { VMEnv } from './VMEnv'; const { ccclass, property, menu, help } = _decorator; @@ -19,7 +19,7 @@ export default class VMProgress extends VMCustom { visible: false, override: true }) - watchPath: string = ''; + watchPath = ''; @property({ type: [CCString], @@ -27,7 +27,7 @@ export default class VMProgress extends VMCustom { }) protected watchPathArr: string[] = ['[min]', '[max]']; - templateMode: boolean = true; + templateMode = true; @property({ visible: function () { @@ -36,7 +36,7 @@ export default class VMProgress extends VMCustom { }, tooltip: '字符串格式化,和 VMLabel 的字段一样,需要填入对应的格式化字符串' }) - stringFormat: string = ''; + stringFormat = ''; onLoad() { if (this.watchPathArr.length < 2 || this.watchPathArr[0] == '[min]' || this.watchPathArr[1] == '[max]') { @@ -52,18 +52,18 @@ export default class VMProgress extends VMCustom { } onValueInit() { - let max = this.watchPathArr.length; + const max = this.watchPathArr.length; for (let i = 0; i < max; i++) { this.templateValueArr[i] = this.VM.getValue(this.watchPathArr[i]); } - let value = this.templateValueArr[0] / this.templateValueArr[1]; + const value = this.templateValueArr[0] / this.templateValueArr[1]; this.setComponentValue(value); } setComponentValue(value: any) { if (this.stringFormat !== '') { - let res = StringFormatFunction.deal(value, this.stringFormat); + const res = StringFormatFunction.deal(value, this.stringFormat); super.setComponentValue(res); } else { @@ -81,9 +81,9 @@ export default class VMProgress extends VMCustom { onValueChanged(n: any, o: any, pathArr: string[]) { if (this.templateMode === false) return; - let path = pathArr.join('.'); + const path = pathArr.join('.'); // 寻找缓存位置 - let index = this.watchPathArr.findIndex(v => v === path); + const index = this.watchPathArr.findIndex((v) => v === path); if (index >= 0) { // 如果是所属的路径,就可以替换文本了 this.templateValueArr[index] = n; //缓存值 @@ -95,4 +95,4 @@ export default class VMProgress extends VMCustom { this.setComponentValue(value); } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/VMState.ts b/assets/libs/model-view/VMState.ts index 057a329..e5e8561 100644 --- a/assets/libs/model-view/VMState.ts +++ b/assets/libs/model-view/VMState.ts @@ -1,4 +1,5 @@ -import { Button, CCInteger, Color, Enum, Node, Sprite, UIOpacity, UIRenderer, _decorator, color } from 'cc'; +import type { Color } from 'cc'; +import { Button, CCInteger, Enum, Node, Sprite, UIOpacity, UIRenderer, _decorator, color } from 'cc'; import { VMBase } from './VMBase'; import { VM } from './ViewModel'; @@ -6,23 +7,23 @@ const { ccclass, property, menu, help } = _decorator; /** 比较条件 */ enum CONDITION { - "==", // 正常计算,比较 等于 - "!=", // 正常计算,比较 不等于 - ">", // 正常计算,比较> - ">=", // 正常计算,比较>= - "<", // 正常计算,比较< - "<=", // 正常计算,比较>= - "range" // 计算在范围内 + '==', // 正常计算,比较 等于 + '!=', // 正常计算,比较 不等于 + '>', // 正常计算,比较> + '>=', // 正常计算,比较>= + '<', // 正常计算,比较< + '<=', // 正常计算,比较>= + 'range' // 计算在范围内 } enum ACTION { - NODE_ACTIVE, // 满足条件的节点激活,不满足的不激活(只对子节点的激活有效果,当前节点active = false时,组件就失去效果了,如果设置当前节点可用NODE_VISIBLE代替) - NODE_VISIBLE, // 满足条件的节点显示,不满足的不显示 - NODE_OPACITY, // 满足条件的节点改变不透明度,不满足的还原255 - NODE_COLOR, // 满足条件的节点改变颜色,不满足的恢复白色 - COMPONENT_CUSTOM, // 自定义控制组件模式 - SPRITE_GRAYSCALE, // 满足条件的节点cc.Sprite组件,纹理变黑白 - BUTTON_INTERACTABLE, // 满足条件的节点cc.BUTTON组件, + NODE_ACTIVE, // 满足条件的节点激活,不满足的不激活(只对子节点的激活有效果,当前节点active = false时,组件就失去效果了,如果设置当前节点可用NODE_VISIBLE代替) + NODE_VISIBLE, // 满足条件的节点显示,不满足的不显示 + NODE_OPACITY, // 满足条件的节点改变不透明度,不满足的还原255 + NODE_COLOR, // 满足条件的节点改变颜色,不满足的恢复白色 + COMPONENT_CUSTOM, // 自定义控制组件模式 + SPRITE_GRAYSCALE, // 满足条件的节点cc.Sprite组件,纹理变黑白 + BUTTON_INTERACTABLE, // 满足条件的节点cc.BUTTON组件, } enum CHILD_MODE_TYPE { @@ -39,17 +40,17 @@ enum CHILD_MODE_TYPE { @help('https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037846&doc_id=2873565') export default class VMState extends VMBase { @property - watchPath: string = ""; + watchPath = ''; @property({ tooltip: '遍历子节点,根据子节点的名字或名字转换为值,判断值满足条件 来激活' }) - foreachChildMode: boolean = false; + foreachChildMode = false; @property({ type: Enum(CONDITION), }) - condition: CONDITION = CONDITION["=="]; + condition: CONDITION = CONDITION['==']; @property({ type: Enum(CHILD_MODE_TYPE), @@ -59,7 +60,7 @@ export default class VMState extends VMBase { return this.foreachChildMode === true; } }) - foreachChildType: CHILD_MODE_TYPE = CHILD_MODE_TYPE.NODE_INDEX; + foreachChildType: CHILD_MODE_TYPE = CHILD_MODE_TYPE.NODE_INDEX; @property({ displayName: 'Value: a', @@ -68,7 +69,7 @@ export default class VMState extends VMBase { return this.foreachChildMode === false; } }) - valueA: number = 0; + valueA = 0; @property({ displayName: 'Value: b', @@ -77,13 +78,13 @@ export default class VMState extends VMBase { return this.foreachChildMode === false && this.condition === CONDITION.range; } }) - valueB: number = 0; + valueB = 0; @property({ type: Enum(ACTION), tooltip: '一旦满足条件就对节点执行操作' }) - valueAction: ACTION = ACTION.NODE_ACTIVE; + valueAction: ACTION = ACTION.NODE_ACTIVE; @property({ visible: function () { @@ -94,43 +95,43 @@ export default class VMState extends VMBase { type: CCInteger, displayName: 'Action Opacity' }) - valueActionOpacity: number = 0; + valueActionOpacity = 0; @property({ visible: function () { // @ts-ignore - return this.valueAction === ACTION.NODE_COLOR + return this.valueAction === ACTION.NODE_COLOR; }, displayName: 'Action Color' }) - valueActionColor: Color = color(155, 155, 155); + valueActionColor: Color = color(155, 155, 155); @property({ visible: function () { // @ts-ignore - return this.valueAction === ACTION.COMPONENT_CUSTOM + return this.valueAction === ACTION.COMPONENT_CUSTOM; }, displayName: 'Component Name' }) - valueComponentName: string = ''; + valueComponentName = ''; @property({ visible: function () { // @ts-ignore - return this.valueAction === ACTION.COMPONENT_CUSTOM + return this.valueAction === ACTION.COMPONENT_CUSTOM; }, displayName: 'Component Property' }) - valueComponentProperty: string = ''; + valueComponentProperty = ''; @property({ visible: function () { // @ts-ignore - return this.valueAction === ACTION.COMPONENT_CUSTOM + return this.valueAction === ACTION.COMPONENT_CUSTOM; }, displayName: 'Default Value' }) - valueComponentDefaultValue: string = ''; + valueComponentDefaultValue = ''; @property({ visible: function () { @@ -139,13 +140,13 @@ export default class VMState extends VMBase { }, displayName: 'Action Value' }) - valueComponentActionValue: string = ''; + valueComponentActionValue = ''; @property({ type: [Node], tooltip: '需要执行条件的节点,如果不填写则默认会执行本节点以及本节点的所有子节点 的状态' }) - watchNodes: Node[] = []; + watchNodes: Node[] = []; onLoad() { super.onLoad(); @@ -166,7 +167,7 @@ export default class VMState extends VMBase { // 当值初始化时 protected onValueInit() { - let value = VM.getValue(this.watchPath); + const value = VM.getValue(this.watchPath); this.checkNodeFromValue(value); } @@ -179,120 +180,120 @@ export default class VMState extends VMBase { private checkNodeFromValue(value: any) { if (this.foreachChildMode) { this.watchNodes.forEach((node, index) => { - let v = (this.foreachChildType === CHILD_MODE_TYPE.NODE_INDEX) ? index : node.name; - let check = this.conditionCheck(value, v); + const v = (this.foreachChildType === CHILD_MODE_TYPE.NODE_INDEX) ? index : node.name; + const check = this.conditionCheck(value, v); // log('遍历模式', value, node.name, check); this.setNodeState(node, check); - }) + }); } else { - let check = this.conditionCheck(value, this.valueA, this.valueB); + const check = this.conditionCheck(value, this.valueA, this.valueB); this.setNodesStates(check); } } // 更新 多个节点 的 状态 private setNodesStates(checkState?: boolean) { - let nodes = this.watchNodes; - let check = checkState; + const nodes = this.watchNodes; + const check = checkState; nodes.forEach((node) => { this.setNodeState(node, check); - }) + }); } /** 更新单个节点的状态 */ private setNodeState(node: Node, checkState?: boolean) { - let n = this.valueAction; - let check = checkState; + const n = this.valueAction; + const check = checkState; switch (n) { - case ACTION.NODE_ACTIVE: - node.active = check ? true : false; - break; - case ACTION.NODE_VISIBLE: { - let opacity = node.getComponent(UIOpacity); - if (opacity == null) - opacity = node.addComponent(UIOpacity); + case ACTION.NODE_ACTIVE: + node.active = check ? true : false; + break; + case ACTION.NODE_VISIBLE: { + let opacity = node.getComponent(UIOpacity); + if (opacity == null) + opacity = node.addComponent(UIOpacity); - if (opacity) { - opacity.opacity = check ? 255 : 0; - } - break; + if (opacity) { + opacity.opacity = check ? 255 : 0; } - case ACTION.NODE_OPACITY: { - let opacity = node.getComponent(UIOpacity); - if (opacity == null) - opacity = node.addComponent(UIOpacity); + break; + } + case ACTION.NODE_OPACITY: { + let opacity = node.getComponent(UIOpacity); + if (opacity == null) + opacity = node.addComponent(UIOpacity); - if (opacity) { - opacity.opacity = check ? this.valueActionOpacity : 255; - } - break; + if (opacity) { + opacity.opacity = check ? this.valueActionOpacity : 255; } - case ACTION.NODE_COLOR: { - let uir = node.getComponent(UIRenderer); - if (uir) { - uir.color = check ? this.valueActionColor : color(255, 255, 255); - } - break; + break; + } + case ACTION.NODE_COLOR: { + const uir = node.getComponent(UIRenderer); + if (uir) { + uir.color = check ? this.valueActionColor : color(255, 255, 255); } - case ACTION.COMPONENT_CUSTOM: - let comp: any = node.getComponent(this.valueComponentName); - if (comp == null) return; - if (this.valueComponentProperty in comp) { - comp[this.valueComponentProperty] = check ? this.valueComponentActionValue : this.valueComponentDefaultValue; - } - break; - case ACTION.SPRITE_GRAYSCALE: { - let sprite = node.getComponent(Sprite); - if (sprite) { - sprite.grayscale = check!; - } - break; + break; + } + case ACTION.COMPONENT_CUSTOM: + const comp: any = node.getComponent(this.valueComponentName); + if (comp == null) return; + if (this.valueComponentProperty in comp) { + comp[this.valueComponentProperty] = check ? this.valueComponentActionValue : this.valueComponentDefaultValue; } - case ACTION.BUTTON_INTERACTABLE: { - let sprite = node.getComponent(Button); - if (sprite) { - sprite.interactable = check!; - } - break; + break; + case ACTION.SPRITE_GRAYSCALE: { + const sprite = node.getComponent(Sprite); + if (sprite) { + sprite.grayscale = check!; } - default: - break; + break; + } + case ACTION.BUTTON_INTERACTABLE: { + const sprite = node.getComponent(Button); + if (sprite) { + sprite.interactable = check!; + } + break; + } + default: + break; } } /** 条件检查 */ private conditionCheck(v: any, a: any, b?: any): boolean { - let cod = CONDITION; + const cod = CONDITION; switch (this.condition) { - case cod["=="]: - if (v == a) return true; - break; - case cod["!="]: - if (v != a) return true; - break; - case cod["<"]: - if (v < a) return true; - break; - case cod[">"]: - if (v > a) return true; - break; - case cod[">="]: - if (v >= a) return true; - break; - case cod["<"]: - if (v < a) return true; - break; - case cod["<="]: - if (v <= a) return true; - break; - case cod["range"]: - if (v >= a && v <= b) return true; - break; - default: - break; + case cod['==']: + if (v == a) return true; + break; + case cod['!=']: + if (v != a) return true; + break; + case cod['<']: + if (v < a) return true; + break; + case cod['>']: + if (v > a) return true; + break; + case cod['>=']: + if (v >= a) return true; + break; + case cod['<']: + if (v < a) return true; + break; + case cod['<=']: + if (v <= a) return true; + break; + case cod['range']: + if (v >= a && v <= b) return true; + break; + default: + break; } return false; } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/ViewModel.ts b/assets/libs/model-view/ViewModel.ts index ea77da9..34e095d 100644 --- a/assets/libs/model-view/ViewModel.ts +++ b/assets/libs/model-view/ViewModel.ts @@ -6,10 +6,12 @@ const DEBUG_SHOW_PATH = false; /** 通过 . 路径设置值 */ function setValueFromPath(obj: any, path: string, value: any, tag: string | null = '') { - let props = path.split('.'); + const props = path.split('.'); for (let i = 0; i < props.length; i++) { const propName = props[i]; - if (propName in obj === false) { console.error('[' + propName + '] not find in ' + tag + '.' + path); break; } + if (propName in obj === false) { + console.error('[' + propName + '] not find in ' + tag + '.' + path); break; + } if (i == props.length - 1) { obj[propName] = value; } @@ -21,13 +23,15 @@ function setValueFromPath(obj: any, path: string, value: any, tag: string | null /** 通过 . 路径 获取值 */ function getValueFromPath(obj: any, path: string, def?: any, tag: string | null = ''): any { - let props = path.split('.'); + const props = path.split('.'); for (let i = 0; i < props.length; i++) { const propName = props[i]; - if ((propName in obj === false)) { console.error('[' + propName + '] not find in ' + tag + '.' + path); return def; } + if ((propName in obj === false)) { + console.error('[' + propName + '] not find in ' + tag + '.' + path); return def; + } obj = obj[propName]; } - if (obj === null || typeof obj === "undefined") obj = def;//如果g == null 则返回一个默认值 + if (obj === null || typeof obj === 'undefined') obj = def;//如果g == null 则返回一个默认值 return obj; } @@ -41,25 +45,25 @@ class ViewModel { this._tag = tag; } - public $data: T; + $data: T; // 索引值用的标签 private _tag: string | null = null; /** 激活状态, 将会通过 director.emit 发送值变动的信号, 适合需要屏蔽的情况 */ - public active: boolean = true; + active = true; /** 是否激活根路径回调通知, 不激活的情况下 只能监听末端路径值来判断是否变化 */ - public emitToRootPath: boolean = false; + emitToRootPath = false; // 回调函数 请注意 回调的 path 数组是 引用类型,禁止修改 private _callback(n: any, o: any, path: string[]): void { if (this.active == true) { - let name = VM_EMIT_HEAD + this._tag + '.' + path.join('.') + const name = VM_EMIT_HEAD + this._tag + '.' + path.join('.'); if (DEBUG_SHOW_PATH) log('>>', n, o, path); - director.emit(name, n, o, [this._tag].concat(path)); // 通知末端路径 + director.emit(name, n, o, [this._tag].concat(path)); // 通知末端路径 - if (this.emitToRootPath) director.emit(VM_EMIT_HEAD + this._tag, n, o, path); // 通知主路径 + if (this.emitToRootPath) director.emit(VM_EMIT_HEAD + this._tag, n, o, path); // 通知主路径 // if (path.length >= 2) { // for (let i = 0; i < path.length - 1; i++) { @@ -71,12 +75,12 @@ class ViewModel { } // 通过路径设置数据的方法 - public setValue(path: string, value: any) { + setValue(path: string, value: any) { setValueFromPath(this.$data, path, value, this._tag); } // 获取路径的值 - public getValue(path: string, def?: any): any { + getValue(path: string, def?: any): any { return getValueFromPath(this.$data, path, def, this._tag); } } @@ -93,9 +97,9 @@ class VMManager { * @param tag 对应该数据的标签(用于识别为哪个VM,不允许重复) * @param activeRootObject 激活主路径通知,可能会有性能影响,一般不使用 */ - add(data: T, tag: string = 'global', activeRootObject: boolean = false) { - let vm = new ViewModel(data, tag); - let has = this._mvs.get(tag); + add(data: T, tag = 'global', activeRootObject = false) { + const vm = new ViewModel(data, tag); + const has = this._mvs.get(tag); if (tag.includes('.')) { console.error('cant write . in tag:', tag); return; @@ -112,7 +116,7 @@ class VMManager { /** * 移除并且销毁 VM 对象 - * @param tag + * @param tag */ remove(tag: string) { this._mvs.delete(tag); @@ -123,7 +127,7 @@ class VMManager { * @param tag 数据tag */ get(tag: string): ViewModel | undefined { - let res = this._mvs.get(tag); + const res = this._mvs.get(tag); return res; } @@ -134,11 +138,15 @@ class VMManager { */ addValue(path: string, value: any) { path = path.trim();//防止空格,自动剔除 - let rs = path.split('.'); - if (rs.length < 2) { console.error('Cant find path:' + path) }; - let vm = this.get(rs[0]); - if (!vm) { console.error('Cant Set VM:' + rs[0]); return; }; - let resPath = rs.slice(1).join('.'); + const rs = path.split('.'); + if (rs.length < 2) { + console.error('Cant find path:' + path); + }; + const vm = this.get(rs[0]); + if (!vm) { + console.error('Cant Set VM:' + rs[0]); return; + }; + const resPath = rs.slice(1).join('.'); vm.setValue(resPath, vm.getValue(resPath) + value); } @@ -148,14 +156,18 @@ class VMManager { * @param def - 如果取不到值的返回的默认值 */ getValue(path: string, def?: any): any { - path = path.trim(); // 防止空格,自动剔除 + path = path.trim(); // 防止空格,自动剔除 if (path === '') return ''; - let rs = path.split('.'); - if (rs.length < 2) { console.error('Get Value Cant find path:' + path); return; }; - let vm = this.get(rs[0]); - if (!vm) { console.error('Cant Get VM:' + rs[0]); return; }; + const rs = path.split('.'); + if (rs.length < 2) { + console.error('Get Value Cant find path:' + path); return; + }; + const vm = this.get(rs[0]); + if (!vm) { + console.error('Cant Get VM:' + rs[0]); return; + }; return vm.getValue(rs.slice(1).join('.'), def); } @@ -165,11 +177,15 @@ class VMManager { * @param value - 需要设置的值 */ setValue(path: string, value: any) { - path = path.trim(); // 防止空格,自动剔除 - let rs = path.split('.'); - if (rs.length < 2) { console.error('Set Value Cant find path:' + path); return; }; - let vm = this.get(rs[0]); - if (!vm) { console.error('Cant Set VM:' + rs[0]); return; }; + path = path.trim(); // 防止空格,自动剔除 + const rs = path.split('.'); + if (rs.length < 2) { + console.error('Set Value Cant find path:' + path); return; + }; + const vm = this.get(rs[0]); + if (!vm) { + console.error('Cant Set VM:' + rs[0]); return; + }; vm.setValue(rs.slice(1).join('.'), value); } @@ -179,7 +195,7 @@ class VMManager { /** 等同于 director.on */ bindPath(path: string, callback: Function, target?: any, useCapture?: boolean): void { - path = path.trim(); // 防止空格,自动剔除 + path = path.trim(); // 防止空格,自动剔除 if (path == '') { console.error(target.node.name, '节点绑定的路径为空'); return; @@ -205,21 +221,21 @@ class VMManager { /** 冻结所有标签的 VM,视图将不会受到任何信息 */ inactive(): void { - this._mvs.forEach(mv => { + this._mvs.forEach((mv) => { mv.active = false; - }) + }); } /** 激活所有标签的 VM*/ active(): void { - this._mvs.forEach(mv => { + this._mvs.forEach((mv) => { mv.active = false; - }) + }); } } /** - * VM管理对象,使用文档: + * VM管理对象,使用文档: * https://gitee.com/dgflash/oops-framework/wikis/pages?sort_id=12037849&doc_id=2873565 */ -export let VM = new VMManager(); \ No newline at end of file +export const VM = new VMManager(); diff --git a/assets/libs/model-view/ui/BhvButtonGroup.ts b/assets/libs/model-view/ui/BhvButtonGroup.ts index 6136750..5fc54bf 100644 --- a/assets/libs/model-view/ui/BhvButtonGroup.ts +++ b/assets/libs/model-view/ui/BhvButtonGroup.ts @@ -1,4 +1,5 @@ -import { Button, color, Color, Component, Enum, EventHandler, SpriteFrame, _decorator } from "cc"; +import type { Color } from 'cc'; +import { Button, color, Component, Enum, EventHandler, SpriteFrame, _decorator } from 'cc'; const { ccclass, property, menu } = _decorator; @@ -12,28 +13,12 @@ enum PARAM_TYPE { * 将该组件的所处节点的所有子节点,绑定相同的回调对象,并将组件名设置到customEventData属性中 */ @ccclass -@menu("OopsFramework/UI/Button Group (按钮组控制)") +@menu('OopsFramework/UI/Button Group (按钮组控制)') export class BhvButtonGroup extends Component { @property({ type: Enum(Button.Transition) }) - transition: number = Button.Transition.NONE; - - @property({ - visible: function () { - // @ts-ignore - return this.transition === Button.Transition.COLOR - } - }) - hoverColor: Color = color(255, 255, 255); - - @property({ - visible: function () { - // @ts-ignore - return this.transition === Button.Transition.COLOR - } - }) - normalColor: Color = color(214, 214, 214); + transition: number = Button.Transition.NONE; @property({ visible: function () { @@ -41,7 +26,7 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.COLOR; } }) - pressedColor: Color = color(211, 211, 211); + hoverColor: Color = color(255, 255, 255); @property({ visible: function () { @@ -49,7 +34,23 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.COLOR; } }) - disabledColor: Color = color(124, 124, 124); + normalColor: Color = color(214, 214, 214); + + @property({ + visible: function () { + // @ts-ignore + return this.transition === Button.Transition.COLOR; + } + }) + pressedColor: Color = color(211, 211, 211); + + @property({ + visible: function () { + // @ts-ignore + return this.transition === Button.Transition.COLOR; + } + }) + disabledColor: Color = color(124, 124, 124); @property({ type: SpriteFrame, @@ -58,7 +59,7 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.SPRITE; } }) - normalSprite: SpriteFrame | null = null; + normalSprite: SpriteFrame | null = null; @property({ type: SpriteFrame, @@ -67,7 +68,7 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.SPRITE; } }) - pressedSprite: SpriteFrame | null = null; + pressedSprite: SpriteFrame | null = null; @property({ type: SpriteFrame, @@ -76,7 +77,7 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.SPRITE; } }) - hoverSprite: SpriteFrame | null = null; + hoverSprite: SpriteFrame | null = null; @property({ type: SpriteFrame, @@ -85,7 +86,7 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.SPRITE; } }) - disabledSprite: SpriteFrame | null = null; + disabledSprite: SpriteFrame | null = null; @property({ visible: function () { @@ -93,7 +94,7 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.SCALE || this.transition === Button.Transition.COLOR; } }) - duration: number = 1.0; + duration = 1.0; @property({ visible: function () { @@ -101,23 +102,23 @@ export class BhvButtonGroup extends Component { return this.transition === Button.Transition.SCALE; } }) - zoomScale: number = 1.1; + zoomScale = 1.1; @property({ type: Enum(PARAM_TYPE) }) - paramType: PARAM_TYPE = PARAM_TYPE.CHILDREN_INDEX; + paramType: PARAM_TYPE = PARAM_TYPE.CHILDREN_INDEX; @property({ type: [EventHandler] }) - touchEvents: EventHandler[] = []; + touchEvents: EventHandler[] = []; @property({ tooltip: '规避3.x引擎BUG,EventHandler.component位为空导致找不到触发事件的脚本名的问题', readonly: true }) - EventHandler_component: string = "VMModify"; + EventHandler_component = 'VMModify'; onLoad() { this.node.children.forEach((node, nodeIndex) => { @@ -143,8 +144,8 @@ export class BhvButtonGroup extends Component { // 绑定回调事件 this.touchEvents.forEach((event) => { // 克隆数据,每个节点获取的都是不同的回调 - let hd = new EventHandler();//copy对象 - hd.component = event.component == "" ? this.EventHandler_component : event.component; + const hd = new EventHandler();//copy对象 + hd.component = event.component == '' ? this.EventHandler_component : event.component; hd.handler = event.handler; hd.target = event.target; if (this.paramType === PARAM_TYPE.CHILDREN_INDEX) { @@ -154,7 +155,7 @@ export class BhvButtonGroup extends Component { hd.customEventData = node.name; } comp.clickEvents.push(hd); - }) + }); }); } } diff --git a/assets/libs/model-view/ui/BhvFrameIndex.ts b/assets/libs/model-view/ui/BhvFrameIndex.ts index 749dc47..8bb6552 100644 --- a/assets/libs/model-view/ui/BhvFrameIndex.ts +++ b/assets/libs/model-view/ui/BhvFrameIndex.ts @@ -1,4 +1,4 @@ -import { CCInteger, Component, error, Sprite, SpriteFrame, _decorator } from "cc"; +import { CCInteger, Component, error, Sprite, SpriteFrame, _decorator } from 'cc'; const { ccclass, property, executeInEditMode, requireComponent, menu } = _decorator; @@ -6,13 +6,13 @@ const { ccclass, property, executeInEditMode, requireComponent, menu } = _decora @ccclass @executeInEditMode @requireComponent(Sprite) -@menu("OopsFramework/UI/Frame Index (图片切换)") +@menu('OopsFramework/UI/Frame Index (图片切换)') export class BhvFrameIndex extends Component { @property({ type: [SpriteFrame], tooltip: 'sprite将会用到帧图片' }) - spriteFrames: Array = [null]; + spriteFrames: Array = [null]; @property({ type: CCInteger, @@ -24,25 +24,29 @@ export class BhvFrameIndex extends Component { set index(value: number) { if (value < 0) return; this._index = value % this.spriteFrames.length; - let sprite = this.node.getComponent(Sprite)!; - //设置 Sprite 组件的spriteFrame属性,变换图片 + const sprite = this.node.getComponent(Sprite)!; + //设置 Sprite 组件的spriteFrame属性,变换图片 sprite.spriteFrame = this.spriteFrames[this._index]; } @property - private _index: number = 0; + private _index = 0; /** 通过设置帧名字来设置对象 */ setName(name: string) { - let index = this.spriteFrames.findIndex(v => { return v!.name == name }); - if (index < 0) { error('frameIndex 设置了不存在的name:', name) } + const index = this.spriteFrames.findIndex((v) => { + return v!.name == name; + }); + if (index < 0) { + error('frameIndex 设置了不存在的name:', name); + } this.index = index || 0; } /** 随机范围设置帧图片 */ random(min?: number, max?: number) { if (!this.spriteFrames) return; - let frameMax = this.spriteFrames.length; + const frameMax = this.spriteFrames.length; if (min == null || min < 0) min = 0; if (max == null || max > frameMax) max = frameMax; diff --git a/assets/libs/model-view/ui/BhvRollNumber.ts b/assets/libs/model-view/ui/BhvRollNumber.ts index e39da04..7bc8bac 100644 --- a/assets/libs/model-view/ui/BhvRollNumber.ts +++ b/assets/libs/model-view/ui/BhvRollNumber.ts @@ -1,4 +1,4 @@ -import { _decorator, Component, Enum, Label, lerp } from "cc"; +import { _decorator, Component, Enum, Label, lerp } from 'cc'; const { ccclass, property, menu } = _decorator; @@ -24,23 +24,23 @@ type CustomCallback = (curValue: number, targetValue: number) => string; * 将会使用 lerp 自动滚动数字到目标数值 */ @ccclass -@menu("OopsFramework/UI/Roll Number (滚动数字)") +@menu('OopsFramework/UI/Roll Number (滚动数字)') export class BhvRollNumber extends Component { @property({ type: Label, tooltip: '需要滚动的 Label 组件,如果不进行设置,就会从自己的节点自动查找' }) - label: Label | null = null; + label: Label | null = null; @property({ tooltip: '当前的滚动值(开始的滚动值)' }) - value: number = 0; + value = 0; @property({ tooltip: '是否显示正负符号' }) - showPlusSymbol: boolean = false; + showPlusSymbol = false; @property({ tooltip: '滚动的目标值' @@ -53,7 +53,7 @@ export class BhvRollNumber extends Component { this.scroll();//数据变动了就开始滚动 } @property - private _targetValue: number = 100; + private _targetValue = 100; /** 滚动的线性差值 0 ~ 1 */ @property({ @@ -62,12 +62,12 @@ export class BhvRollNumber extends Component { max: 1, min: 0 }) - lerp = 0.1; + lerp = 0.1; @property({ tooltip: '是否在开始时就播放' }) - private playAtStart: boolean = true; + private playAtStart = true; @property({ tooltip: '在滚动之前会等待几秒', @@ -75,7 +75,7 @@ export class BhvRollNumber extends Component { max: 1, min: 0 }) - private runWaitTimer: number = 0; + private runWaitTimer = 0; @property({ type: Enum(VALUE_TYPE), @@ -86,7 +86,7 @@ export class BhvRollNumber extends Component { /** 自定义string 处理函数 */ onCustom: CustomCallback | null = null; - private isScrolling: boolean = false; + private isScrolling = false; onLoad() { if (this.label == undefined) { @@ -101,7 +101,7 @@ export class BhvRollNumber extends Component { /** 开始滚动数字 */ scroll() { - if (this.isScrolling) return; // 已经在滚动了就返回 + if (this.isScrolling) return; // 已经在滚动了就返回 if (this.runWaitTimer > 0) { this.scheduleOnce(() => { this.isScrolling = true; @@ -134,49 +134,49 @@ export class BhvRollNumber extends Component { /** 更新文本 */ updateLabel() { - let value = this.value; + const value = this.value; let string = ''; switch (this.valueType) { - case VALUE_TYPE.INTEGER: // 最终显示整数类型 - string = Math.round(value) + ''; - break; - case VALUE_TYPE.FIXED_2: // 最终显示两位小数类型 - string = value.toFixed(2); - break; - case VALUE_TYPE.TIMER: // 最终显示 计时器类型 - string = parseTimer(value); - break; - case VALUE_TYPE.PERCENTAGE: // 最终显示 百分比 - string = Math.round(value * 100) + '%'; - break; - case VALUE_TYPE.KMBT_FIXED2: // 长单位缩放,只计算到 KMBT - if (value >= Number.MAX_VALUE) { - string = 'MAX'; - } - else if (value > 1000000000000) { - string = (value / 1000000000000).toFixed(2) + 'T'; - } - else if (value > 1000000000) { - string = (value / 1000000000).toFixed(2) + 'B'; - } - else if (value > 1000000) { - string = (value / 1000000).toFixed(2) + 'M'; - } - else if (value > 1000) { - string = (value / 1000).toFixed(2) + "K"; - } - else { - string = Math.round(value).toString(); - } - break; - case VALUE_TYPE.CUSTOMER: // 自定义设置模式 (通过给定的自定义函数..处理) - if (this.onCustom) { - string = this.onCustom(this.value, this.targetValue); - } - break; - default: - break; + case VALUE_TYPE.INTEGER: // 最终显示整数类型 + string = Math.round(value) + ''; + break; + case VALUE_TYPE.FIXED_2: // 最终显示两位小数类型 + string = value.toFixed(2); + break; + case VALUE_TYPE.TIMER: // 最终显示 计时器类型 + string = parseTimer(value); + break; + case VALUE_TYPE.PERCENTAGE: // 最终显示 百分比 + string = Math.round(value * 100) + '%'; + break; + case VALUE_TYPE.KMBT_FIXED2: // 长单位缩放,只计算到 KMBT + if (value >= Number.MAX_VALUE) { + string = 'MAX'; + } + else if (value > 1000000000000) { + string = (value / 1000000000000).toFixed(2) + 'T'; + } + else if (value > 1000000000) { + string = (value / 1000000000).toFixed(2) + 'B'; + } + else if (value > 1000000) { + string = (value / 1000000).toFixed(2) + 'M'; + } + else if (value > 1000) { + string = (value / 1000).toFixed(2) + 'K'; + } + else { + string = Math.round(value).toString(); + } + break; + case VALUE_TYPE.CUSTOMER: // 自定义设置模式 (通过给定的自定义函数..处理) + if (this.onCustom) { + string = this.onCustom(this.value, this.targetValue); + } + break; + default: + break; } // 显示正负符号 @@ -191,7 +191,7 @@ export class BhvRollNumber extends Component { } if (this.label) { - if (string === this.label.string) return; // 保证效率,如果上次赋值过,就不重复赋值 + if (string === this.label.string) return; // 保证效率,如果上次赋值过,就不重复赋值 this.label.string = string; } } @@ -210,11 +210,11 @@ export class BhvRollNumber extends Component { } /** 时间格式转换 */ -function parseTimer(timer: number = 0, isFullTimer: boolean = true) { - let t: number = Math.floor(timer); - let hours: number = Math.floor(t / 3600); - let mins: number = Math.floor((t % 3600) / 60); - let secs: number = t % 60; +function parseTimer(timer = 0, isFullTimer = true) { + const t: number = Math.floor(timer); + const hours: number = Math.floor(t / 3600); + const mins: number = Math.floor((t % 3600) / 60); + const secs: number = t % 60; let m = '' + mins; let s = '' + secs; if (secs < 10) s = '0' + secs; @@ -229,4 +229,4 @@ function parseTimer(timer: number = 0, isFullTimer: boolean = true) { if (mins < 10) m = '0' + mins; return m + ':' + s; } -} \ No newline at end of file +} diff --git a/assets/libs/model-view/ui/BhvSwitchPage.ts b/assets/libs/model-view/ui/BhvSwitchPage.ts index 244b31d..8bc9882 100644 --- a/assets/libs/model-view/ui/BhvSwitchPage.ts +++ b/assets/libs/model-view/ui/BhvSwitchPage.ts @@ -1,18 +1,19 @@ -import { CCInteger, Component, Node, _decorator } from "cc"; -import { VMEnv } from "../VMEnv"; +import type { Node } from 'cc'; +import { CCInteger, Component, _decorator } from 'cc'; +import { VMEnv } from '../VMEnv'; const { ccclass, property, executeInEditMode, menu } = _decorator; /** 页面切换 */ @ccclass @executeInEditMode -@menu("OopsFramework/UI/Switch Page (页面切换)") +@menu('OopsFramework/UI/Switch Page (页面切换)') export class BhvSwitchPage extends Component { @property - isLoopPage: boolean = false; + isLoopPage = false; @property - private _index: number = 0; + private _index = 0; get index(): number { return this._index; } @@ -22,7 +23,7 @@ export class BhvSwitchPage extends Component { set index(v: number) { if (this.isChanging) return; v = Math.round(v); - let count = this.node.children.length - 1; + const count = this.node.children.length - 1; if (this.isLoopPage) { if (v > count) v = 0; @@ -43,11 +44,11 @@ export class BhvSwitchPage extends Component { } } - private preIndex: number = 0; + private preIndex = 0; //判断是否在 changing 页面状态 - private _isChanging: boolean = false; + private _isChanging = false; /**只读,是否在changing 的状态 */ get isChanging(): boolean { return this._isChanging; @@ -60,7 +61,7 @@ export class BhvSwitchPage extends Component { private _updateEditorPage(page: number) { if (!VMEnv.editor) return; - let children = this.node.children; + const children = this.node.children; for (let i = 0; i < children.length; i++) { const node = children[i]; if (i == page) { @@ -73,13 +74,13 @@ export class BhvSwitchPage extends Component { } private _updatePage(page: number) { - let children = this.node.children; - let preIndex = this.preIndex; - let curIndex = this.index; + const children = this.node.children; + const preIndex = this.preIndex; + const curIndex = this.index; if (preIndex === curIndex) return;//没有改变就不进行操作 - let preNode: Node = children[preIndex];//旧节点 - let showNode: Node = children[curIndex];//新节点 + const preNode: Node = children[preIndex];//旧节点 + const showNode: Node = children[curIndex];//新节点 preNode.active = false; showNode.active = true; @@ -114,4 +115,4 @@ export class BhvSwitchPage extends Component { return false; } } -} \ No newline at end of file +} diff --git a/assets/libs/network/HttpRequest.ts b/assets/libs/network/HttpRequest.ts index 3a62b60..20342f7 100644 --- a/assets/libs/network/HttpRequest.ts +++ b/assets/libs/network/HttpRequest.ts @@ -4,7 +4,7 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-09 18:10:50 */ -import { error, warn } from "cc"; +import { error, warn } from 'cc'; /** * 使用流程文档可参考、简化与服务器对接、使用新版API体验,可进入下面地址获取新版本,替换network目录中的内容 @@ -12,20 +12,20 @@ import { error, warn } from "cc"; */ /** 当前请求地址集合 */ -var urls: any = {}; +const urls: any = {}; /** 请求参数 */ -var reqparams: any = {}; +const reqparams: any = {}; type HttpCallback = (ret: HttpReturn) => void; /** 请求事件 */ export enum HttpEvent { /** 断网 */ - NO_NETWORK = "http_request_no_network", + NO_NETWORK = 'http_request_no_network', /** 未知错误 */ - UNKNOWN_ERROR = "http_request_unknown_error", + UNKNOWN_ERROR = 'http_request_unknown_error', /** 请求超时 */ - TIMEOUT = "http_request_timout" + TIMEOUT = 'http_request_timout' } /** @@ -33,7 +33,7 @@ export enum HttpEvent { */ export class HttpReturn { /** 是否请求成功 */ - isSucc: boolean = false; + isSucc = false; /** 请求返回数据 */ res?: any; /** 请求错误数据 */ @@ -43,9 +43,9 @@ export class HttpReturn { /** HTTP请求 */ export class HttpRequest { /** 服务器地址 */ - server: string = "http://127.0.0.1/"; + server = 'http://127.0.0.1/'; /** 请求超时时间 */ - timeout: number = 10000; + timeout = 10000; /** 自定义请求头信息 */ private header: Map = new Map(); @@ -71,14 +71,14 @@ export class HttpRequest { oops.http.getWithParams(name, complete, param); */ get(name: string, onComplete: HttpCallback, params: any = null) { - this.sendRequest(name, params, false, onComplete) + this.sendRequest(name, params, false, onComplete); } /** * HTTP GET请求 * @param name 协议名 * @param params 查询参数 - * @example + * @example var txt = await oops.http.getAsync(name); if (txt.isSucc) { console.log(txt.res); @@ -88,7 +88,7 @@ export class HttpRequest { return new Promise((resolve, reject) => { this.sendRequest(name, params, false, (ret: HttpReturn) => { resolve(ret); - }) + }); }); } @@ -150,7 +150,7 @@ export class HttpRequest { * @param name 协议名 */ abort(name: string) { - var xhr = urls[this.server + name]; + const xhr = urls[this.server + name]; if (xhr) { xhr.abort(); } @@ -162,11 +162,11 @@ export class HttpRequest { * @returns 参数字符串 */ private getParamString(params: any) { - var result = ""; - for (var name in params) { - let data = params[name]; + let result = ''; + for (const name in params) { + const data = params[name]; if (data instanceof Object) { - for (var key in data) + for (const key in data) result += `${key}=${data[key]}&`; } else { @@ -176,8 +176,8 @@ export class HttpRequest { return result.substring(0, result.length - 1); } - /** - * Http请求 + /** + * Http请求 * @param name(string) 请求地址 * @param params(JSON) 请求参数 * @param isPost(boolen) 是否为POST方式 @@ -190,14 +190,14 @@ export class HttpRequest { isPost: boolean, onComplete: HttpCallback, responseType?: string, - isOpenTimeout: boolean = true) { + isOpenTimeout = true) { if (name == null || name == '') { - error("请求地址不能为空"); + error('请求地址不能为空'); return; } - var url: string, newUrl: string, paramsStr: string = ""; - if (name.toLocaleLowerCase().indexOf("http") == 0) { + let url: string, newUrl: string, paramsStr = ''; + if (name.toLocaleLowerCase().indexOf('http') == 0) { url = name; } else { @@ -206,10 +206,10 @@ export class HttpRequest { if (params) { paramsStr = this.getParamString(params); - if (url.indexOf("?") > -1) - newUrl = url + "&" + paramsStr; + if (url.indexOf('?') > -1) + newUrl = url + '&' + paramsStr; else - newUrl = url + "?" + paramsStr; + newUrl = url + '?' + paramsStr; } else { newUrl = url; @@ -220,17 +220,17 @@ export class HttpRequest { return; } - var xhr = new XMLHttpRequest(); + const xhr = new XMLHttpRequest(); // 防重复请求功能 urls[newUrl] = xhr; reqparams[newUrl] = paramsStr; if (isPost) { - xhr.open("POST", url); + xhr.open('POST', url); } else { - xhr.open("GET", newUrl); + xhr.open('GET', newUrl); } // 添加自定义请求头信息 @@ -240,7 +240,7 @@ export class HttpRequest { // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); - var data: any = {}; + const data: any = {}; data.url = url; data.params = params; @@ -251,9 +251,9 @@ export class HttpRequest { this.deleteCache(newUrl); ret.isSucc = false; - ret.err = HttpEvent.TIMEOUT; // 超时 + ret.err = HttpEvent.TIMEOUT; // 超时 onComplete(data); - } + }; } // 响应结果 @@ -264,20 +264,20 @@ export class HttpRequest { this.deleteCache(newUrl); ret.isSucc = false; - ret.err = HttpEvent.NO_NETWORK; // 断网 + ret.err = HttpEvent.NO_NETWORK; // 断网 onComplete(ret); } - } + }; xhr.onerror = () => { this.deleteCache(newUrl); ret.isSucc = false; if (xhr.readyState == 0 || xhr.readyState == 1 || xhr.status == 0) { - ret.err = HttpEvent.NO_NETWORK; // 断网 + ret.err = HttpEvent.NO_NETWORK; // 断网 } else { - ret.err = HttpEvent.UNKNOWN_ERROR; // 未知错误 + ret.err = HttpEvent.UNKNOWN_ERROR; // 未知错误 } onComplete(ret); @@ -291,7 +291,7 @@ export class HttpRequest { if (xhr.status == 200 && onComplete) { ret.isSucc = true; if (responseType == 'arraybuffer') { - xhr.responseType = responseType; // 加载非文本格式 + xhr.responseType = responseType; // 加载非文本格式 ret.res = xhr.response; } else { @@ -302,7 +302,7 @@ export class HttpRequest { }; // 发送请求 - if (params == null || params == "") { + if (params == null || params == '') { xhr.send(); } else { @@ -314,4 +314,4 @@ export class HttpRequest { delete urls[url]; delete reqparams[url]; } -} \ No newline at end of file +} diff --git a/assets/libs/network/NetInterface.ts b/assets/libs/network/NetInterface.ts index 4bf7608..2f2523b 100644 --- a/assets/libs/network/NetInterface.ts +++ b/assets/libs/network/NetInterface.ts @@ -39,15 +39,15 @@ export interface IResponseProtocol { /** 回调对象 */ export interface CallbackObject { - target: any, // 回调对象,不为null时调用target.callback(xxx) - callback: NetCallFunc, // 回调函数 + target: any, // 回调对象,不为null时调用target.callback(xxx) + callback: NetCallFunc, // 回调函数 } /** 请求对象 */ export interface RequestObject { - buffer: NetData, // 请求的Buffer - rspCmd: string, // 等待响应指令 - rspObject: CallbackObject | null, // 等待响应的回调对象 + buffer: NetData, // 请求的Buffer + rspCmd: string, // 等待响应指令 + rspObject: CallbackObject | null, // 等待响应的回调对象 } /** 协议辅助接口 */ @@ -73,14 +73,14 @@ export type MessageFunc = (msg: NetData) => void; /** Socket接口 */ export interface ISocket { - onConnected: SocketFunc | null; // 连接回调 - onMessage: MessageFunc | null; // 消息回调 - onError: SocketFunc | null; // 错误回调 - onClosed: SocketFunc | null; // 关闭回调 + onConnected: SocketFunc | null; // 连接回调 + onMessage: MessageFunc | null; // 消息回调 + onError: SocketFunc | null; // 错误回调 + onClosed: SocketFunc | null; // 关闭回调 - connect(options: any): any; // 连接接口 - send(buffer: NetData): number; // 数据发送接口 - close(code?: number, reason?: string): void; // 关闭接口 + connect(options: any): any; // 连接接口 + send(buffer: NetData): number; // 数据发送接口 + close(code?: number, reason?: string): void; // 关闭接口 } /** 网络提示接口 */ @@ -89,4 +89,4 @@ export interface INetworkTips { reconnectTips(isShow: boolean): void; requestTips(isShow: boolean): void; responseErrorCode(code: number): void; -} \ No newline at end of file +} diff --git a/assets/libs/network/NetManager.ts b/assets/libs/network/NetManager.ts index b88ca88..b9636b2 100644 --- a/assets/libs/network/NetManager.ts +++ b/assets/libs/network/NetManager.ts @@ -4,8 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-09 18:10:50 */ -import { CallbackObject, IRequestProtocol, NetData } from "./NetInterface"; -import { NetConnectOptions, NetNode } from "./NetNode"; +import type { CallbackObject, IRequestProtocol, NetData } from './NetInterface'; +import type { NetConnectOptions, NetNode } from './NetNode'; /** * 使用流程文档可参考、简化与服务器对接、使用新版API体验,可进入下面地址获取新版本,替换network目录中的内容 @@ -33,13 +33,13 @@ export class NetManager { * @param channelId 通道编号 * @example // 游戏服务器心跳协议 - class GameProtocol extends NetProtocolPako { + class GameProtocol extends NetProtocolPako { // 自定义心跳协议 - getHearbeat(): NetData { + getHearbeat(): NetData { return '{"action":"LoginAction","method":"heart","data":"null","callback":"LoginAction_heart"}'; } } - + var net = new NetNodeGame(); var ws = new WebSock(); // WebSocket 网络连接对象 var gp = new GameProtocol(); // 网络通讯协议对象 @@ -47,7 +47,7 @@ export class NetManager { net.init(ws, gp, gt); NetManager.getInstance().setNetNode(net, NetChannelType.Game); */ - setNetNode(node: NetNode, channelId: number = 0) { + setNetNode(node: NetNode, channelId = 0) { this._channels[channelId] = node; } @@ -67,7 +67,7 @@ export class NetManager { } NetManager.getInstance().connect(options, NetChannelType.Game); */ - connect(options: NetConnectOptions, channelId: number = 0): boolean { + connect(options: NetConnectOptions, channelId = 0): boolean { if (this._channels[channelId]) { return this._channels[channelId].connect(options); } @@ -75,8 +75,8 @@ export class NetManager { } /** 节点连接发送数据*/ - send(buf: NetData, force: boolean = false, channelId: number = 0): number { - let node = this._channels[channelId]; + send(buf: NetData, force = false, channelId = 0): number { + const node = this._channels[channelId]; if (node) { return node!.send(buf, force); } @@ -100,8 +100,8 @@ export class NetManager { } return this.request(protocol, rspObject, showTips, force); */ - request(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips: boolean = true, force: boolean = false, channelId: number = 0) { - let node = this._channels[channelId]; + request(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips = true, force = false, channelId = 0) { + const node = this._channels[channelId]; if (node) { node.request(reqProtocol, rspObject, showTips, force); } @@ -124,8 +124,8 @@ export class NetManager { } return this.request(protocol, rspObject, showTips, force); */ - requestUnique(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips: boolean = true, force: boolean = false, channelId: number = 0): boolean { - let node = this._channels[channelId]; + requestUnique(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips = true, force = false, channelId = 0): boolean { + const node = this._channels[channelId]; if (node) { return node.requestUnique(reqProtocol, rspObject, showTips, force); } @@ -137,12 +137,12 @@ export class NetManager { * @param code 关闭码 * @param reason 关闭原因 * @param channelId 通道编号 - * @example + * @example * NetManager.getInstance().close(undefined, undefined, NetChannelType.Game); */ - close(code?: number, reason?: string, channelId: number = 0) { + close(code?: number, reason?: string, channelId = 0) { if (this._channels[channelId]) { return this._channels[channelId].closeSocket(code, reason); } } -} \ No newline at end of file +} diff --git a/assets/libs/network/NetNode.ts b/assets/libs/network/NetNode.ts index 76862cf..0e8be02 100644 --- a/assets/libs/network/NetNode.ts +++ b/assets/libs/network/NetNode.ts @@ -1,6 +1,6 @@ -import { error, warn } from "cc"; -import { Logger } from "../../core/common/log/Logger"; -import { CallbackObject, INetworkTips, IProtocolHelper, IRequestProtocol, ISocket, NetCallFunc, NetData, RequestObject } from "./NetInterface"; +import { error, warn } from 'cc'; +import { Logger } from '../../core/common/log/Logger'; +import type { CallbackObject, INetworkTips, IProtocolHelper, IRequestProtocol, ISocket, NetCallFunc, NetData, RequestObject } from './NetInterface'; /* * CocosCreator网络节点基类,以及网络相关接口定义 @@ -15,7 +15,7 @@ type CheckFunc = (checkedFunc: VoidFunc) => void; type VoidFunc = () => void; type BoolFunc = () => boolean; -var NetNodeStateStrs = ["已关闭", "连接中", "验证中", "可传输数据"]; +const NetNodeStateStrs = ['已关闭', '连接中', '验证中', '可传输数据']; /** 网络提示类型枚举 */ export enum NetTipsType { @@ -26,53 +26,53 @@ export enum NetTipsType { /** 网络状态枚举 */ export enum NetNodeState { - Closed, // 已关闭 - Connecting, // 连接中 - Checking, // 验证中 - Working, // 可传输数据 + Closed, // 已关闭 + Connecting, // 连接中 + Checking, // 验证中 + Working, // 可传输数据 } /** 网络连接参数 */ export interface NetConnectOptions { - host?: string, // 地址 - port?: number, // 端口 - url?: string, // url,与地址+端口二选一 - autoReconnect?: number, // -1 永久重连,0不自动重连,其他正整数为自动重试次数 + host?: string, // 地址 + port?: number, // 端口 + url?: string, // url,与地址+端口二选一 + autoReconnect?: number, // -1 永久重连,0不自动重连,其他正整数为自动重试次数 } /** 网络节点 */ export class NetNode { protected _connectOptions: NetConnectOptions | null = null; - protected _autoReconnect: number = 0; - protected _isSocketInit: boolean = false; // Socket是否初始化过 - protected _isSocketOpen: boolean = false; // Socket是否连接成功过 - protected _state: NetNodeState = NetNodeState.Closed; // 节点当前状态 - protected _socket: ISocket | null = null; // Socket对象(可能是原生socket、websocket、wx.socket...) + protected _autoReconnect = 0; + protected _isSocketInit = false; // Socket是否初始化过 + protected _isSocketOpen = false; // Socket是否连接成功过 + protected _state: NetNodeState = NetNodeState.Closed; // 节点当前状态 + protected _socket: ISocket | null = null; // Socket对象(可能是原生socket、websocket、wx.socket...) - protected _networkTips: INetworkTips | null = null; // 网络提示ui对象(请求提示、断线重连提示等) - protected _protocolHelper: IProtocolHelper | null = null; // 包解析对象 - protected _connectedCallback: CheckFunc | null = null; // 连接完成回调 - protected _disconnectCallback: BoolFunc | null = null; // 断线回调 - protected _callbackExecuter: ExecuterFunc | null = null; // 回调执行 + protected _networkTips: INetworkTips | null = null; // 网络提示ui对象(请求提示、断线重连提示等) + protected _protocolHelper: IProtocolHelper | null = null; // 包解析对象 + protected _connectedCallback: CheckFunc | null = null; // 连接完成回调 + protected _disconnectCallback: BoolFunc | null = null; // 断线回调 + protected _callbackExecuter: ExecuterFunc | null = null; // 回调执行 - protected _keepAliveTimer: any = null; // 心跳定时器 - protected _receiveMsgTimer: any = null; // 接收数据定时器 - protected _reconnectTimer: any = null; // 重连定时器 - protected _heartTime: number = 10000; // 心跳间隔 - protected _receiveTime: number = 6000000; // 多久没收到数据断开 - protected _reconnetTimeOut: number = 8000000; // 重连间隔 - protected _requests: RequestObject[] = Array(); // 请求列表 - protected _listener: { [key: string]: CallbackObject[] | null } = {} // 监听者列表 + protected _keepAliveTimer: any = null; // 心跳定时器 + protected _receiveMsgTimer: any = null; // 接收数据定时器 + protected _reconnectTimer: any = null; // 重连定时器 + protected _heartTime = 10000; // 心跳间隔 + protected _receiveTime = 6000000; // 多久没收到数据断开 + protected _reconnetTimeOut = 8000000; // 重连间隔 + protected _requests: RequestObject[] = Array(); // 请求列表 + protected _listener: { [key: string]: CallbackObject[] | null } = {}; // 监听者列表 /********************** 网络相关处理 *********************/ init(socket: ISocket, protocol: IProtocolHelper, networkTips: INetworkTips | null = null, execFunc: ExecuterFunc | null = null) { - Logger.instance.logNet(`网络初始化`); + Logger.instance.logNet('网络初始化'); this._socket = socket; this._protocolHelper = protocol; this._networkTips = networkTips; this._callbackExecuter = execFunc ? execFunc : (callback: CallbackObject, buffer: NetData) => { callback.callback.call(callback.target, buffer); - } + }; } /** @@ -89,7 +89,7 @@ export class NetNode { this.updateNetTips(NetTipsType.Connecting, false); return false; } - if (this._connectOptions == null && typeof options.autoReconnect == "number") { + if (this._connectOptions == null && typeof options.autoReconnect === 'number') { this._autoReconnect = options.autoReconnect; } this._connectOptions = options; @@ -101,10 +101,18 @@ export class NetNode { protected initSocket() { if (this._socket) { - this._socket.onConnected = (event) => { this.onConnected(event) }; - this._socket.onMessage = (msg) => { this.onMessage(msg) }; - this._socket.onError = (event) => { this.onError(event) }; - this._socket.onClosed = (event) => { this.onClosed(event) }; + this._socket.onConnected = (event) => { + this.onConnected(event); + }; + this._socket.onMessage = (msg) => { + this.onMessage(msg); + }; + this._socket.onError = (event) => { + this.onError(event); + }; + this._socket.onClosed = (event) => { + this.onClosed(event); + }; this._isSocketInit = true; } } @@ -125,12 +133,14 @@ export class NetNode { /** 网络连接成功 */ protected onConnected(event: any) { - Logger.instance.logNet("网络已连接") + Logger.instance.logNet('网络已连接'); this._isSocketOpen = true; // 如果设置了鉴权回调,在连接完成后进入鉴权阶段,等待鉴权结束 if (this._connectedCallback !== null) { this._state = NetNodeState.Checking; - this._connectedCallback(() => { this.onChecked() }); + this._connectedCallback(() => { + this.onChecked(); + }); } else { this.onChecked(); @@ -140,21 +150,21 @@ export class NetNode { /** 连接验证成功,进入工作状态 */ protected onChecked() { - Logger.instance.logNet("连接验证成功,进入工作状态"); + Logger.instance.logNet('连接验证成功,进入工作状态'); this._state = NetNodeState.Working; // 关闭连接或重连中的状态显示 this.updateNetTips(NetTipsType.Connecting, false); this.updateNetTips(NetTipsType.ReConnecting, false); // 重发待发送信息 - var requests = this._requests.concat(); + const requests = this._requests.concat(); if (requests.length > 0) { Logger.instance.logNet(`请求【${this._requests.length}】个待发送的信息`); - for (var i = 0; i < requests.length;) { - let req = requests[i]; + for (let i = 0; i < requests.length;) { + const req = requests[i]; this._socket!.send(req.buffer); - if (req.rspObject == null || req.rspCmd != "") { + if (req.rspObject == null || req.rspCmd != '') { requests.splice(i, 1); } else { @@ -170,11 +180,11 @@ export class NetNode { protected onMessage(msg: any): void { // Logger.logNet(`接受消息状态为【${NetNodeStateStrs[this._state]}】`); - var json = JSON.parse(msg); + const json = JSON.parse(msg); // 进行头部的校验(实际包长与头部长度是否匹配) if (!this._protocolHelper!.checkResponsePackage(json)) { - error(`校验接受消息数据异常`); + error('校验接受消息数据异常'); return; } @@ -189,13 +199,13 @@ export class NetNode { // 重置心跳包发送器 this.resetHearbeatTimer(); // 触发消息执行 - let rspCmd = this._protocolHelper!.getPackageId(json); + const rspCmd = this._protocolHelper!.getPackageId(json); Logger.instance.logNet(`接受到命令【${rspCmd}】的消息`); // 优先触发request队列 if (this._requests.length > 0) { - for (let reqIdx in this._requests) { - let req = this._requests[reqIdx]; + for (const reqIdx in this._requests) { + const req = this._requests[reqIdx]; if (req.rspCmd == rspCmd && req.rspObject) { Logger.instance.logNet(`触发请求命令【${rspCmd}】的回调`); this._callbackExecuter!(req.rspObject, json.data); @@ -212,7 +222,7 @@ export class NetNode { } } - let listeners = this._listener[rspCmd]; + const listeners = this._listener[rspCmd]; if (null != listeners) { for (const rsp of listeners) { Logger.instance.logNet(`触发监听命令【${rspCmd}】的回调`); @@ -230,7 +240,7 @@ export class NetNode { // 执行断线回调,返回false表示不进行重连 if (this._disconnectCallback && !this._disconnectCallback()) { - Logger.instance.logNet(`断开连接`); + Logger.instance.logNet('断开连接'); return; } @@ -289,7 +299,7 @@ export class NetNode { * @param buf 网络数据 * @param force 是否强制发送 */ - send(buf: NetData, force: boolean = false): number { + send(buf: NetData, force = false): number { if (this._state == NetNodeState.Working || force) { return this._socket!.send(buf); } @@ -297,7 +307,7 @@ export class NetNode { this._state == NetNodeState.Connecting) { this._requests.push({ buffer: buf, - rspCmd: "", + rspCmd: '', rspObject: null }); Logger.instance.logNet(`当前状态为【${NetNodeStateStrs[this._state]}】,繁忙并缓冲发送数据`); @@ -316,8 +326,8 @@ export class NetNode { * @param showTips 是否触发请求提示 * @param force 是否强制发送 */ - request(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips: boolean = true, force: boolean = false) { - var rspCmd = this._protocolHelper!.handlerRequestPackage(reqProtocol); + request(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips = true, force = false) { + const rspCmd = this._protocolHelper!.handlerRequestPackage(reqProtocol); this.base_request(reqProtocol, rspCmd, rspObject, showTips, force); } @@ -328,8 +338,8 @@ export class NetNode { * @param showTips 是否触发请求提示 * @param force 是否强制发送 */ - requestUnique(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips: boolean = true, force: boolean = false): boolean { - var rspCmd = this._protocolHelper!.handlerRequestPackage(reqProtocol); + requestUnique(reqProtocol: IRequestProtocol, rspObject: CallbackObject, showTips = true, force = false): boolean { + const rspCmd = this._protocolHelper!.handlerRequestPackage(reqProtocol); for (let i = 0; i < this._requests.length; ++i) { if (this._requests[i].rspCmd == rspCmd) { @@ -342,8 +352,8 @@ export class NetNode { return true; } - private base_request(reqProtocol: IRequestProtocol, rspCmd: string, rspObject: CallbackObject, showTips: boolean = true, force: boolean = false) { - var buf: NetData = JSON.stringify(reqProtocol); // 转为二进制流发送 + private base_request(reqProtocol: IRequestProtocol, rspCmd: string, rspObject: CallbackObject, showTips = true, force = false) { + const buf: NetData = JSON.stringify(reqProtocol); // 转为二进制流发送 if (this._state == NetNodeState.Working || force) { this._socket!.send(buf); @@ -382,19 +392,19 @@ export class NetNode { * @param cmd 命令字串 * @param callback 回调方法 * @param target 目标对象 - * @returns + * @returns */ addResponeHandler(cmd: string, callback: NetCallFunc, target?: any): boolean { if (callback == null) { error(`命令为【${cmd}】添加响应处理程序错误`); return false; } - let rspObject = { target, callback }; + const rspObject = { target, callback }; if (null == this._listener[cmd]) { this._listener[cmd] = [rspObject]; } else { - let index = this.getNetListenersIndex(cmd, rspObject); + const index = this.getNetListenersIndex(cmd, rspObject); if (-1 == index) { this._listener[cmd]!.push(rspObject); } @@ -410,7 +420,7 @@ export class NetNode { */ removeResponeHandler(cmd: string, callback: NetCallFunc, target?: any) { if (null != this._listener[cmd] && callback != null) { - let index = this.getNetListenersIndex(cmd, { target, callback }); + const index = this.getNetListenersIndex(cmd, { target, callback }); if (-1 != index) { this._listener[cmd]!.splice(index, 1); } @@ -421,9 +431,9 @@ export class NetNode { * 清除所有监听或指定命令的监听 * @param cmd 命令字串(默认不填为清除所有) */ - cleanListeners(cmd: string = "") { - if (cmd == "") { - this._listener = {} + cleanListeners(cmd = '') { + if (cmd == '') { + this._listener = {}; } else { delete this._listener[cmd]; @@ -433,7 +443,7 @@ export class NetNode { protected getNetListenersIndex(cmd: string, rspObject: CallbackObject): number { let index = -1; for (let i = 0; i < this._listener[cmd]!.length; i++) { - let iterator = this._listener[cmd]![i]; + const iterator = this._listener[cmd]![i]; if (iterator.callback == rspObject.callback && iterator.target == rspObject.target) { index = i; @@ -450,7 +460,7 @@ export class NetNode { } this._receiveMsgTimer = setTimeout(() => { - warn("接收消息定时器关闭网络连接"); + warn('接收消息定时器关闭网络连接'); this._socket!.close(); }, this._receiveTime); } @@ -461,7 +471,7 @@ export class NetNode { } this._keepAliveTimer = setTimeout(() => { - Logger.instance.logNet("网络节点保持活跃发送心跳信息"); + Logger.instance.logNet('网络节点保持活跃发送心跳信息'); this.send(this._protocolHelper!.getHearbeat()); }, this._heartTime); } @@ -488,4 +498,4 @@ export class NetNode { this._autoReconnect = 0; this.clearTimer(); } -} \ No newline at end of file +} diff --git a/assets/libs/network/NetProtocolPako.ts b/assets/libs/network/NetProtocolPako.ts index 3637b8a..4dde123 100644 --- a/assets/libs/network/NetProtocolPako.ts +++ b/assets/libs/network/NetProtocolPako.ts @@ -4,23 +4,23 @@ * @LastEditors: dgflash * @LastEditTime: 2022-04-21 13:51:33 */ -import { IProtocolHelper, IRequestProtocol, IResponseProtocol, NetData } from "./NetInterface"; +import type { IProtocolHelper, IRequestProtocol, IResponseProtocol, NetData } from './NetInterface'; -var unzip = function (str: string) { - let charData = str.split('').map(function (x) { +const unzip = function (str: string) { + const charData = str.split('').map((x) => { return x.charCodeAt(0); }); - let binData = new Uint8Array(charData); + const binData = new Uint8Array(charData); //@ts-ignore - let data = pako.inflate(binData, { to: 'string' }); + const data = pako.inflate(binData, { to: 'string' }); return data; -} +}; -var zip = function (str: string) { +const zip = function (str: string) { //@ts-ignore - let binaryString = pako.gzip(str, { to: 'string' }); + const binaryString = pako.gzip(str, { to: 'string' }); return binaryString; -} +}; /** Pako.js 数据压缩协议 */ export class NetProtocolPako implements IProtocolHelper { @@ -29,7 +29,7 @@ export class NetProtocolPako implements IProtocolHelper { } getHearbeat(): NetData { - return ""; + return ''; } getPackageLen(msg: NetData): number { @@ -55,7 +55,7 @@ export class NetProtocolPako implements IProtocolHelper { } handlerRequestPackage(reqProtocol: IRequestProtocol): string { - var rspCmd = reqProtocol.cmd; + const rspCmd = reqProtocol.cmd; reqProtocol.callback = rspCmd; if (reqProtocol.isCompress) { reqProtocol.data = zip(reqProtocol.data); @@ -66,4 +66,4 @@ export class NetProtocolPako implements IProtocolHelper { getPackageId(respProtocol: IResponseProtocol): string { return respProtocol.callback!; } -} \ No newline at end of file +} diff --git a/assets/libs/network/WebSock.ts b/assets/libs/network/WebSock.ts index 1ceaca9..af61596 100644 --- a/assets/libs/network/WebSock.ts +++ b/assets/libs/network/WebSock.ts @@ -4,8 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-09 17:42:19 */ -import { Logger } from "../../core/common/log/Logger"; -import { ISocket, MessageFunc, NetData } from "./NetInterface"; +import { Logger } from '../../core/common/log/Logger'; +import type { ISocket, MessageFunc, NetData } from './NetInterface'; type Connected = (event: any) => void; @@ -16,7 +16,7 @@ type Connected = (event: any) => void; * 3. 数据发送与接收 */ export class WebSock implements ISocket { - private _ws: WebSocket | null = null; // websocket对象 + private _ws: WebSocket | null = null; // websocket对象 /** 网络连接成功事件 */ onConnected: ((this: WebSocket, ev: Event) => any) | null = null; @@ -31,7 +31,7 @@ export class WebSock implements ISocket { connect(options: any) { if (this._ws) { if (this._ws.readyState === WebSocket.CONNECTING) { - Logger.logNet("websocket connecting, wait for a moment...") + Logger.logNet('websocket connecting, wait for a moment...'); return false; } } @@ -41,16 +41,16 @@ export class WebSock implements ISocket { url = options.url; } else { - let ip = options.ip; - let port = options.port; - let protocol = options.protocol; + const ip = options.ip; + const port = options.port; + const protocol = options.protocol; url = `${protocol}://${ip}:${port}`; } this._ws = new WebSocket(url); - this._ws.binaryType = options.binaryType ? options.binaryType : "arraybuffer"; + this._ws.binaryType = options.binaryType ? options.binaryType : 'arraybuffer'; this._ws.onmessage = (event) => { - let onMessage: MessageFunc = this.onMessage!; + const onMessage: MessageFunc = this.onMessage!; onMessage(event.data); }; this._ws.onopen = this.onConnected; @@ -60,7 +60,7 @@ export class WebSock implements ISocket { } /** - * 发送数据 + * 发送数据 * @param buffer 网络数据 */ send(buffer: NetData): number { @@ -81,4 +81,4 @@ export class WebSock implements ISocket { this._ws.close(code, reason); } } -} \ No newline at end of file +} diff --git a/assets/libs/render-texture/RtToModel.ts b/assets/libs/render-texture/RtToModel.ts index 48411f4..4f12983 100644 --- a/assets/libs/render-texture/RtToModel.ts +++ b/assets/libs/render-texture/RtToModel.ts @@ -5,10 +5,10 @@ const { ccclass, property } = _decorator; @ccclass('RtToModel') export class RtToModel extends Component { @property(Camera) - camara: Camera = null!; + camara: Camera = null!; @property(MeshRenderer) - model: MeshRenderer = null!; + model: MeshRenderer = null!; private rt: RenderTexture = new RenderTexture(); diff --git a/assets/libs/render-texture/RtToSprite.ts b/assets/libs/render-texture/RtToSprite.ts index f034b90..f9a0aac 100644 --- a/assets/libs/render-texture/RtToSprite.ts +++ b/assets/libs/render-texture/RtToSprite.ts @@ -1,4 +1,5 @@ -import { Camera, Component, EventTouch, Node, RenderTexture, Sprite, SpriteFrame, UITransform, Vec3, _decorator, gfx } from 'cc'; +import type { EventTouch, Vec3 } from 'cc'; +import { Camera, Component, Node, RenderTexture, Sprite, SpriteFrame, UITransform, _decorator, gfx } from 'cc'; const { ccclass, property } = _decorator; /** 三维模型显示到二维精灵上 */ @@ -6,36 +7,36 @@ const { ccclass, property } = _decorator; export class RtToSprite extends Component { @property({ type: Camera, - tooltip: "渲染模型的三维摄像机" + tooltip: '渲染模型的三维摄像机' }) - camera: Camera | null = null; + camera: Camera | null = null; @property({ type: Sprite, - tooltip: "显示模型的二维精灵组件" + tooltip: '显示模型的二维精灵组件' }) - sprite: Sprite | null = null; + sprite: Sprite | null = null; @property({ - tooltip: "是否触摸控制旋转" + tooltip: '是否触摸控制旋转' }) - rotation: boolean = false; + rotation = false; @property({ type: Node, - tooltip: "三维模型", + tooltip: '三维模型', visible: function () { //@ts-ignore return this.rotation === true; }, }) - model: Node | null = null; + model: Node | null = null; private rt: RenderTexture = new RenderTexture(); - private touched = false; // 是否触摸节点 + private touched = false; // 是否触摸节点 start() { - let size = this.sprite!.getComponent(UITransform)!; + const size = this.sprite!.getComponent(UITransform)!; this.refreshRenderTexture(size.width, size.height); if (this.rotation) { @@ -52,8 +53,8 @@ export class RtToSprite extends Component { protected onTouchMove(event: EventTouch) { if (this.touched) { - let eulerAngles: Vec3 = this.model!.eulerAngles; - let deltaX = event.touch!.getDelta().x!; + const eulerAngles: Vec3 = this.model!.eulerAngles; + const deltaX = event.touch!.getDelta().x!; eulerAngles.y += -deltaX; this.model!.eulerAngles = eulerAngles; } @@ -75,8 +76,8 @@ export class RtToSprite extends Component { passInfo: pi }); - let spriteframe: SpriteFrame = this.sprite!.spriteFrame!; - let sp: SpriteFrame = new SpriteFrame(); + const spriteframe: SpriteFrame = this.sprite!.spriteFrame!; + const sp: SpriteFrame = new SpriteFrame(); sp.reset({ originalSize: spriteframe.originalSize, rect: spriteframe.rect, diff --git a/assets/module/common/CCBusiness.ts b/assets/module/common/CCBusiness.ts index e8a6836..d1591bd 100644 --- a/assets/module/common/CCBusiness.ts +++ b/assets/module/common/CCBusiness.ts @@ -5,9 +5,9 @@ * @LastEditTime: 2025-09-18 17:20:51 */ -import { EventDispatcher } from "../../core/common/event/EventDispatcher"; -import { ListenerFunc } from "../../core/common/event/EventMessage"; -import { CCEntity } from "./CCEntity"; +import { EventDispatcher } from '../../core/common/event/EventDispatcher'; +import type { ListenerFunc } from '../../core/common/event/EventMessage'; +import type { CCEntity } from './CCEntity'; /** 业务逻辑 */ export class CCBusiness { @@ -82,4 +82,4 @@ export class CCBusiness { } //#endregion -} \ No newline at end of file +} diff --git a/assets/module/common/CCEntity.ts b/assets/module/common/CCEntity.ts index e83e6bc..1a23cec 100644 --- a/assets/module/common/CCEntity.ts +++ b/assets/module/common/CCEntity.ts @@ -1,16 +1,17 @@ -import { __private, Node } from "cc"; -import { resLoader } from "../../core/common/loader/ResLoader"; -import { gui } from "../../core/gui/Gui"; -import { LayerUIElement, UIParam } from "../../core/gui/layer/LayerUIElement"; -import { oops } from "../../core/Oops"; -import { ViewUtil } from "../../core/utils/ViewUtil"; -import { ecs } from "../../libs/ecs/ECS"; -import { ECSEntity } from "../../libs/ecs/ECSEntity"; -import { CompType } from "../../libs/ecs/ECSModel"; -import { CCBusiness } from "./CCBusiness"; -import { CCView } from "./CCView"; -import { CCViewVM } from "./CCViewVM"; -import { GameComponent } from "./GameComponent"; +import type { __private, Node } from 'cc'; +import { resLoader } from '../../core/common/loader/ResLoader'; +import { gui } from '../../core/gui/Gui'; +import type { UIParam } from '../../core/gui/layer/LayerUIElement'; +import { LayerUIElement } from '../../core/gui/layer/LayerUIElement'; +import { oops } from '../../core/Oops'; +import { ViewUtil } from '../../core/utils/ViewUtil'; +import { ecs } from '../../libs/ecs/ECS'; +import type { ECSEntity } from '../../libs/ecs/ECSEntity'; +import type { CompType } from '../../libs/ecs/ECSModel'; +import type { CCBusiness } from './CCBusiness'; +import type { CCView } from './CCView'; +import type { CCViewVM } from './CCViewVM'; +import { GameComponent } from './GameComponent'; export type ECSCtor = __private.__types_globals__Constructor | __private.__types_globals__AbstractedConstructor; export type ECSView = CCViewVM | CCView; @@ -26,7 +27,7 @@ export abstract class CCEntity extends ecs.Entity { * @param clss 单例子实体类数组 */ addChildSingletons(...clss: any[]) { - for (let ctor of clss) { + for (const ctor of clss) { this.addChildSingleton(ctor); } } @@ -42,7 +43,7 @@ export abstract class CCEntity extends ecs.Entity { console.error(`${cls.name} 单例子实体已存在`); return null!; } - let entity = ecs.getEntity(cls); + const entity = ecs.getEntity(cls); this.singletons.set(cls, entity); this.addChild(entity); return entity as T; @@ -59,7 +60,7 @@ export abstract class CCEntity extends ecs.Entity { /** 移除单例子实体 */ removeChildSingleton(cls: any) { - let entity = this.singletons.get(cls); + const entity = this.singletons.get(cls); if (entity) { this.singletons.delete(cls); this.removeChild(entity); @@ -158,10 +159,10 @@ export abstract class CCEntity extends ecs.Entity { /** * 批量添加组件 * @param ctors 组件类 - * @returns + * @returns */ addBusinesss>(...clss: any[]) { - for (let ctor of clss) { + for (const ctor of clss) { this.addBusiness(ctor); } } @@ -177,7 +178,7 @@ export abstract class CCEntity extends ecs.Entity { console.error(`${cls.name} 业务逻辑组件已存在`); return null!; } - let business = new cls(); + const business = new cls(); business.ent = this; business.init(); this.businesss.set(cls, business); @@ -200,7 +201,7 @@ export abstract class CCEntity extends ecs.Entity { */ removeBusiness(cls: any) { if (this.businesss) { - let business = this.businesss.get(cls); + const business = this.businesss.get(cls); if (business) this.businesss.delete(cls); } } @@ -213,10 +214,10 @@ export abstract class CCEntity extends ecs.Entity { } if (this.businesss) { - this.businesss.forEach(business => business.destroy()); + this.businesss.forEach((business) => business.destroy()); this.businesss.clear(); this.businesss = null!; } super.destroy(); } -} \ No newline at end of file +} diff --git a/assets/module/common/CCView.ts b/assets/module/common/CCView.ts index 01ccbe5..aef4291 100644 --- a/assets/module/common/CCView.ts +++ b/assets/module/common/CCView.ts @@ -5,22 +5,22 @@ * @LastEditTime: 2022-09-06 17:20:51 */ -import { ecs } from '../../libs/ecs/ECS'; +import type { ecs } from '../../libs/ecs/ECS'; import { ECSModel } from '../../libs/ecs/ECSModel'; -import { CCEntity } from './CCEntity'; +import type { CCEntity } from './CCEntity'; import { GameComponent } from './GameComponent'; -/** +/** * ECS 游戏显示对象组件 - * + * * 功能介绍: * 1. 对象拥有 cc.Component 组件功能与 ecs.Comp 组件功能 * 2. 对象自带全局事件监听、释放、发送全局消息功能 * 3. 对象管理的所有节点摊平,直接通过节点名获取cc.Node对象 - * + * * 应用场景 * 1. 网络游戏,优先有数据对象,然后创建视图对象,当释放视图组件时,部分场景不希望释放数据对象 - * + * * @example @ccclass('RoleViewComp') @ecs.register('RoleView', false) @@ -29,17 +29,17 @@ export class RoleViewComp extends CCView { spine: sp.Skeleton = null!; onLoad(){ - + } } */ export abstract class CCView extends GameComponent implements ecs.IComp { - static tid: number = -1; + static tid = -1; static compName: string; canRecycle!: boolean; ent!: T; - tid: number = -1; + tid = -1; /** 从父节点移除自己 */ remove() { @@ -53,4 +53,4 @@ export abstract class CCView extends GameComponent implement } abstract reset(): void; -} \ No newline at end of file +} diff --git a/assets/module/common/CCViewVM.ts b/assets/module/common/CCViewVM.ts index 6f1219c..9697e99 100644 --- a/assets/module/common/CCViewVM.ts +++ b/assets/module/common/CCViewVM.ts @@ -5,23 +5,23 @@ * @LastEditTime: 2022-09-06 17:22:05 */ -import { ecs } from '../../libs/ecs/ECS'; +import type { ecs } from '../../libs/ecs/ECS'; import { ECSModel } from '../../libs/ecs/ECSModel'; import VMParent from '../../libs/model-view/VMParent'; -import { CCEntity } from './CCEntity'; +import type { CCEntity } from './CCEntity'; -/** +/** * 支持 MVVM 功能的 ECS 游戏显示对象组件 - * + * * 使用方法: * 1. 对象拥有 cc.Component 组件功能与 ecs.Comp 组件功能 * 2. 对象自带全局事件监听、释放、发送全局消息功能 * 3. 对象管理的所有节点摊平,直接通过节点名获取cc.Node对象(节点名不能有重名) * 4. 对象支持 VMParent 所有功能 - * + * * 应用场景 * 1. 网络游戏,优先有数据对象,然后创建视图对象,当释放视图组件时,部分场景不希望释放数据对象 - * + * * @example @ccclass('LoadingViewComp') @ecs.register('LoadingView', false) @@ -41,17 +41,17 @@ export class LoadingViewComp extends CCViewVM { private progress: number = 0; reset(): void { - + } } */ export abstract class CCViewVM extends VMParent implements ecs.IComp { - static tid: number = -1; + static tid = -1; static compName: string; canRecycle!: boolean; ent!: T; - tid: number = -1; + tid = -1; /** 从父节点移除自己 */ remove() { @@ -65,4 +65,4 @@ export abstract class CCViewVM extends VMParent implements e } abstract reset(): void; -} \ No newline at end of file +} diff --git a/assets/module/common/GameCollision.ts b/assets/module/common/GameCollision.ts index e7962a3..82a4452 100644 --- a/assets/module/common/GameCollision.ts +++ b/assets/module/common/GameCollision.ts @@ -4,7 +4,8 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-02 09:45:41 */ -import { _decorator, ccenum, Collider, Component, ICollisionEvent, ITriggerEvent } from "cc"; +import type { ICollisionEvent, ITriggerEvent } from 'cc'; +import { _decorator, ccenum, Collider, Component } from 'cc'; const { ccclass, property } = _decorator; @@ -19,12 +20,12 @@ export enum CollisionType { } ccenum(CollisionType); -const Event_TriggerEnter = "onTriggerEnter"; -const Event_TriggerStay = "onTriggerStay"; -const Event_TriggerExit = "onTriggerExit"; -const Event_CollisionEnter = "onCollisionEnter"; -const Event_CollisionStay = "onCollisionStay"; -const Event_CollisionExit = "onCollisionExit"; +const Event_TriggerEnter = 'onTriggerEnter'; +const Event_TriggerStay = 'onTriggerStay'; +const Event_TriggerExit = 'onTriggerExit'; +const Event_CollisionEnter = 'onCollisionEnter'; +const Event_CollisionStay = 'onCollisionStay'; +const Event_CollisionExit = 'onCollisionExit'; /** 碰撞器与触发器 */ @ccclass('GameCollision') @@ -32,7 +33,7 @@ export class GameCollision extends Component { protected collider: Collider = null!; @property({ type: CollisionType, tooltip: '碰撞物体类型' }) - type: CollisionType = CollisionType.Ballistic; + type: CollisionType = CollisionType.Ballistic; onLoad() { this.collider = this.getComponent(Collider)!; @@ -50,15 +51,15 @@ export class GameCollision extends Component { private onTrigger(event: ITriggerEvent) { switch (event.type) { - case Event_TriggerEnter: - this.onTriggerEnter(event); - break; - case Event_TriggerStay: - this.onTriggerStay(event); - break; - case Event_TriggerExit: - this.onTriggerExit(event); - break; + case Event_TriggerEnter: + this.onTriggerEnter(event); + break; + case Event_TriggerStay: + this.onTriggerStay(event); + break; + case Event_TriggerExit: + this.onTriggerExit(event); + break; } } @@ -68,15 +69,15 @@ export class GameCollision extends Component { private onCollision(event: ICollisionEvent) { switch (event.type) { - case Event_CollisionEnter: - this.onCollisionEnter(event); - break; - case Event_CollisionStay: - this.onCollisionStay(event); - break; - case Event_CollisionExit: - this.onCollisionExit(event); - break; + case Event_CollisionEnter: + this.onCollisionEnter(event); + break; + case Event_CollisionStay: + this.onCollisionStay(event); + break; + case Event_CollisionExit: + this.onCollisionExit(event); + break; } } diff --git a/assets/module/common/GameComponent.ts b/assets/module/common/GameComponent.ts index c9ad13c..c85d360 100644 --- a/assets/module/common/GameComponent.ts +++ b/assets/module/common/GameComponent.ts @@ -4,14 +4,17 @@ * @LastEditors: dgflash * @LastEditTime: 2022-12-13 11:36:00 */ -import { Asset, Button, Component, EventHandler, EventKeyboard, EventTouch, Input, Node, Prefab, Sprite, SpriteFrame, __private, _decorator, input, instantiate, isValid } from "cc"; -import { oops } from "../../core/Oops"; -import { AudioEffect } from "../../core/common/audio/AudioEffect"; -import { IAudioParams } from "../../core/common/audio/IAudio"; -import { EventDispatcher } from "../../core/common/event/EventDispatcher"; -import { EventMessage, ListenerFunc } from "../../core/common/event/EventMessage"; -import { AssetType, CompleteCallback, Paths, ProgressCallback, resLoader } from "../../core/common/loader/ResLoader"; -import { ViewUtil } from "../../core/utils/ViewUtil"; +import type { Asset, EventKeyboard, EventTouch, Sprite, __private } from 'cc'; +import { Button, Component, EventHandler, Input, Node, Prefab, SpriteFrame, _decorator, input, instantiate, isValid } from 'cc'; +import { oops } from '../../core/Oops'; +import type { AudioEffect } from '../../core/common/audio/AudioEffect'; +import type { IAudioParams } from '../../core/common/audio/IAudio'; +import { EventDispatcher } from '../../core/common/event/EventDispatcher'; +import type { ListenerFunc } from '../../core/common/event/EventMessage'; +import { EventMessage } from '../../core/common/event/EventMessage'; +import type { AssetType, CompleteCallback, Paths, ProgressCallback } from '../../core/common/loader/ResLoader'; +import { resLoader } from '../../core/common/loader/ResLoader'; +import { ViewUtil } from '../../core/utils/ViewUtil'; const { ccclass } = _decorator; @@ -38,7 +41,7 @@ interface ResRecord { * 1、当前对象加载的资源,会在对象释放时,自动释放引用的资源 * 2、当前对象支持启动游戏引擎提供的各种常用逻辑事件 */ -@ccclass("GameComponent") +@ccclass('GameComponent') export class GameComponent extends Component { //#region 全局事件管理 private _event: EventDispatcher | null = null; @@ -110,7 +113,7 @@ export class GameComponent extends Component { //#region 资源加载管理 /** 资源路径 */ - private resPaths: Map> = null!; // 资源使用记录 + private resPaths: Map> = null!; // 资源使用记录 /** * 获取资源 @@ -131,18 +134,18 @@ export class GameComponent extends Component { private addPathToRecord(type: ResType, bundleName: string, paths?: string | string[] | AssetType | ProgressCallback | CompleteCallback | null) { if (this.resPaths == null) this.resPaths = new Map(); - var rps = this.resPaths.get(type); + let rps = this.resPaths.get(type); if (rps == null) { rps = new Map(); this.resPaths.set(type, rps); } if (paths instanceof Array) { - let realBundle = bundleName; + const realBundle = bundleName; for (let index = 0; index < paths.length; index++) { - let realPath = paths[index]; - let key = this.getResKey(realBundle, realPath); - let rp = rps.get(key); + const realPath = paths[index]; + const key = this.getResKey(realBundle, realPath); + const rp = rps.get(key); if (rp) { rp.refCount++; } @@ -151,11 +154,11 @@ export class GameComponent extends Component { } } } - else if (typeof paths === "string") { - let realBundle = bundleName; - let realPath = paths; - let key = this.getResKey(realBundle, realPath); - let rp = rps.get(key); + else if (typeof paths === 'string') { + const realBundle = bundleName; + const realPath = paths; + const key = this.getResKey(realBundle, realPath); + const rp = rps.get(key); if (rp) { rp.refCount++; } @@ -164,10 +167,10 @@ export class GameComponent extends Component { } } else { - let realBundle = oops.res.defaultBundleName; - let realPath = bundleName; - let key = this.getResKey(realBundle, realPath); - let rp = rps.get(key); + const realBundle = oops.res.defaultBundleName; + const realPath = bundleName; + const key = this.getResKey(realBundle, realPath); + const rp = rps.get(key); if (rp) { rp.refCount++; } @@ -178,7 +181,7 @@ export class GameComponent extends Component { } private getResKey(realBundle: string, realPath: string): string { - let key = `${realBundle}:${realPath}`; + const key = `${realBundle}:${realPath}`; return key; } @@ -202,7 +205,7 @@ export class GameComponent extends Component { * @param onComplete 加载完成回调 */ loadAny(bundleName: string | string[], paths: string[] | ProgressCallback, onProgress?: ProgressCallback | CompleteCallback, onComplete?: CompleteCallback): void { - if (typeof bundleName === "string" && paths instanceof Array) { + if (typeof bundleName === 'string' && paths instanceof Array) { this.addPathToRecord(ResType.Load, bundleName, paths); } else { @@ -236,7 +239,7 @@ export class GameComponent extends Component { ) { let realDir: string; let realBundle: string; - if (typeof dir === "string") { + if (typeof dir === 'string') { realDir = dir; realBundle = bundleName; } @@ -322,7 +325,7 @@ export class GameComponent extends Component { else if (params.bundle == null) { params.bundle = resLoader.defaultBundleName; } - let ae = await oops.audio.playEffect(url, params); + const ae = await oops.audio.playEffect(url, params); if (ae) { this.addPathToRecord(ResType.Load, ae.params.bundle!, url); resolve(ae); @@ -345,7 +348,7 @@ export class GameComponent extends Component { * Label1(event: EventTouch) { console.log(event.target.name); } * Label2(event: EventTouch) { console.log(event.target.name); } */ - protected setButton(bindRootEvent: boolean = true) { + protected setButton(bindRootEvent = true) { // 自定义按钮批量绑定触摸事件 if (bindRootEvent) { this.node.on(Node.EventType.TOUCH_END, (event: EventTouch) => { @@ -493,4 +496,4 @@ export class GameComponent extends Component { this.resPaths = null!; } } -} \ No newline at end of file +} diff --git a/assets/module/common/GameStorage.ts b/assets/module/common/GameStorage.ts index 59a8bca..b2f51ff 100644 --- a/assets/module/common/GameStorage.ts +++ b/assets/module/common/GameStorage.ts @@ -1,7 +1,7 @@ /** 框架内本地存储键值 */ export enum GameStorage { /** 设置音频音量、开关 */ - Audio = "OopsFrameworkAudio", + Audio = 'OopsFrameworkAudio', /** 可设置指定时间内跳过提示 */ - PromptSkip = "OopsFrameworkPromptSkip", -} \ No newline at end of file + PromptSkip = 'OopsFrameworkPromptSkip', +} diff --git a/assets/module/config/BuildTimeConstants.ts b/assets/module/config/BuildTimeConstants.ts index 81fc32a..0358fb1 100644 --- a/assets/module/config/BuildTimeConstants.ts +++ b/assets/module/config/BuildTimeConstants.ts @@ -20,4 +20,4 @@ export class BuildTimeConstants { console.log(enviroment); } -} \ No newline at end of file +} diff --git a/assets/module/config/Config.ts b/assets/module/config/Config.ts index 1a1b830..6dcec0c 100644 --- a/assets/module/config/Config.ts +++ b/assets/module/config/Config.ts @@ -5,9 +5,9 @@ * @LastEditTime: 2022-11-01 15:47:16 */ -import { BuildTimeConstants } from "./BuildTimeConstants"; -import { GameConfig } from "./GameConfig"; -import { GameQueryConfig } from "./GameQueryConfig"; +import { BuildTimeConstants } from './BuildTimeConstants'; +import type { GameConfig } from './GameConfig'; +import type { GameQueryConfig } from './GameQueryConfig'; /** 游戏配置静态访问类 */ export class Config { @@ -19,4 +19,4 @@ export class Config { /** 浏览器查询参数 */ query!: GameQueryConfig; -} \ No newline at end of file +} diff --git a/assets/module/config/GameConfig.ts b/assets/module/config/GameConfig.ts index 2f0ac6c..cf7fe49 100644 --- a/assets/module/config/GameConfig.ts +++ b/assets/module/config/GameConfig.ts @@ -4,16 +4,16 @@ * @LastEditors: dgflash * @LastEditTime: 2023-02-14 14:27:22 */ -import { oops } from "../../core/Oops"; +import { oops } from '../../core/Oops'; /** 游戏自定义参数分组类型 */ export enum GameConfigCustomType { /** 开发环境 */ - Dev = "dev", + Dev = 'dev', /** 测试环境 */ - Test = "test", + Test = 'test', /** 生产环境 */ - Prod = "prod", + Prod = 'prod', } /* 游戏配置解析,对应 resources/config/config.json 配置 */ @@ -73,19 +73,19 @@ export class GameConfig { /** 获取当前客户端支持的语言类型 */ get language(): Array { - return this._data.language.type || ["zh"]; + return this._data.language.type || ['zh']; } /** 获取当前客户端支持的语言 Json 配置路径 */ get languagePathJson(): string { - return this._data.language.path.json || "language/json"; + return this._data.language.path.json || 'language/json'; } /** 获取当前客户端支持的语言纹理配置路径 */ get languagePathTexture(): string { - return this._data.language.path.texture || "language/texture"; + return this._data.language.path.texture || 'language/texture'; } /** 默认语言 */ get languageDefault(): string { - return this._data.language.default || "zh"; + return this._data.language.default || 'zh'; } /** 远程资源名 */ @@ -105,14 +105,14 @@ export class GameConfig { constructor(config: any) { this._data = Object.freeze(config.json); this.setConfigType(this._data.type); - oops.log.logConfig(this._data, "游戏配置"); + oops.log.logConfig(this._data, '游戏配置'); } /** * 设置游戏参数类型 - * @param type + * @param type */ setConfigType(type: GameConfigCustomType) { this._configType = type; } -} \ No newline at end of file +} diff --git a/assets/module/config/GameQueryConfig.ts b/assets/module/config/GameQueryConfig.ts index bb1ad25..6fcf6a0 100644 --- a/assets/module/config/GameQueryConfig.ts +++ b/assets/module/config/GameQueryConfig.ts @@ -4,9 +4,9 @@ * @LastEditors: dgflash * @LastEditTime: 2022-09-06 17:29:45 */ -import { sys } from "cc"; -import { oops } from "../../core/Oops"; -import { StringUtil } from "../../core/utils/StringUtil"; +import { sys } from 'cc'; +import { oops } from '../../core/Oops'; +import { StringUtil } from '../../core/utils/StringUtil'; /** * 获取和处理浏览器地址栏参数 @@ -16,17 +16,17 @@ import { StringUtil } from "../../core/utils/StringUtil"; export class GameQueryConfig { /** 调试模式开关 */ get debug(): string { - return this._data["debug"]; + return this._data['debug']; } /** 玩家帐号名 */ get username(): string { - return this._data["username"]; + return this._data['username']; } /** 语言 */ get lang(): string { - return this._data["lang"] || "zh"; + return this._data['lang'] || 'zh'; } private _data: any = null; @@ -43,30 +43,30 @@ export class GameQueryConfig { } this._data = this.parseUrl(); - if (!this._data["username"]) { - this._data["username"] = StringUtil.guid(); + if (!this._data['username']) { + this._data['username'] = StringUtil.guid(); } - oops.log.logConfig(this._data, "查询参数"); + oops.log.logConfig(this._data, '查询参数'); } private parseUrl() { - if (typeof window !== "object") return {}; + if (typeof window !== 'object') return {}; if (!window.document) return {}; - let url = window.document.location.href.toString(); - let u = url.split("?"); - if (typeof (u[1]) == "string") { - u = u[1].split("&"); - let get: any = {}; + const url = window.document.location.href.toString(); + let u = url.split('?'); + if (typeof (u[1]) === 'string') { + u = u[1].split('&'); + const get: any = {}; for (let i = 0, l = u.length; i < l; ++i) { - let j = u[i]; - let x = j.indexOf("="); + const j = u[i]; + const x = j.indexOf('='); if (x < 0) { continue; } - let key = j.substring(0, x); - let value = j.substring(x + 1); + const key = j.substring(0, x); + const value = j.substring(x + 1); get[decodeURIComponent(key)] = value && decodeURIComponent(value); } return get; @@ -75,4 +75,4 @@ export class GameQueryConfig { return {}; } } -} \ No newline at end of file +}