dzkcc-mflow 0.0.22 → 0.0.24

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
@@ -2,30 +2,9 @@
2
2
 
3
3
  一个专为 Cocos Creator 引擎开发的模块化设计与流程管理框架。
4
4
 
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-最佳实践)
5
+ - **GitHub**: https://github.com/duanzhk/cocos-modular-flow-framework
19
6
 
20
- ---
21
-
22
- ## 1. 框架概述
23
-
24
- ### 1.1 简介
25
-
26
- Modular Flow Framework (MF) 是一个为 Cocos Creator 引擎开发的模块化设计和流程管理框架。该框架旨在提供解耦和依赖注入的能力,帮助开发者构建更加清晰、可维护的游戏项目。
27
-
28
- ### 1.2 核心特性
7
+ ## 核心特性
29
8
 
30
9
  ✨ **模块化设计** - 通过 Manager 和 Model 模式实现业务逻辑的模块化管理
31
10
  ✨ **依赖注入** - 基于装饰器的自动依赖注入和 Symbol 映射
@@ -36,26 +15,36 @@ Modular Flow Framework (MF) 是一个为 Cocos Creator 引擎开发的模块化
36
15
  ✨ **HTTP 网络** - 简洁易用的 HTTP 客户端,支持 RESTful API
37
16
  ✨ **WebSocket 实时通信** - 支持自动重连、心跳检测的 WebSocket 客户端
38
17
  ✨ **红点系统** - 树形结构的红点提示管理系统
18
+ ✨ **类型自动推断** - 无需泛型即可享受完整的类型提示
39
19
  ✨ **开发工具** - 配套的 Cocos Creator 编辑器插件
40
20
 
41
- ### 1.3 安装
21
+ ## 快速开始
22
+
23
+ ### 安装
42
24
 
43
25
  ```bash
44
26
  npm i dzkcc-mflow@beta
45
27
  ```
46
28
 
47
- 安装完成后,**重启 Cocos Creator 编辑器**,框架会自动安装配套的编辑器插件。
48
-
49
- ---
29
+ ### 配置 TypeScript
50
30
 
51
- ## 2. 快速开始
31
+ 修改项目的 `tsconfig.json`:
52
32
 
53
- ### 2.1 创建 Core 入口
33
+ ```json
34
+ {
35
+ "extends": "./temp/tsconfig.cocos.json",
36
+ "compilerOptions": {
37
+ "strict": false,
38
+ "paths": {
39
+ "dzkcc-mflow/*": ["./node_modules/dzkcc-mflow/dist/*"]
40
+ }
41
+ }
42
+ }
43
+ ```
54
44
 
55
- 在项目中创建一个继承自 `CocosCore` 的类:
45
+ ### 创建入口
56
46
 
57
47
  ```typescript
58
- // GameCore.ts
59
48
  import { CocosCore } from 'dzkcc-mflow/libs';
60
49
  import { _decorator } from 'cc';
61
50
 
@@ -67,521 +56,52 @@ export class GameCore extends CocosCore {
67
56
  }
68
57
  ```
69
58
 
