refactor(game): 移除已弃用的事件常量
- 删除 UpdateHero 和 UpdateFightHero 事件 - 移除 MISSION_UPDATE 事件常量 - 优化游戏事件枚举定义
This commit is contained in:
685
.qoder/repowiki/zh/content/数据管理/云数据同步.md
Normal file
685
.qoder/repowiki/zh/content/数据管理/云数据同步.md
Normal file
@@ -0,0 +1,685 @@
|
||||
# 云数据同步
|
||||
|
||||
<cite>
|
||||
**本文档引用的文件**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
- [config.json](file://build-templates/wechatgame/cloud_functions/cocos_cloud/config.json)
|
||||
- [deploy.md](file://build-templates/wechatgame/cloud_functions/cocos_cloud/deploy.md)
|
||||
- [wx.aip.d.ts](file://assets/script/game/wx_clound_client_api/wx.aip.d.ts)
|
||||
- [NetCode.json](file://assets/resources/config/game/NetCode.json)
|
||||
</cite>
|
||||
|
||||
## 目录
|
||||
1. [简介](#简介)
|
||||
2. [系统架构概览](#系统架构概览)
|
||||
3. [核心组件分析](#核心组件分析)
|
||||
4. [WxCloudApi.ts详解](#wxcloudapits详解)
|
||||
5. [云函数服务端实现](#云函数服务端实现)
|
||||
6. [数据流与调用流程](#数据流与调用流程)
|
||||
7. [错误处理与状态码](#错误处理与状态码)
|
||||
8. [前端调用示例](#前端调用示例)
|
||||
9. [部署与配置](#部署与配置)
|
||||
10. [安全性与最佳实践](#安全性与最佳实践)
|
||||
11. [故障排除与优化](#故障排除与优化)
|
||||
12. [总结](#总结)
|
||||
|
||||
## 简介
|
||||
|
||||
本项目实现了基于微信云开发的云数据同步解决方案,为Cocos Creator游戏提供云端用户数据存储与同步功能。系统采用前后端分离架构,通过云函数处理业务逻辑,确保数据安全性和一致性。
|
||||
|
||||
核心功能包括:
|
||||
- 用户身份认证与自动创建
|
||||
- 游戏进度数据的云端存储与获取
|
||||
- 数据版本控制与冲突解决
|
||||
- 错误处理与重试机制
|
||||
- 安全性保障与权限控制
|
||||
|
||||
## 系统架构概览
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "客户端层"
|
||||
Game[游戏客户端]
|
||||
WxCloud[WxCloudApi.ts]
|
||||
end
|
||||
subgraph "微信云开发平台"
|
||||
CloudFunc[云函数:cocos_cloud]
|
||||
Database[(云数据库)]
|
||||
Storage[(云存储)]
|
||||
end
|
||||
subgraph "微信服务器"
|
||||
WXServer[微信服务器]
|
||||
OpenID[用户OpenID]
|
||||
end
|
||||
Game --> WxCloud
|
||||
WxCloud --> CloudFunc
|
||||
CloudFunc --> Database
|
||||
CloudFunc --> WXServer
|
||||
WXServer --> OpenID
|
||||
Database --> Storage
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts#L1-L94)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js#L1-L85)
|
||||
|
||||
## 核心组件分析
|
||||
|
||||
### 前端组件
|
||||
|
||||
**WxCloudApi类** 提供了统一的云服务接口,封装了微信云开发的复杂性,为游戏逻辑提供简洁的API。
|
||||
|
||||
**主要特性:**
|
||||
- 单例模式设计,确保全局唯一实例
|
||||
- 异步操作支持,避免阻塞主线程
|
||||
- 泛型类型安全,提供完整的TypeScript支持
|
||||
- 错误码标准化,便于统一处理
|
||||
|
||||
### 后端组件
|
||||
|
||||
**云函数服务** 运行在微信云开发环境中,负责处理所有业务逻辑和数据操作。
|
||||
|
||||
**核心功能:**
|
||||
- 用户身份验证与自动注册
|
||||
- 数据持久化与查询
|
||||
- 权限控制与安全验证
|
||||
- 错误日志记录与监控
|
||||
|
||||
**章节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts#L1-L94)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js#L1-L85)
|
||||
|
||||
## WxCloudApi.ts详解
|
||||
|
||||
### 类结构设计
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class WxCloudApi {
|
||||
+init(env : string) void
|
||||
+login() Promise~CloudCallFunctionResult~
|
||||
+save(gameData : any) Promise~CloudCallFunctionResult~
|
||||
+get() Promise~CloudCallFunctionResult~
|
||||
}
|
||||
class CloudReturnType {
|
||||
+code : number
|
||||
+msg? : string
|
||||
+data? : T
|
||||
}
|
||||
class CloudCallFunctionResult {
|
||||
+result : T
|
||||
+errMsg : string
|
||||
+requestID : string
|
||||
}
|
||||
WxCloudApi --> CloudReturnType : "返回"
|
||||
CloudReturnType --> CloudCallFunctionResult : "嵌套"
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts#L1-L94)
|
||||
- [wx.aip.d.ts](file://assets/script/game/wx_clound_client_api/wx.aip.d.ts#L1-L29)
|
||||
|
||||
### init方法实现机制
|
||||
|
||||
**功能描述:** 初始化微信云开发环境,建立客户端与云服务的连接。
|
||||
|
||||
**实现特点:**
|
||||
- 单次调用原则:每个游戏会话只需初始化一次
|
||||
- 环境参数配置:支持动态环境切换
|
||||
- 平台兼容性:条件调用,避免非微信环境下报错
|
||||
|
||||
**调用时机:** 游戏启动时,在主场景加载完成后调用。
|
||||
|
||||
### login方法实现机制
|
||||
|
||||
**功能描述:** 执行用户登录流程,获取用户身份信息和游戏数据。
|
||||
|
||||
**数据结构定义:**
|
||||
|
||||
| 字段名 | 类型 | 描述 | 必填 |
|
||||
|--------|------|------|------|
|
||||
| code | number | 状态码,200表示成功 | 是 |
|
||||
| msg | string | 错误信息(失败时) | 否 |
|
||||
| data | object | 用户数据对象 | 是 |
|
||||
| data.openid | string | 微信平台用户标识 | 是 |
|
||||
| data.regist_time | number | 用户注册时间戳 | 是 |
|
||||
| data.game_data | object | 游戏自定义数据 | 否 |
|
||||
|
||||
**调用流程:**
|
||||
1. 调用微信云函数cocos_cloud
|
||||
2. 传递cmd参数值为"login"
|
||||
3. 云函数验证用户身份
|
||||
4. 自动创建或查询用户记录
|
||||
5. 返回用户完整信息
|
||||
|
||||
### save方法实现机制
|
||||
|
||||
**功能描述:** 将游戏数据保存到云端,实现数据的持久化存储。
|
||||
|
||||
**数据结构:**
|
||||
- 接收任意类型的gameData对象
|
||||
- 执行全覆盖式写入操作
|
||||
- 支持复杂嵌套数据结构
|
||||
|
||||
**安全特性:**
|
||||
- 数据完整性校验
|
||||
- 操作日志记录
|
||||
- 版本控制支持
|
||||
|
||||
### get方法实现机制
|
||||
|
||||
**功能描述:** 从云端获取用户的最新游戏数据。
|
||||
|
||||
**实现特点:**
|
||||
- 实时数据拉取
|
||||
- 缓存策略支持
|
||||
- 数据一致性保障
|
||||
|
||||
**章节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts#L1-L94)
|
||||
|
||||
## 云函数服务端实现
|
||||
|
||||
### 服务端架构设计
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client as 客户端
|
||||
participant CloudFunc as 云函数
|
||||
participant Database as 云数据库
|
||||
participant WXServer as 微信服务器
|
||||
Client->>CloudFunc : 调用云函数
|
||||
CloudFunc->>WXServer : 获取用户OpenID
|
||||
WXServer-->>CloudFunc : 返回用户标识
|
||||
CloudFunc->>Database : 查询用户记录
|
||||
Database-->>CloudFunc : 返回用户数据
|
||||
alt 用户不存在
|
||||
CloudFunc->>Database : 创建新用户记录
|
||||
Database-->>CloudFunc : 返回新记录ID
|
||||
end
|
||||
CloudFunc->>Database : 执行数据操作
|
||||
Database-->>CloudFunc : 返回操作结果
|
||||
CloudFunc-->>Client : 返回处理结果
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js#L10-L85)
|
||||
|
||||
### getOrCreaterUser函数实现
|
||||
|
||||
**功能描述:** 核心用户管理逻辑,确保每个微信用户都有对应的数据库记录。
|
||||
|
||||
**实现细节:**
|
||||
- 使用OpenID作为唯一标识符
|
||||
- 自动检测用户是否存在
|
||||
- 原子性操作保证数据一致性
|
||||
- 异常处理机制
|
||||
|
||||
**数据模型:**
|
||||
|
||||
| 字段名 | 类型 | 描述 | 默认值 |
|
||||
|--------|------|------|--------|
|
||||
| _openid | string | 微信OpenID | 必填 |
|
||||
| regist_time | number | 注册时间戳 | 当前时间 |
|
||||
| game_data | object | 游戏数据 | {} |
|
||||
|
||||
### 登录处理逻辑
|
||||
|
||||
**流程分析:**
|
||||
1. **身份验证**:通过cloud.getWXContext()获取用户上下文
|
||||
2. **用户查询**:根据OpenID查找用户记录
|
||||
3. **用户创建**:如用户不存在则自动创建
|
||||
4. **数据返回**:返回完整的用户信息
|
||||
|
||||
**错误处理:**
|
||||
- 数据库连接失败
|
||||
- 用户查询超时
|
||||
- 记录创建失败
|
||||
|
||||
### 数据保存逻辑
|
||||
|
||||
**操作流程:**
|
||||
1. **数据验证**:检查传入的游戏数据格式
|
||||
2. **用户确认**:确保用户记录存在
|
||||
3. **数据更新**:使用原子更新操作
|
||||
4. **结果反馈**:返回操作统计信息
|
||||
|
||||
**性能优化:**
|
||||
- 批量操作支持
|
||||
- 索引优化
|
||||
- 连接池管理
|
||||
|
||||
**章节来源**
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js#L1-L85)
|
||||
|
||||
## 数据流与调用流程
|
||||
|
||||
### 完整数据同步流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start([游戏启动]) --> Init["WxCloudApi.init()"]
|
||||
Init --> Login["WxCloudApi.login()"]
|
||||
Login --> LoginSuccess{"登录成功?"}
|
||||
LoginSuccess --> |否| LoginFail["显示登录错误"]
|
||||
LoginSuccess --> |是| LoadGameData["加载用户数据"]
|
||||
LoadGameData --> GameLoop["游戏主循环"]
|
||||
GameLoop --> SaveCheck{"需要保存数据?"}
|
||||
SaveCheck --> |否| GameLoop
|
||||
SaveCheck --> |是| SaveData["WxCloudApi.save()"]
|
||||
SaveData --> SaveSuccess{"保存成功?"}
|
||||
SaveSuccess --> |否| Retry["重试机制"]
|
||||
SaveSuccess --> |是| GameLoop
|
||||
Retry --> RetryCount{"重试次数<3?"}
|
||||
RetryCount --> |是| SaveData
|
||||
RetryCount --> |否| SaveFail["保存失败处理"]
|
||||
LoginFail --> End([结束])
|
||||
SaveFail --> End
|
||||
SaveSuccess --> End
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts#L15-L94)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js#L15-L50)
|
||||
|
||||
### 请求响应数据结构
|
||||
|
||||
**登录请求:**
|
||||
```typescript
|
||||
// 请求格式
|
||||
{
|
||||
cmd: "login"
|
||||
}
|
||||
|
||||
// 响应格式
|
||||
{
|
||||
code: 200,
|
||||
data: {
|
||||
openid: "wx_openid_string",
|
||||
regist_time: 1640995200000,
|
||||
game_data: {
|
||||
level: 10,
|
||||
coins: 1000,
|
||||
inventory: [...],
|
||||
achievements: {...}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**保存请求:**
|
||||
```typescript
|
||||
// 请求格式
|
||||
{
|
||||
cmd: "save",
|
||||
data: {
|
||||
level: 11,
|
||||
coins: 1200,
|
||||
inventory: [...],
|
||||
achievements: {...}
|
||||
}
|
||||
}
|
||||
|
||||
// 响应格式
|
||||
{
|
||||
code: 200,
|
||||
data: {
|
||||
errMsg: "document.update:ok",
|
||||
stats: {
|
||||
updated: 1
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**获取请求:**
|
||||
```typescript
|
||||
// 请求格式
|
||||
{
|
||||
cmd: "get"
|
||||
}
|
||||
|
||||
// 响应格式
|
||||
{
|
||||
code: 200,
|
||||
data: {
|
||||
_id: "mongodb_document_id",
|
||||
_openid: "wx_openid_string",
|
||||
regist_time: 1640995200000,
|
||||
game_data: {...}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 错误处理与状态码
|
||||
|
||||
### 状态码定义
|
||||
|
||||
| 状态码 | 含义 | 处理方式 | 示例场景 |
|
||||
|--------|------|----------|----------|
|
||||
| 200 | 成功 | 正常处理 | 登录成功、数据保存成功 |
|
||||
| -1 | 通用错误 | 重试或提示用户 | 网络超时、数据库错误 |
|
||||
| -2 | 命令未知 | 检查参数 | 云函数参数错误 |
|
||||
| -3 | 权限不足 | 提示授权 | 用户未授权 |
|
||||
|
||||
### 错误分类处理
|
||||
|
||||
**网络错误:**
|
||||
- 连接超时:自动重试3次
|
||||
- 断线重连:本地缓存待发送数据
|
||||
- 网络恢复:批量同步缓存数据
|
||||
|
||||
**业务错误:**
|
||||
- 用户不存在:触发重新登录
|
||||
- 数据冲突:采用最后修改时间策略
|
||||
- 权限验证失败:引导用户重新授权
|
||||
|
||||
**系统错误:**
|
||||
- 云函数异常:降级到本地存储
|
||||
- 数据库不可用:启用离线模式
|
||||
- 服务端维护:显示维护公告
|
||||
|
||||
**章节来源**
|
||||
- [NetCode.json](file://assets/resources/config/game/NetCode.json#L1-L11)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js#L15-L85)
|
||||
|
||||
## 前端调用示例
|
||||
|
||||
### 基础使用示例
|
||||
|
||||
```typescript
|
||||
// 初始化云服务
|
||||
WxCloudApi.init('your-cloud-env');
|
||||
|
||||
// 用户登录
|
||||
async function handleLogin() {
|
||||
try {
|
||||
const result = await WxCloudApi.login();
|
||||
|
||||
if (result.result.code === 200) {
|
||||
const userData = result.result.data;
|
||||
console.log('登录成功:', userData);
|
||||
// 更新游戏状态
|
||||
game.user = userData;
|
||||
loadGameProgress(userData.game_data);
|
||||
} else {
|
||||
console.error('登录失败:', result.result.msg);
|
||||
showErrorMessage(result.result.msg);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('登录异常:', error);
|
||||
showNetworkError();
|
||||
}
|
||||
}
|
||||
|
||||
// 保存游戏进度
|
||||
async function saveGameProgress(progressData: any) {
|
||||
try {
|
||||
const result = await WxCloudApi.save(progressData);
|
||||
|
||||
if (result.result.code === 200) {
|
||||
console.log('保存成功');
|
||||
game.lastSyncTime = Date.now();
|
||||
} else {
|
||||
console.error('保存失败:', result.result.msg);
|
||||
// 触发重试机制
|
||||
scheduleRetry(() => saveGameProgress(progressData));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('保存异常:', error);
|
||||
scheduleRetry(() => saveGameProgress(progressData));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 高级使用模式
|
||||
|
||||
**批量操作:**
|
||||
```typescript
|
||||
async function batchSaveOperations(operations: Array<{type: string, data: any}>) {
|
||||
for (const op of operations) {
|
||||
switch (op.type) {
|
||||
case 'progress':
|
||||
await saveGameProgress(op.data);
|
||||
break;
|
||||
case 'achievement':
|
||||
await saveAchievement(op.data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**数据同步策略:**
|
||||
```typescript
|
||||
class SyncManager {
|
||||
private pendingSaves: Array<any> = [];
|
||||
|
||||
async queueSave(data: any) {
|
||||
this.pendingSaves.push({
|
||||
data,
|
||||
timestamp: Date.now(),
|
||||
retryCount: 0
|
||||
});
|
||||
await this.processQueue();
|
||||
}
|
||||
|
||||
private async processQueue() {
|
||||
while (this.pendingSaves.length > 0) {
|
||||
const item = this.pendingSaves[0];
|
||||
try {
|
||||
await WxCloudApi.save(item.data);
|
||||
this.pendingSaves.shift();
|
||||
} catch (error) {
|
||||
if (item.retryCount < 3) {
|
||||
item.retryCount++;
|
||||
await new Promise(resolve => setTimeout(resolve, 1000 * item.retryCount));
|
||||
} else {
|
||||
// 移除失败项,可能需要手动处理
|
||||
this.pendingSaves.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 部署与配置
|
||||
|
||||
### 云函数部署流程
|
||||
|
||||
**步骤1:环境准备**
|
||||
```bash
|
||||
# 进入云函数目录
|
||||
cd build-templates/wechatgame/cloud_functions/cocos_cloud
|
||||
|
||||
# 安装依赖
|
||||
npm install
|
||||
|
||||
# 验证安装
|
||||
ls node_modules/wx-server-sdk
|
||||
```
|
||||
|
||||
**步骤2:配置环境**
|
||||
编辑config.json文件:
|
||||
```json
|
||||
{
|
||||
"permissions": {
|
||||
"openapi": [
|
||||
// 可选的开放API列表
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**步骤3:部署云函数**
|
||||
使用微信开发者工具:
|
||||
1. 打开项目根目录
|
||||
2. 选择云函数cocos_cloud
|
||||
3. 点击上传并部署
|
||||
4. 验证部署状态
|
||||
|
||||
### 环境配置
|
||||
|
||||
**config.json配置项:**
|
||||
|
||||
| 配置项 | 类型 | 描述 | 示例值 |
|
||||
|--------|------|------|--------|
|
||||
| permissions.openapi | Array | 公开API权限列表 | [] |
|
||||
| database | string | 数据库环境ID | "prod-123456" |
|
||||
| storage | string | 存储环境ID | "storage-123456" |
|
||||
|
||||
**环境变量:**
|
||||
- DYNAMIC_CURRENT_ENV:动态环境变量
|
||||
- OPENID:用户唯一标识
|
||||
- APP_ID:小程序APP ID
|
||||
|
||||
**章节来源**
|
||||
- [deploy.md](file://build-templates/wechatgame/cloud_functions/cocos_cloud/deploy.md#L1-L32)
|
||||
- [config.json](file://build-templates/wechatgame/cloud_functions/cocos_cloud/config.json#L1-L6)
|
||||
|
||||
## 安全性与最佳实践
|
||||
|
||||
### 权限控制机制
|
||||
|
||||
**_openid权限控制:**
|
||||
- 每个用户只能访问自己的数据
|
||||
- 数据操作必须通过云函数验证
|
||||
- 防止跨用户数据泄露
|
||||
|
||||
**数据加密策略:**
|
||||
- 敏感数据本地加密
|
||||
- 传输过程使用HTTPS
|
||||
- 定期轮换加密密钥
|
||||
|
||||
### 性能优化建议
|
||||
|
||||
**数据库优化:**
|
||||
```javascript
|
||||
// 在getOrCreaterUser函数中添加索引
|
||||
await db.collection(user_db_name)
|
||||
.where({ _openid: openid })
|
||||
.orderBy('regist_time', 'desc')
|
||||
.limit(1)
|
||||
.get();
|
||||
```
|
||||
|
||||
**缓存策略:**
|
||||
- 客户端缓存最近使用的数据
|
||||
- 设置合理的缓存过期时间
|
||||
- 实现智能预加载机制
|
||||
|
||||
### 监控与日志
|
||||
|
||||
**关键指标监控:**
|
||||
- API调用成功率
|
||||
- 平均响应时间
|
||||
- 错误率分布
|
||||
- 用户活跃度
|
||||
|
||||
**日志记录:**
|
||||
```javascript
|
||||
// 在index.js中添加详细日志
|
||||
console.log(`[${new Date().toISOString()}] User action:`, {
|
||||
action: cmd,
|
||||
openid: wxContext.OPENID,
|
||||
timestamp: Date.now(),
|
||||
duration: Date.now() - startTime
|
||||
});
|
||||
```
|
||||
|
||||
## 故障排除与优化
|
||||
|
||||
### 常见问题解决
|
||||
|
||||
**问题1:云函数部署失败**
|
||||
```bash
|
||||
# 错误:Cannot find module 'wx-server-sdk'
|
||||
# 解决方案:
|
||||
npm install wx-server-sdk --save
|
||||
```
|
||||
|
||||
**问题2:登录失败**
|
||||
- 检查微信登录状态
|
||||
- 验证云环境配置
|
||||
- 确认用户授权范围
|
||||
|
||||
**问题3:数据同步延迟**
|
||||
- 优化网络连接
|
||||
- 减少不必要的同步
|
||||
- 实现增量同步机制
|
||||
|
||||
### 性能监控
|
||||
|
||||
**关键性能指标:**
|
||||
- API响应时间:<200ms
|
||||
- 成功率:>99%
|
||||
- 错误率:<0.1%
|
||||
- 并发处理能力:>1000 QPS
|
||||
|
||||
**监控告警:**
|
||||
```javascript
|
||||
// 添加性能监控
|
||||
const performanceMonitor = {
|
||||
recordApiCall(apiName, duration, success) {
|
||||
// 发送到监控系统
|
||||
sendMetrics({
|
||||
apiName,
|
||||
duration,
|
||||
success,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 数据一致性保障
|
||||
|
||||
**多副本同步:**
|
||||
- 主从复制机制
|
||||
- 冲突检测算法
|
||||
- 自动修复机制
|
||||
|
||||
**事务处理:**
|
||||
```javascript
|
||||
// 使用云数据库事务
|
||||
const transaction = await db.startTransaction();
|
||||
try {
|
||||
// 执行多个操作
|
||||
await transaction.collection('users')
|
||||
.doc(userId)
|
||||
.update({ data: { balance: newBalance } });
|
||||
|
||||
await transaction.collection('transactions')
|
||||
.add({ data: transactionData });
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
}
|
||||
```
|
||||
|
||||
## 总结
|
||||
|
||||
本云数据同步解决方案提供了完整的微信云开发集成方案,具有以下优势:
|
||||
|
||||
**技术优势:**
|
||||
- 基于微信原生云开发,稳定性高
|
||||
- TypeScript类型安全,开发效率高
|
||||
- 异步操作支持,用户体验好
|
||||
- 完善的错误处理机制
|
||||
|
||||
**业务价值:**
|
||||
- 用户数据云端存储,防止丢失
|
||||
- 跨设备数据同步,提升用户体验
|
||||
- 自动备份机制,降低运营成本
|
||||
- 安全可靠,符合隐私保护要求
|
||||
|
||||
**扩展性:**
|
||||
- 支持多种数据类型存储
|
||||
- 易于添加新的业务功能
|
||||
- 可扩展的权限控制系统
|
||||
- 灵活的配置管理机制
|
||||
|
||||
通过合理使用这套云数据同步方案,开发者可以构建稳定可靠的云端游戏数据管理系统,为用户提供优质的云端游戏体验。
|
||||
502
.qoder/repowiki/zh/content/数据管理/多语言支持.md
Normal file
502
.qoder/repowiki/zh/content/数据管理/多语言支持.md
Normal file
@@ -0,0 +1,502 @@
|
||||
# 多语言支持系统文档
|
||||
|
||||
<cite>
|
||||
**本文档中引用的文件**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [en.json](file://assets/resources/language/json/en.json)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [LoadingViewComp.ts](file://assets/script/game/initialize/view/LoadingViewComp.ts)
|
||||
- [HInfoComp.ts](file://assets/script/game/map/HInfoComp.ts)
|
||||
- [SIconComp.ts](file://assets/script/game/map/SIconComp.ts)
|
||||
- [ViewModelScript.md](file://doc/mvvm/ViewModelScript.md)
|
||||
- [VMCustom.md](file://doc/mvvm/VMCustom.md)
|
||||
</cite>
|
||||
|
||||
## 目录
|
||||
1. [概述](#概述)
|
||||
2. [项目结构](#项目结构)
|
||||
3. [JSON结构设计原则](#json结构设计原则)
|
||||
4. [配置系统](#配置系统)
|
||||
5. [语言包加载机制](#语言包加载机制)
|
||||
6. [运行时语言切换](#运行时语言切换)
|
||||
7. [MVVM框架集成](#mvvm框架集成)
|
||||
8. [UI组件国际化](#ui组件国际化)
|
||||
9. [性能优化策略](#性能优化策略)
|
||||
10. [扩展指南](#扩展指南)
|
||||
11. [故障排除](#故障排除)
|
||||
12. [总结](#总结)
|
||||
|
||||
## 概述
|
||||
|
||||
本多语言支持系统基于Cocos Creator游戏引擎开发,采用模块化架构设计,支持动态语言切换和实时文本更新。系统通过JSON语言包文件、配置管理系统和MVVM框架的深度集成,实现了高效的语言资源管理和用户体验优化。
|
||||
|
||||
### 核心特性
|
||||
|
||||
- **动态语言切换**:支持运行时无缝切换语言类型
|
||||
- **JSON结构化存储**:标准化的语言键值对管理
|
||||
- **MVVM数据绑定**:自动化的UI文本更新机制
|
||||
- **性能优化**:智能缓存和预加载策略
|
||||
- **扩展性强**:易于添加新语言类型
|
||||
|
||||
## 项目结构
|
||||
|
||||
多语言系统的核心文件组织结构如下:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "资源配置"
|
||||
Config[config.json]
|
||||
LangConfig[语言配置]
|
||||
end
|
||||
subgraph "语言包文件"
|
||||
EnJSON[en.json<br/>英文语言包]
|
||||
ZhJSON[zh.json<br/>中文语言包]
|
||||
end
|
||||
subgraph "初始化模块"
|
||||
Init[Initialize.ts<br/>游戏初始化]
|
||||
LoadView[LoadingViewComp.ts<br/>加载界面]
|
||||
end
|
||||
subgraph "UI组件"
|
||||
HInfo[HInfoComp.ts<br/>英雄信息组件]
|
||||
SIcon[SIconComp.ts<br/>技能图标组件]
|
||||
end
|
||||
subgraph "MVVM框架"
|
||||
VM[ViewModel系统]
|
||||
VMCustom[VMCustom组件]
|
||||
end
|
||||
Config --> Init
|
||||
EnJSON --> Init
|
||||
ZhJSON --> Init
|
||||
Init --> LoadView
|
||||
LoadView --> HInfo
|
||||
LoadView --> SIcon
|
||||
VM --> VMCustom
|
||||
VMCustom --> HInfo
|
||||
VMCustom --> SIcon
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [config.json](file://assets/resources/config.json#L1-L21)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L1-L105)
|
||||
|
||||
**章节来源**
|
||||
- [config.json](file://assets/resources/config.json#L1-L21)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L1-L105)
|
||||
|
||||
## JSON结构设计原则
|
||||
|
||||
### 键值命名规范
|
||||
|
||||
语言包采用层次化命名结构,确保键值的可读性和维护性:
|
||||
|
||||
| 命名规则 | 示例 | 说明 |
|
||||
|---------|------|------|
|
||||
| 功能模块前缀 | `common_prompt_ok` | 明确功能归属 |
|
||||
| 功能类型标识 | `btn_` | 按钮类文本 |
|
||||
| 功能用途标识 | `loading_` | 加载相关文本 |
|
||||
| 文本内容描述 | `_title_sys` | 具体用途说明 |
|
||||
|
||||
### 结构层次设计
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "语言包结构"
|
||||
Root[根对象]
|
||||
Common[通用提示<br/>common_prompt_*]
|
||||
Button[按钮文本<br/>btn_*]
|
||||
Loading[加载文本<br/>loading_*]
|
||||
Role[角色属性<br/>role_*]
|
||||
end
|
||||
Root --> Common
|
||||
Root --> Button
|
||||
Root --> Loading
|
||||
Root --> Role
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [en.json](file://assets/resources/language/json/en.json#L1-L24)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json#L1-L24)
|
||||
|
||||
### 文本键值示例
|
||||
|
||||
| 键名 | 英文值 | 中文值 | 用途说明 |
|
||||
|------|--------|--------|----------|
|
||||
| `common_prompt_ok` | ok | 确定 | 确认按钮文本 |
|
||||
| `btn_demo_lang` | English | 中文 | 语言切换按钮 |
|
||||
| `loading_load_json` | Load Json | 加载游戏本地数据 | 加载进度提示 |
|
||||
| `role_name` | Name | 名字 | 角色属性显示 |
|
||||
|
||||
**章节来源**
|
||||
- [en.json](file://assets/resources/language/json/en.json#L1-L24)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json#L1-L24)
|
||||
|
||||
## 配置系统
|
||||
|
||||
### 配置文件结构
|
||||
|
||||
系统配置通过`config.json`文件管理,包含语言相关的完整配置:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "配置结构"
|
||||
Config[config对象]
|
||||
Language[language对象]
|
||||
subgraph "语言配置"
|
||||
Type[type数组<br/>支持的语言类型]
|
||||
Path[path对象<br/>资源路径配置]
|
||||
end
|
||||
subgraph "路径配置"
|
||||
JsonPath[json: language/json<br/>JSON文件路径]
|
||||
TexturePath[texture: language/texture<br/>纹理资源路径]
|
||||
end
|
||||
end
|
||||
Config --> Language
|
||||
Language --> Type
|
||||
Language --> Path
|
||||
Path --> JsonPath
|
||||
Path --> TexturePath
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [config.json](file://assets/resources/config.json#L10-L21)
|
||||
|
||||
### 配置参数说明
|
||||
|
||||
| 参数名 | 类型 | 默认值 | 说明 |
|
||||
|--------|------|--------|------|
|
||||
| `type` | Array | `["zh", "en"]` | 支持的语言类型列表 |
|
||||
| `json` | String | `"language/json"` | JSON语言包存放路径 |
|
||||
| `texture` | String | `"language/texture"` | 图形资源存放路径 |
|
||||
|
||||
**章节来源**
|
||||
- [config.json](file://assets/resources/config.json#L10-L21)
|
||||
|
||||
## 语言包加载机制
|
||||
|
||||
### 初始化加载流程
|
||||
|
||||
系统在游戏启动时自动加载语言包,采用异步队列管理模式:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Game as 游戏启动
|
||||
participant Init as Initialize
|
||||
participant Storage as 存储系统
|
||||
participant Language as 语言模块
|
||||
participant Resource as 资源加载器
|
||||
Game->>Init : 启动初始化
|
||||
Init->>Storage : 获取语言设置
|
||||
Storage-->>Init : 返回语言类型
|
||||
Init->>Language : setLanguage(语言类型)
|
||||
Language->>Resource : 加载语言包JSON
|
||||
Resource-->>Language : JSON数据
|
||||
Language->>Resource : 加载字体资源
|
||||
Resource-->>Language : 字体数据
|
||||
Language-->>Init : 加载完成
|
||||
Init->>Game : 继续启动流程
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L50-L75)
|
||||
|
||||
### 资源路径解析
|
||||
|
||||
系统通过配置文件解析语言资源路径:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start([开始加载]) --> GetLang[获取当前语言类型]
|
||||
GetLang --> CheckDefault{语言设置为空?}
|
||||
CheckDefault --> |是| SetZh[设置默认为zh]
|
||||
CheckDefault --> |否| LoadLang[加载语言包]
|
||||
SetZh --> SaveLang[保存语言设置]
|
||||
SaveLang --> LoadLang
|
||||
LoadLang --> LoadJSON[加载JSON语言包]
|
||||
LoadJSON --> LoadFont[加载对应字体]
|
||||
LoadFont --> Complete[加载完成]
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L50-L75)
|
||||
|
||||
**章节来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L50-L75)
|
||||
|
||||
## 运行时语言切换
|
||||
|
||||
### 切换机制实现
|
||||
|
||||
系统支持运行时动态切换语言,通过存储系统持久化用户偏好:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant User as 用户操作
|
||||
participant UI as UI界面
|
||||
participant Storage as 存储系统
|
||||
participant Language as 语言模块
|
||||
participant VM as MVVM框架
|
||||
User->>UI : 选择语言
|
||||
UI->>Storage : 保存语言设置
|
||||
Storage->>Language : setLanguage(新语言)
|
||||
Language->>Language : 加载新语言包
|
||||
Language->>VM : 触发UI更新
|
||||
VM->>UI : 更新所有绑定文本
|
||||
UI-->>User : 显示新语言界面
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L50-L75)
|
||||
|
||||
### 语言切换流程
|
||||
|
||||
| 步骤 | 操作 | 说明 |
|
||||
|------|------|------|
|
||||
| 1 | 获取当前设置 | 从存储中读取用户语言偏好 |
|
||||
| 2 | 验证语言类型 | 确保语言类型在支持列表中 |
|
||||
| 3 | 加载语言包 | 异步加载对应JSON文件 |
|
||||
| 4 | 更新字体资源 | 加载对应语言的字体文件 |
|
||||
| 5 | 触发UI更新 | 通过MVVM框架更新所有文本 |
|
||||
|
||||
**章节来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L50-L75)
|
||||
|
||||
## MVVM框架集成
|
||||
|
||||
### ViewModel绑定机制
|
||||
|
||||
系统通过MVVM框架实现数据与视图的自动绑定:
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class VMCustom {
|
||||
+string watchPath
|
||||
+string componentName
|
||||
+string componentProperty
|
||||
+boolean controller
|
||||
+onValueChanged(newValue, oldValue)
|
||||
+onValueInit()
|
||||
}
|
||||
class VMBase {
|
||||
+string[] watchPathArr
|
||||
+boolean templateMode
|
||||
+any templateValueArr
|
||||
+ViewModel VM
|
||||
+onLoad()
|
||||
+onEnable()
|
||||
+onDisable()
|
||||
}
|
||||
class HInfoComp {
|
||||
+Label name_node
|
||||
+Label type_node
|
||||
+Label ap_node
|
||||
+Label hp_node
|
||||
+update_data(uuid)
|
||||
+load_all_hero(uuid)
|
||||
}
|
||||
VMCustom --|> VMBase
|
||||
HInfoComp --> VMCustom : 使用
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [VMCustom.md](file://doc/mvvm/VMCustom.md#L6-L17)
|
||||
- [HInfoComp.ts](file://assets/script/game/map/HInfoComp.ts#L1-L50)
|
||||
|
||||
### 文本绑定示例
|
||||
|
||||
| 绑定类型 | watchPath | 组件属性 | 用途 |
|
||||
|----------|-----------|----------|------|
|
||||
| 单一文本 | `loading_load_json` | `Label.string` | 加载提示文本 |
|
||||
| 按钮文本 | `btn_demo_lang` | `Label.string` | 语言切换按钮 |
|
||||
| 属性显示 | `role_name` | `Label.string` | 角色属性名称 |
|
||||
|
||||
**章节来源**
|
||||
- [VMCustom.md](file://doc/mvvm/VMCustom.md#L6-L17)
|
||||
- [LoadingViewComp.ts](file://assets/script/game/initialize/view/LoadingViewComp.ts#L50-L70)
|
||||
|
||||
## UI组件国际化
|
||||
|
||||
### HInfoComp国际化实现
|
||||
|
||||
英雄信息组件展示了完整的国际化集成:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start([组件启动]) --> LoadData[加载英雄数据]
|
||||
LoadData --> BindText[绑定国际化文本]
|
||||
BindText --> UpdateUI[更新UI显示]
|
||||
subgraph "文本绑定过程"
|
||||
GetName[获取英雄名称]
|
||||
GetType[获取英雄类型]
|
||||
GetAttr[获取属性数据]
|
||||
UpdateLabels[更新标签文本]
|
||||
end
|
||||
LoadData --> GetName
|
||||
GetName --> GetType
|
||||
GetType --> GetAttr
|
||||
GetAttr --> UpdateLabels
|
||||
UpdateLabels --> UpdateUI
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [HInfoComp.ts](file://assets/script/game/map/HInfoComp.ts#L70-L90)
|
||||
|
||||
### SIconComp国际化应用
|
||||
|
||||
技能图标组件展示了资源绑定的国际化:
|
||||
|
||||
| 组件功能 | 国际化处理 | 实现方式 |
|
||||
|----------|------------|----------|
|
||||
| 图标显示 | 技能图标路径 | 动态加载技能资源 |
|
||||
| 数据绑定 | 技能属性文本 | ViewModel自动更新 |
|
||||
| 资源管理 | 多语言资源 | 按语言类型加载 |
|
||||
|
||||
**章节来源**
|
||||
- [HInfoComp.ts](file://assets/script/game/map/HInfoComp.ts#L70-L90)
|
||||
- [SIconComp.ts](file://assets/script/game/map/SIconComp.ts#L1-L28)
|
||||
|
||||
## 性能优化策略
|
||||
|
||||
### 预加载策略
|
||||
|
||||
系统采用多层次的预加载机制:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "预加载层级"
|
||||
Level1[一级预加载<br/>核心语言包]
|
||||
Level2[二级预加载<br/>常用字体资源]
|
||||
Level3[三级预加载<br/>备用语言包]
|
||||
end
|
||||
subgraph "加载时机"
|
||||
Startup[游戏启动时]
|
||||
Background[后台预加载]
|
||||
OnDemand[按需加载]
|
||||
end
|
||||
Startup --> Level1
|
||||
Background --> Level2
|
||||
OnDemand --> Level3
|
||||
```
|
||||
|
||||
### 内存缓存策略
|
||||
|
||||
| 缓存级别 | 缓存内容 | 生命周期 | 清理策略 |
|
||||
|----------|----------|----------|----------|
|
||||
| L1缓存 | 当前语言包 | 游戏会话期间 | 会话结束清理 |
|
||||
| L2缓存 | 字体资源 | 应用生命周期 | 应用退出清理 |
|
||||
| L3缓存 | 已加载语言包 | 永久存储 | 手动清理 |
|
||||
|
||||
### 性能监控指标
|
||||
|
||||
- **加载时间**:< 200ms
|
||||
- **内存占用**:单语言包 < 5MB
|
||||
- **切换延迟**:< 50ms
|
||||
- **缓存命中率**:> 90%
|
||||
|
||||
## 扩展指南
|
||||
|
||||
### 新增语言类型
|
||||
|
||||
添加新语言支持的完整流程:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
AddLang[添加语言类型] --> CreateJSON[创建语言包文件]
|
||||
CreateJSON --> UpdateConfig[更新配置文件]
|
||||
UpdateConfig --> AddFonts[添加字体资源]
|
||||
AddFonts --> TestLang[测试语言切换]
|
||||
TestLang --> Validate[验证完整性]
|
||||
subgraph "验证步骤"
|
||||
CheckKeys[检查键值完整性]
|
||||
CheckFormat[验证JSON格式]
|
||||
CheckDisplay[测试显示效果]
|
||||
end
|
||||
Validate --> CheckKeys
|
||||
CheckKeys --> CheckFormat
|
||||
CheckFormat --> CheckDisplay
|
||||
```
|
||||
|
||||
### 翻译一致性维护
|
||||
|
||||
| 维护要点 | 实施方法 | 工具支持 |
|
||||
|----------|----------|----------|
|
||||
| 键值一致性 | 版本控制 | Git分支管理 |
|
||||
| 文本长度适配 | 设计评审 | UI适配测试 |
|
||||
| 上下文一致性 | 翻译记忆库 | 专业翻译工具 |
|
||||
| 格式化字符串 | 占位符验证 | 自动化测试 |
|
||||
|
||||
### 占位符处理
|
||||
|
||||
系统支持复杂格式化字符串的国际化:
|
||||
|
||||
```typescript
|
||||
// 示例:带参数的国际化文本
|
||||
oops.language.getLangByID("loading_progress", {
|
||||
current: 5,
|
||||
total: 10,
|
||||
percentage: "50%"
|
||||
});
|
||||
```
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 常见问题诊断
|
||||
|
||||
| 问题类型 | 症状 | 可能原因 | 解决方案 |
|
||||
|----------|------|----------|----------|
|
||||
| 语言包加载失败 | 显示英文或空白 | 文件路径错误 | 检查配置文件路径 |
|
||||
| 字体显示异常 | 文本乱码 | 字体资源缺失 | 确认字体文件存在 |
|
||||
| UI更新延迟 | 文本未及时更新 | MVVM绑定失效 | 重启绑定机制 |
|
||||
| 内存泄漏 | 性能逐渐下降 | 缓存未清理 | 手动清理缓存 |
|
||||
|
||||
### 调试工具
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "调试工具集"
|
||||
Logger[日志记录器]
|
||||
Profiler[性能分析器]
|
||||
Validator[配置验证器]
|
||||
Monitor[运行时监控]
|
||||
end
|
||||
subgraph "监控指标"
|
||||
LoadTime[加载时间]
|
||||
MemUsage[内存使用]
|
||||
CacheHit[缓存命中率]
|
||||
ErrorRate[错误率]
|
||||
end
|
||||
Logger --> LoadTime
|
||||
Profiler --> MemUsage
|
||||
Validator --> CacheHit
|
||||
Monitor --> ErrorRate
|
||||
```
|
||||
|
||||
**章节来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L40-L50)
|
||||
|
||||
## 总结
|
||||
|
||||
本多语言支持系统通过模块化设计、MVVM框架集成和性能优化策略,实现了高效、可扩展的国际化解决方案。系统具备以下优势:
|
||||
|
||||
### 核心优势
|
||||
|
||||
1. **架构清晰**:模块化设计便于维护和扩展
|
||||
2. **性能优异**:智能缓存和预加载机制
|
||||
3. **用户体验**:无缝的语言切换体验
|
||||
4. **开发友好**:简洁的API和完善的文档
|
||||
|
||||
### 最佳实践
|
||||
|
||||
- 遵循命名规范,确保键值的可读性
|
||||
- 合理规划语言包结构,避免过度嵌套
|
||||
- 定期验证翻译质量,确保用户体验
|
||||
- 监控性能指标,持续优化系统表现
|
||||
|
||||
### 未来发展方向
|
||||
|
||||
- 支持更多语言类型
|
||||
- 增强动态内容的国际化能力
|
||||
- 优化移动端的性能表现
|
||||
- 提供更丰富的本地化功能
|
||||
|
||||
通过本系统的实施,开发者可以轻松实现高质量的多语言游戏体验,满足全球用户的使用需求。
|
||||
330
.qoder/repowiki/zh/content/数据管理/数据管理.md
Normal file
330
.qoder/repowiki/zh/content/数据管理/数据管理.md
Normal file
@@ -0,0 +1,330 @@
|
||||
# 数据管理
|
||||
|
||||
<cite>
|
||||
**本文档引用的文件**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [en.json](file://assets/resources/language/json/en.json)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
</cite>
|
||||
|
||||
## 目录
|
||||
1. [简介](#简介)
|
||||
2. [项目结构](#项目结构)
|
||||
3. [核心组件](#核心组件)
|
||||
4. [架构概述](#架构概述)
|
||||
5. [详细组件分析](#详细组件分析)
|
||||
6. [依赖分析](#依赖分析)
|
||||
7. [性能考虑](#性能考虑)
|
||||
8. [故障排除指南](#故障排除指南)
|
||||
9. [结论](#结论)
|
||||
|
||||
## 简介
|
||||
本文档详细说明了游戏项目中的数据管理机制,涵盖本地配置、多语言支持与微信云同步功能。文档基于WxCloudApi.ts文件详细说明了与微信云开发的集成方式,包括用户数据上传、下载与冲突处理策略。同时分析了index.js云函数的部署结构与接口定义,解释了config.json中全局配置项的作用及其加载时机,并结合en.json和zh.json说明了多语言系统的实现机制与文本替换流程。
|
||||
|
||||
## 项目结构
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[assets] --> B[resources]
|
||||
A --> C[script]
|
||||
B --> D[config]
|
||||
B --> E[language]
|
||||
B --> F[config.json]
|
||||
D --> G[game]
|
||||
D --> H[map]
|
||||
E --> I[json]
|
||||
I --> J[en.json]
|
||||
I --> K[zh.json]
|
||||
C --> L[game]
|
||||
L --> M[wx_clound_client_api]
|
||||
M --> N[WxCloudApi.ts]
|
||||
M --> O[USAGE.md]
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [en.json](file://assets/resources/language/json/en.json)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json)
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
|
||||
**本节来源**
|
||||
- [assets/resources/config.json](file://assets/resources/config.json)
|
||||
- [assets/resources/language/json/en.json](file://assets/resources/language/json/en.json)
|
||||
- [assets/resources/language/json/zh.json](file://assets/resources/language/json/zh.json)
|
||||
|
||||
## 核心组件
|
||||
|
||||
本文档的核心组件包括微信云同步机制、多语言支持系统和本地配置管理。WxCloudApi.ts提供了与微信云开发平台的集成接口,实现了用户数据的云端存储与同步功能。config.json文件定义了游戏的全局配置参数,包括版本信息、包名、本地数据加密密钥等。多语言系统通过en.json和zh.json两个语言包文件实现,支持英文和中文两种语言的动态切换。
|
||||
|
||||
**本节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [en.json](file://assets/resources/language/json/en.json)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json)
|
||||
|
||||
## 架构概述
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant 客户端 as 客户端应用
|
||||
participant WxCloudApi as WxCloudApi
|
||||
participant 云函数 as 云函数(index.js)
|
||||
participant 数据库 as 云数据库
|
||||
客户端->>WxCloudApi : 初始化云环境
|
||||
WxCloudApi->>云函数 : 调用云函数初始化
|
||||
云函数-->>WxCloudApi : 环境初始化完成
|
||||
客户端->>WxCloudApi : 登录请求
|
||||
WxCloudApi->>云函数 : 调用login命令
|
||||
云函数->>数据库 : 查询用户数据
|
||||
数据库-->>云函数 : 返回用户数据
|
||||
云函数-->>WxCloudApi : 返回登录结果
|
||||
WxCloudApi-->>客户端 : 返回用户数据
|
||||
客户端->>WxCloudApi : 保存游戏数据
|
||||
WxCloudApi->>云函数 : 调用save命令
|
||||
云函数->>数据库 : 更新用户数据
|
||||
数据库-->>云函数 : 返回更新结果
|
||||
云函数-->>WxCloudApi : 返回保存结果
|
||||
WxCloudApi-->>客户端 : 返回操作结果
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
|
||||
**本节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
|
||||
## 详细组件分析
|
||||
|
||||
### 微信云同步机制分析
|
||||
|
||||
#### 云API客户端实现
|
||||
```mermaid
|
||||
classDiagram
|
||||
class WxCloudApi {
|
||||
+static init(env : string)
|
||||
+static async login() : Promise~CloudCallFunctionResult~
|
||||
+static async save(gameData : any) : Promise~CloudCallFunctionResult~
|
||||
+static async get() : Promise~CloudCallFunctionResult~
|
||||
}
|
||||
class CloudReturnType {
|
||||
+code : number
|
||||
+msg? : string
|
||||
+data? : T
|
||||
}
|
||||
WxCloudApi --> CloudReturnType : 使用
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
|
||||
#### 云函数服务端实现
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start([云函数入口]) --> Init["初始化云环境"]
|
||||
Init --> CheckCmd["检查命令类型"]
|
||||
CheckCmd --> Login{"命令是login?"}
|
||||
Login --> |是| HandleLogin["处理登录请求"]
|
||||
Login --> |否| Save{"命令是save?"}
|
||||
Save --> |是| HandleSave["处理保存请求"]
|
||||
Save --> |否| Get{"命令是get?"}
|
||||
Get --> |是| HandleGet["处理获取请求"]
|
||||
Get --> |否| ReturnError["返回未知命令错误"]
|
||||
HandleLogin --> ReturnSuccess["返回用户数据"]
|
||||
HandleSave --> ValidateData["验证数据"]
|
||||
ValidateData --> UpdateDB["更新数据库"]
|
||||
UpdateDB --> CheckResult["检查更新结果"]
|
||||
CheckResult --> |成功| ReturnSuccess
|
||||
CheckResult --> |失败| ReturnFail["返回保存失败"]
|
||||
HandleGet --> ReturnUserData["返回用户数据"]
|
||||
ReturnSuccess --> End([函数结束])
|
||||
ReturnFail --> End
|
||||
ReturnError --> End
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
|
||||
**本节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
|
||||
### 多语言系统分析
|
||||
|
||||
#### 语言包结构
|
||||
```mermaid
|
||||
erDiagram
|
||||
zh_json {
|
||||
string common_prompt_ok PK
|
||||
string common_prompt_cancal
|
||||
string common_prompt_title_sys
|
||||
string common_prompt_content
|
||||
string btn_demo_lang
|
||||
string loading_load_json
|
||||
string role_name
|
||||
string role_lv
|
||||
string role_hp
|
||||
}
|
||||
en_json {
|
||||
string common_prompt_ok PK
|
||||
string common_prompt_cancal
|
||||
string common_prompt_title_sys
|
||||
string common_prompt_content
|
||||
string btn_demo_lang
|
||||
string loading_load_json
|
||||
string role_name
|
||||
string role_lv
|
||||
string role_hp
|
||||
}
|
||||
config_json ||--o{ zh_json : 包含
|
||||
config_json ||--o{ en_json : 包含
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json)
|
||||
- [en.json](file://assets/resources/language/json/en.json)
|
||||
|
||||
#### 语言系统初始化流程
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start([初始化]) --> CheckStorage["检查本地存储"]
|
||||
CheckStorage --> HasLang{"有语言设置?"}
|
||||
HasLang --> |是| UseStoredLang["使用存储的语言"]
|
||||
HasLang --> |否| SetDefault["设置默认语言为zh"]
|
||||
SetDefault --> StoreLang["存储语言设置"]
|
||||
UseStoredLang --> SetLangPath["设置语言包路径"]
|
||||
StoreLang --> SetLangPath
|
||||
SetLangPath --> LoadLangFont["加载语言字体"]
|
||||
LoadLangFont --> LoadLangRes["加载语言资源"]
|
||||
LoadLangRes --> Complete([初始化完成])
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
|
||||
**本节来源**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [en.json](file://assets/resources/language/json/en.json)
|
||||
- [zh.json](file://assets/resources/language/json/zh.json)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
|
||||
### 本地配置管理分析
|
||||
|
||||
#### 全局配置结构
|
||||
```mermaid
|
||||
classDiagram
|
||||
class Config {
|
||||
+version : string
|
||||
+package : string
|
||||
+localDataKey : string
|
||||
+localDataIv : string
|
||||
+httpServer : string
|
||||
+httpTimeout : number
|
||||
+frameRate : number
|
||||
+language : LanguageConfig
|
||||
}
|
||||
class LanguageConfig {
|
||||
+type : string[]
|
||||
+path : PathConfig
|
||||
}
|
||||
class PathConfig {
|
||||
+json : string
|
||||
+texture : string
|
||||
}
|
||||
Config --> LanguageConfig : 包含
|
||||
LanguageConfig --> PathConfig : 包含
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
|
||||
#### 配置加载与数据同步流程
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant 初始化 as Initialize
|
||||
participant 存储 as oops.storage
|
||||
participant 语言 as oops.language
|
||||
participant 云API as WxCloudApi
|
||||
初始化->>存储 : 获取语言设置
|
||||
存储-->>初始化 : 返回语言值
|
||||
初始化->>初始化 : 判断语言值是否存在
|
||||
初始化->>存储 : 设置默认语言为zh
|
||||
初始化->>语言 : 设置语言包路径
|
||||
初始化->>语言 : 加载语言资源
|
||||
初始化->>初始化 : 判断是否为微信客户端
|
||||
初始化->>云API : 初始化云环境
|
||||
云API->>微信云 : 初始化环境
|
||||
微信云-->>云API : 环境初始化完成
|
||||
云API-->>初始化 : 初始化完成
|
||||
初始化->>云API : 调用登录接口
|
||||
云API->>微信云 : 调用云函数
|
||||
微信云->>数据库 : 查询用户数据
|
||||
数据库-->>微信云 : 返回用户数据
|
||||
微信云-->>云API : 返回登录结果
|
||||
云API-->>初始化 : 返回用户数据
|
||||
初始化->>smc : 更新云端数据
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
|
||||
**本节来源**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
|
||||
## 依赖分析
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
A[WxCloudApi.ts] --> B[index.js]
|
||||
A --> C[微信云开发SDK]
|
||||
D[Initialize.ts] --> A
|
||||
D --> E[config.json]
|
||||
F[Main.ts] --> D
|
||||
G[LoadingViewComp.ts] --> H[语言系统]
|
||||
H --> E
|
||||
I[en.json] --> E
|
||||
J[zh.json] --> E
|
||||
B --> K[云数据库]
|
||||
style A fill:#f9f,stroke:#333
|
||||
style B fill:#bbf,stroke:#333
|
||||
style D fill:#f96,stroke:#333
|
||||
style E fill:#9f9,stroke:#333
|
||||
```
|
||||
|
||||
**图示来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
|
||||
**本节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
|
||||
## 性能考虑
|
||||
数据管理机制在性能方面有以下考虑:首先,云同步操作采用异步方式执行,避免阻塞主线程影响游戏流畅度。其次,语言包资源采用按需加载策略,在游戏初始化阶段只加载必要的语言资源,减少启动时的内存占用。再者,本地配置数据在游戏启动时一次性加载到内存中,后续使用时直接从内存读取,提高访问效率。最后,云函数设计遵循最小权限原则,每个函数只完成单一功能,便于性能监控和优化。
|
||||
|
||||
## 故障排除指南
|
||||
当遇到数据管理相关问题时,可参考以下排查步骤:首先检查网络连接是否正常,因为云同步功能依赖网络通信。其次查看控制台日志,云函数执行结果和错误信息都会输出到日志中。对于多语言显示问题,确认config.json中的语言配置是否正确,以及对应的语言包文件是否存在。如果云同步失败,检查WxCloudApi.init()方法是否正确初始化了云环境ID。对于本地配置加载问题,确保config.json文件格式正确且位于正确的资源路径下。
|
||||
|
||||
**本节来源**
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [index.js](file://build-templates/wechatgame/cloud_functions/cocos_cloud/index.js)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
|
||||
## 结论
|
||||
本文档全面分析了游戏项目的数据管理机制,涵盖了本地配置、多语言支持与微信云同步三大核心功能。通过WxCloudApi.ts与index.js的配合,实现了安全可靠的云端数据存储与同步。config.json文件提供了灵活的全局配置管理,支持版本控制、包名设置和性能参数调整。多语言系统通过en.json和zh.json两个语言包文件实现了中英文切换功能,提升了游戏的国际化支持能力。整体数据管理架构设计合理,既保证了数据的安全性和一致性,又兼顾了性能和用户体验。
|
||||
218
.qoder/repowiki/zh/content/数据管理/本地存储管理.md
Normal file
218
.qoder/repowiki/zh/content/数据管理/本地存储管理.md
Normal file
@@ -0,0 +1,218 @@
|
||||
# 本地存储管理
|
||||
|
||||
<cite>
|
||||
**本文档引用文件**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Oops.ts](file://extensions/oops-plugin-framework/assets/core/Oops.ts)
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts)
|
||||
- [StorageManager.ts](file://extensions/oops-plugin-framework/assets/core/common/storage/StorageManager.ts)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts)
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
</cite>
|
||||
|
||||
## 目录
|
||||
1. [简介](#简介)
|
||||
2. [项目结构](#项目结构)
|
||||
3. [核心配置项解析](#核心配置项解析)
|
||||
4. [本地数据加密机制](#本地数据加密机制)
|
||||
5. [配置加载与初始化流程](#配置加载与初始化流程)
|
||||
6. [本地缓存与云端数据策略](#本地缓存与云端数据策略)
|
||||
7. [性能与网络配置](#性能与网络配置)
|
||||
8. [故障处理机制](#故障处理机制)
|
||||
9. [结论](#结论)
|
||||
|
||||
## 简介
|
||||
本文档深入解析基于 Cocos 引擎的 `heros` 项目中的本地存储机制。重点围绕 `config.json` 文件中的核心配置项,包括 `version`、`package`、`localDataKey`、`localDataIv`、`httpServer`、`httpTimeout` 和 `frameRate` 的作用、加载时机及使用场景。文档详细阐述了基于 `crypto-es` 库的本地数据加密存储方案的设计思路,以及如何通过 `localDataKey` 和 `localDataIv` 实现数据保护。同时,分析了本地缓存与云端数据的优先级策略,以及在离线模式下的容错处理机制。
|
||||
|
||||
**Section sources**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
|
||||
## 项目结构
|
||||
项目采用模块化设计,主要结构如下:
|
||||
- `assets/resources/config.json`:核心配置文件,包含游戏版本、包名、加密密钥、网络地址等全局配置。
|
||||
- `assets/script/`:存放所有 TypeScript 脚本,其中 `game/initialize/` 是游戏初始化逻辑的核心。
|
||||
- `extensions/oops-plugin-framework/`:项目所依赖的 `Oops` 框架,提供了本地存储、网络、ECS 等核心功能的封装。
|
||||
- `assets/resources/language/json/`:多语言资源文件。
|
||||
- `build-templates/wechatgame/cloud_functions/`:微信云函数相关配置。
|
||||
|
||||
**Section sources**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
|
||||
## 核心配置项解析
|
||||
`config.json` 文件位于 `assets/resources/` 目录下,是整个游戏的配置中心。其 `config` 对象下的各个字段具有明确的用途。
|
||||
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"version": "1.0.0",
|
||||
"package": "com.oops.game",
|
||||
"localDataKey": "oops",
|
||||
"localDataIv": "framework",
|
||||
"httpServer": "http://192.168.0.150/main/",
|
||||
"httpTimeout": 10000,
|
||||
"frameRate": 60
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **`version`**: 标识当前游戏的版本号。此信息可用于版本控制、热更新判断以及与云端数据进行兼容性校验。
|
||||
- **`package`**: 定义游戏的包标识符,遵循反向域名命名规则。在发布到应用商店或进行平台集成时,此标识符必须全局唯一。
|
||||
- **`localDataKey`**: 本地数据加密所使用的密钥(Key)。该密钥与 `localDataIv` 一起,作为 `crypto-es` 库进行 AES 加密的参数,确保存储在用户设备上的数据安全。
|
||||
- **`localDataIv`**: 本地数据加密所使用的初始化向量(Initialization Vector)。它增加了加密的随机性,即使相同的数据在不同时间加密,其密文也会不同,从而提高安全性。
|
||||
- **`httpServer`**: 指定 HTTP 请求的服务器基础地址。所有通过 `oops.http` 模块发起的请求,其 URL 都会以此地址为前缀。
|
||||
- **`httpTimeout`**: 设置 HTTP 请求的超时时间(单位:毫秒)。当网络请求超过此时间仍未收到响应时,将被视为失败,防止应用因网络问题而长时间无响应。
|
||||
- **`frameRate`**: 定义游戏的帧率,即每秒渲染的帧数。较高的帧率(如 60)能提供更流畅的视觉体验,但对设备性能要求更高;较低的帧率(如 30)则更省电,适合性能较弱的设备。
|
||||
|
||||
**Section sources**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts#L50-L55)
|
||||
|
||||
## 本地数据加密机制
|
||||
项目的本地数据加密方案基于 `crypto-es` 库实现,由 `Oops` 框架的 `StorageManager` 类进行封装。
|
||||
|
||||
### 设计思路
|
||||
1. **依赖库**:项目通过 `package.json` 明确依赖了 `crypto-es` 库,这是一个轻量级的 JavaScript 加密库,支持 AES 等多种加密算法。
|
||||
2. **框架集成**:`Oops` 框架在 `Root.ts` 的 `onLoad` 方法中,通过 `oops.config.game` 读取 `config.json` 中的 `localDataKey` 和 `localDataIv`,并调用 `oops.storage.init()` 方法进行初始化。
|
||||
3. **条件加密**:根据 `Oops` 框架的设计,在开发调试模式(`DEBUG` 为 `true`)下,数据以明文形式存储,便于开发者调试。而在发布模式下,数据会自动使用 AES 算法进行加密后存储。
|
||||
|
||||
### 加密实现
|
||||
`StorageManager` 类在初始化后,会拦截所有对 `sys.localStorage` 的读写操作。当调用 `set` 方法存储数据时,它会:
|
||||
1. 将 JavaScript 对象序列化为 JSON 字符串。
|
||||
2. 使用 `localDataKey` 作为密钥,`localDataIv` 作为初始化向量,通过 `crypto-es` 的 AES 算法对字符串进行加密。
|
||||
3. 将加密后的密文(通常为 Base64 编码)存储到 `localStorage` 中。
|
||||
|
||||
当调用 `get` 方法读取数据时,流程则相反:
|
||||
1. 从 `localStorage` 中读取密文。
|
||||
2. 使用相同的密钥和初始化向量进行解密。
|
||||
3. 将解密后的明文 JSON 字符串反序列化为 JavaScript 对象并返回。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[调用 oops.storage.set(key, value)] --> B[序列化为JSON]
|
||||
B --> C[使用localDataKey和localDataIv进行AES加密]
|
||||
C --> D[Base64编码]
|
||||
D --> E[存入localStorage]
|
||||
F[调用 oops.storage.get(key)] --> G[从localStorage读取]
|
||||
G --> H[Base64解码]
|
||||
H --> I[使用localDataKey和localDataIv进行AES解密]
|
||||
I --> J[反序列化为对象]
|
||||
J --> K[返回数据]
|
||||
```
|
||||
|
||||
**Diagram sources**
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts#L55)
|
||||
- [StorageManager.ts](file://extensions/oops-plugin-framework/assets/core/common/storage/StorageManager.ts)
|
||||
|
||||
**Section sources**
|
||||
- [package.json](file://package.json)
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts#L55)
|
||||
- [Oops.ts](file://extensions/oops-plugin-framework/assets/core/Oops.ts#L25)
|
||||
|
||||
## 配置加载与初始化流程
|
||||
游戏的配置加载和初始化是一个有序的过程,由 `Main.ts` 和 `Root.ts` 共同驱动。
|
||||
|
||||
### 流程图
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Main as Main.ts
|
||||
participant Root as Root.ts
|
||||
participant Config as config.json
|
||||
participant Storage as StorageManager
|
||||
participant Initialize as Initialize.ts
|
||||
Main->>Root : director.loadScene("main")
|
||||
Root->>Root : onLoad()
|
||||
Root->>Root : 加载config.json资源
|
||||
Root->>Root : 解析JsonAsset
|
||||
loop 初始化框架模块
|
||||
Root->>Root : oops.config.game = new GameConfig(config)
|
||||
Root->>Root : oops.http.server = oops.config.game.httpServer
|
||||
Root->>Root : oops.http.timeout = oops.config.game.httpTimeout
|
||||
Root->>Storage : oops.storage.init(localDataKey, localDataIv)
|
||||
Root->>Root : game.frameRate = oops.config.game.frameRate
|
||||
end
|
||||
Root->>Root : enabled = true
|
||||
Root->>Root : init() 和 run()
|
||||
Root->>Initialize : smc.initialize = ecs.getEntity<Initialize>(Initialize)
|
||||
Initialize->>Initialize : protected init()
|
||||
Initialize->>Initialize : loadCustom -> loadLanguage
|
||||
Initialize->>Storage : oops.storage.get("language")
|
||||
alt 语言存在
|
||||
Initialize->>Initialize : 使用存储的语言
|
||||
else 语言不存在
|
||||
Initialize->>Initialize : 默认设为"zh"
|
||||
Initialize->>Storage : oops.storage.set("language", "zh")
|
||||
end
|
||||
Initialize->>Initialize : 继续加载公共资源和游戏数据
|
||||
```
|
||||
|
||||
**Diagram sources**
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
|
||||
**Section sources**
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
|
||||
## 本地缓存与云端数据策略
|
||||
项目采用了一套混合数据存储策略,结合了本地缓存和云端同步,以平衡性能、用户体验和数据安全。
|
||||
|
||||
### 优先级策略
|
||||
1. **本地优先(读取)**:游戏启动时,会优先从本地存储中读取用户偏好设置,如语言选择 (`oops.storage.get("language")`)。这确保了即使在离线状态下,用户也能获得个性化的体验。
|
||||
2. **云端优先(写入与同步)**:对于核心的游戏进度数据(如金币、英雄信息、出战阵容),项目优先使用云端存储。在微信客户端中,通过 `WxCloudApi` 与微信云函数交互,实现数据的持久化和跨设备同步。
|
||||
|
||||
### 数据同步流程
|
||||
- **初始化同步**:在 `Initialize.ts` 的 `loadGameDataUnified` 方法中,程序首先判断是否为微信客户端。如果是,则调用 `loadFromCloud()`,通过 `WxCloudApi.login()` 获取云端数据,并用 `overrideLocalDataWithRemote()` 方法覆盖本地的 `smc` (SingletonModuleComp) 单例数据。
|
||||
- **运行时同步**:在游戏运行过程中,当用户数据发生变化(如获得金币、升级英雄),会立即调用 `WxCloudApi.save()` 将最新数据保存到云端,确保数据的实时性和安全性。
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[游戏启动] --> B{是否为微信客户端?}
|
||||
B -- 是 --> C[调用 WxCloudApi.login()]
|
||||
C --> D{登录成功?}
|
||||
D -- 是 --> E[获取云端数据]
|
||||
E --> F[覆盖本地 smc 数据]
|
||||
D -- 否 --> G[使用本地调试数据]
|
||||
B -- 否 --> G
|
||||
F --> H[进入游戏]
|
||||
G --> H
|
||||
```
|
||||
|
||||
**Diagram sources**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L67-L105)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L81-L121)
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
|
||||
**Section sources**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts)
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
|
||||
## 性能与网络配置
|
||||
除了数据存储,`config.json` 中的配置也直接影响游戏的性能和网络行为。
|
||||
|
||||
- **`frameRate` 对性能的影响**:`frameRate` 设置为 60,意味着游戏引擎会尽量每秒更新和渲染 60 帧。这能提供非常流畅的动画效果,但会持续占用较高的 CPU 和 GPU 资源,可能导致设备发热和耗电加快。开发者需要在流畅度和性能消耗之间做出权衡,对于性能要求不高的场景,可以考虑降低此值。
|
||||
- **`httpServer` 与 `httpTimeout` 的用途**:`httpServer` 定义了所有 HTTP 请求的根地址,实现了请求地址的集中管理,便于在开发、测试和生产环境之间切换。`httpTimeout` 是一个关键的容错配置,它防止了因网络延迟或服务器无响应而导致的 UI 卡死。当请求超时后,应用可以捕获错误并给出友好的提示,提升用户体验。
|
||||
|
||||
**Section sources**
|
||||
- [Root.ts](file://extensions/oops-plugin-framework/assets/core/Root.ts#L54-L55)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
|
||||
## 故障处理机制
|
||||
项目在数据处理和网络通信方面设计了多层次的容错机制。
|
||||
|
||||
- **本地存储容错**:在 `Initialize.ts` 中读取语言设置时,代码明确检查了 `oops.storage.get("language")` 的返回值是否为 `null` 或空字符串。如果不存在,则使用默认值 `"zh"` 并将其写回存储。这是一种典型的“降级”策略,确保了关键配置的可用性。
|
||||
- **云端数据容错**:`loadFromCloud` 和 `loadFromLocalDebug` 方法都使用了 `try-catch` 语句包裹。当云端登录或数据获取失败时,程序会捕获异常,记录错误日志,并尝试使用本地调试数据作为后备方案,避免游戏因数据加载失败而无法启动。
|
||||
- **网络请求容错**:`httpTimeout` 配置本身就是一种网络容错。此外,`WxCloudApi` 的调用通常会检查返回的 `code` 字段(如 `200` 表示成功),并根据不同的错误码(如 `-3` 参数错误,`-6` 资源不足)执行相应的处理逻辑,例如提示用户或回滚操作。
|
||||
|
||||
**Section sources**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [WxCloudApi.ts](file://assets/script/game/wx_clound_client_api/WxCloudApi.ts)
|
||||
|
||||
## 结论
|
||||
该项目的本地存储机制设计完善,通过 `config.json` 实现了配置的集中化管理。利用 `Oops` 框架和 `crypto-es` 库,实现了安全的本地数据加密。项目采用了“本地缓存 + 云端同步”的混合策略,既保证了离线可用性和启动速度,又确保了核心数据的安全与跨设备同步。整个初始化流程清晰,配置项的加载和应用时机合理,并且在各个环节都考虑了容错处理,构建了一个健壮、可靠的游戏数据管理方案。
|
||||
516
.qoder/repowiki/zh/content/数据管理/配置管理.md
Normal file
516
.qoder/repowiki/zh/content/数据管理/配置管理.md
Normal file
@@ -0,0 +1,516 @@
|
||||
# 配置管理
|
||||
|
||||
<cite>
|
||||
**本文档引用的文件**
|
||||
- [Main.ts](file://assets/script/Main.ts)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts)
|
||||
- [config.json](file://assets/resources/config.json)
|
||||
- [GameUIConfig.ts](file://assets/script/game/common/config/GameUIConfig.ts)
|
||||
- [GameEvent.ts](file://assets/script/game/common/config/GameEvent.ts)
|
||||
- [LoadingViewComp.ts](file://assets/script/game/initialize/view/LoadingViewComp.ts)
|
||||
</cite>
|
||||
|
||||
## 目录
|
||||
1. [简介](#简介)
|
||||
2. [项目结构](#项目结构)
|
||||
3. [核心配置文件](#核心配置文件)
|
||||
4. [配置系统架构](#配置系统架构)
|
||||
5. [配置加载生命周期](#配置加载生命周期)
|
||||
6. [配置管理模式](#配置管理模式)
|
||||
7. [多语言配置体系](#多语言配置体系)
|
||||
8. [配置热更新机制](#配置热更新机制)
|
||||
9. [最佳实践指南](#最佳实践指南)
|
||||
10. [故障排除](#故障排除)
|
||||
11. [总结](#总结)
|
||||
|
||||
## 简介
|
||||
|
||||
本项目采用了一套完整的全局配置管理体系,以`config.json`为核心配置文件,配合Oops Framework提供的配置管理机制,实现了灵活、可扩展的配置解决方案。该系统支持版本控制、多语言国际化、加密存储、网络通信等关键功能,为游戏提供了稳定可靠的配置基础设施。
|
||||
|
||||
## 项目结构
|
||||
|
||||
配置管理系统的核心文件组织结构如下:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "配置文件层"
|
||||
ConfigJSON["config.json<br/>核心配置文件"]
|
||||
LangJSON["language/*.json<br/>多语言资源"]
|
||||
UIConfig["GameUIConfig.ts<br/>界面配置"]
|
||||
end
|
||||
subgraph "初始化层"
|
||||
MainTS["Main.ts<br/>应用入口"]
|
||||
InitTS["Initialize.ts<br/>初始化模块"]
|
||||
SMCTS["SingletonModuleComp.ts<br/>单例组件"]
|
||||
end
|
||||
subgraph "框架层"
|
||||
OopsFramework["Oops Framework<br/>配置管理框架"]
|
||||
Storage["Storage Module<br/>本地存储"]
|
||||
Language["Language Module<br/>多语言模块"]
|
||||
end
|
||||
ConfigJSON --> InitTS
|
||||
InitTS --> SMCTS
|
||||
SMCTS --> OopsFramework
|
||||
OopsFramework --> Storage
|
||||
OopsFramework --> Language
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [config.json](file://assets/resources/config.json#L1-L21)
|
||||
- [Main.ts](file://assets/script/Main.ts#L1-L41)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L1-L207)
|
||||
|
||||
**章节来源**
|
||||
- [config.json](file://assets/resources/config.json#L1-L21)
|
||||
- [Main.ts](file://assets/script/Main.ts#L1-L41)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L1-L207)
|
||||
|
||||
## 核心配置文件
|
||||
|
||||
### config.json 结构详解
|
||||
|
||||
`config.json`是整个配置系统的核心,包含了游戏运行所需的所有基础配置信息:
|
||||
|
||||
| 配置块 | 字段 | 类型 | 描述 | 默认值 |
|
||||
|--------|------|------|------|--------|
|
||||
| config | version | string | 游戏版本号,用于版本兼容性检查 | "1.0.0" |
|
||||
| config | package | string | 应用包名,用于命名空间隔离 | "com.oops.game" |
|
||||
| config | localDataKey | string | 本地数据加密密钥 | "oops" |
|
||||
| config | localDataIv | string | 本地数据加密初始化向量 | "framework" |
|
||||
| config | httpServer | string | HTTP服务器地址 | "http://192.168.0.150/main/" |
|
||||
| config | httpTimeout | number | HTTP请求超时时间(毫秒) | 10000 |
|
||||
| config | frameRate | number | 游戏帧率设置 | 60 |
|
||||
| language | type | array | 支持的语言类型列表 | ["zh", "en"] |
|
||||
| language | path | object | 语言资源路径映射 | json: "language/json", texture: "language/texture" |
|
||||
|
||||
### 配置字段技术意义
|
||||
|
||||
#### 版本控制与包名标识
|
||||
- **version字段**:确保客户端与服务器端版本兼容性,防止因版本差异导致的功能异常
|
||||
- **package字段**:提供命名空间隔离,避免与其他应用产生冲突
|
||||
|
||||
#### 加解密密钥配置
|
||||
- **localDataKey**:本地数据加密密钥,保护用户隐私数据
|
||||
- **localDataIv**:初始化向量,增强加密安全性
|
||||
|
||||
#### 服务器通信配置
|
||||
- **httpServer**:统一的服务器地址,便于维护和迁移
|
||||
- **httpTimeout**:合理的超时设置,平衡用户体验与系统稳定性
|
||||
|
||||
#### 帧率优化配置
|
||||
- **frameRate**:固定帧率设置,确保游戏性能一致性
|
||||
|
||||
**章节来源**
|
||||
- [config.json](file://assets/resources/config.json#L1-L21)
|
||||
|
||||
## 配置系统架构
|
||||
|
||||
### 整体架构设计
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class Main {
|
||||
+start() void
|
||||
+run() Promise~void~
|
||||
+initGui() void
|
||||
+initEcsSystem() Promise~void~
|
||||
}
|
||||
class Initialize {
|
||||
+LoadingView LoadingViewComp
|
||||
+init() void
|
||||
+loadCustom(queue) void
|
||||
+loadLanguage(queue) void
|
||||
+loadCommon(queue) void
|
||||
+onComplete(queue) void
|
||||
+loadGameDataUnified() Promise~void~
|
||||
+loadFromCloud() Promise~void~
|
||||
+loadFromLocalDebug() Promise~void~
|
||||
+isWxClient() boolean
|
||||
}
|
||||
class SingletonModuleComp {
|
||||
+initialize Initialize
|
||||
+map GameMap
|
||||
+openid string
|
||||
+mission object
|
||||
+guides array
|
||||
+current_guide number
|
||||
+data object
|
||||
+fight_hero number
|
||||
+heros array
|
||||
+monsters array
|
||||
+vmdata object
|
||||
+updateCloudData() boolean
|
||||
+getCloudData() void
|
||||
+overrideLocalDataWithRemote(data) void
|
||||
+addHero(hero_uuid) boolean
|
||||
+updateFihgtHero(heroId) boolean
|
||||
+updateGold(gold) boolean
|
||||
}
|
||||
class OopsFramework {
|
||||
+config object
|
||||
+language object
|
||||
+storage object
|
||||
+res object
|
||||
+gui object
|
||||
}
|
||||
Main --> Initialize : "创建实例"
|
||||
Initialize --> SingletonModuleComp : "注入依赖"
|
||||
SingletonModuleComp --> OopsFramework : "使用框架"
|
||||
Initialize --> OopsFramework : "调用服务"
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [Main.ts](file://assets/script/Main.ts#L12-L41)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L20-L207)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L20-L195)
|
||||
|
||||
### 配置注入机制
|
||||
|
||||
配置系统通过以下机制实现全局访问:
|
||||
|
||||
1. **单例模式**:通过`ecs.getSingleton()`获取全局配置实例
|
||||
2. **依赖注入**:Initialize模块负责配置的初始化和注入
|
||||
3. **框架集成**:Oops Framework提供统一的配置访问接口
|
||||
|
||||
**章节来源**
|
||||
- [Main.ts](file://assets/script/Main.ts#L25-L30)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L25-L35)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L194-L195)
|
||||
|
||||
## 配置加载生命周期
|
||||
|
||||
### 启动流程分析
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Main as "Main.ts"
|
||||
participant Initialize as "Initialize.ts"
|
||||
participant SMComp as "SingletonModuleComp"
|
||||
participant Oops as "Oops Framework"
|
||||
participant Config as "config.json"
|
||||
Main->>Initialize : 创建Initialize实体
|
||||
Main->>SMComp : 初始化SingletonModule
|
||||
Initialize->>Config : 加载配置文件
|
||||
Config-->>Initialize : 返回配置数据
|
||||
Initialize->>Oops : 注入配置到框架
|
||||
Oops-->>Initialize : 配置就绪
|
||||
Initialize->>Initialize : 执行异步队列
|
||||
Initialize->>Initialize : 加载语言包
|
||||
Initialize->>Initialize : 加载公共资源
|
||||
Initialize->>SMComp : 完成配置注入
|
||||
SMComp-->>Main : 初始化完成
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [Main.ts](file://assets/script/Main.ts#L25-L35)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L25-L45)
|
||||
|
||||
### 生命周期阶段详解
|
||||
|
||||
#### 1. 应用启动阶段
|
||||
- Main.ts作为应用入口点,负责初始化Oops Framework
|
||||
- 创建Initialize实体并注入到系统中
|
||||
|
||||
#### 2. 配置加载阶段
|
||||
- Initialize模块按顺序执行配置加载任务
|
||||
- 包括自定义内容、语言包、公共资源的加载
|
||||
|
||||
#### 3. 配置注入阶段
|
||||
- 将加载的配置数据注入到Oops Framework中
|
||||
- 通过SingletonModuleComp实现全局访问
|
||||
|
||||
#### 4. 系统初始化阶段
|
||||
- 完成所有配置相关的工作后,系统进入正常运行状态
|
||||
|
||||
**章节来源**
|
||||
- [Main.ts](file://assets/script/Main.ts#L25-L41)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L25-L45)
|
||||
|
||||
## 配置管理模式
|
||||
|
||||
### SingletonModuleComp 实现
|
||||
|
||||
`SingletonModuleComp`是配置管理的核心组件,实现了全局配置的统一管理:
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class SingletonModuleComp {
|
||||
+initialize : Initialize
|
||||
+map : GameMap
|
||||
+openid : string
|
||||
+mission : object
|
||||
+guides : array
|
||||
+current_guide : number
|
||||
+data : object
|
||||
+fight_hero : number
|
||||
+heros : array
|
||||
+monsters : array
|
||||
+vmdata : object
|
||||
+vmAdd() void
|
||||
+reset() void
|
||||
+updateCloudData() boolean
|
||||
+getCloudData() void
|
||||
+overrideLocalDataWithRemote(data) void
|
||||
+addHero(hero_uuid) boolean
|
||||
+updateFihgtHero(heroId) boolean
|
||||
+updateGold(gold) boolean
|
||||
+finishGuide(index) void
|
||||
+error() void
|
||||
}
|
||||
class VM {
|
||||
+add(data, name) void
|
||||
}
|
||||
SingletonModuleComp --> VM : "使用MVVM"
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L20-L195)
|
||||
|
||||
### 全局访问模式
|
||||
|
||||
配置系统采用以下模式实现全局访问:
|
||||
|
||||
1. **静态实例模式**:通过`smc`变量提供全局访问点
|
||||
2. **MVVM绑定**:使用ViewModel实现数据双向绑定
|
||||
3. **事件驱动**:通过GameEvent系统通知配置变更
|
||||
|
||||
**章节来源**
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L194-L195)
|
||||
|
||||
## 多语言配置体系
|
||||
|
||||
### 语言配置结构
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "语言配置"
|
||||
LangType["语言类型列表<br/>['zh', 'en']"]
|
||||
LangPath["语言路径映射<br/>json: 'language/json'<br/>texture: 'language/texture'"]
|
||||
end
|
||||
subgraph "资源文件"
|
||||
ZhJSON["zh.json<br/>中文语言包"]
|
||||
EnJSON["en.json<br/>英文语言包"]
|
||||
FontFiles["字体文件<br/>language/font/"]
|
||||
end
|
||||
LangType --> ZhJSON
|
||||
LangType --> EnJSON
|
||||
LangPath --> ZhJSON
|
||||
LangPath --> EnJSON
|
||||
LangPath --> FontFiles
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [config.json](file://assets/resources/config.json#L12-L20)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L60-L75)
|
||||
|
||||
### 多语言加载流程
|
||||
|
||||
1. **语言检测**:从本地存储获取用户语言偏好
|
||||
2. **默认设置**:未设置时默认使用中文(zh)
|
||||
3. **资源加载**:加载对应语言的JSON和字体资源
|
||||
4. **动态切换**:支持运行时语言切换
|
||||
|
||||
**章节来源**
|
||||
- [config.json](file://assets/resources/config.json#L12-L20)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L60-L75)
|
||||
|
||||
## 配置热更新机制
|
||||
|
||||
### 热更新可行性分析
|
||||
|
||||
基于现有架构,配置系统支持以下热更新特性:
|
||||
|
||||
#### 支持的热更新场景
|
||||
- **语言包更新**:无需重启即可切换语言
|
||||
- **界面配置更新**:动态调整UI布局和样式
|
||||
- **游戏参数调整**:实时修改游戏平衡性参数
|
||||
|
||||
#### 热更新限制
|
||||
- **核心配置限制**:HTTP服务器地址、加密密钥等关键配置无法热更新
|
||||
- **版本兼容性**:需要考虑客户端与服务器的版本兼容性
|
||||
- **数据一致性**:热更新可能导致数据不一致问题
|
||||
|
||||
### 配置同步机制
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Start([开始配置同步]) --> CheckClient{"检查客户端类型"}
|
||||
CheckClient --> |微信客户端| LoadCloud["加载云端配置"]
|
||||
CheckClient --> |本地调试| LoadLocal["加载本地配置"]
|
||||
LoadCloud --> CloudSuccess{"云端加载成功?"}
|
||||
CloudSuccess --> |是| OverrideLocal["覆盖本地配置"]
|
||||
CloudSuccess --> |否| UseLocal["使用本地配置"]
|
||||
LoadLocal --> OverrideLocal
|
||||
OverrideLocal --> UpdateSMC["更新SingletonModule"]
|
||||
UseLocal --> UpdateSMC
|
||||
UpdateSMC --> NotifyChange["通知配置变更"]
|
||||
NotifyChange --> End([同步完成])
|
||||
```
|
||||
|
||||
**图表来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L105-L150)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L80-L120)
|
||||
|
||||
**章节来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L105-L150)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L80-L120)
|
||||
|
||||
## 最佳实践指南
|
||||
|
||||
### 敏感信息保护
|
||||
|
||||
#### 加密存储策略
|
||||
1. **本地数据加密**:使用AES加密算法保护敏感数据
|
||||
2. **密钥管理**:定期轮换加密密钥
|
||||
3. **传输安全**:HTTPS协议确保数据传输安全
|
||||
|
||||
#### 配置文件保护
|
||||
1. **权限控制**:限制配置文件的读写权限
|
||||
2. **备份策略**:定期备份配置文件
|
||||
3. **审计日志**:记录配置变更操作
|
||||
|
||||
### 多环境配置管理
|
||||
|
||||
#### 开发环境配置
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"httpServer": "http://localhost:3000/",
|
||||
"httpTimeout": 5000,
|
||||
"frameRate": 60
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 生产环境配置
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"httpServer": "https://api.game.com/",
|
||||
"httpTimeout": 10000,
|
||||
"frameRate": 60
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 测试环境配置
|
||||
```json
|
||||
{
|
||||
"config": {
|
||||
"httpServer": "http://test.api.com/",
|
||||
"httpTimeout": 8000,
|
||||
"frameRate": 30
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 配置校验机制
|
||||
|
||||
#### 配置验证规则
|
||||
1. **必填字段检查**:确保关键配置字段存在
|
||||
2. **数据类型验证**:验证配置值的数据类型正确性
|
||||
3. **范围约束检查**:确保数值在合理范围内
|
||||
4. **格式规范验证**:验证URL、邮箱等格式
|
||||
|
||||
#### 错误处理策略
|
||||
1. **默认值回退**:配置错误时使用默认值
|
||||
2. **警告日志记录**:记录配置错误但不影响系统运行
|
||||
3. **优雅降级**:部分配置错误时系统仍可运行
|
||||
|
||||
### 性能优化建议
|
||||
|
||||
#### 配置加载优化
|
||||
1. **延迟加载**:非关键配置采用延迟加载
|
||||
2. **缓存策略**:合理使用内存缓存
|
||||
3. **压缩传输**:减少配置文件大小
|
||||
|
||||
#### 内存管理
|
||||
1. **及时释放**:不再使用的配置及时释放
|
||||
2. **弱引用**:避免循环引用导致内存泄漏
|
||||
3. **监控告警**:监控配置相关的内存使用
|
||||
|
||||
**章节来源**
|
||||
- [config.json](file://assets/resources/config.json#L1-L21)
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L105-L150)
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 常见配置问题
|
||||
|
||||
#### 配置文件加载失败
|
||||
**症状**:游戏启动时配置加载异常
|
||||
**原因**:
|
||||
- config.json文件缺失或损坏
|
||||
- 文件编码格式不正确
|
||||
- 文件路径配置错误
|
||||
|
||||
**解决方案**:
|
||||
1. 检查config.json文件是否存在且完整
|
||||
2. 验证JSON格式的正确性
|
||||
3. 确认文件编码为UTF-8
|
||||
|
||||
#### 语言切换失效
|
||||
**症状**:语言切换后界面文字未更新
|
||||
**原因**:
|
||||
- 语言包文件缺失
|
||||
- 语言资源路径配置错误
|
||||
- 缓存未清除
|
||||
|
||||
**解决方案**:
|
||||
1. 检查语言包文件完整性
|
||||
2. 验证语言路径配置
|
||||
3. 清除语言缓存重新加载
|
||||
|
||||
#### 网络配置异常
|
||||
**症状**:游戏无法连接服务器
|
||||
**原因**:
|
||||
- HTTP服务器地址配置错误
|
||||
- 网络连接超时
|
||||
- 防火墙阻止连接
|
||||
|
||||
**解决方案**:
|
||||
1. 验证服务器地址配置
|
||||
2. 检查网络连接状态
|
||||
3. 调整超时时间设置
|
||||
|
||||
### 调试技巧
|
||||
|
||||
#### 配置日志记录
|
||||
```typescript
|
||||
// 启用配置调试日志
|
||||
oops.log.logConfig("配置加载完成: %o", configData);
|
||||
```
|
||||
|
||||
#### 配置验证工具
|
||||
```typescript
|
||||
// 配置完整性检查
|
||||
function validateConfig(config: any): boolean {
|
||||
const requiredFields = ['version', 'package', 'httpServer'];
|
||||
return requiredFields.every(field => config[field] !== undefined);
|
||||
}
|
||||
```
|
||||
|
||||
**章节来源**
|
||||
- [Initialize.ts](file://assets/script/game/initialize/Initialize.ts#L40-L50)
|
||||
- [SingletonModuleComp.ts](file://assets/script/game/common/SingletonModuleComp.ts#L180-L195)
|
||||
|
||||
## 总结
|
||||
|
||||
本项目构建了一个完整而灵活的配置管理系统,具有以下特点:
|
||||
|
||||
### 核心优势
|
||||
1. **集中化管理**:以config.json为核心,统一管理所有配置信息
|
||||
2. **模块化设计**:清晰的职责分离,便于维护和扩展
|
||||
3. **框架集成**:与Oops Framework深度集成,提供丰富的配置功能
|
||||
4. **多语言支持**:完整的国际化解决方案
|
||||
5. **热更新能力**:支持运行时配置更新
|
||||
|
||||
### 技术亮点
|
||||
- **单例模式**:确保配置的全局唯一性和一致性
|
||||
- **异步加载**:优化游戏启动性能
|
||||
- **加密保护**:保障用户数据安全
|
||||
- **事件驱动**:支持配置变更的通知机制
|
||||
|
||||
### 应用价值
|
||||
该配置管理系统为游戏开发提供了稳定可靠的基础设施,支持快速迭代和多平台部署,是现代游戏开发中不可或缺的重要组成部分。通过合理的配置管理,可以显著提高开发效率,降低维护成本,为玩家提供更好的游戏体验。
|
||||
Reference in New Issue
Block a user