dzkcc-mflow 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,769 +1,1758 @@
1
1
  # Modular Flow Framework
2
2
 
3
- ## 1.1 框架概述
3
+ 一个专为 Cocos Creator 引擎开发的模块化设计与流程管理框架。
4
4
 
5
- Cocos模块化流程框架(Modular Flow Framework)是一个为Cocos Creator引擎开发的模块化设计和流程管理框架。该框架旨在提供解耦和依赖注入的能力,帮助开发者构建更加清晰、可维护的游戏项目。
5
+ ## 📚 目录
6
+
7
+ - [1. 框架概述](#1-框架概述)
8
+ - [2. 快速开始](#2-快速开始)
9
+ - [3. 核心概念](#3-核心概念)
10
+ - [4. 装饰器系统](#4-装饰器系统)
11
+ - [5. UI 系统](#5-ui-系统)
12
+ - [6. 事件系统](#6-事件系统)
13
+ - [7. 资源管理](#7-资源管理)
14
+ - [8. 网络通信](#8-网络通信)
15
+ - [9. 红点系统](#9-红点系统)
16
+ - [10. 开发工具](#10-开发工具)
17
+ - [11. 完整示例](#11-完整示例)
18
+ - [12. 最佳实践](#12-最佳实践)
19
+
20
+ ---
21
+
22
+ ## 1. 框架概述
23
+
24
+ ### 1.1 简介
25
+
26
+ Modular Flow Framework (MF) 是一个为 Cocos Creator 引擎开发的模块化设计和流程管理框架。该框架旨在提供解耦和依赖注入的能力,帮助开发者构建更加清晰、可维护的游戏项目。
6
27
 
7
28
  ### 1.2 核心特性
8
29
 
9
- - **模块化设计**:通过Manager和Model模式实现业务逻辑的模块化管理
10
- - **依赖注入**:通过装饰器实现自动依赖注入
11
- - **服务定位器**:统一的服务管理机制
12
- - **UI管理系统**:完整的UI界面管理方案
13
- - **事件系统**:强大的事件广播和监听机制
14
- - **资源加载系统**:统一的资源加载和释放管理
15
- - **HTTP网络请求系统**:简洁易用的HTTP客户端
16
- - **WebSocket实时通信**:支持自动重连、心跳检测的WebSocket客户端
17
- - **开发工具**:配套的Cocos Creator编辑器插件
30
+ ✨ **模块化设计** - 通过 Manager Model 模式实现业务逻辑的模块化管理
31
+ ✨ **依赖注入** - 基于装饰器的自动依赖注入和 Symbol 映射
32
+ ✨ **服务定位器** - 统一的服务管理机制,实现服务解耦
33
+ **UI 管理系统** - 完整的 UI 界面管理方案,支持视图栈和分组
34
+ ✨ **事件系统** - 强大的事件广播和监听机制,支持粘性事件
35
+ ✨ **资源加载系统** - 统一的资源加载和自动释放管理
36
+ **HTTP 网络** - 简洁易用的 HTTP 客户端,支持 RESTful API
37
+ **WebSocket 实时通信** - 支持自动重连、心跳检测的 WebSocket 客户端
38
+ ✨ **红点系统** - 树形结构的红点提示管理系统
39
+ ✨ **开发工具** - 配套的 Cocos Creator 编辑器插件
18
40
 
19
- ### 1.3 安装说明
41
+ ### 1.3 安装
20
42
 
21
43
  ```bash
22
44
  npm i dzkcc-mflow@beta
23
45
  ```
24
46
 
25
- 安装完成后,重启Cocos Creator引擎。
47
+ 安装完成后,**重启 Cocos Creator 编辑器**,框架会自动安装配套的编辑器插件。
48
+
49
+ ---
26
50
 
27
- ## 2. 核心概念
51
+ ## 2. 快速开始
28
52
 
29
- ### 2.1 Core核心
53
+ ### 2.1 创建 Core 入口
30
54
 
31
- Core是框架的核心,负责管理所有的Manager和Model实例。它继承自`AbstractCore`类,提供了注册和获取Manager/Model的接口。
55
+ 在项目中创建一个继承自 `CocosCore` 的类:
32
56
 
33
57
  ```typescript
34
- // 自定义Core需要继承CocosCore
35
- export class GameCore extends CocosCore { }
36
- ```
58
+ // GameCore.ts
59
+ import { CocosCore } from 'dzkcc-mflow/libs';
60
+ import { _decorator } from 'cc';
37
61
 
38
- 在场景中挂载GameCore组件即可初始化框架。
62
+ const { ccclass } = _decorator;
39
63
 
40
- ### 2.2 ServiceLocator服务定位器
64
+ @ccclass('GameCore')
65
+ export class GameCore extends CocosCore {
66
+ // CocosCore 会自动初始化框架
67
+ }
68
+ ```
41
69
 
42
- ServiceLocator用于管理跨领域的基础服务,如EventManager、ResLoader、UIManager等。
70
+ ### 2.2 挂载到场景
43
71
 
44
- ```typescript
45
- // 注册服务
46
- ServiceLocator.regService('serviceKey', serviceInstance);
72
+ 1. 在 Cocos Creator 编辑器中打开主场景
73
+ 2. 在 Canvas 节点上添加 `GameCore` 组件
74
+ 3. 保存场景
47
75
 
48
- // 获取服务
49
- const service = ServiceLocator.getService<ServiceType>('serviceKey');
50
- ```
51
76
 
52
- ### 2.3 Manager管理器
77
+ ### 2.3 使用全局对象
53
78
 
54
- Manager负责管理业务领域内的具体实现,通常处理业务逻辑。Manager需要实现`IManager`接口。
79
+ 框架提供了全局对象 `mf`(Modular Flow 的缩写)用于访问框架功能:
55
80
 
56
81
  ```typescript
57
- export abstract class AbstractManager implements IManager {
58
- abstract initialize(): void;
59
- dispose(): void;
60
- }
61
- ```
82
+ // 访问 Manager
83
+ const gameManager = mf.core.getManager(ManagerNames.GameManager);
62
84
 
63
- ### 2.4 Model模型
85
+ // 访问 Model
86
+ const userModel = mf.core.getModel(ModelNames.UserModel);
64
87
 
65
- Model用于数据管理,实现`IModel`接口。
88
+ // 打开 UI
89
+ await mf.gui.open(ViewNames.HomeView);
66
90
 
67
- ```typescript
68
- export interface IModel {
69
- initialize(): void;
70
- }
71
- ```
91
+ // 发送事件
92
+ mf.event.dispatch('gameStart');
72
93
 
73
- ### 2.5 装饰器系统
94
+ // 加载资源
95
+ const prefab = await mf.res.loadPrefab('prefabs/player');
74
96
 
75
- 框架提供了装饰器来简化Manager和Model的注册:
97
+ // HTTP 请求
98
+ const data = await mf.http.get('/api/user/profile');
76
99
 
77
- ```typescript
78
- // 注册Manager
79
- @manager()
80
- export class GameManager extends AbstractManager {
81
- // 实现逻辑
82
- }
100
+ // WebSocket 连接
101
+ mf.socket.connect('wss://game-server.com/ws');
83
102
 
84
- // 注册Model
85
- @model()
86
- export class GameModel implements IModel {
87
- initialize(): void {
88
- // 初始化逻辑
89
- }
90
- }
103
+ // 红点提示
104
+ mf.reddot.setCount('main/bag', 5);
91
105
  ```
92
106
 
93
- ## 3. UI系统
107
+ ## 3. 核心概念
94
108
 
95
- ### 3.1 BaseView基础视图
109
+ ### 3.1 架构图
96
110
 
97
- 所有UI界面都应该继承`BaseView`类,它提供了以下特性:
111
+ ```
112
+ ┌─────────────────────────────────────────────────┐
113
+ │ 全局对象 mf │
114
+ │ (统一访问入口,暴露所有框架能力) │
115
+ └──────────────────┬──────────────────────────────┘
116
+
117
+ ┌──────────────┼──────────────┐
118
+ │ │ │
119
+ ▼ ▼ ▼
120
+ ┌─────────┐ ┌──────────┐ ┌──────────┐
121
+ │ Core │ │ Services │ │ Views │
122
+ │(核心容器)│ │(基础服务) │ │ (UI界面) │
123
+ └─────────┘ └──────────┘ └──────────┘
124
+ │ │ │
125
+ ├─ Manager ─┐ ├─ UIManager ├─ BaseView
126
+ │ │ ├─ ResLoader └─ 自动资源管理
127
+ ├─ Model ───┤ ├─ EventMgr 自动事件清理
128
+ │ │ ├─ HttpMgr
129
+ └─ Symbol ──┘ ├─ SocketMgr
130
+ 映射系统 └─ RedDotMgr
131
+ ```
98
132
 
99
- - 自动事件监听管理(自动注册和注销)
100
- - 自动资源加载管理(自动释放)
101
- - 统一的生命周期方法
133
+ ### 3.2 Core 核心容器
102
134
 
103
- ```typescript
104
- export abstract class BaseView extends Component implements IView {
105
- abstract onPause(): void;
106
- abstract onResume(): void;
107
- abstract onEnter(args?: any): void;
108
- onExit(): void;
109
- }
110
- ```
135
+ `Core` 是框架的核心,负责管理所有 Manager 和 Model 实例。
111
136
 
112
- ### 3.2 UIManager界面管理器
137
+ **核心职责:**
138
+ - 注册和实例化 Manager
139
+ - 注册和实例化 Model
140
+ - 提供统一的访问接口
141
+ - 自动调用初始化方法
113
142
 
114
- UIManager负责管理UI界面的打开、关闭、层级等操作。
143
+ **使用方式:**
115
144
 
116
145
  ```typescript
117
- // 打开界面
118
- const view = await mf.gui.open(ViewType, args);
119
-
120
- // 关闭界面
121
- mf.gui.close(viewInstance);
146
+ // 获取 Manager
147
+ const gameManager = mf.core.getManager(ManagerNames.GameManager);
122
148
 
123
- // 带分组的界面管理
124
- const view = await mf.gui.openAndPush(ViewType, 'group', args);
125
- mf.gui.closeAndPop('group');
149
+ // 获取 Model
150
+ const userModel = mf.core.getModel(ModelNames.UserModel);
126
151
  ```
127
152
 
128
- ## 4. 事件系统
153
+ ### 3.3 ServiceLocator 服务定位器
129
154
 
130
- ### 4.1 Broadcaster事件广播器
155
+ `ServiceLocator` 用于管理跨领域的基础服务,实现解耦。
131
156
 
132
- 框架提供了基于类型的事件系统,通过Broadcaster实现。
157
+ **内置服务:**
158
+ - `core` - Core 实例
159
+ - `EventManager` - 事件管理器
160
+ - `UIManager` - UI 管理器
161
+ - `ResLoader` - 资源加载器
162
+ - `HttpManager` - HTTP 管理器
163
+ - `WebSocketManager` - WebSocket 管理器
164
+ - `RedDotManager` - 红点管理器
165
+
166
+ **自定义服务:**
133
167
 
134
168
  ```typescript
135
- // 监听事件
136
- mf.event.on('eventKey', (data) => {
137
- // 处理事件
138
- });
169
+ import { ServiceLocator } from 'dzkcc-mflow/core';
170
+
171
+ // 注册服务
172
+ ServiceLocator.regService('MyService', new MyService());
139
173
 
140
- // 广播事件
141
- mf.event.dispatch('eventKey', data);
174
+ // 获取服务
175
+ const myService = ServiceLocator.getService<MyService>('MyService');
142
176
 
143
- // 一次性监听
144
- mf.event.once('eventKey', (data) => {
145
- // 只会触发一次
146
- });
177
+ // 移除服务
178
+ ServiceLocator.remove('MyService');
147
179
  ```
148
180
 
149
- ### 4.2 粘性事件
181
+ ### 3.4 Manager 管理器
150
182
 
151
- 粘性事件可以在没有监听者时暂存,等有监听者时再触发:
183
+ Manager 负责处理特定领域的业务逻辑。
152
184
 
153
- ```typescript
154
- // 发送粘性事件
155
- mf.event.dispatchSticky('stickyEvent', data);
185
+ **基类:** `AbstractManager`
156
186
 
157
- // 移除粘性事件
158
- mf.event.removeStickyBroadcast('stickyEvent');
159
- ```
187
+ **生命周期:**
188
+ 1. `initialize()` - 在注册时被调用
189
+ 2. `dispose()` - 在销毁时被调用
160
190
 
161
- ## 5. 资源加载系统
191
+ **内置能力:**
192
+ - 获取 Model:`this.getModel(modelSymbol)`
193
+ - 获取事件管理器:`this.getEventManager()`
194
+ - 获取 HTTP 管理器:`this.getHttpManager()`
195
+ - 获取 WebSocket 管理器:`this.getWebSocketManager()`
162
196
 
163
- ### 5.1 ResLoader资源加载器
197
+ ### 3.5 Model 数据模型
164
198
 
165
- ResLoader提供了统一的资源加载和释放接口:
199
+ Model 用于数据管理,遵循单一职责原则。
166
200
 
167
- ```typescript
168
- // 加载预制体
169
- const prefab = await mf.res.loadPrefab('path/to/prefab');
201
+ **接口:** `IModel`
170
202
 
171
- // 加载精灵帧
172
- const spriteFrame = await mf.res.loadSpriteFrame(spriteComponent, 'path/to/sprite');
203
+ **生命周期:**
204
+ - `initialize()` - 在注册时被调用
173
205
 
174
- // 加载Spine动画
175
- const spineData = await mf.res.loadSpine(spineComponent, 'path/to/spine');
206
+ ### 3.6 View 视图
176
207
 
177
- // 释放资源
178
- mf.res.release('path/to/asset');
179
- ```
208
+ View 是 UI 界面的基类,提供完整的生命周期管理。
180
209
 
181
- ## 6. HTTP网络请求系统
210
+ **基类:** `BaseView`
182
211
 
183
- ### 6.1 HttpManager HTTP管理器
212
+ **生命周期:**
213
+ 1. `onEnter(args?)` - 界面打开时调用
214
+ 2. `onPause()` - 界面被覆盖时调用(栈模式)
215
+ 3. `onResume()` - 界面恢复显示时调用(栈模式)
216
+ 4. `onExit()` - 界面关闭时调用(自动清理事件)
217
+ 5. `onDestroy()` - 界面销毁时调用(自动释放资源)
184
218
 
185
- HttpManager提供了简洁易用的HTTP客户端功能,支持常见的HTTP方法:
219
+ **内置能力:**
220
+ - 自动事件管理:通过 `this.event` 监听的事件会自动清理
221
+ - 自动资源管理:通过 `this.res` 加载的资源会自动释放
222
+ - 获取 Manager:`this.getManager(managerSymbol)`
223
+ - 获取 Model:`this.getModel(modelSymbol)`
186
224
 
187
- ```typescript
188
- // GET 请求
189
- const userData = await mf.http.get('/api/users/123', { includeProfile: true });
225
+ ### 3.7 Symbol 映射系统
190
226
 
191
- // POST 请求
192
- const newUser = await mf.http.post('/api/users', {
193
- name: 'John',
194
- email: 'john@example.com'
195
- });
227
+ 框架使用 Symbol 作为标识符,配合 Names 对象实现类型安全和代码补全。
196
228
 
197
- // PUT 请求
198
- const updatedUser = await mf.http.put('/api/users/123', {
199
- name: 'John Doe'
200
- });
229
+ **三种 Names 对象:**
230
+ - `ModelNames` - Model Symbol 映射
231
+ - `ManagerNames` - Manager 的 Symbol 映射
232
+ - `ViewNames` - View 的 Symbol 映射
201
233
 
202
- // DELETE 请求
203
- await mf.http.delete('/api/users/123');
234
+ **优势:**
235
+ - ✅ IDE 代码补全
236
+ - ✅ 类型安全
237
+ - ✅ 避免字符串拼写错误
238
+ - ✅ 便于重构
204
239
 
205
- // 自定义请求
206
- const result = await mf.http.request({
207
- url: '/api/upload',
208
- method: 'POST',
209
- data: formData,
210
- headers: {
211
- 'Authorization': 'Bearer token'
212
- },
213
- timeout: 30000
214
- });
215
- ```
240
+ ## 4. 装饰器系统
216
241
 
217
- ### 6.2 功能特性
242
+ 框架提供了三个核心装饰器,用于注册 Manager、Model 和 View。
218
243
 
219
- 1. **Promise-based API**:所有请求都返回Promise,支持async/await
220
- 2. **超时控制**:默认10秒超时,可自定义
221
- 3. **自动JSON解析**:自动解析JSON响应
222
- 4. **错误处理**:统一的错误处理机制
223
- 5. **请求拦截**:支持自定义请求头
224
- 6. **URL参数处理**:自动处理GET请求的查询参数
244
+ ### 4.1 @manager() - Manager 装饰器
225
245
 
226
- ### 6.3 使用示例
246
+ 用于注册 Manager 到全局注册表。
227
247
 
228
248
  ```typescript
229
- // 在Manager中使用
230
- @manager()
231
- export class UserManager extends AbstractManager {
232
- async getUserProfile(userId: string): Promise<any> {
233
- try {
234
- const profile = await mf.http.get(`/api/users/${userId}/profile`);
235
- return profile;
236
- } catch (error) {
237
- console.error('Failed to fetch user profile:', error);
238
- throw error;
239
- }
249
+ import { manager, AbstractManager, ManagerNames } from 'dzkcc-mflow/core';
250
+
251
+ @manager('Game') // 指定名称为 'Game'
252
+ export class GameManager extends AbstractManager {
253
+ private score: number = 0;
254
+
255
+ initialize(): void {
256
+ console.log('GameManager 初始化');
240
257
  }
241
258
 
242
- async updateUser(userId: string, data: any): Promise<any> {
243
- try {
244
- const result = await mf.http.put(`/api/users/${userId}`, data, {
245
- 'Authorization': `Bearer ${this.getAuthToken()}`
246
- });
247
- return result;
248
- } catch (error) {
249
- console.error('Failed to update user:', error);
250
- throw error;
251
- }
259
+ dispose(): void {
260
+ console.log('GameManager 销毁');
252
261
  }
253
262
 
254
- private getAuthToken(): string {
255
- // 获取认证令牌的逻辑
256
- return 'your-auth-token';
263
+ addScore(value: number): void {
264
+ this.score += value;
265
+ this.getEventManager().dispatch('scoreChanged', this.score);
257
266
  }
258
267
  }
259
- ```
260
268
 
261
- ## 7. WebSocket 实时通信系统
269
+ // 使用
270
+ const gameManager = mf.core.getManager(ManagerNames.Game);
271
+ gameManager.addScore(10);
272
+ ```
262
273
 
263
- ### 7.1 WebSocketManager WebSocket管理器
274
+ ### 4.2 @model() - Model 装饰器
264
275
 
265
- WebSocketManager提供了完整的 WebSocket 客户端功能,支持:
276
+ 用于注册 Model 到全局注册表。
266
277
 
267
278
  ```typescript
268
- // 连接 WebSocket 服务器
269
- mf.socket.connect('ws://localhost:8080/game');
270
-
271
- // 或使用安全连接
272
- mf.socket.connect('wss://game-server.example.com/ws');
273
-
274
- // 配置自动重连和心跳
275
- mf.socket.configure({
276
- reconnect: true, // 启用自动重连
277
- reconnectInterval: 3000, // 重连间隔 3 秒
278
- reconnectAttempts: 5, // 最多重连 5 次
279
- heartbeat: true, // 启用心跳
280
- heartbeatInterval: 30000, // 心跳间隔 30 秒
281
- heartbeatMessage: 'ping' // 心跳消息
282
- });
283
-
284
- // 监听事件
285
- mf.socket.on('open', (event) => {
286
- console.log('连接成功');
287
- });
288
-
289
- mf.socket.on('message', (event) => {
290
- console.log('收到消息:', event.data);
291
- });
292
-
293
- mf.socket.on('error', (event) => {
294
- console.error('连接错误:', event);
295
- });
296
-
297
- mf.socket.on('close', (event) => {
298
- console.log('连接关闭');
299
- });
300
-
301
- // 发送消息(支持多种数据类型)
302
- // 1. 发送对象(自动转换为 JSON)
303
- mf.socket.send({ type: 'move', x: 100, y: 200 });
304
-
305
- // 2. 发送字符串
306
- mf.socket.send('Hello Server');
279
+ import { model, IModel, ModelNames } from 'dzkcc-mflow/core';
307
280
 
308
- // 检查连接状态
309
- if (mf.socket.isConnected()) {
310
- // 已连接
281
+ @model('User') // 指定名称为 'User'
282
+ export class UserModel implements IModel {
283
+ private _playerName: string = '';
284
+ private _level: number = 1;
285
+
286
+ initialize(): void {
287
+ console.log('UserModel 初始化');
288
+ }
289
+
290
+ get playerName(): string {
291
+ return this._playerName;
292
+ }
293
+
294
+ set playerName(name: string) {
295
+ this._playerName = name;
296
+ }
297
+
298
+ get level(): number {
299
+ return this._level;
300
+ }
301
+
302
+ levelUp(): void {
303
+ this._level++;
304
+ }
311
305
  }
312
306
 
313
- // 断开连接
314
- mf.socket.disconnect();
307
+ // 使用
308
+ const userModel = mf.core.getModel(ModelNames.User);
309
+ userModel.playerName = 'Alice';
310
+ userModel.levelUp();
315
311
  ```
316
312
 
317
- ### 7.2 发送不同类型的数据
313
+ ### 4.3 @view() - View 装饰器
318
314
 
319
- WebSocket 支持多种数据类型的发送:
315
+ 用于注册 View 到全局注册表,配合 `ViewNames` 使用。
320
316
 
321
317
  ```typescript
322
- // ==================== 1. 发送 JSON 对象(推荐)====================
323
- // 自动序列化为 JSON 字符串
324
- mf.socket.send({
325
- type: 'player_move',
326
- position: { x: 100, y: 200 },
327
- timestamp: Date.now()
328
- });
318
+ import { view, ViewNames } from 'dzkcc-mflow/core';
319
+ import { BaseView } from 'dzkcc-mflow/libs';
320
+ import { _decorator, Button, Label } from 'cc';
329
321
 
330
- // ==================== 2. 发送纯文本 ====================
331
- mf.socket.send('ping');
322
+ const { ccclass, property } = _decorator;
332
323
 
333
- // ==================== 3. 发送二进制数据(ArrayBuffer)====================
334
- // 适用场景:发送游戏状态快照、地图数据等需要高效传输的场景
335
- function sendBinaryData() {
336
- // 创建 ArrayBuffer(8 字节)
337
- const buffer = new ArrayBuffer(8);
338
- const view = new DataView(buffer);
339
-
340
- // 写入玩家 ID(4 字节整数)
341
- view.setInt32(0, 12345, true);
324
+ @view('Home') // 注册为 'Home'
325
+ @ccclass('HomeView')
326
+ export class HomeView extends BaseView {
327
+ @property(Label)
328
+ titleLabel: Label = null!;
342
329
 
343
- // 写入玩家位置(2 个 2 字节整数)
344
- view.setInt16(4, 100, true); // x 坐标
345
- view.setInt16(6, 200, true); // y 坐标
330
+ @property(Button)
331
+ startButton: Button = null!;
346
332
 
347
- // 发送二进制数据
348
- mf.socket.send(buffer);
349
- }
350
-
351
- // 接收二进制数据示例
352
- mf.socket.on('message', (event: MessageEvent) => {
353
- if (event.data instanceof ArrayBuffer) {
354
- const view = new DataView(event.data);
355
- const playerId = view.getInt32(0, true);
356
- const x = view.getInt16(4, true);
357
- const y = view.getInt16(6, true);
358
- console.log(`玩家 ${playerId} 移动到 (${x}, ${y})`);
333
+ onEnter(args?: any): void {
334
+ console.log('HomeView 打开', args);
335
+ this.startButton.node.on('click', this.onStartClick, this);
359
336
  }
360
- });
361
-
362
- // ==================== 4. 发送文件(Blob)====================
363
- // 适用场景:上传截图、录像回放、自定义地图等
364
- async function sendScreenshot() {
365
- // 方式 1:从 Canvas 获取 Blob
366
- const canvas = document.querySelector('canvas') as HTMLCanvasElement;
367
- canvas.toBlob((blob) => {
368
- if (blob) {
369
- mf.socket.send(blob);
370
- }
371
- }, 'image/png');
372
337
 
373
- // 方式 2:从文件选择器获取
374
- const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
375
- const file = fileInput.files?.[0];
376
- if (file) {
377
- mf.socket.send(file);
338
+ onExit(): void {
339
+ // 自动清理事件监听
378
340
  }
379
341
 
380
- // 方式 3:创建自定义 Blob
381
- const data = new Blob(['自定义数据内容'], { type: 'text/plain' });
382
- mf.socket.send(data);
383
- }
384
-
385
- // 接收 Blob 数据示例
386
- mf.socket.on('message', async (event: MessageEvent) => {
387
- if (event.data instanceof Blob) {
388
- // 读取 Blob 数据
389
- const text = await event.data.text();
390
- console.log('收到文件数据:', text);
391
-
392
- // 或者作为 ArrayBuffer 读取
393
- const buffer = await event.data.arrayBuffer();
394
- console.log('文件大小:', buffer.byteLength, '字节');
342
+ onPause(): void {
343
+ console.log('HomeView 暂停');
395
344
  }
396
- });
397
-
398
- // ==================== 5. 发送 TypedArray(Uint8Array 等)====================
399
- // 适用场景:发送图像数据、音频流等
400
- function sendImageData() {
401
- // 创建一个 256 字节的数据
402
- const imageData = new Uint8Array(256);
403
- for (let i = 0; i < imageData.length; i++) {
404
- imageData[i] = i;
345
+
346
+ onResume(): void {
347
+ console.log('HomeView 恢复');
405
348
  }
406
349
 
407
- // 发送 TypedArray(会自动转换为 ArrayBuffer)
408
- mf.socket.send(imageData.buffer);
350
+ private onStartClick(): void {
351
+ mf.gui.open(ViewNames.Game);
352
+ }
409
353
  }
410
- ```
411
354
 
355
+ // 使用 - 通过 Symbol 打开视图
356
+ await mf.gui.open(ViewNames.Home, { userId: 123 });
412
357
 
413
- ### 7.3 功能特性
358
+ // 关闭视图
359
+ mf.gui.close(ViewNames.Home); // 关闭但保留缓存
360
+ mf.gui.close(ViewNames.Home, true); // 关闭并销毁
361
+ ```
414
362
 
415
- 1. **自动重连**:连接断开后自动尝试重连,可配置重连次数和间隔
416
- 2. **心跳检测**:定期发送心跳消息保持连接
417
- 3. **消息队列**:连接断开时缓存消息,重连后自动发送
418
- 4. **事件管理**:统一的事件监听和触发机制
419
- 5. **连接状态管理**:实时获取连接状态
420
- 6. **自动序列化**:对象类型自动转换为 JSON 字符串
421
- 7. **多数据类型支持**:支持 string、object、ArrayBuffer、Blob 等
363
+ ### 4.4 装饰器参数
422
364
 
423
- ### 7.4 实战案例:多人对战游戏
365
+ 所有装饰器都支持可选的 `name` 参数:
424
366
 
425
367
  ```typescript
426
- // ==================== 案例 1:实时对战位置同步 ====================
427
- // 使用二进制数据传输,减少带宽占用
428
- class BattleNetworkManager {
429
- // 发送玩家位置(二进制,只需 12 字节)
430
- sendPlayerPosition(playerId: number, x: number, y: number, rotation: number) {
431
- const buffer = new ArrayBuffer(12);
432
- const view = new DataView(buffer);
433
-
434
- view.setInt32(0, playerId, true); // 玩家 ID(4 字节)
435
- view.setFloat32(4, x, true); // X 坐标(4 字节)
436
- view.setFloat32(8, y, true); // Y 坐标(4 字节)
437
-
438
- mf.socket.send(buffer);
439
- }
440
-
441
- // 接收其他玩家位置
442
- setupPositionReceiver() {
443
- mf.socket.on('message', (event: MessageEvent) => {
444
- if (event.data instanceof ArrayBuffer) {
445
- const view = new DataView(event.data);
446
- const playerId = view.getInt32(0, true);
447
- const x = view.getFloat32(4, true);
448
- const y = view.getFloat32(8, true);
449
-
450
- // 更新其他玩家位置
451
- this.updateOtherPlayerPosition(playerId, x, y);
452
- }
453
- });
454
- }
455
-
456
- private updateOtherPlayerPosition(playerId: number, x: number, y: number) {
457
- // 更新游戏中其他玩家的位置
458
- console.log(`玩家 ${playerId} 移动到 (${x}, ${y})`);
459
- }
460
- }
368
+ // 指定名称
369
+ @manager('Game')
370
+ @model('User')
371
+ @view('Home')
372
+
373
+ // 不指定名称时,自动使用类名
374
+ @manager() // 使用 'GameManager'
375
+ @model() // 使用 'UserModel'
376
+ @view() // 使用 'HomeView'
377
+ ```
461
378
 
462
- // ==================== 案例 2:截图分享功能 ====================
463
- // 使用 Blob 上传游戏截图
464
- class ScreenshotManager {
465
- async captureAndSend() {
466
- // 获取游戏 Canvas
467
- const canvas = document.querySelector('canvas') as HTMLCanvasElement;
468
-
469
- // 转换为 Blob
470
- canvas.toBlob((blob) => {
471
- if (blob) {
472
- // 发送截图到服务器
473
- mf.socket.send(blob);
474
- console.log(`发送截图,大小: ${blob.size} 字节`);
475
- }
476
- }, 'image/jpeg', 0.8); // JPEG 格式,80% 质量
477
- }
478
-
479
- // 接收其他玩家的截图
480
- setupScreenshotReceiver() {
481
- mf.socket.on('message', async (event: MessageEvent) => {
482
- if (event.data instanceof Blob) {
483
- // 创建图片 URL
484
- const imageUrl = URL.createObjectURL(event.data);
485
-
486
- // 显示图片
487
- const img = new Image();
488
- img.src = imageUrl;
489
- document.body.appendChild(img);
490
-
491
- console.log('收到截图');
492
- }
493
- });
494
- }
495
- }
379
+ ### 4.5 Names 对象代码补全
496
380
 
497
- // ==================== 案例 3:混合数据类型 ====================
498
- // 根据消息类型选择最优传输方式
499
- class SmartNetworkManager {
500
- send(messageType: string, data: any) {
501
- switch (messageType) {
502
- case 'chat':
503
- // 聊天消息:使用 JSON
504
- mf.socket.send({
505
- type: 'chat',
506
- message: data.message,
507
- playerId: data.playerId
508
- });
509
- break;
510
-
511
- case 'position':
512
- // 位置更新:使用二进制(高频更新)
513
- this.sendPositionBinary(data);
514
- break;
515
-
516
- case 'screenshot':
517
- // 截图:使用 Blob
518
- mf.socket.send(data.blob);
519
- break;
520
-
521
- case 'skill':
522
- // 技能释放:使用 JSON
523
- mf.socket.send({
524
- type: 'skill',
525
- skillId: data.skillId,
526
- targetId: data.targetId,
527
- timestamp: Date.now()
528
- });
529
- break;
530
- }
531
- }
532
-
533
- private sendPositionBinary(data: any) {
534
- const buffer = new ArrayBuffer(12);
535
- const view = new DataView(buffer);
536
- view.setInt32(0, data.playerId, true);
537
- view.setFloat32(4, data.x, true);
538
- view.setFloat32(8, data.y, true);
539
- mf.socket.send(buffer);
540
- }
541
- }
381
+ 装饰器注册后,对应的 Names 对象会自动添加属性,IDE 会提供代码补全:
382
+
383
+ ```typescript
384
+ // ManagerNames 自动包含所有注册的 Manager
385
+ ManagerNames.Game
386
+ ManagerNames.Player
387
+ ManagerNames.Audio
388
+
389
+ // ModelNames 自动包含所有注册的 Model
390
+ ModelNames.User
391
+ ModelNames.Inventory
392
+ ModelNames.Config
393
+
394
+ // ViewNames 自动包含所有注册的 View
395
+ ViewNames.Home
396
+ ViewNames.Game
397
+ ViewNames.Settings
542
398
  ```
543
399
 
544
- ### 7.5 Manager 集成示例
400
+ ---
401
+
402
+ ## 5. UI 系统
403
+
404
+ ### 5.1 BaseView 基础视图
405
+
406
+ 所有 UI 界面都应该继承 `BaseView` 类。
407
+
408
+ **核心特性:**
409
+ - ✅ 自动事件管理 - `this.event` 监听的事件会自动清理
410
+ - ✅ 自动资源管理 - `this.res` 加载的资源会自动释放
411
+ - ✅ 生命周期方法 - 完整的生命周期钩子
412
+ - ✅ 内置访问能力 - 可直接获取 Manager 和 Model
413
+
414
+ **基本用法:**
545
415
 
546
416
  ```typescript
547
- // 在Manager中使用
548
- @manager()
549
- export class GameNetworkManager extends AbstractManager {
550
- initialize() {
551
- // 配置 WebSocket
552
- mf.socket.configure({
553
- reconnect: true,
554
- reconnectInterval: 3000,
555
- reconnectAttempts: 10,
556
- heartbeat: true,
557
- heartbeatInterval: 30000
558
- });
559
-
560
- // 设置事件监听
561
- mf.socket.on('open', this.onConnected.bind(this));
562
- mf.socket.on('message', this.onMessage.bind(this));
563
- mf.socket.on('error', this.onError.bind(this));
564
- mf.socket.on('close', this.onClose.bind(this));
565
- }
566
-
567
- connect(token: string) {
568
- const wsUrl = `wss://game-server.example.com/ws?token=${token}`;
569
- mf.socket.connect(wsUrl);
570
- }
571
-
572
- private onConnected(event: Event) {
573
- console.log('连接成功');
574
- this.sendLogin();
575
- }
417
+ import { view, ViewNames, ManagerNames, ModelNames } from 'dzkcc-mflow/core';
418
+ import { BaseView } from 'dzkcc-mflow/libs';
419
+ import { _decorator, Sprite, Label } from 'cc';
420
+
421
+ const { ccclass, property } = _decorator;
422
+
423
+ @view('Game')
424
+ @ccclass('GameView')
425
+ export class GameView extends BaseView {
426
+ @property(Label)
427
+ scoreLabel: Label = null!;
576
428
 
577
- private onMessage(event: MessageEvent) {
578
- const data = JSON.parse(event.data);
579
- // 处理服务器消息
580
- this.handleServerMessage(data);
581
- }
429
+ @property(Sprite)
430
+ playerSprite: Sprite = null!;
582
431
 
583
- private onError(event: Event) {
584
- console.error('连接错误');
432
+ onEnter(args?: any): void {
433
+ // 监听事件(自动清理)
434
+ this.event.on('scoreChanged', this.onScoreChanged, this);
435
+
436
+ // 加载资源(自动释放)
437
+ this.res.loadSpriteFrame(this.playerSprite, 'textures/player');
438
+
439
+ // 获取 Manager
440
+ const gameManager = this.getManager(ManagerNames.Game);
441
+
442
+ // 获取 Model
443
+ const userModel = this.getModel(ModelNames.User);
585
444
  }
586
445
 
587
- private onClose(event: CloseEvent) {
588
- console.log('连接关闭');
446
+ onExit(): void {
447
+ // 事件监听会自动清理,无需手动 off
589
448
  }
590
449
 
591
- sendPlayerMove(x: number, y: number) {
592
- // 直接发送对象,自动序列化为 JSON
593
- mf.socket.send({
594
- type: 'player_move',
595
- position: { x, y },
596
- timestamp: Date.now()
597
- });
450
+ onPause(): void {
451
+ // 界面被其他界面覆盖时调用
598
452
  }
599
453
 
600
- private sendLogin() {
601
- // 直接发送对象,自动序列化为 JSON
602
- mf.socket.send({
603
- type: 'login',
604
- userId: this.getUserId()
605
- });
454
+ onResume(): void {
455
+ // 界面从暂停状态恢复时调用
606
456
  }
607
457
 
608
- private handleServerMessage(data: any) {
609
- // 使用事件系统分发消息
610
- mf.event.dispatch(`server_${data.type}`, data);
458
+ private onScoreChanged(score: number): void {
459
+ this.scoreLabel.string = `分数: ${score}`;
611
460
  }
612
461
  }
613
462
  ```
614
463
 
615
- ## 8. 开发工具
464
+ ### 5.2 UIManager 界面管理器
465
+
466
+ 通过 `mf.gui` 访问 UI 管理功能。
616
467
 
617
- 框架配套了Cocos Creator编辑器插件`mflow-tools`,可以:
468
+ **基本操作:**
618
469
 
619
- 1. 自动生成UI脚本
620
- 2. 自动引用Prefab上需要操作的元素
621
- 3. 自动挂载脚本组件
470
+ ```typescript
471
+ import { ViewNames } from 'dzkcc-mflow/core';
472
+
473
+ // 打开界面
474
+ const view = await mf.gui.open(ViewNames.Home);
622
475
 
623
- ### 8.1 使用方法
476
+ // 打开界面并传参
477
+ await mf.gui.open(ViewNames.Game, { level: 1, difficulty: 'hard' });
624
478
 
625
- 1. 在Prefab中,将需要引用的节点重命名为`#属性名#组件类型`格式,例如:
626
- - `#titleLabel#Label` 表示引用Label组件
627
- - `#closeButton#Button` 表示引用Button组件
628
- - `#contentNode` 表示引用Node节点
479
+ // 关闭界面(保留缓存)
480
+ mf.gui.close(ViewNames.Home);
629
481
 
630
- 2. 在Hierarchy面板中右键点击Prefab节点,选择"导出到脚本"
482
+ // 关闭并销毁界面(释放资源)
483
+ mf.gui.close(ViewNames.Home, true);
631
484
 
632
- 3. 插件会自动生成基础脚本和业务脚本,并自动设置引用关系
485
+ // 通过视图实例关闭
486
+ const view = await mf.gui.open(ViewNames.Settings);
487
+ mf.gui.close(view);
488
+ ```
633
489
 
634
- ## 9. 完整示例
490
+ ### 5.3 视图栈管理
635
491
 
636
- ### 9.1 创建Manager
492
+ 支持分组的视图栈,适用于关卡、向导等场景。
637
493
 
638
494
  ```typescript
639
- @manager()
640
- export class GameManager extends AbstractManager {
641
- private _score: number = 0;
642
-
643
- initialize(): void {
644
- console.log('GameManager initialized');
645
- }
646
-
647
- get score(): number {
648
- return this._score;
649
- }
650
-
651
- addScore(value: number): void {
652
- this._score += value;
653
- // 广播分数变化事件
654
- this.getEventManager().dispatch('scoreChanged', this._score);
655
- }
656
- }
495
+ import { ViewNames } from 'dzkcc-mflow/core';
496
+
497
+ // 打开视图并入栈
498
+ await mf.gui.openAndPush(ViewNames.Level1, 'game', { levelId: 1 });
499
+ await mf.gui.openAndPush(ViewNames.Level2, 'game', { levelId: 2 });
500
+
501
+ // 关闭栈顶视图并弹出(会自动恢复上一个视图)
502
+ mf.gui.closeAndPop('game'); // Level2 关闭,Level1 恢复
503
+
504
+ // 清空整个栈
505
+ mf.gui.clearStack('game'); // 所有关卡视图关闭
506
+
507
+ // 清空栈并销毁
508
+ mf.gui.clearStack('game', true);
509
+
510
+ // 获取栈顶视图
511
+ const topView = mf.gui.getTopView();
657
512
  ```
658
513
 
659
- ### 9.2 创建Model
514
+ ### 5.4 视图生命周期详解
660
515
 
661
516
  ```typescript
662
- @model()
663
- export class GameModel implements IModel {
664
- private _playerName: string = '';
517
+ @view('Example')
518
+ @ccclass('ExampleView')
519
+ export class ExampleView extends BaseView {
520
+ // 1. 界面打开时调用
521
+ onEnter(args?: any): void {
522
+ console.log('界面打开', args);
523
+ // 注册事件监听
524
+ // 初始化界面数据
525
+ }
665
526
 
666
- initialize(): void {
667
- console.log('GameModel initialized');
527
+ // 2. 界面被其他界面覆盖时调用(栈模式)
528
+ onPause(): void {
529
+ console.log('界面暂停');
530
+ // 暂停动画
531
+ // 暂停计时器
668
532
  }
669
533
 
670
- get playerName(): string {
671
- return this._playerName;
534
+ // 3. 界面从暂停状态恢复时调用(栈模式)
535
+ onResume(): void {
536
+ console.log('界面恢复');
537
+ // 恢复动画
538
+ // 恢复计时器
672
539
  }
673
540
 
674
- set playerName(name: string) {
675
- this._playerName = name;
541
+ // 4. 界面关闭时调用
542
+ onExit(): void {
543
+ console.log('界面关闭');
544
+ // 自动清理通过 this.event 注册的事件
545
+ // 可以在这里做额外的清理工作
546
+ }
547
+
548
+ // 5. 界面销毁时调用(框架自动调用)
549
+ protected onDestroy(): void {
550
+ console.log('界面销毁');
551
+ // 自动释放通过 this.res 加载的资源
552
+ // 可以在这里做额外的清理工作
676
553
  }
677
554
  }
678
555
  ```
679
556
 
680
- ### 9.3 创建UI界面
557
+ ### 5.5 Prefab 路径配置
681
558
 
682
- ```typescript
683
- // BaseHomeView.ts (由工具自动生成)
684
- import { _decorator, Component, Label, Button } from 'cc';
685
- import { BaseView } from "dzkcc-mflow/libs";
559
+ 视图需要配置 Prefab 路径,框架提供了开发工具自动生成。
686
560
 
687
- const { ccclass, property, disallowMultiple } = _decorator;
561
+ **手动配置方式:**
688
562
 
689
- @disallowMultiple()
690
- export abstract class BaseHomeView extends BaseView {
563
+ ```typescript
564
+ @view('Home')
565
+ @ccclass('HomeView')
566
+ export class HomeView extends BaseView {
691
567
  /** @internal */
692
- private static readonly __path__: string = "ui/home";
568
+ private static readonly __path__: string = 'ui/home'; // Prefab 路径
693
569
 
694
- @property({ type: Label }) titleLabel: Label = null!;
695
- @property({ type: Button }) startButton: Button = null!;
570
+ onEnter(): void {}
571
+ onPause(): void {}
572
+ onResume(): void {}
696
573
  }
574
+ ```
697
575
 
698
- // HomeView.ts (业务实现)
699
- import { BaseHomeView } from './BaseHomeView';
700
- import { _decorator } from 'cc';
576
+ **推荐:使用开发工具自动生成**(见第 10 章)
701
577
 
702
- const { ccclass, property } = _decorator;
578
+ ---
703
579
 
704
- @ccclass('HomeView')
705
- export class HomeView extends BaseHomeView {
706
- onEnter(args?: any): void {
707
- // 监听按钮点击
708
- this.startButton.node.on(Button.EventType.CLICK, this.onStartClick, this);
709
-
710
- // 监听分数变化
711
- this.event.on('scoreChanged', this.onScoreChanged, this);
580
+ ## 6. 事件系统
581
+
582
+ 框架提供了强大的事件广播和监听机制,基于 `Broadcaster` 实现。
583
+
584
+ ### 6.1 基本用法
585
+
586
+ ```typescript
587
+ // 监听事件
588
+ mf.event.on('gameStart', (data) => {
589
+ console.log('游戏开始', data);
590
+ });
591
+
592
+ // 派发事件
593
+ mf.event.dispatch('gameStart', { level: 1 });
594
+
595
+ // 一次性监听
596
+ mf.event.once('gameOver', (score) => {
597
+ console.log('游戏结束,分数:', score);
598
+ });
599
+
600
+ // 移除监听
601
+ const handler = (data) => console.log(data);
602
+ mf.event.on('test', handler);
603
+ mf.event.off('test', handler);
604
+
605
+ // 移除所有监听
606
+ mf.event.offAll('test');
607
+ ```
608
+
609
+ ### 6.2 粘性事件
610
+
611
+ 粘性事件会保存最后一次派发的数据,新的监听者会立即收到。
612
+
613
+ ```typescript
614
+ // 派发粘性事件
615
+ mf.event.dispatchSticky('userLogin', { userId: 123, name: 'Alice' });
616
+
617
+ // 即使在派发之后才监听,也能立即收到数据
618
+ setTimeout(() => {
619
+ mf.event.on('userLogin', (userData) => {
620
+ console.log('用户登录信息:', userData); // 立即触发
621
+ });
622
+ }, 1000);
623
+
624
+ // 移除粘性事件
625
+ mf.event.removeStickyBroadcast('userLogin');
626
+ ```
627
+
628
+ ### 6.3 在 View 中使用事件
629
+
630
+ `BaseView` 提供了自动清理的事件监听:
631
+
632
+ ```typescript
633
+ @view('Game')
634
+ @ccclass('GameView')
635
+ export class GameView extends BaseView {
636
+ onEnter(): void {
637
+ // 使用 this.event 监听,会在 onExit 时自动清理
638
+ this.event.on('scoreChanged', this.updateScore, this);
639
+ this.event.on('levelUp', this.onLevelUp, this);
712
640
  }
713
641
 
714
642
  onExit(): void {
715
- // BaseView会自动清理事件监听
643
+ // 自动清理所有通过 this.event 监听的事件
644
+ // 无需手动 off
716
645
  }
717
646
 
718
- onPause(): void {
719
- // 界面暂停时的处理
647
+ private updateScore(score: number): void {
648
+ console.log('分数更新:', score);
720
649
  }
721
650
 
722
- onResume(): void {
723
- // 界面恢复时的处理
651
+ private onLevelUp(level: number): void {
652
+ console.log('等级提升:', level);
724
653
  }
654
+ }
655
+ ```
656
+
657
+ ### 6.4 在 Manager 中使用事件
658
+
659
+ ```typescript
660
+ @manager('Game')
661
+ export class GameManager extends AbstractManager {
662
+ private score: number = 0;
725
663
 
726
- private onStartClick(): void {
727
- // 获取GameManager并调用方法
728
- const gameManager = this.getManager(GameManager);
729
- gameManager.addScore(10);
664
+ initialize(): void {
665
+ // 在 Manager 中获取事件管理器
666
+ const eventMgr = this.getEventManager();
667
+
668
+ eventMgr.on('enemyKilled', this.onEnemyKilled, this);
730
669
  }
731
670
 
732
- private onScoreChanged(score: number): void {
733
- this.titleLabel.string = `分数: ${score}`;
671
+ addScore(value: number): void {
672
+ this.score += value;
673
+ // 派发事件
674
+ this.getEventManager().dispatch('scoreChanged', this.score);
675
+ }
676
+
677
+ private onEnemyKilled(enemyData: any): void {
678
+ this.addScore(enemyData.reward);
679
+ }
680
+
681
+ dispose(): void {
682
+ // Manager 销毁时清理事件监听
683
+ this.getEventManager().offAll(undefined, this);
684
+ }
685
+ }
686
+ ```
687
+
688
+ ### 6.5 带回调的事件
689
+
690
+ 事件支持回调机制,用于双向通信:
691
+
692
+ ```typescript
693
+ // 监听事件并提供回调
694
+ mf.event.on('requestData', (params, callback) => {
695
+ const result = fetchData(params);
696
+ callback?.(result); // 回调返回结果
697
+ });
698
+
699
+ // 派发事件并接收回调
700
+ mf.event.dispatch('requestData', { id: 123 }, (result) => {
701
+ console.log('收到结果:', result);
702
+ });
703
+ ```
704
+
705
+ ### 6.6 类型安全的事件(可选)
706
+
707
+ 可以扩展 `IEventMsgKey` 接口实现类型安全:
708
+
709
+ ```typescript
710
+ // 定义事件消息键类型
711
+ declare module 'dzkcc-mflow/core' {
712
+ interface IEventMsgKey {
713
+ 'gameStart': { level: number };
714
+ 'scoreChanged': number;
715
+ 'userLogin': { userId: number; name: string };
716
+ }
717
+ }
718
+
719
+ // 现在事件会有类型提示
720
+ mf.event.dispatch('scoreChanged', 100); // ✅ 正确
721
+ mf.event.dispatch('scoreChanged', 'abc'); // ❌ 类型错误
722
+ ```
723
+
724
+ ---
725
+
726
+ ## 7. 资源管理
727
+
728
+ 框架提供了统一的资源加载和释放管理,通过 `mf.res` 访问。
729
+
730
+ ### 7.1 基本用法
731
+
732
+ ```typescript
733
+ import { Prefab, SpriteFrame } from 'cc';
734
+
735
+ // 加载 Prefab
736
+ const prefab = await mf.res.loadPrefab('prefabs/enemy');
737
+ const node = instantiate(prefab);
738
+
739
+ // 加载 SpriteFrame(自动设置到 Sprite 组件)
740
+ const sprite = this.node.getComponent(Sprite)!;
741
+ await mf.res.loadSpriteFrame(sprite, 'textures/player');
742
+
743
+ // 加载 Spine 动画(自动设置到 Skeleton 组件)
744
+ const skeleton = this.node.getComponent(sp.Skeleton)!;
745
+ await mf.res.loadSpine(skeleton, 'spine/hero');
746
+
747
+ // 加载通用资源
748
+ const asset = await mf.res.loadAsset('path/to/asset', AssetType);
749
+ ```
750
+
751
+ ### 7.2 释放资源
752
+
753
+ ```typescript
754
+ // 通过路径释放
755
+ mf.res.release('prefabs/enemy', Prefab);
756
+
757
+ // 通过资源对象释放
758
+ mf.res.release(asset);
759
+
760
+ // 强制释放(立即销毁,不管引用计数)
761
+ mf.res.release(asset, true);
762
+ ```
763
+
764
+ ### 7.3 在 View 中自动管理资源
765
+
766
+ `BaseView` 提供了自动资源管理:
767
+
768
+ ```typescript
769
+ @view('Game')
770
+ @ccclass('GameView')
771
+ export class GameView extends BaseView {
772
+ @property(Sprite)
773
+ avatarSprite: Sprite = null!;
774
+
775
+ onEnter(): void {
776
+ // 使用 this.res 加载,会在界面销毁时自动释放
777
+ this.res.loadSpriteFrame(this.avatarSprite, 'textures/avatar');
778
+
779
+ // 加载多个资源
780
+ this.res.loadPrefab('prefabs/item1');
781
+ this.res.loadPrefab('prefabs/item2');
782
+ }
783
+
784
+ // 界面销毁时,所有通过 this.res 加载的资源会自动释放
785
+ }
786
+ ```
787
+
788
+ ### 7.4 Bundle 资源包
789
+
790
+ 支持从不同的 Bundle 加载资源:
791
+
792
+ ```typescript
793
+ // 从 resources Bundle 加载(默认)
794
+ await mf.res.loadPrefab('prefabs/ui');
795
+
796
+ // 从自定义 Bundle 加载
797
+ await mf.res.loadPrefab('prefabs/level1', 'game-bundle');
798
+
799
+ // 加载 SpriteFrame 从自定义 Bundle
800
+ await mf.res.loadSpriteFrame(sprite, 'textures/bg', 'ui-bundle');
801
+ ```
802
+
803
+ ### 7.5 资源引用计数
804
+
805
+ 框架使用 Cocos Creator 的引用计数系统:
806
+
807
+ - `loadAsset()` 会自动 `addRef()`
808
+ - `release()` 会自动 `decRef()`
809
+ - 引用计数为 0 时自动销毁资源
810
+
811
+ ```typescript
812
+ // 多次加载同一资源,共享同一实例,引用计数累加
813
+ const asset1 = await mf.res.loadPrefab('prefabs/common'); // refCount = 1
814
+ const asset2 = await mf.res.loadPrefab('prefabs/common'); // refCount = 2
815
+
816
+ // 释放资源,引用计数递减
817
+ mf.res.release(asset1); // refCount = 1
818
+ mf.res.release(asset2); // refCount = 0,资源被销毁
819
+ ```
820
+
821
+ ## 8. 网络通信
822
+
823
+ ### 8.1 HTTP 请求
824
+
825
+ 框架提供了简洁易用的 HTTP 客户端,通过 `mf.http` 访问。
826
+
827
+ **基本用法:**
828
+
829
+ ```typescript
830
+ // GET 请求
831
+ const userData = await mf.http.get('/api/users/123');
832
+
833
+ // GET 请求带参数
834
+ const list = await mf.http.get('/api/users', { page: 1, size: 20 });
835
+
836
+ // POST 请求
837
+ const newUser = await mf.http.post('/api/users', {
838
+ name: 'Alice',
839
+ email: 'alice@example.com'
840
+ });
841
+
842
+ // PUT 请求
843
+ const updated = await mf.http.put('/api/users/123', {
844
+ name: 'Alice Updated'
845
+ });
846
+
847
+ // DELETE 请求
848
+ await mf.http.delete('/api/users/123');
849
+
850
+ // 自定义请求
851
+ const result = await mf.http.request({
852
+ url: '/api/upload',
853
+ method: 'POST',
854
+ data: formData,
855
+ headers: {
856
+ 'Authorization': 'Bearer token123'
857
+ },
858
+ timeout: 30000
859
+ });
860
+ ```
861
+
862
+ **在 Manager 中使用:**
863
+
864
+ ```typescript
865
+ @manager('User')
866
+ export class UserManager extends AbstractManager {
867
+ initialize(): void {}
868
+
869
+ async login(username: string, password: string): Promise<any> {
870
+ try {
871
+ // 通过 getHttpManager() 获取 HTTP 管理器
872
+ const result = await this.getHttpManager().post('/api/auth/login', {
873
+ username,
874
+ password
875
+ });
876
+
877
+ // 登录成功,派发事件
878
+ this.getEventManager().dispatch('userLogin', result);
879
+ return result;
880
+ } catch (error) {
881
+ console.error('登录失败:', error);
882
+ throw error;
883
+ }
884
+ }
885
+
886
+ async getUserProfile(userId: number): Promise<any> {
887
+ const token = this.getAuthToken();
888
+ return await this.getHttpManager().get(`/api/users/${userId}`, {}, {
889
+ 'Authorization': `Bearer ${token}`
890
+ });
891
+ }
892
+
893
+ private getAuthToken(): string {
894
+ // 从本地存储获取 token
895
+ return localStorage.getItem('token') || '';
896
+ }
897
+ }
898
+ ```
899
+
900
+ ### 8.2 WebSocket 实时通信
901
+
902
+ 框架提供了功能完整的 WebSocket 客户端,支持自动重连、心跳检测等特性。
903
+
904
+ **基本用法:**
905
+
906
+ ```typescript
907
+ // 连接服务器
908
+ mf.socket.connect('wss://game-server.com/ws');
909
+
910
+ // 配置连接参数
911
+ mf.socket.configure({
912
+ reconnect: true, // 启用自动重连
913
+ reconnectInterval: 3000, // 重连间隔 3 秒
914
+ reconnectAttempts: 5, // 最多重连 5 次
915
+ heartbeat: true, // 启用心跳
916
+ heartbeatInterval: 30000, // 心跳间隔 30 秒
917
+ heartbeatMessage: 'ping' // 心跳消息
918
+ });
919
+
920
+ // 监听事件
921
+ mf.socket.on('open', (event) => {
922
+ console.log('WebSocket 连接成功');
923
+ });
924
+
925
+ mf.socket.on('message', (event) => {
926
+ const data = JSON.parse(event.data);
927
+ console.log('收到消息:', data);
928
+ });
929
+
930
+ mf.socket.on('error', (event) => {
931
+ console.error('WebSocket 错误:', event);
932
+ });
933
+
934
+ mf.socket.on('close', (event) => {
935
+ console.log('WebSocket 连接关闭');
936
+ });
937
+
938
+ // 发送消息
939
+ mf.socket.send({ type: 'move', x: 100, y: 200 });
940
+
941
+ // 检查连接状态
942
+ if (mf.socket.isConnected()) {
943
+ console.log('已连接');
944
+ }
945
+
946
+ // 断开连接
947
+ mf.socket.disconnect();
948
+ ```
949
+
950
+ **支持的数据类型:**
951
+
952
+ ```typescript
953
+ // 1. JSON 对象(推荐)
954
+ mf.socket.send({ type: 'chat', message: 'Hello' });
955
+
956
+ // 2. 字符串
957
+ mf.socket.send('ping');
958
+
959
+ // 3. 二进制数据(ArrayBuffer)
960
+ const buffer = new ArrayBuffer(8);
961
+ const view = new DataView(buffer);
962
+ view.setInt32(0, 12345);
963
+ mf.socket.send(buffer);
964
+
965
+ // 4. Blob(文件数据)
966
+ const blob = new Blob(['data'], { type: 'text/plain' });
967
+ mf.socket.send(blob);
968
+ ```
969
+
970
+ **在 Manager 中使用:**
971
+
972
+ ```typescript
973
+ @manager('Network')
974
+ export class NetworkManager extends AbstractManager {
975
+ initialize(): void {
976
+ // 通过 getWebSocketManager() 获取 WebSocket 管理器
977
+ const socket = this.getWebSocketManager();
978
+
979
+ // 配置 WebSocket
980
+ socket.configure({
981
+ reconnect: true,
982
+ reconnectInterval: 3000,
983
+ reconnectAttempts: 10,
984
+ heartbeat: true,
985
+ heartbeatInterval: 30000
986
+ });
987
+
988
+ // 监听事件
989
+ socket.on('open', this.onConnected.bind(this));
990
+ socket.on('message', this.onMessage.bind(this));
991
+ socket.on('error', this.onError.bind(this));
992
+ socket.on('close', this.onClose.bind(this));
993
+ }
994
+
995
+ connect(token: string): void {
996
+ const wsUrl = `wss://game-server.com/ws?token=${token}`;
997
+ this.getWebSocketManager().connect(wsUrl);
998
+ }
999
+
1000
+ sendGameAction(action: string, data: any): void {
1001
+ this.getWebSocketManager().send({
1002
+ type: action,
1003
+ data,
1004
+ timestamp: Date.now()
1005
+ });
1006
+ }
1007
+
1008
+ private onConnected(event: Event): void {
1009
+ console.log('WebSocket 连接成功');
1010
+ this.getEventManager().dispatch('socketConnected');
1011
+ }
1012
+
1013
+ private onMessage(event: MessageEvent): void {
1014
+ try {
1015
+ const data = JSON.parse(event.data);
1016
+ // 通过事件系统分发消息
1017
+ this.getEventManager().dispatch(`socket_${data.type}`, data);
1018
+ } catch (error) {
1019
+ console.error('解析消息失败:', error);
1020
+ }
1021
+ }
1022
+
1023
+ private onError(event: Event): void {
1024
+ console.error('WebSocket 错误');
1025
+ }
1026
+
1027
+ private onClose(event: CloseEvent): void {
1028
+ console.log('WebSocket 连接关闭');
1029
+ this.getEventManager().dispatch('socketClosed');
1030
+ }
1031
+
1032
+ dispose(): void {
1033
+ this.getWebSocketManager().disconnect();
1034
+ }
1035
+ }
1036
+ ```
1037
+
1038
+ ## 9. 红点系统
1039
+
1040
+ 框架提供了树形结构的红点提示管理系统,通过 `mf.reddot` 访问。
1041
+
1042
+ ### 9.1 基本用法
1043
+
1044
+ ```typescript
1045
+ // 设置红点数量
1046
+ mf.reddot.setCount('main/bag/weapon', 5);
1047
+ mf.reddot.setCount('main/bag/armor', 3);
1048
+ mf.reddot.setCount('main/mail', 10);
1049
+
1050
+ // 获取红点数量(包含子节点)
1051
+ const weaponCount = mf.reddot.getCount('main/bag/weapon'); // 5
1052
+ const bagCount = mf.reddot.getCount('main/bag'); // 8 (weapon + armor)
1053
+ const mainCount = mf.reddot.getCount('main'); // 18 (bag + mail)
1054
+
1055
+ // 增加/减少红点数量
1056
+ mf.reddot.addCount('main/bag/weapon', 2); // 增加 2
1057
+ mf.reddot.addCount('main/bag/weapon', -1); // 减少 1
1058
+
1059
+ // 检查是否有红点
1060
+ if (mf.reddot.hasRedDot('main/bag')) {
1061
+ console.log('背包有新物品');
1062
+ }
1063
+
1064
+ // 清空红点
1065
+ mf.reddot.clearRedDot('main/mail');
1066
+ ```
1067
+
1068
+ ### 9.2 监听红点变化
1069
+
1070
+ ```typescript
1071
+ // 监听红点变化
1072
+ mf.reddot.on('main/bag', (totalCount, selfCount) => {
1073
+ console.log(`背包红点: ${totalCount} (自身: ${selfCount})`);
1074
+ // 更新 UI 显示
1075
+ });
1076
+
1077
+ // 移除监听
1078
+ const handler = (total, self) => console.log(total, self);
1079
+ mf.reddot.on('main/bag', handler);
1080
+ mf.reddot.off('main/bag', handler);
1081
+ ```
1082
+
1083
+ ### 9.3 在 View 中使用
1084
+
1085
+ ```typescript
1086
+ import { view, ViewNames } from 'dzkcc-mflow/core';
1087
+ import { BaseView } from 'dzkcc-mflow/libs';
1088
+ import { _decorator, Label } from 'cc';
1089
+
1090
+ const { ccclass, property } = _decorator;
1091
+
1092
+ @view('Main')
1093
+ @ccclass('MainView')
1094
+ export class MainView extends BaseView {
1095
+ @property(Label)
1096
+ bagRedDot: Label = null!;
1097
+
1098
+ @property(Label)
1099
+ mailRedDot: Label = null!;
1100
+
1101
+ onEnter(): void {
1102
+ // 监听红点变化
1103
+ mf.reddot.on('main/bag', this.updateBagRedDot.bind(this));
1104
+ mf.reddot.on('main/mail', this.updateMailRedDot.bind(this));
1105
+ }
1106
+
1107
+ onExit(): void {
1108
+ // 移除监听
1109
+ mf.reddot.off('main/bag', this.updateBagRedDot.bind(this));
1110
+ mf.reddot.off('main/mail', this.updateMailRedDot.bind(this));
1111
+ }
1112
+
1113
+ private updateBagRedDot(totalCount: number): void {
1114
+ this.bagRedDot.string = totalCount > 0 ? totalCount.toString() : '';
1115
+ this.bagRedDot.node.active = totalCount > 0;
1116
+ }
1117
+
1118
+ private updateMailRedDot(totalCount: number): void {
1119
+ this.mailRedDot.string = totalCount > 0 ? totalCount.toString() : '';
1120
+ this.mailRedDot.node.active = totalCount > 0;
1121
+ }
1122
+
1123
+ onPause(): void {}
1124
+ onResume(): void {}
1125
+ }
1126
+ ```
1127
+
1128
+ ### 9.4 红点路径规则
1129
+
1130
+ 红点系统使用树形结构,路径使用 `/` 分隔:
1131
+
1132
+ ```
1133
+ main
1134
+ ├── bag
1135
+ │ ├── weapon
1136
+ │ ├── armor
1137
+ │ └── consumable
1138
+ ├── mail
1139
+ │ ├── system
1140
+ │ └── friend
1141
+ └── quest
1142
+ ├── main
1143
+ └── daily
1144
+ ```
1145
+
1146
+ **特性:**
1147
+ - 子节点的红点会自动累加到父节点
1148
+ - 支持任意深度的树形结构
1149
+ - 路径大小写敏感
1150
+
1151
+ ---
1152
+
1153
+ ## 10. 开发工具
1154
+
1155
+ 框架配套了 Cocos Creator 编辑器插件 `mflow-tools`,用于提升开发效率。
1156
+
1157
+ ### 10.1 功能特性
1158
+
1159
+ ✨ **自动生成 UI 脚本** - 根据 Prefab 自动生成基础视图类
1160
+ ✨ **自动引用组件** - 自动设置 `@property` 引用
1161
+ ✨ **自动挂载脚本** - 自动将脚本挂载到 Prefab
1162
+ ✨ **命名约定识别** - 通过节点命名自动识别组件类型
1163
+
1164
+ ### 10.2 命名约定
1165
+
1166
+ 在 Prefab 中,将需要引用的节点重命名为 `#属性名#组件类型` 格式:
1167
+
1168
+ ```
1169
+ #titleLabel#Label -> 引用 Label 组件
1170
+ #closeButton#Button -> 引用 Button 组件
1171
+ #avatarSprite#Sprite -> 引用 Sprite 组件
1172
+ #contentNode -> 引用 Node 节点(省略组件类型)
1173
+ #listView#ScrollView -> 引用 ScrollView 组件
1174
+ ```
1175
+
1176
+ ### 10.3 使用方法
1177
+
1178
+ 1. **设置节点命名**
1179
+
1180
+ 在 Cocos Creator 编辑器中创建 Prefab,将需要引用的节点按照命名约定重命名:
1181
+
1182
+ ![节点命名示例]
1183
+ ```
1184
+ HomeView (Prefab 根节点)
1185
+ ├── #titleLabel#Label
1186
+ ├── #contentNode
1187
+ │ ├── #avatarSprite#Sprite
1188
+ │ └── #nameLabel#Label
1189
+ └── #closeButton#Button
1190
+ ```
1191
+
1192
+ 2. **导出脚本**
1193
+
1194
+ 在 Hierarchy 面板中右键点击 Prefab 根节点,选择 **"MFlow Tools → 导出到脚本"**
1195
+
1196
+ 3. **自动生成**
1197
+
1198
+ 插件会自动生成两个文件:
1199
+
1200
+ **BaseHomeView.ts**(基础类,由工具生成,不要手动修改)
1201
+ ```typescript
1202
+ import { _decorator, Label, Node, Sprite, Button } from 'cc';
1203
+ import { BaseView } from 'dzkcc-mflow/libs';
1204
+
1205
+ const { ccclass, property } = _decorator;
1206
+
1207
+ @ccclass('BaseHomeView')
1208
+ export abstract class BaseHomeView extends BaseView {
1209
+ /** @internal */
1210
+ private static readonly __path__: string = 'ui/home';
1211
+
1212
+ @property(Label) titleLabel: Label = null!;
1213
+ @property(Node) contentNode: Node = null!;
1214
+ @property(Sprite) avatarSprite: Sprite = null!;
1215
+ @property(Label) nameLabel: Label = null!;
1216
+ @property(Button) closeButton: Button = null!;
1217
+
1218
+ // 抽象方法由子类实现
1219
+ abstract onEnter(args?: any): void;
1220
+ abstract onExit(): void;
1221
+ abstract onPause(): void;
1222
+ abstract onResume(): void;
1223
+ }
1224
+ ```
1225
+
1226
+ **HomeView.ts**(业务类,手动实现业务逻辑)
1227
+ ```typescript
1228
+ import { _decorator } from 'cc';
1229
+ import { BaseHomeView } from './BaseHomeView';
1230
+ import { view } from 'dzkcc-mflow/core';
1231
+
1232
+ const { ccclass } = _decorator;
1233
+
1234
+ @view('Home')
1235
+ @ccclass('HomeView')
1236
+ export class HomeView extends BaseHomeView {
1237
+ onEnter(args?: any): void {
1238
+ // 实现业务逻辑
1239
+ }
1240
+
1241
+ onExit(): void {}
1242
+ onPause(): void {}
1243
+ onResume(): void {}
1244
+ }
1245
+ ```
1246
+
1247
+ 4. **脚本自动挂载**
1248
+
1249
+ 插件会自动将生成的脚本挂载到 Prefab 上,并设置好所有组件引用。
1250
+
1251
+ ---
1252
+
1253
+ ## 11. 完整示例
1254
+
1255
+ 下面是一个简单的塔防游戏示例,展示框架的完整使用流程。
1256
+
1257
+ ### 11.1 项目结构
1258
+
1259
+ ```
1260
+ assets/
1261
+ ├── scripts/
1262
+ │ ├── GameCore.ts # 游戏入口
1263
+ │ ├── managers/
1264
+ │ │ ├── GameManager.ts # 游戏管理器
1265
+ │ │ ├── EnemyManager.ts # 敌人管理器
1266
+ │ │ └── TowerManager.ts # 塔管理器
1267
+ │ ├── models/
1268
+ │ │ ├── GameModel.ts # 游戏数据模型
1269
+ │ │ └── PlayerModel.ts # 玩家数据模型
1270
+ │ └── views/
1271
+ │ ├── HomeView.ts # 主界面
1272
+ │ ├── GameView.ts # 游戏界面
1273
+ │ └── ResultView.ts # 结算界面
1274
+ └── resources/
1275
+ └── prefabs/
1276
+ ├── ui/
1277
+ │ ├── home.prefab
1278
+ │ ├── game.prefab
1279
+ │ └── result.prefab
1280
+ └── entities/
1281
+ ├── tower.prefab
1282
+ └── enemy.prefab
1283
+ ```
1284
+
1285
+ ### 11.2 GameCore.ts - 游戏入口
1286
+
1287
+ ```typescript
1288
+ import { CocosCore } from 'dzkcc-mflow/libs';
1289
+ import { _decorator } from 'cc';
1290
+
1291
+ // 导入所有模块(使用装饰器后会自动注册)
1292
+ import './managers/GameManager';
1293
+ import './managers/EnemyManager';
1294
+ import './managers/TowerManager';
1295
+ import './models/GameModel';
1296
+ import './models/PlayerModel';
1297
+ import './views/HomeView';
1298
+ import './views/GameView';
1299
+ import './views/ResultView';
1300
+
1301
+ const { ccclass } = _decorator;
1302
+
1303
+ @ccclass('GameCore')
1304
+ export class GameCore extends CocosCore {
1305
+ protected onLoad(): void {
1306
+ super.onLoad();
1307
+
1308
+ // 框架初始化完成后,打开主界面
1309
+ this.scheduleOnce(() => {
1310
+ mf.gui.open(ViewNames.Home);
1311
+ }, 0);
1312
+ }
1313
+ }
1314
+ ```
1315
+
1316
+ ### 11.3 GameModel.ts - 游戏数据模型
1317
+
1318
+ ```typescript
1319
+ import { model, IModel } from 'dzkcc-mflow/core';
1320
+
1321
+ @model('Game')
1322
+ export class GameModel implements IModel {
1323
+ private _level: number = 1;
1324
+ private _score: number = 0;
1325
+ private _gold: number = 500;
1326
+ private _life: number = 10;
1327
+
1328
+ initialize(): void {
1329
+ console.log('GameModel 初始化');
1330
+ }
1331
+
1332
+ get level(): number {
1333
+ return this._level;
1334
+ }
1335
+
1336
+ set level(value: number) {
1337
+ this._level = value;
1338
+ }
1339
+
1340
+ get score(): number {
1341
+ return this._score;
1342
+ }
1343
+
1344
+ addScore(value: number): void {
1345
+ this._score += value;
1346
+ }
1347
+
1348
+ get gold(): number {
1349
+ return this._gold;
1350
+ }
1351
+
1352
+ addGold(value: number): void {
1353
+ this._gold += value;
1354
+ }
1355
+
1356
+ get life(): number {
1357
+ return this._life;
1358
+ }
1359
+
1360
+ loseLife(value: number = 1): void {
1361
+ this._life = Math.max(0, this._life - value);
1362
+ }
1363
+
1364
+ reset(): void {
1365
+ this._level = 1;
1366
+ this._score = 0;
1367
+ this._gold = 500;
1368
+ this._life = 10;
1369
+ }
1370
+ }
1371
+ ```
1372
+
1373
+ ### 11.4 PlayerModel.ts - 玩家数据模型
1374
+
1375
+ ```typescript
1376
+ import { model, IModel } from 'dzkcc-mflow/core';
1377
+
1378
+ @model('Player')
1379
+ export class PlayerModel implements IModel {
1380
+ private _name: string = '';
1381
+ private _highScore: number = 0;
1382
+
1383
+ initialize(): void {
1384
+ console.log('PlayerModel 初始化');
1385
+ this.loadFromStorage();
1386
+ }
1387
+
1388
+ get name(): string {
1389
+ return this._name;
1390
+ }
1391
+
1392
+ set name(value: string) {
1393
+ this._name = value;
1394
+ this.saveToStorage();
1395
+ }
1396
+
1397
+ get highScore(): number {
1398
+ return this._highScore;
1399
+ }
1400
+
1401
+ updateHighScore(score: number): void {
1402
+ if (score > this._highScore) {
1403
+ this._highScore = score;
1404
+ this.saveToStorage();
1405
+ }
1406
+ }
1407
+
1408
+ private loadFromStorage(): void {
1409
+ const data = localStorage.getItem('playerData');
1410
+ if (data) {
1411
+ const parsed = JSON.parse(data);
1412
+ this._name = parsed.name || '';
1413
+ this._highScore = parsed.highScore || 0;
1414
+ }
1415
+ }
1416
+
1417
+ private saveToStorage(): void {
1418
+ localStorage.setItem('playerData', JSON.stringify({
1419
+ name: this._name,
1420
+ highScore: this._highScore
1421
+ }));
734
1422
  }
735
1423
  }
736
1424
  ```
737
1425
 
738
- ### 9.4 在场景中使用
1426
+ ### 11.5 GameManager.ts - 游戏管理器
739
1427
 
740
1428
  ```typescript
741
- // 在游戏启动时
742
- export class GameApp extends Component {
743
- start(): void {
744
- // 打开主界面
745
- mf.gui.open(HomeView);
1429
+ import { manager, AbstractManager, ManagerNames, ModelNames } from 'dzkcc-mflow/core';
1430
+ import { GameModel } from '../models/GameModel';
1431
+ import { PlayerModel } from '../models/PlayerModel';
1432
+
1433
+ @manager('Game')
1434
+ export class GameManager extends AbstractManager {
1435
+ private gameModel: GameModel = null!;
1436
+ private playerModel: PlayerModel = null!;
1437
+
1438
+ initialize(): void {
1439
+ console.log('GameManager 初始化');
1440
+
1441
+ // 获取 Model
1442
+ this.gameModel = this.getModel<GameModel>(ModelNames.Game);
1443
+ this.playerModel = this.getModel<PlayerModel>(ModelNames.Player);
1444
+ }
1445
+
1446
+ startGame(level: number): void {
1447
+ // 重置游戏数据
1448
+ this.gameModel.reset();
1449
+ this.gameModel.level = level;
1450
+
1451
+ // 派发游戏开始事件
1452
+ this.getEventManager().dispatch('gameStart', { level });
1453
+ }
1454
+
1455
+ killEnemy(enemyType: string): void {
1456
+ // 增加分数和金币
1457
+ const reward = this.getEnemyReward(enemyType);
1458
+ this.gameModel.addScore(reward.score);
1459
+ this.gameModel.addGold(reward.gold);
1460
+
1461
+ // 派发事件
1462
+ this.getEventManager().dispatch('enemyKilled', {
1463
+ enemyType,
1464
+ score: this.gameModel.score,
1465
+ gold: this.gameModel.gold
1466
+ });
1467
+ }
1468
+
1469
+ enemyEscape(): void {
1470
+ // 减少生命
1471
+ this.gameModel.loseLife(1);
1472
+
1473
+ // 派发事件
1474
+ this.getEventManager().dispatch('lifeChanged', this.gameModel.life);
1475
+
1476
+ // 检查游戏是否结束
1477
+ if (this.gameModel.life <= 0) {
1478
+ this.gameOver();
1479
+ }
1480
+ }
1481
+
1482
+ private gameOver(): void {
1483
+ // 更新最高分
1484
+ this.playerModel.updateHighScore(this.gameModel.score);
1485
+
1486
+ // 派发游戏结束事件
1487
+ this.getEventManager().dispatch('gameOver', {
1488
+ score: this.gameModel.score,
1489
+ highScore: this.playerModel.highScore
1490
+ });
1491
+ }
1492
+
1493
+ private getEnemyReward(enemyType: string): { score: number; gold: number } {
1494
+ // 根据敌人类型返回奖励
1495
+ const rewards: Record<string, { score: number; gold: number }> = {
1496
+ 'small': { score: 10, gold: 5 },
1497
+ 'medium': { score: 20, gold: 10 },
1498
+ 'large': { score: 50, gold: 25 }
1499
+ };
1500
+ return rewards[enemyType] || rewards['small'];
746
1501
  }
747
1502
  }
748
1503
  ```
749
1504
 
750
- ## 10. 最佳实践
1505
+ ### 11.6 HomeView.ts - 主界面
1506
+
1507
+ ```typescript
1508
+ import { view, ViewNames, ModelNames } from 'dzkcc-mflow/core';
1509
+ import { BaseView } from 'dzkcc-mflow/libs';
1510
+ import { _decorator, Button, Label } from 'cc';
1511
+ import { PlayerModel } from '../models/PlayerModel';
1512
+
1513
+ const { ccclass, property } = _decorator;
1514
+
1515
+ @view('Home')
1516
+ @ccclass('HomeView')
1517
+ export class HomeView extends BaseView {
1518
+ @property(Label)
1519
+ welcomeLabel: Label = null!;
1520
+
1521
+ @property(Label)
1522
+ highScoreLabel: Label = null!;
1523
+
1524
+ @property(Button)
1525
+ startButton: Button = null!;
1526
+
1527
+ private playerModel: PlayerModel = null!;
1528
+
1529
+ onEnter(args?: any): void {
1530
+ // 获取 Model
1531
+ this.playerModel = this.getModel<PlayerModel>(ModelNames.Player);
1532
+
1533
+ // 更新 UI
1534
+ this.welcomeLabel.string = `欢迎, ${this.playerModel.name || '玩家'}!`;
1535
+ this.highScoreLabel.string = `最高分: ${this.playerModel.highScore}`;
1536
+
1537
+ // 监听按钮点击
1538
+ this.startButton.node.on(Button.EventType.CLICK, this.onStartClick, this);
1539
+ }
1540
+
1541
+ onExit(): void {
1542
+ // BaseView 会自动清理事件监听
1543
+ }
1544
+
1545
+ onPause(): void {}
1546
+ onResume(): void {}
1547
+
1548
+ private async onStartClick(): Promise<void> {
1549
+ // 关闭主界面
1550
+ mf.gui.close(ViewNames.Home);
1551
+
1552
+ // 打开游戏界面
1553
+ await mf.gui.open(ViewNames.Game, { level: 1 });
1554
+ }
1555
+ }
1556
+ ```
1557
+
1558
+ ### 11.7 GameView.ts - 游戏界面
1559
+
1560
+ ```typescript
1561
+ import { view, ViewNames, ManagerNames, ModelNames } from 'dzkcc-mflow/core';
1562
+ import { BaseView } from 'dzkcc-mflow/libs';
1563
+ import { _decorator, Label, Node } from 'cc';
1564
+ import { GameManager } from '../managers/GameManager';
1565
+ import { GameModel } from '../models/GameModel';
1566
+
1567
+ const { ccclass, property } = _decorator;
1568
+
1569
+ @view('Game')
1570
+ @ccclass('GameView')
1571
+ export class GameView extends BaseView {
1572
+ @property(Label)
1573
+ scoreLabel: Label = null!;
1574
+
1575
+ @property(Label)
1576
+ goldLabel: Label = null!;
1577
+
1578
+ @property(Label)
1579
+ lifeLabel: Label = null!;
1580
+
1581
+ @property(Node)
1582
+ gameContainer: Node = null!;
1583
+
1584
+ private gameManager: GameManager = null!;
1585
+ private gameModel: GameModel = null!;
1586
+
1587
+ onEnter(args?: any): void {
1588
+ // 获取 Manager 和 Model
1589
+ this.gameManager = this.getManager<GameManager>(ManagerNames.Game);
1590
+ this.gameModel = this.getModel<GameModel>(ModelNames.Game);
1591
+
1592
+ // 监听游戏事件(会自动清理)
1593
+ this.event.on('enemyKilled', this.onEnemyKilled, this);
1594
+ this.event.on('lifeChanged', this.onLifeChanged, this);
1595
+ this.event.on('gameOver', this.onGameOver, this);
1596
+
1597
+ // 开始游戏
1598
+ const level = args?.level || 1;
1599
+ this.gameManager.startGame(level);
1600
+
1601
+ // 更新 UI
1602
+ this.updateUI();
1603
+ }
1604
+
1605
+ onExit(): void {
1606
+ // BaseView 会自动清理事件监听
1607
+ }
1608
+
1609
+ onPause(): void {}
1610
+ onResume(): void {}
1611
+
1612
+ private onEnemyKilled(data: any): void {
1613
+ this.updateUI();
1614
+ }
1615
+
1616
+ private onLifeChanged(life: number): void {
1617
+ this.lifeLabel.string = `生命: ${life}`;
1618
+ }
1619
+
1620
+ private async onGameOver(data: any): Promise<void> {
1621
+ // 关闭游戏界面
1622
+ mf.gui.close(ViewNames.Game);
1623
+
1624
+ // 打开结算界面
1625
+ await mf.gui.open(ViewNames.Result, {
1626
+ score: data.score,
1627
+ highScore: data.highScore
1628
+ });
1629
+ }
1630
+
1631
+ private updateUI(): void {
1632
+ this.scoreLabel.string = `分数: ${this.gameModel.score}`;
1633
+ this.goldLabel.string = `金币: ${this.gameModel.gold}`;
1634
+ this.lifeLabel.string = `生命: ${this.gameModel.life}`;
1635
+ }
1636
+ }
1637
+ ```
1638
+
1639
+ ### 11.8 ResultView.ts - 结算界面
1640
+
1641
+ ```typescript
1642
+ import { view, ViewNames } from 'dzkcc-mflow/core';
1643
+ import { BaseView } from 'dzkcc-mflow/libs';
1644
+ import { _decorator, Button, Label } from 'cc';
1645
+
1646
+ const { ccclass, property } = _decorator;
1647
+
1648
+ @view('Result')
1649
+ @ccclass('ResultView')
1650
+ export class ResultView extends BaseView {
1651
+ @property(Label)
1652
+ scoreLabel: Label = null!;
1653
+
1654
+ @property(Label)
1655
+ highScoreLabel: Label = null!;
1656
+
1657
+ @property(Button)
1658
+ restartButton: Button = null!;
1659
+
1660
+ @property(Button)
1661
+ homeButton: Button = null!;
1662
+
1663
+ onEnter(args?: any): void {
1664
+ // 显示分数
1665
+ this.scoreLabel.string = `本局分数: ${args?.score || 0}`;
1666
+ this.highScoreLabel.string = `最高分: ${args?.highScore || 0}`;
1667
+
1668
+ // 监听按钮点击
1669
+ this.restartButton.node.on(Button.EventType.CLICK, this.onRestartClick, this);
1670
+ this.homeButton.node.on(Button.EventType.CLICK, this.onHomeClick, this);
1671
+ }
1672
+
1673
+ onExit(): void {}
1674
+ onPause(): void {}
1675
+ onResume(): void {}
1676
+
1677
+ private async onRestartClick(): Promise<void> {
1678
+ mf.gui.close(ViewNames.Result);
1679
+ await mf.gui.open(ViewNames.Game, { level: 1 });
1680
+ }
1681
+
1682
+ private async onHomeClick(): Promise<void> {
1683
+ mf.gui.close(ViewNames.Result);
1684
+ await mf.gui.open(ViewNames.Home);
1685
+ }
1686
+ }
1687
+ ```
1688
+
1689
+ ---
1690
+
1691
+ ## 12. 最佳实践
1692
+
1693
+ ### 12.1 设计原则
1694
+
1695
+ ✅ **单一职责** - 每个 Manager/Model 只负责一个特定领域
1696
+ ✅ **依赖注入** - 使用装饰器自动注入依赖
1697
+ ✅ **事件驱动** - 通过事件系统实现模块解耦
1698
+ ✅ **资源管理** - 使用 BaseView 自动管理资源生命周期
1699
+
1700
+ ### 12.2 命名规范
1701
+
1702
+ - **Manager**: 以 `Manager` 结尾,如 `GameManager`、`AudioManager`
1703
+ - **Model**: 以 `Model` 结尾,如 `UserModel`、`ConfigModel`
1704
+ - **View**: 以 `View` 结尾,如 `HomeView`、`GameView`
1705
+ - **装饰器名称**: 简短清晰,如 `@manager('Game')`、`@model('User')`
1706
+
1707
+ ### 12.3 项目结构
1708
+
1709
+ ```
1710
+ assets/scripts/
1711
+ ├── GameCore.ts # 游戏入口
1712
+ ├── managers/ # 业务管理器
1713
+ │ ├── GameManager.ts
1714
+ │ ├── AudioManager.ts
1715
+ │ └── NetworkManager.ts
1716
+ ├── models/ # 数据模型
1717
+ │ ├── UserModel.ts
1718
+ │ ├── ConfigModel.ts
1719
+ │ └── InventoryModel.ts
1720
+ ├── views/ # UI 视图
1721
+ │ ├── HomeView.ts
1722
+ │ ├── BattleView.ts
1723
+ │ └── SettingsView.ts
1724
+ ├── components/ # 可复用组件
1725
+ │ ├── ItemSlot.ts
1726
+ │ └── HealthBar.ts
1727
+ └── utils/ # 工具函数
1728
+ ├── MathUtil.ts
1729
+ └── StringUtil.ts
1730
+ ```
1731
+
1732
+ ### 12.4 注意事项
1733
+
1734
+ ⚠️ **避免循环依赖** - Manager 不应该相互依赖,通过事件系统通信
1735
+ ⚠️ **资源释放** - 使用 `BaseView` 的自动资源管理,避免内存泄漏
1736
+ ⚠️ **事件清理** - 在 Manager 的 `dispose()` 中清理事件监听
1737
+ ⚠️ **异步处理** - 注意 UI 打开/关闭的异步操作,使用 `await`
1738
+ ⚠️ **WebSocket 连接** - 在场景切换时记得断开连接
1739
+
1740
+ ---
1741
+
1742
+ ## 13. License
1743
+
1744
+ MIT License
1745
+
1746
+ Copyright (c) 2024 duanzhk
1747
+
1748
+ ---
1749
+
1750
+ ## 14. 支持与反馈
751
1751
 
752
- 1. **模块化设计**:将相关的业务逻辑封装在对应的Manager中
753
- 2. **数据驱动**:使用Model管理数据状态
754
- 3. **事件解耦**:通过事件系统实现模块间通信
755
- 4. **资源管理**:使用BaseView自动管理资源加载和释放
756
- 5. **依赖注入**:使用装饰器简化依赖管理
757
- 6. **网络请求**:使用HttpManager统一管理网络请求
758
- 7. **实时通信**:使用WebSocketManager处理实时消息,配合事件系统分发
759
- 8. **工具辅助**:使用mflow-tools提高开发效率
1752
+ - **GitHub**: [cocos-modular-flow-framework](https://github.com/duanzhk/cocos-modular-flow-framework)
1753
+ - **文档**: [在线文档](https://github.com/duanzhk/cocos-modular-flow-framework/blob/main/README.md)
1754
+ - **问题反馈**: [Issues](https://github.com/duanzhk/cocos-modular-flow-framework/issues)
760
1755
 
761
- ## 11. 注意事项
1756
+ ---
762
1757
 
763
- 1. 确保在使用框架功能前Core已经初始化
764
- 2. 注意资源的正确加载和释放,避免内存泄漏
765
- 3. 合理使用事件系统,避免事件监听过多影响性能
766
- 4. 使用BaseView的子类时,确保正确实现所有抽象方法
767
- 5. 网络请求时注意错误处理和超时设置
768
- 6. WebSocket 连接时记得在场景切换时断开连接,避免内存泄漏
769
- 7. 合理配置心跳和重连参数,平衡连接稳定性和服务器压力
1758
+ Made with ❤️ by duanzhk