70
- ### 2.2 挂载到场景
71
-
72
- 1. 在 Cocos Creator 编辑器中打开主场景
73
- 2. 在 Canvas 节点上添加 `GameCore` 组件
74
- 3. 保存场景
75
-
76
-
77
- ### 2.3 使用全局对象
78
-
79
- 框架提供了全局对象 `mf`(Modular Flow 的缩写)用于访问框架功能:
80
-
81
- ```typescript
82
- // 访问 Manager
83
- const gameManager = mf.core.getManager(ManagerNames.GameManager);
84
-
85
- // 访问 Model
86
- const userModel = mf.core.getModel(ModelNames.UserModel);
87
-
88
- // 打开 UI
89
- await mf.gui.open(ViewNames.HomeView);
90
-
91
- // 发送事件
92
- mf.event.dispatch('gameStart');
93
-
94
- // 加载资源
95
- const prefab = await mf.res.loadPrefab('prefabs/player');
96
-
97
- // HTTP 请求
98
- const data = await mf.http.get('/api/user/profile');
99
-
100
- // WebSocket 连接
101
- mf.socket.connect('wss://game-server.com/ws');
102
-
103
- // 红点提示
104
- mf.reddot.setCount('main/bag', 5);
105
- ```
106
-
107
- ## 3. 核心概念
108
-
109
- ### 3.1 架构图
110
-
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
- ```
132
-
133
- ### 3.2 Core 核心容器
134
-
135
- `Core` 是框架的核心,负责管理所有 Manager 和 Model 实例。
136
-
137
- **核心职责:**
138
- - 注册和实例化 Manager
139
- - 注册和实例化 Model
140
- - 提供统一的访问接口
141
- - 自动调用初始化方法
142
-
143
- **使用方式:**
144
-
145
- ```typescript
146
- // 获取 Manager
147
- const gameManager = mf.core.getManager(ManagerNames.GameManager);
148
-
149
- // 获取 Model
150
- const userModel = mf.core.getModel(ModelNames.UserModel);
151
- ```
152
-
153
- ### 3.3 ServiceLocator 服务定位器
154
-
155
- `ServiceLocator` 用于管理跨领域的基础服务,实现解耦。
156
-
157
- **内置服务:**
158
- - `core` - Core 实例
159
- - `EventManager` - 事件管理器
160
- - `UIManager` - UI 管理器
161
- - `ResLoader` - 资源加载器
162
- - `HttpManager` - HTTP 管理器
163
- - `WebSocketManager` - WebSocket 管理器
164
- - `RedDotManager` - 红点管理器
165
-
166
- **自定义服务:**
167
-
168
- ```typescript
169
- import { ServiceLocator } from 'dzkcc-mflow/core';
170
-
171
- // 注册服务
172
- ServiceLocator.regService('MyService', new MyService());
173
-
174
- // 获取服务
175
- const myService = ServiceLocator.getService<MyService>('MyService');
176
-
177
- // 移除服务
178
- ServiceLocator.remove('MyService');
179
- ```
180
-
181
- ### 3.4 Manager 管理器
182
-
183
- Manager 负责处理特定领域的业务逻辑。
184
-
185
- **基类:** `AbstractManager`
186
-
187
- **生命周期:**
188
- 1. `initialize()` - 在注册时被调用
189
- 2. `dispose()` - 在销毁时被调用
190
-
191
- **内置能力:**
192
- - 获取 Model:`this.getModel(modelSymbol)`
193
- - 获取事件管理器:`this.getEventManager()`
194
- - 获取 HTTP 管理器:`this.getHttpManager()`
195
- - 获取 WebSocket 管理器:`this.getWebSocketManager()`
196
-
197
- ### 3.5 Model 数据模型
198
-
199
- Model 用于数据管理,遵循单一职责原则。
200
-
201
- **接口:** `IModel`
202
-
203
- **生命周期:**
204
- - `initialize()` - 在注册时被调用
205
-
206
- ### 3.6 View 视图
207
-
208
- View 是 UI 界面的基类,提供完整的生命周期管理。
209
-
210
- **基类:** `BaseView`
211
-
212
- **生命周期:**
213
- 1. `onEnter(args?)` - 界面打开时调用
214
- 2. `onPause()` - 界面被覆盖时调用(栈模式)
215
- 3. `onResume()` - 界面恢复显示时调用(栈模式)
216
- 4. `onExit()` - 界面关闭时调用(自动清理事件)
217
- 5. `onDestroy()` - 界面销毁时调用(自动释放资源)
218
-
219
- **内置能力:**
220
- - 自动事件管理:通过 `this.event` 监听的事件会自动清理
221
- - 自动资源管理:通过 `this.res` 加载的资源会自动释放
222
- - 获取 Manager:`this.getManager(managerSymbol)`
223
- - 获取 Model:`this.getModel(modelSymbol)`
224
-
225
- ### 3.7 Symbol 映射系统
226
-
227
- 框架使用 Symbol 作为标识符,配合 Names 对象实现类型安全和代码补全。
228
-
229
- **三种 Names 对象:**
230
- - `ModelNames` - Model 的 Symbol 映射
231
- - `ManagerNames` - Manager 的 Symbol 映射
232
- - `ViewNames` - View 的 Symbol 映射
233
-
234
- **优势:**
235
- - ✅ IDE 代码补全
236
- - ✅ 类型安全
237
- - ✅ 避免字符串拼写错误
238
- - ✅ 便于重构
239
-
240
- ## 4. 装饰器系统
241
-
242
- 框架提供了三个核心装饰器,用于注册 Manager、Model 和 View。
243
-
244
- ### 4.1 @manager() - Manager 装饰器
245
-
246
- 用于注册 Manager 到全局注册表。
247
-
248
- ```typescript
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 初始化');
257
- }
258
-
259
- dispose(): void {
260
- console.log('GameManager 销毁');
261
- }
262
-
263
- addScore(value: number): void {
264
- this.score += value;
265
- this.getEventManager().dispatch('scoreChanged', this.score);
266
- }
267
- }
268
-
269
- // 使用
270
- const gameManager = mf.core.getManager(ManagerNames.Game);
271
- gameManager.addScore(10);
272
- ```
273
-
274
- ### 4.2 @model() - Model 装饰器
275
-
276
- 用于注册 Model 到全局注册表。
277
-
278
- ```typescript
279
- import { model, IModel, ModelNames } from 'dzkcc-mflow/core';
280
-
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
- }
305
- }
306
-
307
- // 使用
308
- const userModel = mf.core.getModel(ModelNames.User);
309
- userModel.playerName = 'Alice';
310
- userModel.levelUp();
311
- ```
312
-
313
- ### 4.3 @view() - View 装饰器
314
-
315
- 用于注册 View 到全局注册表,配合 `ViewNames` 使用。
316
-
317
- ```typescript
318
- import { view, ViewNames } from 'dzkcc-mflow/core';
319
- import { BaseView } from 'dzkcc-mflow/libs';
320
- import { _decorator, Button, Label } from 'cc';
59
+ 📖 **详细指南**: [快速开始](./docs/QUICK_START.md)
321
60
 
322
- const { ccclass, property } = _decorator;
61
+ ## 核心功能模块
323
62
 
324
- @view('Home') // 注册为 'Home'
325
- @ccclass('HomeView')
326
- export class HomeView extends BaseView {
327
- @property(Label)
328
- titleLabel: Label = null!;
329
-
330
- @property(Button)
331
- startButton: Button = null!;
332
-
333
- onEnter(args?: any): void {
334
- console.log('HomeView 打开', args);
335
- this.startButton.node.on('click', this.onStartClick, this);
336
- }
337
-
338
- onExit(): void {
339
- // 自动清理事件监听
340
- }
341
-
342
- onPause(): void {
343
- console.log('HomeView 暂停');
344
- }
345
-
346
- onResume(): void {
347
- console.log('HomeView 恢复');
348
- }
349
-
350
- private onStartClick(): void {
351
- mf.gui.open(ViewNames.Game);
352
- }
353
- }
63
+ ### 1. 核心概念
354
64
 
355
- // 使用 - 通过 Symbol 打开视图
356
- await mf.gui.open(ViewNames.Home, { userId: 123 });
65
+ 了解框架的基础架构、Core 容器、ServiceLocator、Manager、Model、View Symbol 映射系统。
357
66
 
358
- // 关闭视图
359
- mf.gui.close(ViewNames.Home); // 关闭但保留缓存
360
- mf.gui.close(ViewNames.Home, true); // 关闭并销毁
361
- ```
67
+ 📖 **查看文档**: [核心概念](./docs/CORE_CONCEPTS.md)
362
68
 
363
- ### 4.4 装饰器参数
69
+ ### 2. 装饰器系统
364
70
 
365
- 所有装饰器都支持可选的 `name` 参数:
71
+ 使用 `@manager()`、`@model()`、`@view()` 装饰器注册组件,实现自动依赖注入。
366
72
 
367
73
  ```typescript
368
- // 指定名称
369
74
  @manager('Game')
370
- @model('User')
371
- @view('Home')
372
-
373
- // 不指定名称时,自动使用类名
374
- @manager() // 使用 'GameManager'
375
- @model() // 使用 'UserModel'
376
- @view() // 使用 'HomeView'
377
- ```
378
-
379
- ### 4.5 Names 对象代码补全
75
+ export class GameManager extends AbstractManager {}
380
76
 
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
398
- ```
399
-
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
- **基本用法:**
77
+ @model('User')
78
+ export class UserModel implements IModel {}
415
79
 
416
- ```typescript
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!;
428
-
429
- @property(Sprite)
430
- playerSprite: Sprite = null!;
431
-
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);
444
- }
445
-
446
- onExit(): void {
447
- // 事件监听会自动清理,无需手动 off
448
- }
449
-
450
- onPause(): void {
451
- // 界面被其他界面覆盖时调用
452
- }
453
-
454
- onResume(): void {
455
- // 界面从暂停状态恢复时调用
456
- }
457
-
458
- private onScoreChanged(score: number): void {
459
- this.scoreLabel.string = `分数: ${score}`;
460
- }
461
- }
80
+ @view('Home')
81
+ @ccclass('HomeView')
82
+ export class HomeView extends BaseView {}
462
83
  ```
463
84
 
464
- ### 5.2 UIManager 界面管理器
85
+ 📖 **查看文档**: [装饰器系统](./docs/DECORATORS.md)
465
86
 
466
- 通过 `mf.gui` 访问 UI 管理功能。
87
+ ### 3. UI 系统
467
88
 
468
- **基本操作:**
89
+ 完整的 UI 界面管理,支持生命周期、视图栈、自动事件清理和资源释放。
469
90
 
470
91
  ```typescript
471
- import { ViewNames } from 'dzkcc-mflow/core';
472
-
473
92
  // 打开界面
474
- const view = await mf.gui.open(ViewNames.Home);
93
+ await mf.gui.open(ViewNames.Home, { data: 'value' });
475
94
 
476
- // 打开界面并传参
477
- await mf.gui.open(ViewNames.Game, { level: 1, difficulty: 'hard' });
478
-
479
- // 关闭界面(保留缓存)
480
- mf.gui.close(ViewNames.Home);
481
-
482
- // 关闭并销毁界面(释放资源)
483
- mf.gui.close(ViewNames.Home, true);
484
-
485
- // 通过视图实例关闭
486
- const view = await mf.gui.open(ViewNames.Settings);
487
- mf.gui.close(view);
95
+ // 视图栈管理
96
+ await mf.gui.openAndPush(ViewNames.Level1, 'game');
97
+ mf.gui.closeAndPop('game');
488
98
  ```
489
99
 
490
- ### 5.3 视图栈管理
491
-
492
- 支持分组的视图栈,适用于关卡、向导等场景。
100
+ 📖 **查看文档**: [UI 系统](./docs/UI_SYSTEM.md)
493
101
 
494
- ```typescript
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'); // 所有关卡视图关闭
102
+ ### 4. 事件系统
506
103
 
507
- // 清空栈并销毁
508
- mf.gui.clearStack('game', true);
509
-
510
- // 获取栈顶视图
511
- const topView = mf.gui.getTopView();
512
- ```
513
-
514
- ### 5.4 视图生命周期详解
515
-
516
- ```typescript
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
- }
526
-
527
- // 2. 界面被其他界面覆盖时调用(栈模式)
528
- onPause(): void {
529
- console.log('界面暂停');
530
- // 暂停动画
531
- // 暂停计时器
532
- }
533
-
534
- // 3. 界面从暂停状态恢复时调用(栈模式)
535
- onResume(): void {
536
- console.log('界面恢复');
537
- // 恢复动画
538
- // 恢复计时器
539
- }
540
-
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
- // 可以在这里做额外的清理工作
553
- }
554
- }
555
- ```
556
-
557
- ### 5.5 Prefab 路径配置
558
-
559
- 视图需要配置 Prefab 路径,框架提供了开发工具自动生成。
560
-
561
- **手动配置方式:**
562
-
563
- ```typescript
564
- @view('Home')
565
- @ccclass('HomeView')
566
- export class HomeView extends BaseView {
567
- /** @internal */
568
- private static readonly __path__: string = 'ui/home'; // Prefab 路径
569
-
570
- onEnter(): void {}
571
- onPause(): void {}
572
- onResume(): void {}
573
- }
574
- ```
575
-
576
- **推荐:使用开发工具自动生成**(见第 10 章)
577
-
578
- ---
579
-
580
- ## 6. 事件系统
581
-
582
- 框架提供了强大的事件广播和监听机制,基于 `Broadcaster` 实现。
583
-
584
- ### 6.1 基本用法
104
+ 强大的事件广播和监听机制,支持粘性事件和类型安全。
585
105
 
586
106
  ```typescript
587
107
  // 监听事件
@@ -591,1168 +111,188 @@ mf.event.on('gameStart', (data) => {
591
111
 
592
112
  // 派发事件
593
113
  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);
640
- }
641
-
642
- onExit(): void {
643
- // 自动清理所有通过 this.event 监听的事件
644
- // 无需手动 off
645
- }
646
-
647
- private updateScore(score: number): void {
648
- console.log('分数更新:', score);
649
- }
650
-
651
- private onLevelUp(level: number): void {
652
- console.log('等级提升:', level);
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;
663
-
664
- initialize(): void {
665
- // 在 Manager 中获取事件管理器
666
- const eventMgr = this.getEventManager();
667
-
668
- eventMgr.on('enemyKilled', this.onEnemyKilled, this);
669
- }
670
-
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
114
  ```
750
115
 
751
- ### 7.2 释放资源
752
-
753
- ```typescript
754
- // 通过路径释放
755
- mf.res.release('prefabs/enemy', Prefab);
756
-
757
- // 通过资源对象释放
758
- mf.res.release(asset);
116
+ 📖 **查看文档**: [事件系统](./docs/EVENT_SYSTEM.md)
759
117
 
760
- // 强制释放(立即销毁,不管引用计数)
761
- mf.res.release(asset, true);
762
- ```
763
-
764
- ### 7.3 在 View 中自动管理资源
118
+ ### 5. 资源管理
765
119
 
766
- `BaseView` 提供了自动资源管理:
120
+ 统一的资源加载和释放管理,支持自动资源管理。
767
121
 
768
122
  ```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
123
+ // 加载资源
124
+ const prefab = await mf.res.loadPrefab('prefabs/player');
815
125
 
816
- // 释放资源,引用计数递减
817
- mf.res.release(asset1); // refCount = 1
818
- mf.res.release(asset2); // refCount = 0,资源被销毁
126
+ // View 中自动管理
127
+ this.res.loadSpriteFrame(this.sprite, 'textures/icon');
128
+ // onDestroy 时自动释放
819
129
  ```
820
130
 
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
- });
131
+ 📖 **查看文档**: [资源管理](./docs/RESOURCE_MANAGEMENT.md)
841
132
 
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
- ```
133
+ ### 6. 网络通信
861
134
 
862
- **在 Manager 中使用:**
135
+ 简洁易用的 HTTP 和 WebSocket 客户端。
863
136
 
864
137
  ```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
- **基本用法:**
138
+ // HTTP 请求
139
+ const data = await mf.http.get('/api/user/profile');
140
+ await mf.http.post('/api/login', { username, password });
905
141
 
906
- ```typescript
907
- // 连接服务器
142
+ // WebSocket 连接
908
143
  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
144
  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
145
  ```
949
146
 
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);
147
+ 📖 **查看文档**: [网络通信](./docs/NETWORK.md)
964
148
 
965
- // 4. Blob(文件数据)
966
- const blob = new Blob(['data'], { type: 'text/plain' });
967
- mf.socket.send(blob);
968
- ```
149
+ ### 7. 红点系统
969
150
 
970
- **在 Manager 中使用:**
151
+ 树形结构的红点提示管理,支持自动累加和变化监听。
971
152
 
972
153
  ```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
- // 设置红点数量
154
+ // 设置红点
1046
155
  mf.reddot.setCount('main/bag/weapon', 5);
1047
- mf.reddot.setCount('main/bag/armor', 3);
1048
- mf.reddot.setCount('main/mail', 10);
1049
156
 
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');
157
+ // 监听变化
158
+ mf.reddot.on('main/bag', (totalCount) => {
159
+ this.updateUI(totalCount);
160
+ });
1066
161
  ```
1067
162
 
1068
- ### 9.2 监听红点变化
163
+ 📖 **查看文档**: [红点系统](./docs/REDDOT_SYSTEM.md)
1069
164
 
1070
- ```typescript
1071
- // 监听红点变化
1072
- mf.reddot.on('main/bag', (totalCount, selfCount) => {
1073
- console.log(`背包红点: ${totalCount} (自身: ${selfCount})`);
1074
- // 更新 UI 显示
1075
- });
165
+ ### 8. 类型自动推断 ⭐
1076
166
 
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 中使用
167
+ 无需泛型、无需 import 具体类,自动推断 `getModel` 和 `getManager` 的返回类型!
1084
168
 
1085
169
  ```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;
170
+ // 只需要一次性配置类型映射
171
+ // types/core-types.d.ts
172
+ declare module 'dzkcc-mflow/core' {
173
+ interface ModelTypeMap {
174
+ [ModelNames.User]: UserModel;
1121
175
  }
1122
-
1123
- onPause(): void {}
1124
- onResume(): void {}
1125
176
  }
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
177
 
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
- }
178
+ // 使用时自动推断类型
179
+ const userModel = mf.core.getModel(ModelNames.User);
180
+ userModel.name; // 有完整的代码补全
1224
181
  ```
1225
182
 
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;
183
+ **维护类型映射**:
1233
184
 
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
- }
185
+ ```bash
186
+ npm run generate:types # 自动生成类型映射
1245
187
  ```
1246
188
 
1247
- 4. **脚本自动挂载**
189
+ 📖 **查看文档**: [类型自动推断](./docs/TYPE_INFERENCE.md)
1248
190
 
1249
- 插件会自动将生成的脚本挂载到 Prefab 上,并设置好所有组件引用。
191
+ ### 9. 开发工具
1250
192
 
1251
- ---
1252
-
1253
- ## 11. 完整示例
193
+ Cocos Creator 编辑器插件,自动生成 UI 脚本,自动设置组件引用。
1254
194
 
1255
- 下面是一个简单的塔防游戏示例,展示框架的完整使用流程。
195
+ **使用方法**:
196
+ 1. 按命名约定重命名节点(如 `#titleLabel#Label`)
197
+ 2. 右键选择 "MFlow Tools → 导出到脚本"
198
+ 3. 自动生成基类和业务类
1256
199
 
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
- ```
200
+ 📖 **查看文档**: [开发工具](./docs/DEV_TOOLS.md)
1284
201
 
1285
- ### 11.2 GameCore.ts - 游戏入口
202
+ ## 完整示例
1286
203
 
1287
- ```typescript
1288
- import { CocosCore } from 'dzkcc-mflow/libs';
1289
- import { _decorator } from 'cc';
204
+ 查看一个完整的塔防游戏示例,了解如何使用框架的各个功能。
1290
205
 
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';
206
+ 📖 **查看示例**: [完整示例](./docs/COMPLETE_EXAMPLE.md)
1300
207
 
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
- ```
208
+ ## 最佳实践
1315
209
 
1316
- ### 11.3 GameModel.ts - 游戏数据模型
210
+ 了解设计原则、命名规范、项目结构、性能优化和常见注意事项。
1317
211
 
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
- ```
212
+ 📖 **查看文档**: [最佳实践](./docs/BEST_PRACTICES.md)
1372
213
 
1373
- ### 11.4 PlayerModel.ts - 玩家数据模型
214
+ ## 架构图
1374
215
 
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
- }));
1422
- }
1423
- }
1424
216
  ```
1425
-
1426
- ### 11.5 GameManager.ts - 游戏管理器
1427
-
1428
- ```typescript
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'];
1501
- }
1502
- }
1503
- ```
1504
-
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
- }
217
+ ┌─────────────────────────────────────────────────┐
218
+ │ 全局对象 mf │
219
+ │ (统一访问入口,暴露所有框架能力) │
220
+ └──────────────────┬──────────────────────────────┘
221
+
222
+ ┌──────────────┼──────────────┐
223
+ │ │ │
224
+ ▼ ▼ ▼
225
+ ┌─────────┐ ┌──────────┐ ┌──────────┐
226
+ │ Core │ │ Services │ │ Views │
227
+ │(核心容器)│ │(基础服务) │ │ (UI界面) │
228
+ └─────────┘ └──────────┘ └──────────┘
229
+ │ │ │
230
+ ├─ Manager ─┐ ├─ UIManager ├─ BaseView
231
+ │ │ ├─ ResLoader └─ 自动资源管理
232
+ ├─ Model ───┤ ├─ EventMgr 自动事件清理
233
+ │ │ ├─ HttpMgr
234
+ └─ Symbol ──┘ ├─ SocketMgr
235
+ 映射系统 └─ RedDotMgr
1556
236
  ```
1557
237
 
1558
- ### 11.7 GameView.ts - 游戏界面
238
+ ## 使用全局对象
1559
239
 
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 - 结算界面
240
+ 框架提供了全局对象 `mf` 用于访问所有功能:
1640
241
 
1641
242
  ```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
- ---
243
+ // 访问 Manager
244
+ mf.core.getManager(ManagerNames.GameManager);
1690
245
 
1691
- ## 12. 最佳实践
246
+ // 访问 Model
247
+ mf.core.getModel(ModelNames.UserModel);
1692
248
 
1693
- ### 12.1 设计原则
249
+ // UI 管理
250
+ mf.gui.open(ViewNames.HomeView);
1694
251
 
1695
- **单一职责** - 每个 Manager/Model 只负责一个特定领域
1696
- ✅ **依赖注入** - 使用装饰器自动注入依赖
1697
- ✅ **事件驱动** - 通过事件系统实现模块解耦
1698
- ✅ **资源管理** - 使用 BaseView 自动管理资源生命周期
252
+ // 事件系统
253
+ mf.event.dispatch('gameStart');
1699
254
 
1700
- ### 12.2 命名规范
255
+ // 资源加载
256
+ mf.res.loadPrefab('prefabs/player');
1701
257
 
1702
- - **Manager**: 以 `Manager` 结尾,如 `GameManager`、`AudioManager`
1703
- - **Model**: 以 `Model` 结尾,如 `UserModel`、`ConfigModel`
1704
- - **View**: 以 `View` 结尾,如 `HomeView`、`GameView`
1705
- - **装饰器名称**: 简短清晰,如 `@manager('Game')`、`@model('User')`
258
+ // HTTP 请求
259
+ mf.http.get('/api/user/profile');
1706
260
 
1707
- ### 12.3 项目结构
261
+ // WebSocket
262
+ mf.socket.connect('wss://server.com/ws');
1708
263
 
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
264
+ // 红点系统
265
+ mf.reddot.setCount('main/bag', 5);
1730
266
  ```
1731
267
 
1732
- ### 12.4 注意事项
268
+ ## 文档索引
1733
269
 
1734
- ⚠️ **避免循环依赖** - Manager 不应该相互依赖,通过事件系统通信
1735
- ⚠️ **资源释放** - 使用 `BaseView` 的自动资源管理,避免内存泄漏
1736
- ⚠️ **事件清理** - Manager 的 `dispose()` 中清理事件监听
1737
- ⚠️ **异步处理** - 注意 UI 打开/关闭的异步操作,使用 `await`
1738
- ⚠️ **WebSocket 连接** - 在场景切换时记得断开连接
270
+ | 文档 | 说明 |
271
+ |------|------|
272
+ | [快速开始](./docs/QUICK_START.md) | 安装和基本使用 |
273
+ | [核心概念](./docs/CORE_CONCEPTS.md) | 框架核心概念和架构 |
274
+ | [装饰器系统](./docs/DECORATORS.md) | @manager、@model、@view 使用 |
275
+ | [UI 系统](./docs/UI_SYSTEM.md) | 界面管理和生命周期 |
276
+ | [事件系统](./docs/EVENT_SYSTEM.md) | 事件广播和监听 |
277
+ | [资源管理](./docs/RESOURCE_MANAGEMENT.md) | 资源加载和释放 |
278
+ | [网络通信](./docs/NETWORK.md) | HTTP 和 WebSocket |
279
+ | [红点系统](./docs/REDDOT_SYSTEM.md) | 红点提示管理 |
280
+ | [类型自动推断](./docs/TYPE_INFERENCE.md) | 类型映射和自动推断 |
281
+ | [开发工具](./docs/DEV_TOOLS.md) | 编辑器插件使用 |
282
+ | [完整示例](./docs/COMPLETE_EXAMPLE.md) | 塔防游戏示例 |
283
+ | [最佳实践](./docs/BEST_PRACTICES.md) | 设计原则和规范 |
1739
284
 
1740
- ---
1741
-
1742
- ## 13. License
285
+ ## License
1743
286
 
1744
287
  MIT License
1745
288
 
1746
289
  Copyright (c) 2024 duanzhk
1747
290
 
1748
- ---
1749
-
1750
- ## 14. 支持与反馈
291
+ ## 支持与反馈
1751
292
 
1752
293
  - **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
294
  - **问题反馈**: [Issues](https://github.com/duanzhk/cocos-modular-flow-framework/issues)
1755
295
 
1756
296
  ---
1757
297
 
1758
- Made with ❤️ by duanzhk
298
+ Made with ❤️ by duanzhk