84 Commits

Author SHA1 Message Date
48216b72f7 Merge pull request 'revert d671e4d3117ae8d902cb15a43a1c1d9c30fc8e27' (#14) from moyin-patch-1 into main
Reviewed-on: #14
2026-01-14 16:45:00 +08:00
229461c83f revert d671e4d311
revert Merge pull request '聊天系统' (#13) from qbb0530/whale-town-front:main into main

Reviewed-on: #13
2026-01-14 16:44:46 +08:00
d671e4d311 Merge pull request '聊天系统' (#13) from qbb0530/whale-town-front:main into main
Reviewed-on: #13
2026-01-14 15:22:13 +08:00
625fe0ff6c merge upstream 2026-01-14 15:19:15 +08:00
WhaleTown Developer
0e5b9f947b refactor: 移除SocketIOClient并更新认证场景
- 移除SocketIOClient.gd及.uid文件
- 更新ChatManager以适配新的架构
- 添加认证UI图片资源和背景音乐
- 优化AuthScene布局和配置
- 更新MainScene和项目配置
2026-01-11 23:12:35 +08:00
7cca58cb07 Merge pull request 'feature/whaletown-developer-skill' (#12) from feature/whaletown-developer-skill into main
Reviewed-on: #12
2026-01-10 19:31:05 +08:00
王浩
749e2c257b assets: 添加认证UI图片资源 2026-01-09 23:24:32 +08:00
王浩
e335a35f6c feat(chat-ui): 更新聊天UI和场景配置
- 优化聊天消息显示
- 调整UI布局
2026-01-09 23:23:41 +08:00
王浩
136e1344a0 fix(chat): 修复WebSocket连接和消息格式
- 修复连接状态检测时机问题
- 修复聊天消息格式为 {t: chat, content, scope}
- 添加 _send_login_message 函数
- 移除空消息心跳避免服务器错误
2026-01-09 23:21:12 +08:00
WhaleTown Developer
25a21f92be feat(chat): 优化聊天UI布局和WebSocket连接
- 更新 WebSocket URL 以支持 Socket.IO 握手参数 (EIO=4)
- 重构聊天面板布局,使用绝对定位和百分比锚点
- 优化输入框样式,添加装饰元素
- 修复输入框焦点释放的事件冲突问题
- 将 ChatUI 集成到主场景中
- 改进主场景容器布局设置
2026-01-08 23:59:21 +08:00
王浩
9c2e3bf15a refactor(chat-ui): 移除HeaderContainer和SendButton,添加装饰图片,修复Enter键监听
- 删除 HeaderContainer 和 StatusLabel(状态显示)
- 删除 SendButton(发送按钮)
- 添加聊天框背景图和装饰图片
- 设置 TextureRect modulate 为白色,修复黑框问题
- 移除 ChatPanel 背景色,使背景透明
- 修复 is_key_pressed 错误,改用 InputEventKey 类型检查
- 移除 _update_connection_status 函数及相关调用
2026-01-08 18:14:48 +08:00
WhaleTown Developer
9e288dbb62 docs: 更新聊天系统实施进度
- 简化文档,移除详细修复记录
- 更新实施状态:所有编译错误已修复
- 记录待后端解决的 Zulip 集成问题
2026-01-08 00:31:07 +08:00
WhaleTown Developer
c8e73bec59 fix: 修复聊天系统编译错误
- 修复 WebSocketManager/SocketIOClient 函数缩进错误
- 重命名 is_connected() 避免与 Object 基类冲突
- 修复 tscn 文件多余前导空格
- 修复测试文件 GUT 断言函数调用
- 添加 GUT 测试框架
2026-01-08 00:11:12 +08:00
王浩
16f24ab26f feat:添加聊天UI资源文件
- 添加聊天界面UI资源(缩略框背景、输入框背景、装饰图片)
- 修复 GrassTile.gd.uid 文件缺失

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-07 17:46:26 +08:00
王浩
414225e8c1 docs:更新项目规范文档
- 在 claude.md 添加 Plan Mode Protocol 章节
- 明确规划阶段的输出要求和执行报告流程
- 强制要求在每个 TODO 完成后更新文档并等待用户确认

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-07 17:42:48 +08:00
王浩
fb7cba4088 feat:实现聊天系统核心功能
- 添加 SocketIOClient.gd 实现 Socket.IO 协议封装
- 添加 WebSocketManager.gd 管理连接生命周期和自动重连
- 添加 ChatManager.gd 实现聊天业务逻辑与会话管理
  - 支持当前会话缓存(最多 100 条消息)
  - 支持历史消息按需加载(每次 100 条)
  - 每次登录/重连自动重置会话缓存
  - 客户端频率限制(10 条/分钟)
  - Token 管理与认证
- 添加 ChatMessage.gd/tscn 消息气泡 UI 组件
- 添加 ChatUI.gd/tscn 聊天界面
- 在 EventNames.gd 添加 7 个聊天事件常量
- 在 AuthManager.gd 添加 game_token 管理方法
- 添加完整的单元测试(128 个测试用例)
  - test_socketio_client.gd (42 个测试)
  - test_websocket_manager.gd (38 个测试)
  - test_chat_manager.gd (48 个测试)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-07 17:42:31 +08:00
7b85147994 chore: 合并 main 分支,统一 CLAUDE.md 格式规范
合并 main 分支对 CLAUDE.md 的格式改进,同时保留 feature 分支新增的标准开发工作流(第 8 节)。

主要改动:
- 更新 Godot 版本要求从 4.2+ 到 4.5+
- 规范化 Markdown 格式(代码块、粗体、列表)
- 保留新增的「Standard Development Workflow」章节
- 调整章节编号(第 9、10 节)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-06 19:41:29 +08:00
e3c4d08021 Merge pull request '修正语法错误' (#11) from qbb0530/whale-town-front:main into main
Reviewed-on: #11
2026-01-05 11:28:13 +08:00
王浩
3bdda47191 修正语法错误 2026-01-04 17:17:34 +08:00
43e0c2b928 feat:添加whaletown-developer标准开发工作流技能
- 创建whaletown-developer skill自动化7步开发流程
- 添加完整的使用说明文档和质量检查清单
- 更新CLAUDE.md集成标准开发工作流说明
- 新增标准开发工作流详细文档

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-04 00:46:48 +08:00
3d6c4e5356 Merge pull request 'feature/网格瓦片系统' (#9) from feature/网格瓦片系统 into main
Reviewed-on: #9
2026-01-03 22:40:55 +08:00
c621d70475 chore:清理空的占位文件
- 删除sprites目录下的空.gitkeep文件
- 删除tools目录下的空README.md文件
2026-01-03 22:37:04 +08:00
f527fa3c38 docs:添加网格瓦片系统功能文档
- 详细说明32x32网格系统的使用方法
- 包含核心组件介绍和API参考
- 提供编辑器和代码使用示例
2026-01-03 22:35:36 +08:00
e9fa21280e scene:创建广场地图场景并添加环境瓦片资源
- 新增square.tscn广场地图场景
- 添加多种环境瓦片纹理资源
- 包含草地、地板、路缘等瓦片素材
2026-01-03 22:35:13 +08:00
a3d384d39d style:统一代码文件末尾换行格式 2026-01-03 22:33:56 +08:00
ced69fd4b6 scene:创建草地瓦片预制体
- 实现GrassTile组件,支持32x32网格对齐
- 添加自动纹理验证和占位符生成
- 提供网格位置设置和世界坐标转换
- 包含位置变化信号和调试功能
2026-01-03 22:30:03 +08:00
7a6e5be4f8 config:更新核心配置支持网格系统
- EventNames添加网格相关事件定义
- ProjectPaths添加网格系统和地形资源路径
2026-01-03 22:28:29 +08:00
ba5b0daa13 feat:实现32x32网格系统核心功能
- 添加GridSystem类提供网格坐标转换
- 支持世界坐标与网格坐标互转
- 提供位置吸附和距离计算方法
- 包含网格区域和边界检查功能
2026-01-03 22:28:06 +08:00
83404d031e Merge pull request 'feature/auth-system-refactor' (#8) from feature/auth-system-refactor into main
Reviewed-on: #8
2026-01-02 21:25:30 +08:00
709242d223 docs:更新项目结构说明和路径配置
- 更新ProjectPaths.gd中的路径常量
- 更新项目结构说明文档
- 清理临时测试文件的uid引用

确保文档与实际项目结构保持一致
2026-01-02 21:20:31 +08:00
2f1ccbc2cd docs:为核心管理器添加详细中文注释
- GameManager.gd:游戏状态管理注释
- NetworkManager.gd:网络请求管理注释
- SceneManager.gd:场景切换管理注释
- StringUtils.gd:字符串工具函数注释

按照docs注释规范,添加文件头、函数说明、参数描述和使用示例
方便协同开发者快速理解和调用
2026-01-02 21:19:53 +08:00
aaaf2b31a8 fix:修复EventSystem中的GDScript语法错误
- 移除不支持的try/except语句
- 改为直接调用回调函数
- 确保EventSystem能正常编译运行
2026-01-02 21:19:25 +08:00
93baf1a5b5 refactor:统一AuthScene命名规范
- 将LoginWindow.tscn重命名为AuthScene.tscn
- 更新MainScene.tscn中的场景引用路径
- 实现命名一致性:
  - 场景文件:AuthScene.tscn
  - 脚本文件:AuthScene.gd
  - 节点名称:AuthScene
- AuthScene比LoginWindow更准确描述功能(登录+注册)
2026-01-02 21:19:04 +08:00
5f915c61b6 refactor:AuthScene解耦重构,实现视图与业务逻辑分离
- 创建AuthManager.gd:负责所有认证业务逻辑
  - 用户登录/注册逻辑
  - 表单验证逻辑
  - 验证码管理逻辑
  - 网络请求管理

- 创建ToastManager.gd:负责Toast消息管理
  - Toast创建和显示
  - 动画和生命周期管理
  - 支持成功/失败样式

- 重构AuthScene.gd:纯视图层实现
  - 只负责UI交互和显示
  - 通过信号与业务层通信
  - 移除所有业务逻辑代码

- 修复GDScript警告:
  - 未使用参数添加下划线前缀
  - 修复变量名与基类方法冲突
  - 修复EventSystem中的try语法错误
  - 修复AuthManager中的方法名不匹配错误

符合docs中的架构要求,实现完全解耦
2026-01-02 21:18:38 +08:00
d256249789 refactor:将MainScene移动到scenes根目录
- 将MainScene从scenes/Maps/移动到scenes/根目录
- 更新project.godot中的主场景路径配置
- 符合项目结构规范,MainScene作为图像显示入口文件
2026-01-02 21:17:56 +08:00
29c6740870 Merge pull request 'feature/project-structure-refactor' (#7) from feature/project-structure-refactor into main
Reviewed-on: #7
2026-01-02 01:03:07 +08:00
7b1affa360 Merge branch 'main' into feature/project-structure-refactor 2026-01-02 01:02:59 +08:00
fa360e1c78 docs:更新项目文档以反映新的结构变更
- 更新 README.md 中的项目结构说明
- 修订项目结构说明文档,反映最新的目录组织
- 确保文档与实际项目结构保持同步
2026-01-02 00:59:25 +08:00
d80feaa02b test:更新测试文件以适配新的项目结构
- 更新 auth_ui_test.tscn 中的场景引用路径
- 修复 enhanced_toast_test.gd 中的脚本路径引用
- 确保测试文件与重构后的项目结构保持一致
2026-01-02 00:59:05 +08:00
f1a60137e1 fix:修复代码警告和UID冲突问题
- 更新 ProjectPaths.gd 中的路径引用,适配新的目录结构
- 修复 SceneManager.gd 中的场景路径问题
- 更新 project.godot 配置,修复 AutoLoad 路径
- 修复 MainScene 相关文件的 UID 冲突
- 解决代码中的路径引用警告
2026-01-02 00:58:51 +08:00
3175c98ea3 refactor:实现新的项目结构组织
- 添加 _Core/components/ 和 _Core/utils/ 目录
- 重新组织 scenes/ 目录结构,按功能分类
- 迁移 StringUtils.gd 到新的 _Core/utils/ 位置
- 迁移 AuthScene.gd 到新的 scenes/ui/ 位置
- 添加 AI 文档支持目录 docs/AI_docs/
- 添加开发参考文档 claude.md
2026-01-02 00:58:34 +08:00
a18c7a54b1 refactor:重构项目结构,删除旧的文件组织
- 删除旧的 UI/Windows/ 目录下的认证相关文件
- 删除旧的 Utils/ 目录下的工具类文件
- 删除旧的 scenes/Components/ 目录结构
- 为新的目录结构让路
2026-01-02 00:58:16 +08:00
fca3eb79dd chore:清理临时文档文件
- 删除迁移完成标记文件 MIGRATION_COMPLETE.md
- 删除重构说明文件 REFACTORING.md
- 删除结构对比文件 STRUCTURE_COMPARISON.md
- 删除临时文档 cloude.md
2026-01-02 00:57:53 +08:00
e128328d93 Merge pull request 'fix: 修复GDScript警告和UID冲突问题' (#6) from fix/code-warnings-and-uid-conflicts into main
Reviewed-on: #6
2025-12-31 19:36:48 +08:00
fdedb21cbd fix: 修复GDScript警告和UID冲突问题
代码修复:
- NetworkManager.gd: 修复参数名冲突和未使用变量警告
- StringUtils.gd: 修复变量名与内置函数char冲突
- ResponseHandler.gd: 移除static关键字,改为实例方法
- AuthScene.gd: 恢复正确的ResponseHandler调用方式

 资源清理:
- 删除assets/sprites/icon/下的重复图标文件
- 删除UI/Theme/下的重复字体和主题文件
- 统一使用assets/路径下的资源文件

 配置修复:
- 修复LoginWindow.tscn和main_scene.tscn中的UID引用
- 更新chinese_theme.tres中的字体路径引用
- 添加project.godot调试设置以减少渲染器警告

 文档更新:
- 更新项目设置指南中的主题和字体路径引用

解决问题:
-  修复所有GDScript编译警告
-  解决UID重复冲突警告
-  统一资源文件路径结构
-  保持Web部署兼容性
2025-12-31 19:35:20 +08:00
d49983079a Merge pull request 'fix/verification-code-button-state' (#5) from fix/verification-code-button-state into main
Reviewed-on: #5
2025-12-31 19:00:19 +08:00
51e79c6c6d Merge branch 'main' into fix/verification-code-button-state 2025-12-31 19:00:09 +08:00
0edd1c740b docs: 完善项目文档和README,修复字符显示问题
- 修复README.md中的emoji字符显示问题
- 移除文档质量评级系统
- 添加贡献者致谢部分,创建详细的CONTRIBUTORS.md
- 创建核心系统文件EventNames.gd和ProjectPaths.gd
- 更新项目配置文件project.godot,添加输入映射
- 完善各模块文档,修正路径引用问题
- 创建文档更新日志CHANGELOG.md
- 优化文档结构和导航系统
2025-12-31 18:58:38 +08:00
a85a7b4d0e docs: 完善项目入门README,强调输入映射配置的重要性
发现的关键问题:
- 项目代码中使用了输入映射,但project.godot中未配置
- 缺少输入映射会导致游戏无法正常运行

 主要改进:
- 强调输入映射配置为必需步骤
- 添加重要提醒和警告标识
- 新增常见启动问题排查指南
- 明确列出必需的6个输入动作
- 完善完成检查清单

 问题排查:
- 游戏无法响应输入  输入映射未配置
- Invalid action错误  缺少必需输入动作
- AutoLoad单例报错  配置验证问题

 确保新人成功:
- 明确标注必需步骤的优先级
- 提供具体的错误解决方案
- 强调验证配置的重要性
2025-12-31 18:17:58 +08:00
51d2ad1629 docs: 修正项目设置指南,确保信息准确
修正的问题:
- 路径错误: core/managers/  _Core/managers/
- 补充完整的AutoLoad配置列表 (5个单例)
- 修正NetworkManager.login()方法调用方式
- 添加实际的project.godot配置验证

 新增内容:
- 完整的AutoLoad配置表格
- 其他重要项目设置 (主题、渲染、窗口)
- 详细的验证测试代码
- 常见问题排查指南
- 配置检查清单

 确保准确性:
- 所有路径基于实际项目结构验证
- 代码示例基于实际API接口
- 配置信息与project.godot文件一致
2025-12-31 18:13:08 +08:00
6f545b04e9 docs: 更新项目结构说明,匹配实际项目结构
主要更新:
- 根据实际项目目录结构重写文档
- 明确三类团队协作模式:开发、美术、策划
- 详细说明每个目录的职责和使用方式
- 添加团队协作指南和工作流程
- 提供实际的代码示例和配置示例

 新增内容:
- 团队协作模式说明 (开发/美术/策划)
- 详细的目录结构和文件说明
- 开发工作流和版本发布流程
- 最佳实践和规范要求

 确保准确性:
- 所有目录结构都基于实际项目检查
- 文件路径和命名完全匹配当前状态
- 团队职责划分清晰明确
2025-12-31 18:08:31 +08:00
1ff677b3b2 docs: 重新组织文档结构,按开发阶段分类
新的目录结构:
  01-项目入门/     # 新人必读,项目基础
  02-开发规范/     # 编码标准和规范
  03-技术实现/     # 具体开发指导
  04-高级开发/     # 进阶开发技巧
  05-部署运维/     # 发布和部署
  06-功能模块/     # 特定功能文档

 新增导航文档:
- docs/README.md - 完整的文档导航和使用指南
- 各目录下的README.md - 分类说明和使用指导

 优化效果:
- 开发者可以按阶段快速定位需要的文档
- 新人有清晰的学习路径
- 不同角色有针对性的文档推荐
- 提供了问题导向的快速查找功能
2025-12-31 18:02:16 +08:00
2998fd2d11 docs: 补充开发规范相关文档
新增文档:
- docs/输入映射配置.md - 游戏输入配置指南
- docs/架构与通信规范.md - 项目架构和组件通信规范
- docs/实现细节规范.md - 游戏对象具体实现要求
- docs/开发哲学与最佳实践.md - 开发理念和编程最佳实践

 覆盖内容:
- 输入映射的配置方法和验证
- EventSystem事件系统使用规范
- 玩家、NPC、TileMap的实现标准
- 代码质量标准和审查清单
- 性能优化和资源管理指导

这些文档补充了开发规范.md中提到但在docs目录中缺失的内容
2025-12-31 17:50:19 +08:00
60edcc9868 docs: 文档中文化和清理
新增:
- 开发规范.md (翻译自CLAUDE.md)

 重命名为中文:
- project_structure.md  项目结构说明.md
- naming_convention.md  命名规范.md
- code_comment_guide.md  代码注释规范.md
- git_commit_guide.md  Git提交规范.md
- api-documentation.md  API接口文档.md
- network_manager_setup.md  网络管理器设置.md
- setup.md  项目设置指南.md
- testing_guide.md  测试指南.md
- web_deployment_guide.md  Web部署指南.md
- module_development.md  模块开发指南.md
- performance_optimization.md  性能优化指南.md
- scene_design.md  场景设计规范.md
- auth/form_validation.md  auth/表单验证规范.md
- auth/testing_guide.md  auth/认证测试指南.md

 删除总结性文档:
- final_update_summary.md
- web_deployment_changelog.md
- CLAUDE.md
2025-12-31 17:45:04 +08:00
d25d8d4dd3 Merge pull request 'fix/verification-code-button-state' (#4) from fix/verification-code-button-state into main
Reviewed-on: #4
2025-12-31 17:28:45 +08:00
190b6c9a66 docs: 清理总结性文档,保留规范类文档
- 删除 docs/CONTRIBUTORS.md (总结性文档)
- 删除 docs/api_update_log.md (已不存在)
- 删除 docs/cleanup_summary.md (已不存在)
- 保留 docs/module_development.md (开发规范)
- 保留 docs/performance_optimization.md (性能规范)
- 保留 docs/scene_design.md (设计规范)
2025-12-31 17:27:13 +08:00
899bc5d5d0 merge: 解决README.md合并冲突,保留main分支内容并整合当前分支特性 2025-12-31 17:21:53 +08:00
e657cfce0e Merge pull request 'refactor:重构项目架构为分层结构' (#3) from qbb0530/whale-town-front:refactor/项目结构重构 into main
Reviewed-on: #3
2025-12-31 16:35:24 +08:00
王浩
b9182bbc2e docs:完善 CLAUDE.md 为 AI 开发规范文档
## 🎯 主要改进

### 1. 明确项目定位
- 清晰定义 "WhaleTown" 为 2D 俯视像素风 RPG
- 指定 Godot 4.2+ 引擎(禁止 3.x 语法)
- 强调分层架构:`_Core`(框架)、`Scenes`(玩法)、`UI`(界面)

### 2. 完善开发规范
-  添加 Input Map 配置(WASD、交互键、暂停键)
-  明确文件路径规则(STRICT LOWERCASE)
-  添加 EventNames.gd 示例代码
-  完善测试代码示例(GUT 框架)
-  优化代码模板(分区注释)

### 3. 强化技术约束
- 📋 严格类型系统(强制静态类型)
- 🏛 事件驱动架构(EventSystem 解耦)
- 🚫 禁止模式列表(yield、Linear Filter 等)
-  必须测试覆盖(所有 Core 管理器)

### 4. 代码模板改进
- 添加结构化注释(Exports、References、Lifecycle、Methods)
- 展示最佳实践(@onready、%UniqueName、私有方法前缀)
- 包含完整的玩家移动示例

### 5. AI 指令优化
- 直接对 AI 说话("Claude: Root folders MUST be lowercase")
- 明确的优先级(STRICT、The Law、MANDATORY)
- 提供决策指南(Area2D vs Body、Enum vs StateChart)

## 📊 文档结构
- 90 行,精炼完整
- Emoji 视觉层级(🛠 命令、📂 文件、📋 标准、🏛 架构)
- 覆盖:文件组织、编码标准、架构设计、测试要求、代码模板

##  质量提升
- 统一路径大小写(tests/ 而非 Tests/)
- 添加 EventNames.gd 完整示例
- 完善测试代码(watch_signals、assert_signal_emitted)
- 明确 Godot 版本约束(4.2+)

## 🎯 目标
为 AI 提供清晰、严格、可执行的开发规范,
确保代码质量和架构一致性。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-31 16:32:54 +08:00
王浩
642a99970c docs:添加项目开发规范文档 CLAUDE.md
## 📋 新增内容

添加了完整的 Claude Code 开发规范文档,包括:

### 核心规范
- **项目概述**: 2D 俯视像素风 RPG 游戏架构
- **编码标准**:
  - 严格类型系统
  - 统一命名规范(PascalCase, snake_case, SCREAMING_SNAKE_CASE)
  - 节点访问规范(@onready, %UniqueName)
  - 最佳实践(await, Callable, Signal Up/Call Down)

### 架构规则
- **解耦原则**: 低层级实体通过 EventSystem 通信
- **场景管理**: 统一使用 SceneManager.change_scene()
- **组件化**: 可复用逻辑封装到 Scenes/Components/

### 实现规范
- **实体结构**:
  - Player: CharacterBody2D + Camera2D
  - NPC: StaticBody2D/CharacterBody2D + InteractionArea
  - Interactables: 共享 InteractableComponent
- **交互系统**: 通过 EventSystem.notify_interaction_triggered()
- **TileMap 规则**: 分层设计(地面、障碍、装饰)

### 文件组织
- 地图: Scenes/Maps/[map_name].tscn
- 实体: Scenes/Entities/[entity_name]/[entity_name].tscn
- 脚本: 与场景文件同目录
- 资源: res://Assets/Sprites/

### 测试标准
- 使用 GUT 测试框架
- 测试文件位置: res://test/unit/ 或 res://test/integration/
- 文件命名: test_*.gd
- 核心逻辑必须有单元测试
- 玩家移动和 NPC 交互需要集成测试

### 开发理念
- 简约至上:函数单一职责
- "栅栏后规则": 即使不可见的代码也要干净优美
- 反馈循环:每个交互都要有特效/音效占位
- 零硬编码:所有路径和配置使用常量或 @export
- "自动工作"的相机:自动检测 TileMap 边界

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-31 16:07:54 +08:00
王浩
0b533189ec refactor:重构项目架构为分层结构
## 🏗️ 主要变更

### 目录结构重构
- 将 core/ 迁移到 _Core/(框架层)
- 将 scenes/ 重构为 Scenes/(玩法层)和 UI/(界面层)
- 将 data/ 迁移到 Config/(配置层)
- 添加 Assets/ 资源层和 Utils/ 工具层
- 将 scripts/ 迁移到 tools/(开发工具)

### 架构分层
- **_Core/**: 框架层 - 全局单例和管理器
- **Scenes/**: 玩法层 - 游戏场景和实体
- **UI/**: 界面层 - HUD、窗口、对话系统
- **Assets/**: 资源层 - 精灵图、音频、字体
- **Config/**: 配置层 - 游戏配置和本地化
- **Utils/**: 工具层 - 通用辅助脚本

### 文件更新
- 更新 project.godot 中的所有路径引用
- 更新自动加载脚本路径
- 更新测试文件的引用路径
- 添加 REFACTORING.md 详细说明
- 添加 MIGRATION_COMPLETE.md 迁移完成标记
- 更新 README.md 反映新架构

### 设计原则
-  清晰的分层(框架/玩法/界面)
-  场景内聚(脚本紧邻场景文件)
-  组件化设计(可复用组件)
-  职责单一(每个目录职责明确)

## 📋 详细信息
查看 REFACTORING.md 了解完整的重构说明和迁移映射表

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-31 11:36:01 +08:00
b1f3c0feff Merge pull request 'feature/网络管理和Web部署系统' (#2) from feature/网络管理和Web部署系统 into main
Reviewed-on: #2
2025-12-25 23:17:30 +08:00
021c8623f8 docs:更新主要项目文档
- 更新README添加Web部署说明
- 精简API文档,移除冗余内容
- 添加新功能使用指南
- 完善项目架构说明
2025-12-25 23:14:29 +08:00
a1b867dfd7 chore:清理废弃的网络测试文件
- 删除旧的NetworkTest.gd测试文件
- 移除对应的UID文件
- 统一使用新的ApiTestScript替代
2025-12-25 23:14:09 +08:00
d17c766246 test:增强认证模块测试覆盖
- 添加认证UI自动化测试
- 实现增强型Toast消息测试
- 完善用户交互测试用例
- 提高测试代码覆盖率
2025-12-25 23:13:49 +08:00
92c4eaed07 refactor:重构认证场景和网络集成
- 重构AuthScene脚本,集成新的NetworkManager
- 优化用户界面布局和交互逻辑
- 改进错误处理和用户反馈机制
- 统一网络请求处理流程
2025-12-25 23:12:49 +08:00
abd683c766 config:更新项目配置支持Web导出
- 启用Web导出功能
- 配置中文字体支持
- 更新项目设置和资源路径
- 优化Web版本性能配置
2025-12-25 23:10:28 +08:00
a05bac6f05 docs:添加完整的项目文档体系
- 添加Web部署完整指南和更新日志
- 创建网络管理器配置文档
- 完善项目设置和测试指南
- 添加API更新日志和清理总结
- 更新脚本使用说明文档
2025-12-25 23:09:59 +08:00
77af0bda39 test:完善API测试框架
- 添加Godot内置API测试脚本
- 实现Python API客户端测试套件
- 添加快速测试和完整测试脚本
- 支持跨平台测试运行(Windows/Linux)
- 更新测试文档和使用指南
2025-12-25 23:09:12 +08:00
8980e3d558 feat:添加字符串工具类
- 实现邮箱格式验证功能
- 添加密码强度检查
- 提供字符串清理和格式化方法
- 支持中文字符处理
2025-12-25 23:07:47 +08:00
1294529d13 asset:添加UI资源和中文字体支持
- 添加微软雅黑字体文件支持中文显示
- 导入Datawhale官方Logo图标
- 创建中文主题配置文件
- 完善游戏图标资源目录
2025-12-25 23:06:50 +08:00
0935c5fd76 feat:添加Web版本自动化部署系统
- 实现跨平台Web导出脚本(Windows/Linux/macOS)
- 添加本地测试服务器启动脚本
- 配置Godot Web导出预设
- 创建Web资源目录结构
- 支持一键导出和本地测试
2025-12-25 23:06:29 +08:00
405710bdde feat:实现统一网络请求管理系统
- 添加NetworkManager核心网络管理器
- 实现ResponseHandler统一响应处理
- 支持GET、POST、PUT、DELETE、PATCH请求类型
- 完善错误处理和超时机制
- 提供统一的信号回调接口
2025-12-25 23:05:49 +08:00
7413574672 Merge pull request 'fix/verification-code-button-state' (#1) from fix/verification-code-button-state into main
Reviewed-on: #1
2025-12-24 20:58:43 +08:00
c0f5d6a537 docs:添加性能优化指南
- 创建全面的性能优化文档
- 涵盖渲染、内存、脚本、网络等各方面优化
- 提供具体的代码示例和最佳实践
- 包含性能监控和调试工具使用方法
- 为开发者提供系统的性能优化指导
2025-12-24 20:51:45 +08:00
0b6b1c2040 docs:完善前端项目文档体系
- 重构README文档,参考后端结构优化内容组织
- 添加模块开发指南,详细说明模块化开发流程
- 创建场景设计规范,规范场景架构和最佳实践
- 建立贡献者名单,记录团队成员和贡献统计
- 完善技术栈介绍和功能特性说明
- 优化文档结构和导航,提升开发者体验
2025-12-24 20:50:31 +08:00
8d071cb2ed chore:清理空目录占位文件
- 删除不再需要的.gitkeep文件
- 目录结构已通过实际文件维护,无需占位符
2025-12-24 20:40:26 +08:00
370cffbdd8 config:更新项目配置和文档
- 更新Godot项目配置,添加自动加载脚本
- 完善.gitignore文件,排除不必要的文件
- 更新README文档,添加项目介绍和使用说明
- 更新主场景配置,集成认证系统
- 添加开发规范文档和项目结构说明
2025-12-24 20:39:33 +08:00
5b67771bbc asset:添加游戏资源目录和测试框架
- 创建音频、字体、材质、着色器等资源目录
- 添加精灵图片资源管理结构
- 建立集成测试、性能测试、单元测试框架
- 为后续资源导入和测试开发做准备
2025-12-24 20:39:14 +08:00
73478c0500 chore:完善项目目录结构和基础框架
- 添加核心系统框架目录结构
- 创建游戏模块化组织架构
- 添加数据配置和本地化支持
- 建立脚本分类管理体系
- 创建场景预制件管理目录
2025-12-24 20:38:57 +08:00
15548ebb52 docs:添加API接口文档
- 详细记录认证相关API接口规范
- 包含请求参数、响应格式和错误代码说明
- 提供完整的使用示例和测试用例
- 涵盖登录、注册、验证码等核心功能接口
2025-12-24 20:38:40 +08:00
47cfc14f68 test:添加认证系统测试套件
- 添加UI测试场景,支持模拟各种认证场景
- 实现API测试脚本,覆盖登录、注册、验证码等接口
- 添加测试文档,说明测试用例和预期结果
- 支持自动化测试和手动测试验证
2025-12-24 20:37:33 +08:00
c6bcca4e7f feat:实现用户认证系统核心功能
- 实现用户登录和注册的完整流程
- 添加邮箱验证码发送和验证功能
- 实现基于邮箱地址的验证码冷却机制
- 添加表单验证和错误提示系统
- 集成Toast消息提示系统
- 支持网络请求处理和错误处理
- 实现按钮状态管理和加载状态显示
2025-12-24 20:37:00 +08:00
f11479f2cc scene:创建用户认证场景和UI资源
- 添加认证场景 auth_scene.tscn,包含登录和注册界面
- 添加认证相关的UI背景图片和框架素材
- 实现响应式布局,支持登录/注册界面切换
- 包含完整的表单输入控件和验证码输入区域
2025-12-24 20:36:35 +08:00
209 changed files with 21972 additions and 1429 deletions

View File

@@ -1,13 +1,7 @@
{ {
"permissions": { "permissions": {
"allow": [ "allow": [
"WebFetch(domain:whaletownend.xinghangee.icu)", "Skill(whaletown-developer)"
"mcp__ide__getDiagnostics",
"Bash(dir /s /b *.gd)",
"Bash(findstr:*)",
"Bash(del nul)",
"Bash(git checkout:*)",
"Bash(git add:*)"
] ]
} }
} }

View File

@@ -0,0 +1,335 @@
---
name: whaletown-developer
description: Automate WhaleTown project's standard development workflow. Use this skill when implementing features, fixing bugs, creating scenes, or any code development tasks. Guides through 7-step process - architecture analysis, implementation, comment/naming validation, testing, and Git commit generation following project conventions.
---
# WhaleTown Standard Development Workflow Skill
This skill automates the standard development workflow for the WhaleTown project, ensuring all developers follow unified specifications and quality standards.
## When to Use This Skill
Activate this skill when:
- Implementing new features ("实现XX功能", "添加XX系统")
- Fixing bugs ("修复XX Bug", "解决XX问题")
- Creating scenes ("创建XX场景", "设计XX界面")
- Developing modules ("开发XX模块", "构建XX组件")
- Any code development task requiring adherence to project standards
## Development Workflow Overview
```
Step 1: Architecture Analysis (读取架构规范)
Step 2: Implementation (按规范编码)
Step 3: Comment Validation (注释规范检查)
Step 4: Naming Validation (命名规范检查)
Step 5: Test Writing (编写测试代码)
Step 6: Test Execution (运行测试验证)
Step 7: Git Commit (生成规范提交信息)
```
## Step-by-Step Workflow
### Step 1: Architecture Analysis
Read and apply the architecture specifications before implementation.
**Actions:**
1. Read `docs/02-开发规范/架构与通信规范.md`
2. Determine file location based on feature type:
- Core systems → `_Core/managers/` or `_Core/systems/`
- Game scenes → `scenes/Maps/`, `scenes/Entities/`, `scenes/Components/`
- UI components → `scenes/ui/`
3. Identify communication method (MUST use EventSystem for cross-module communication)
4. List dependencies (required managers and systems)
5. Design event definitions (add to `_Core/EventNames.gd`)
**Layered Architecture:**
```
UI Layer (界面层) → scenes/ui/
Scenes Layer (游戏层) → scenes/Maps/, scenes/Entities/
_Core Layer (框架层) → _Core/managers/, _Core/systems/
```
**Communication Principle:** "Signal Up, Call Down"
- Parents call child methods (downward calls)
- Children emit signals to notify parents (upward signals)
- Cross-module communication MUST use EventSystem
### Step 2: Implementation
Implement the feature following strict project conventions.
**Requirements:**
- **Type Safety**: All variables and functions MUST have type annotations
```gdscript
var speed: float = 200.0
func move(delta: float) -> void:
```
- **Godot 4.2+ Syntax**: NO `yield()`, use `await`
- **Node Caching**: Use `@onready` to cache node references, avoid `get_node()` in `_process()`
- **EventSystem Communication**: Use EventSystem for cross-module messaging
```gdscript
EventSystem.emit_event(EventNames.PLAYER_MOVED, {"position": global_position})
EventSystem.connect_event(EventNames.INTERACT_PRESSED, _on_interact_pressed)
```
- **Nearest Filter**: All Sprite2D/TileMap resources MUST use Nearest filter (no Linear filter)
- **AutoLoad Restrictions**: Only GameManager, SceneManager, EventSystem, NetworkManager, ResponseHandler allowed as autoloads
- **Low-level Entities**: Do NOT directly reference GameManager in Player/NPC entities, use events instead
### Step 3: Comment Validation
Ensure code comments meet project standards.
**Actions:**
1. Read `docs/02-开发规范/代码注释规范.md`
2. Verify file header comment is complete:
```gdscript
# ============================================================================
# 文件名: FeatureName.gd
# 作用: 简短描述功能
#
# 主要功能:
# - 功能点1
# - 功能点2
#
# 依赖: 列出依赖的管理器/系统
# 作者: [开发者名称]
# 创建时间: YYYY-MM-DD
# ============================================================================
```
3. Verify all public functions have complete documentation:
```gdscript
# 函数功能描述
#
# 参数:
# param_name: Type - 参数说明
#
# 返回值:
# Type - 返回值说明
#
# 使用示例:
# var result = function_name(param)
func function_name(param: Type) -> ReturnType:
```
4. Ensure complex logic has inline comments explaining WHY, not WHAT
### Step 4: Naming Validation
Verify all naming follows project conventions.
**Actions:**
1. Read `docs/02-开发规范/命名规范.md`
2. Validate naming conventions:
- **Class names**: PascalCase (`class_name PlayerController`)
- **Variables/Functions**: camelCase (`var moveSpeed: float`, `func updateMovement()`)
- **Constants**: UPPER_CASE (`const MAX_HEALTH: int = 100`)
- **Private members**: Underscore prefix (`var _velocity: Vector2`)
- **Scene files**: snake_case with suffix (`player_scene.tscn`, `enemy_prefab.tscn`)
- **Script files**: PascalCase.gd (`PlayerController.gd`, `GameManager.gd`)
**Common Patterns:**
```gdscript
# ✅ Correct
const MAX_SPEED: float = 300.0
var currentHealth: int
var _isInitialized: bool = false
func getPlayerPosition() -> Vector2:
func _calculateDamage(baseDamage: int) -> int:
# ❌ Incorrect
const maxSpeed: float = 300.0 # Constants must be UPPER_CASE
var CurrentHealth: int # Variables must be camelCase
var is_initialized: bool = false # No snake_case for variables
func GetPlayerPosition() -> Vector2: # Functions must be camelCase
```
### Step 5: Test Writing
Create unit tests for the implemented functionality.
**Actions:**
1. Read `docs/03-技术实现/测试指南.md`
2. For _Core/ managers/systems, MUST create corresponding test file in `tests/unit/`
3. Test file naming: `test_[name].gd`
4. Test file structure:
```gdscript
extends GutTest
## [FeatureName] 单元测试
var feature: FeatureName
func before_each():
feature = preload("res://_Core/managers/FeatureName.gd").new()
add_child(feature)
func after_each():
feature.queue_free()
func test_initialization():
var result = feature.initialize()
assert_true(result, "Feature should initialize successfully")
func test_core_functionality():
# Test core functionality
pass
```
### Step 6: Test Execution
Run tests to ensure code quality.
**Actions:**
1. Run GUT tests using Bash tool:
```bash
godot --headless -s addons/gut/gut_cmdline.gd -gdir=res://tests/ -ginclude_subdirs
```
2. Verify all tests pass
3. If tests fail:
- Identify the root cause
- Fix the implementation or test
- Re-run tests until all pass
### Step 7: Git Commit
Generate standardized Git commit message.
**Actions:**
1. Read `docs/02-开发规范/Git提交规范.md`
2. Determine commit type based on changes:
- `feat` - New features
- `fix` - Bug fixes
- `docs` - Documentation updates
- `refactor` - Code refactoring
- `perf` - Performance optimization
- `test` - Test additions/modifications
- `scene` - Scene file changes
- `ui` - UI related changes
3. Generate commit message using Chinese colon ():
```
<类型><简短描述>
[可选的详细描述]
```
4. Follow principles:
- **One commit, one change** - Most important rule
- Use imperative verbs (添加, 修复, 更新)
- Keep description concise (< 50 characters)
- If multiple types of changes, split into separate commits
**Examples:**
```bash
# ✅ Good commits
git commit -m "feat实现玩家二段跳功能"
git commit -m "fix修复角色跳跃时的碰撞检测问题"
git commit -m "test添加角色控制器单元测试"
# ❌ Bad commits
git commit -m "fix + feat修复Bug并添加新功能" # Mixed types
git commit -m "update player" # Vague, English
```
## Progress Tracking
Use TodoWrite tool to track workflow progress:
```gdscript
TodoWrite.create_todos([
"Step 1: 架构分析 - 读取架构规范",
"Step 2: 功能实现 - 按规范编码",
"Step 3: 注释规范检查",
"Step 4: 命名规范检查",
"Step 5: 测试代码编写",
"Step 6: 测试验证 - 运行测试",
"Step 7: Git 提交 - 生成提交信息"
])
```
Mark each step as `completed` immediately after finishing.
## Quality Checklist
Before completing the workflow, verify:
- [ ] File location follows layered architecture (_Core, scenes, UI)
- [ ] Uses EventSystem for cross-module communication
- [ ] Event names added to EventNames.gd
- [ ] All variables and functions have type annotations
- [ ] Naming conventions correct (PascalCase/camelCase/UPPER_CASE)
- [ ] File header comment complete
- [ ] Public functions have complete documentation
- [ ] Unit tests created and passing
- [ ] Git commit message follows specification
- [ ] No Godot 3.x syntax (yield → await)
- [ ] Node references cached with @onready
- [ ] Sprite2D/TileMap use Nearest filter
## Reference Documents
The skill automatically reads these documents at appropriate steps:
- Architecture: `docs/02-开发规范/架构与通信规范.md`
- Comments: `docs/02-开发规范/代码注释规范.md`
- Naming: `docs/02-开发规范/命名规范.md`
- Testing: `docs/03-技术实现/测试指南.md`
- Git: `docs/02-开发规范/Git提交规范.md`
- Project Instructions: `claude.md` (root directory)
For detailed checklist reference, see `references/checklist.md` in this skill directory.
## Example Workflow
User request: "实现玩家二段跳功能"
1. **Architecture Analysis** ✅
- Read architecture spec
- Target: `scenes/Entities/Player/Player.gd`
- Communication: Emit `PLAYER_DOUBLE_JUMPED` event
- Dependencies: EventSystem, Input
- Event: Add `PLAYER_DOUBLE_JUMPED` to EventNames.gd
2. **Implementation** ✅
- Create double jump logic with type annotations
- Use EventSystem.emit_event() for notifications
- Cache references with @onready
- Use await instead of yield
3. **Comment Validation** ✅
- Add file header with feature description
- Document double jump function parameters
- Add inline comments for jump logic
4. **Naming Validation** ✅
- Verify: `var canDoubleJump: bool` (camelCase)
- Verify: `const MAX_DOUBLE_JUMPS: int` (UPPER_CASE)
- Verify: `func performDoubleJump()` (camelCase)
5. **Test Writing** ✅
- Create `tests/unit/test_player_double_jump.gd`
- Test initialization, jump execution, limits
6. **Test Execution** ✅
- Run: `godot --headless -s addons/gut/gut_cmdline.gd`
- All tests pass ✅
7. **Git Commit** ✅
```bash
git add scenes/Entities/Player/Player.gd _Core/EventNames.gd tests/unit/test_player_double_jump.gd
git commit -m "feat实现玩家二段跳功能"
```
## Notes
- This skill enforces quality standards through automated validation
- Each step builds upon the previous, ensuring comprehensive quality control
- Skipping steps will result in incomplete or non-compliant code
- The 7-step workflow is designed for team consistency and maintainability

View File

@@ -0,0 +1,285 @@
# WhaleTown Development Quality Checklist
快速参考检查清单,用于验证代码是否符合项目规范。
## 架构检查清单
### 文件位置
- [ ] 核心系统文件位于 `_Core/managers/``_Core/systems/`
- [ ] 游戏场景文件位于 `scenes/Maps/`, `scenes/Entities/`, `scenes/Components/`
- [ ] UI 组件文件位于 `scenes/ui/`
- [ ] 测试文件位于 `tests/unit/``tests/integration/`
### 通信方式
- [ ] 跨模块通信使用 EventSystem
- [ ] 新增事件定义在 `_Core/EventNames.gd`
- [ ] 遵循 "Signal Up, Call Down" 原则
- [ ] 父节点调用子节点方法(向下调用)
- [ ] 子节点发出信号通知父节点(向上信号)
### 依赖管理
- [ ] 仅使用允许的自动加载GameManager, SceneManager, EventSystem, NetworkManager, ResponseHandler
- [ ] 底层实体Player, NPC不直接访问 GameManager
- [ ] 底层实体通过事件系统与全局管理器通信
---
## 代码规范检查清单
### 类型安全
- [ ] 所有变量都有类型注解:`var speed: float = 200.0`
- [ ] 所有函数都有参数和返回值类型:`func move(delta: float) -> void:`
- [ ] 常量都有类型注解:`const MAX_HEALTH: int = 100`
### Godot 4.2+ 语法
- [ ] 使用 `await` 代替 `yield()`
- [ ] 使用 `@onready` 缓存节点引用
- [ ] 避免在 `_process()` 中使用 `get_node()`
- [ ] 信号连接使用 `.connect()` 语法
### 资源设置
- [ ] 所有 Sprite2D 使用 Nearest 滤镜(不使用 Linear
- [ ] 所有 TileMap 使用 Nearest 滤镜
---
## 命名规范检查清单
### 类名
- [ ] 使用 PascalCase`class_name PlayerController`
- [ ] 文件名与类名一致:`PlayerController.gd`
### 变量
- [ ] 公共变量使用 camelCase`var moveSpeed: float`
- [ ] 私有变量使用下划线前缀:`var _velocity: Vector2`
- [ ] 布尔变量使用 is/has/can 前缀:`var isJumping: bool`
### 函数
- [ ] 使用 camelCase`func updateMovement()`
- [ ] 获取函数使用 `get` 前缀:`func getPlayerPosition()`
- [ ] 设置函数使用 `set` 前缀:`func setHealth(value: int)`
- [ ] 判断函数使用 `is/has/can` 前缀:`func isAlive()`, `func canJump()`
- [ ] 私有函数使用下划线前缀:`func _calculateDamage()`
### 常量
- [ ] 使用 UPPER_CASE`const MAX_HEALTH: int = 100`
- [ ] 使用下划线分隔:`const JUMP_FORCE: float = -400.0`
### 枚举
- [ ] 枚举类型使用 PascalCase`enum PlayerState`
- [ ] 枚举值使用 UPPER_CASE`IDLE, WALKING, RUNNING`
### 文件命名
- [ ] 脚本文件PascalCase.gd (`PlayerController.gd`)
- [ ] 场景文件snake_case_scene.tscn (`main_scene.tscn`)
- [ ] 预制体文件snake_case_prefab.tscn (`player_prefab.tscn`)
- [ ] 资源文件snake_case (`sprite_player_idle.png`)
---
## 注释规范检查清单
### 文件头注释
- [ ] 包含文件名
- [ ] 包含作用描述
- [ ] 列出主要功能
- [ ] 列出依赖的管理器/系统
- [ ] 包含作者和创建时间
示例:
```gdscript
# ============================================================================
# 文件名: PlayerController.gd
# 作用: 玩家角色控制器,处理玩家输入和移动逻辑
#
# 主要功能:
# - 处理键盘和手柄输入
# - 控制角色移动和跳跃
# - 管理角色状态切换
#
# 依赖: EventSystem, InputManager
# 作者: [开发者名称]
# 创建时间: 2025-01-03
# ============================================================================
```
### 函数注释
- [ ] 公共函数有完整注释
- [ ] 包含功能描述
- [ ] 列出参数说明(名称、类型、含义)
- [ ] 说明返回值(类型、含义)
- [ ] 提供使用示例(对于复杂函数)
- [ ] 标注注意事项(如果有)
示例:
```gdscript
# 处理玩家输入并更新移动状态
#
# 参数:
# delta: float - 帧时间间隔
#
# 返回值: 无
#
# 注意事项:
# - 需要在 _physics_process 中调用
# - 会自动处理重力和碰撞
func handleMovement(delta: float) -> void:
```
### 行内注释
- [ ] 复杂逻辑有注释说明
- [ ] 注释解释 WHY为什么不解释 WHAT是什么
- [ ] 避免显而易见的注释
- [ ] 使用 TODO/FIXME/NOTE 等标记
---
## 测试规范检查清单
### 测试文件
- [ ] _Core/ 中的管理器/系统都有对应测试文件
- [ ] 测试文件位于 `tests/unit/``tests/integration/`
- [ ] 测试文件命名:`test_[name].gd`
- [ ] 测试文件继承自 GutTest`extends GutTest`
### 测试结构
- [ ] 包含测试类注释
- [ ] 实现 `before_each()` 进行测试前置设置
- [ ] 实现 `after_each()` 进行测试清理
- [ ] 测试方法命名:`test_[功能名称]()`
### 测试覆盖
- [ ] 测试核心功能的正常流程
- [ ] 测试错误处理和边界条件
- [ ] 测试初始化和清理逻辑
- [ ] 所有测试都能通过
示例:
```gdscript
extends GutTest
## PlayerController 单元测试
var player: PlayerController
func before_each():
player = preload("res://scenes/Entities/Player/PlayerController.gd").new()
add_child(player)
func after_each():
player.queue_free()
func test_initialization():
var result = player.initialize()
assert_true(result, "Player should initialize successfully")
func test_movement():
# 测试移动功能
pass
```
---
## Git 提交规范检查清单
### 提交类型
- [ ] 使用正确的提交类型:
- `feat` - 新功能
- `fix` - Bug 修复
- `docs` - 文档更新
- `refactor` - 代码重构
- `test` - 测试相关
- `scene` - 场景文件
- `ui` - UI 相关
### 提交格式
- [ ] 使用中文冒号(:)
- [ ] 描述简洁明了(< 50 字符)
- [ ] 使用动词开头(添加、修复、更新)
- [ ] 一次提交只包含一种类型的改动
### 提交原则
- [ ] 一次提交只做一件事
- [ ] 提交的代码能够正常运行
- [ ] 避免 fix + feat 混合提交
- [ ] 如需多种改动,拆分成多次提交
示例:
```bash
# ✅ 正确
git commit -m "feat实现玩家二段跳功能"
git commit -m "fix修复角色跳跃时的碰撞检测问题"
git commit -m "test添加角色控制器单元测试"
# ❌ 错误
git commit -m "fix + feat修复Bug并添加新功能" # 混合类型
git commit -m "update player" # 描述不清晰,使用英文
git commit -m "fix: 修复Bug" # 使用英文冒号
```
---
## 完整工作流检查清单
使用此清单验证开发任务是否完整执行 7 步工作流:
### Step 1: 架构分析
- [ ] 已读取 `docs/02-开发规范/架构与通信规范.md`
- [ ] 已确定文件位置_Core, scenes, UI
- [ ] 已确定通信方式EventSystem
- [ ] 已列出依赖的管理器/系统
- [ ] 已设计事件定义(如需要)
### Step 2: 功能实现
- [ ] 代码遵循分层架构
- [ ] 所有变量和函数有类型注解
- [ ] 使用 Godot 4.2+ 语法
- [ ] 使用 EventSystem 进行跨模块通信
- [ ] 使用 @onready 缓存节点引用
### Step 3: 注释规范检查
- [ ] 已读取 `docs/02-开发规范/代码注释规范.md`
- [ ] 文件头注释完整
- [ ] 公共函数有完整注释
- [ ] 复杂逻辑有行内注释
### Step 4: 命名规范检查
- [ ] 已读取 `docs/02-开发规范/命名规范.md`
- [ ] 类名使用 PascalCase
- [ ] 变量/函数使用 camelCase
- [ ] 常量使用 UPPER_CASE
- [ ] 私有成员使用下划线前缀
### Step 5: 测试代码编写
- [ ] 已读取 `docs/03-技术实现/测试指南.md`
- [ ] 创建了测试文件 `tests/unit/test_[name].gd`
- [ ] 测试文件继承自 GutTest
- [ ] 编写了核心功能测试
### Step 6: 测试验证
- [ ] 运行了 GUT 测试命令
- [ ] 所有测试通过
- [ ] 如有失败,已修复并重新测试
### Step 7: Git 提交
- [ ] 已读取 `docs/02-开发规范/Git提交规范.md`
- [ ] 生成了符合规范的提交信息
- [ ] 提交类型正确
- [ ] 使用中文冒号
- [ ] 遵循"一次提交只做一件事"原则
---
## 快速自检问题
在提交代码前,问自己以下问题:
1. **架构**: 文件放在正确的位置了吗?
2. **通信**: 是否使用 EventSystem 进行跨模块通信?
3. **类型**: 所有变量和函数都有类型注解吗?
4. **命名**: 命名是否符合规范PascalCase/camelCase/UPPER_CASE
5. **注释**: 文件头和公共函数有完整注释吗?
6. **测试**: 创建并运行测试了吗?所有测试都通过了吗?
7. **提交**: Git 提交信息符合规范吗?
如果以上问题都能回答"是",那么代码已经符合 WhaleTown 项目的质量标准!✅

View File

@@ -0,0 +1,312 @@
# WhaleTown Developer Skill 使用说明
## 📖 简介
`whaletown-developer` 是 WhaleTown 项目的标准开发工作流自动化技能,确保所有开发任务都遵循统一的项目规范和质量标准。
## 🎯 适用场景
在以下情况下使用此 skill
- ✅ 实现新功能("实现玩家二段跳"、"添加存档系统"
- ✅ 修复 Bug"修复角色碰撞问题"、"解决UI显示错误"
- ✅ 创建场景("创建商店场景"、"设计背包界面"
- ✅ 开发模块("开发任务系统"、"构建战斗组件"
- ✅ 任何需要遵循项目规范的代码开发任务
## 🚀 调用方式
### 方式一:通过 Claude推荐
```
用户:帮我实现一个 NPC
Claude/whaletown-developer 实现一个 NPC
```
### 方式二:直接请求
```
用户:使用 whaletown-developer skill 创建玩家移动系统
```
## 📋 7 步工作流程
skill 会自动执行以下标准化流程:
```
Step 1: 架构分析
↓ 读取架构规范,确定文件位置、通信方式、依赖关系
Step 2: 功能实现
↓ 按照类型安全、命名规范、EventSystem 通信等要求编码
Step 3: 注释规范检查
↓ 验证文件头、函数文档、行内注释是否完整
Step 4: 命名规范检查
↓ 验证 PascalCase/camelCase/UPPER_CASE 命名规范
Step 5: 测试代码编写
↓ 为核心功能创建 GUT 单元测试
Step 6: 测试验证
↓ 运行测试确保功能正常
Step 7: Git 提交
↓ 生成符合规范的提交信息
```
## 💡 使用示例
### 示例 1创建玩家控制器
**用户输入:**
```
帮我创建一个玩家角色控制器
```
**Skill 执行:**
1. 分析架构 → 确定放在 `scenes/Entities/Player/PlayerController.gd`
2. 实现功能 → 创建带类型注解的移动、跳跃逻辑
3. 检查注释 → 添加完整的文件头和函数文档
4. 检查命名 → 确保 `moveSpeed``MAX_HEALTH` 等命名正确
5. 编写测试 → 创建 `tests/unit/test_player_controller.gd`
6. 运行测试 → 验证功能正常
7. 生成提交 → `feat实现玩家角色控制器`
### 示例 2修复跳跃 Bug
**用户输入:**
```
修复玩家跳跃时的碰撞检测问题
```
**Skill 执行:**
1. 分析架构 → 定位到 `scenes/Entities/Player/Player.gd`
2. 实现修复 → 修改碰撞检测逻辑
3. 检查注释 → 添加修复说明注释
4. 检查命名 → 确保变量命名规范
5. 编写测试 → 添加碰撞测试用例
6. 运行测试 → 确认 Bug 已修复
7. 生成提交 → `fix修复玩家跳跃时的碰撞检测问题`
### 示例 3添加事件通信
**用户输入:**
```
实现 NPC 对话系统的事件通信
```
**Skill 执行:**
1. 分析架构 → 使用 EventSystem 跨模块通信
2. 实现功能 → 在 EventNames.gd 添加 `NPC_DIALOG_STARTED` 事件
3. 检查注释 → 文档化事件数据格式
4. 检查命名 → 确保事件名称符合规范
5. 编写测试 → 测试事件发送和接收
6. 运行测试 → 验证通信正常
7. 生成提交 → `feat实现NPC对话系统的事件通信`
## ✅ 质量保证
每次使用 skill 后,代码都会符合以下标准:
### 架构层面
- ✅ 文件位置符合分层架构_Core、scenes、UI
- ✅ 使用 EventSystem 实现跨模块通信
- ✅ 事件名称已添加到 EventNames.gd
- ✅ 遵循"Signal Up, Call Down"原则
### 代码质量
- ✅ 所有变量和函数都有类型注解
- ✅ 命名规范正确PascalCase/camelCase/UPPER_CASE
- ✅ 使用 Godot 4.2+ 语法await 而非 yield
- ✅ 节点引用使用 @onready 缓存
### 文档规范
- ✅ 文件头注释完整(文件名、作用、功能、依赖)
- ✅ 公共函数有完整文档(参数、返回值、示例)
- ✅ 复杂逻辑有行内注释说明
### 测试覆盖
- ✅ 核心功能有单元测试
- ✅ 测试文件命名规范test_*.gd
- ✅ 测试通过验证
### Git 规范
- ✅ 提交信息格式正确(类型:描述)
- ✅ 遵循"一次提交只做一件事"原则
- ✅ 使用中文冒号和动词开头
## 📚 相关文档
Skill 会自动读取以下规范文档:
- `docs/02-开发规范/架构与通信规范.md` - 分层架构和 EventSystem
- `docs/02-开发规范/代码注释规范.md` - 注释格式要求
- `docs/02-开发规范/命名规范.md` - 命名约定
- `docs/03-技术实现/测试指南.md` - 测试框架使用
- `docs/02-开发规范/Git提交规范.md` - 提交信息格式
- `CLAUDE.md` - 项目总体指导
## ⚙️ 配置文件
Skill 相关配置文件位置:
```
.claude/skills/whaletown-developer/
├── SKILL.md # Skill 定义文件
├── 使用说明.md # 本文档
└── references/
└── checklist.md # 质量检查清单
```
## 🔄 工作流程可视化
```
用户请求
调用 whaletown-developer skill
[Step 1] 架构分析
├─ 读取架构规范文档
├─ 确定文件位置
├─ 识别通信方式
└─ 设计事件定义
[Step 2] 功能实现
├─ 遵循类型安全
├─ 使用 EventSystem
├─ 缓存节点引用
└─ 使用 Godot 4.2+ 语法
[Step 3] 注释规范检查
├─ 验证文件头注释
├─ 验证函数文档
└─ 检查行内注释
[Step 4] 命名规范检查
├─ 类名 PascalCase
├─ 变量/函数 camelCase
├─ 常量 UPPER_CASE
└─ 私有成员 _prefix
[Step 5] 测试代码编写
├─ 创建测试文件
├─ 编写测试用例
└─ 覆盖核心功能
[Step 6] 测试验证
├─ 运行 GUT 测试
├─ 验证测试通过
└─ 修复失败测试
[Step 7] Git 提交
├─ 确定提交类型
├─ 生成提交信息
└─ 遵循提交规范
完成 ✅
```
## 🎓 最佳实践
### 1. 明确任务描述
```bash
# ✅ 好的描述
"实现玩家二段跳功能"
"修复敌人AI路径寻找Bug"
"创建商店购买界面"
# ❌ 模糊描述
"改一下玩家"
"修复Bug"
"做个界面"
```
### 2. 一次处理一个功能
```bash
# ✅ 推荐
用户:实现玩家移动
用户:实现玩家跳跃
# ❌ 不推荐
用户:实现玩家移动、跳跃、攻击、技能系统
```
### 3. 信任 Skill 流程
- Skill 会按照 7 步流程确保质量
- 不需要手动检查命名、注释等细节
- 专注于功能需求和业务逻辑
### 4. 查看生成的提交信息
- Skill 会在 Step 7 生成规范的提交信息
- 可以直接使用或根据需要微调
## ⚠️ 注意事项
1. **首次使用**
- 确保已阅读 `CLAUDE.md` 了解项目规范
- 确认所有规范文档都已存在
2. **测试环境**
- 确保 GUT 测试框架已安装(如需运行测试)
- Godot 可执行文件在 PATH 中Step 6 测试执行)
3. **中断处理**
- 如果工作流被中断,可以继续执行剩余步骤
- Skill 使用 TodoWrite 追踪进度
4. **规范更新**
- 项目规范文档更新时Skill 会自动读取最新版本
- 无需手动同步
## 🤝 反馈与改进
如果遇到问题或有改进建议:
1. 检查是否所有规范文档都已更新
2. 确认任务描述清晰明确
3. 查看 Skill 执行日志定位问题
4. 向团队报告问题或建议
## 📊 效果对比
### 不使用 Skill
```
开发者手动:
1. 不确定文件放哪里 ❌
2. 可能忘记类型注解 ❌
3. 注释不完整 ❌
4. 命名不一致 ❌
5. 没有测试 ❌
6. 提交信息格式错误 ❌
结果:代码质量参差不齐
```
### 使用 Skill
```
Skill 自动化:
1. 自动确定正确位置 ✅
2. 强制类型安全 ✅
3. 完整注释文档 ✅
4. 统一命名规范 ✅
5. 自动生成测试 ✅
6. 规范提交信息 ✅
结果:高质量、一致性代码
```
## 🎯 总结
whaletown-developer skill 是你的开发助手,它会:
- 🤖 **自动化** 7 步标准流程
- 📏 **标准化** 代码质量
- 🔒 **保证** 规范遵循
-**加速** 开发效率
- 🧪 **确保** 测试覆盖
**记住:专注于功能实现,让 Skill 处理规范和质量!**
---
**开始使用:** 只需告诉 Claude "帮我实现 XXX 功能" 即可!

55
.gitignore vendored
View File

@@ -1,3 +1,58 @@
# Godot 4+ specific ignores # Godot 4+ specific ignores
.godot/ .godot/
/android/ /android/
# Python cache files
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
*.so
# IDE and editor files
.vscode/
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Godot executable files (should not be in version control)
Godot/
*.exe
*.app
*.dmg
# Logs and temporary files
*.log
*.tmp
*.temp
# Build outputs
build/
dist/
*.zip
*.tar.gz
# Environment files
.env
.env.local
.env.*.local
# Test coverage reports
coverage/
*.coverage
.nyc_output/
# Dependency directories
node_modules/
vendor/

15
.vscode/launch.json vendored
View File

@@ -1,15 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "GDScript Godot",
"type": "godot",
"request": "launch",
"project": "${workspaceFolder}",
"port": 6007,
"address": "127.0.0.1",
"launch_game_instance": true,
"launch_scene": false
}
]
}

View File

@@ -1,3 +0,0 @@
{
"godotTools.editorPath.godot4": "d:\\software\\godot\\Godot_v4.5.1-stable_win64.exe"
}

29
Config/game_config.json Normal file
View File

@@ -0,0 +1,29 @@
{
"game": {
"name": "whaleTown",
"version": "1.0.0",
"debug_mode": true
},
"network": {
"api_base_url": "https://whaletownend.xinghangee.icu",
"timeout": 30,
"retry_count": 3
},
"ui": {
"default_font_size": 14,
"toast_duration": 2.0,
"transition_duration": 0.3
},
"gameplay": {
"auto_save_interval": 300,
"max_inventory_slots": 50,
"default_player_stats": {
"level": 1,
"coins": 100,
"exp": 0,
"max_exp": 100,
"energy": 100,
"max_energy": 100
}
}
}

36
Config/zh_CN.json Normal file
View File

@@ -0,0 +1,36 @@
{
"ui": {
"login": "登录",
"register": "注册",
"username": "用户名",
"password": "密码",
"email": "邮箱",
"confirm_password": "确认密码",
"verification_code": "验证码",
"send_code": "发送验证码",
"forgot_password": "忘记密码",
"enter_town": "进入小镇",
"logout": "退出登录"
},
"messages": {
"login_success": "登录成功!正在进入鲸鱼镇...",
"register_success": "注册成功!欢迎加入鲸鱼镇",
"network_error": "网络连接失败,请检查网络连接",
"invalid_username": "用户名只能包含字母、数字和下划线",
"invalid_email": "请输入有效的邮箱地址",
"password_too_short": "密码长度至少8位",
"password_mismatch": "两次输入的密码不一致",
"verification_code_sent": "验证码已发送到您的邮箱,请查收"
},
"game": {
"level": "等级",
"coins": "金币",
"experience": "经验",
"energy": "体力",
"explore": "探索小镇",
"inventory": "背包",
"shop": "商店",
"friends": "好友",
"settings": "设置"
}
}

460
README.md
View File

@@ -1,101 +1,395 @@
# whaleTown # 🐋 WhaleTown - 现代化像素游戏
一个使用 Godot 4.5 引擎开发的游戏项目 > 一个基于 Godot 4.5 引擎开发的企业级 2D 像素风游戏,采用模块化架构设计,集成完整的用户认证系统和游戏核心功能
## 项目信息 [![Godot](https://img.shields.io/badge/Godot-4.5+-blue.svg)](https://godotengine.org/)
[![GDScript](https://img.shields.io/badge/GDScript-Latest-green.svg)](https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/index.html)
[![Documentation](https://img.shields.io/badge/Documentation-Complete-brightgreen.svg)](./docs/)
[![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS%20%7C%20Web-lightgrey.svg)](https://godotengine.org/download)
- **引擎版本**: Godot 4.5 ## 🎯 项目简介
- **渲染器**: Forward Plus
- **项目类型**: 2D 游戏
## 项目结构 WhaleTown 是一个功能完整的现代化像素游戏,具有以下特色:
``` - 🏗️ **企业级架构** - 模块化设计,高度解耦,易于扩展
whaleTown/ - 🔐 **完整认证系统** - 登录、注册、邮箱验证、密码管理
├── addons/ # Godot 插件目录 - 🎮 **丰富游戏功能** - 角色系统、场景管理、事件通信
├── assets/ # 游戏资源文件(图片、音频等) - 🌐 **网络通信** - RESTful API集成支持实时数据交互
├── data/ # 游戏数据文件(配置、关卡数据等) - 📚 **企业级文档** - 18个文档覆盖开发全流程
├── docs/ # 项目文档 - 🧪 **完整测试体系** - API测试、UI测试、性能测试
├── scenes/ # 游戏场景文件 - 🚀 **一键部署** - 支持Web、桌面多平台发布
│ └── main_scene.tscn # 主场景
├── scripts/ # GDScript 脚本文件
├── tests/ # 测试文件
├── icon.svg # 项目图标
└── project.godot # Godot 项目配置文件
```
## 开始使用 ---
### 前置要求 ## 🚀 5分钟快速体验
- [Godot Engine 4.5](https://godotengine.org/download) 或更高版本 ### 📋 准备工作
### 运行项目 **你需要安装:**
- [Godot Engine 4.5+](https://godotengine.org/download) - 游戏引擎
- [Git](https://git-scm.com/) - 版本控制工具
1. 克隆或下载此项目 ### 🛠️ 启动项目
2. 使用 Godot 编辑器打开项目
3. 在编辑器中点击"运行"按钮或按 F5 键启动游戏
### 开发指南
- **场景文件**: 所有场景文件存放在 `scenes/` 目录
- **脚本文件**: 所有 GDScript 脚本存放在 `scripts/` 目录
- **资源文件**: 图片、音频等资源存放在 `assets/` 目录
- **游戏数据**: 配置文件、关卡数据等存放在 `data/` 目录
### 命名规范
本项目遵循统一的命名规范以保持代码一致性:
**核心规则**
- **场景文件**`下划线_scene.tscn``下划线_prefab.tscn`
- 示例:`main_scene.tscn``player_prefab.tscn`
- **脚本文件**`PascalCase.gd`(大驼峰)
- 示例:`PlayerController.gd``UI_MainMenu.gd`
- **节点名称**`camelCase`(小驼峰)
- 示例:`playerHpBar``startButton`
- **变量/函数**`camelCase`(小驼峰)
- 示例:`var moveSpeed``func getPlayerPos()`
- **常量**`UPPER_CASE`(全大写 + 下划线)
- 示例:`const MAX_HEALTH = 100`
- **资源文件**`lower_case`(小写 + 下划线)
- 示例:`bg_main_menu.png``sound_jump.wav`
📖 查看完整的 [命名规范文档](docs/naming_convention.md)
### Git 提交规范
本项目遵循统一的 Git 提交信息格式:`<类型><描述>`
**常用提交类型**
- `init`:项目初始化
- `feat`:新增功能
- `fix`:修复 Bug
- `docs`:文档更新
- `scene`:场景文件相关
- `asset`:资源文件相关
- `ui`UI 界面相关
- `gameplay`:游戏玩法相关
- `refactor`:代码重构
- `perf`:性能优化
**提交示例**
```bash ```bash
git commit -m "init项目初始化搭建Godot文件结构" # 1⃣ 获取项目
git commit -m "feat实现玩家角色的移动和跳跃" git clone <repository-url>
git commit -m "fix修复敌人穿墙的碰撞问题" cd whale-town
git commit -m "scene创建战斗场景并配置相机"
# 2⃣ 打开项目
# 双击 project.godot 文件或在Godot编辑器中选择"导入项目"
# 3⃣ 运行游戏
# 在Godot编辑器中按 F5 或点击"运行项目"按钮
``` ```
📖 查看完整的 [Git 提交规范文档](docs/git_commit_guide.md) 🎉 **成功!** 你应该看到游戏的认证界面
## 贡献 ### 🎮 体验功能
欢迎提交 Issue 和 Pull Request 1. **注册新用户** - 体验完整的邮箱验证流程
2. **登录系统** - 尝试用户名/邮箱登录
3. **游戏界面** - 探索主游戏场景
## 许可证 ### 🧪 测试API可选
[在此添加许可证信息] ```bash
# 安装Python依赖
pip install requests
# 快速API测试
python tests/api/quick_test.py
# 完整功能测试
python tests/api/api_client_test.py
```
---
## 📚 新手开发指南
### 🎯 第一步:了解项目
**⚠️ 重要:开始开发前必读**
1. **[📖 项目入门总览](docs/01-项目入门/README.md)** - 5分钟了解项目
2. **[🏗️ 项目结构说明](docs/01-项目入门/项目结构说明.md)** - 理解架构设计
3. **[⚙️ 项目设置指南](docs/01-项目入门/项目设置指南.md)** - 配置开发环境
4. **[🤖 AI开发指南](docs/AI_docs/README.md)** - AI编程助手专用文档
### 🎯 第二步:学习规范
**代码质量保证**
1. **[📝 命名规范](docs/02-开发规范/命名规范.md)** - 统一命名标准
2. **[🏛️ 架构与通信规范](docs/02-开发规范/架构与通信规范.md)** - 组件通信方式
3. **[💬 代码注释规范](docs/02-开发规范/代码注释规范.md)** - 注释标准
4. **[🔄 Git提交规范](docs/02-开发规范/Git提交规范.md)** - 版本控制规范
### 🎯 第三步:开始开发
**技术实现指导**
1. **[🔧 实现细节规范](docs/03-技术实现/实现细节规范.md)** - 游戏对象实现
2. **[🌐 API接口文档](docs/03-技术实现/API接口文档.md)** - 后端接口使用
3. **[🧪 测试指南](docs/03-技术实现/测试指南.md)** - 测试方法和工具
### 🎯 第四步:高级开发
**进阶技能**
1. **[🚀 性能优化指南](docs/04-高级开发/性能优化指南.md)** - 性能调优
2. **[🎬 场景设计规范](docs/04-高级开发/场景设计规范.md)** - 场景架构
3. **[🧩 模块开发指南](docs/04-高级开发/模块开发指南.md)** - 模块化开发
### 🎯 第五步:项目发布
**部署和运维**
1. **[🌐 Web部署指南](docs/05-部署运维/Web部署指南.md)** - 完整部署流程
---
## 🏗️ 项目架构一览
### 📁 目录结构
```
WhaleTown/ # 🐋 项目根目录
├── 📚 docs/ # 📖 完整文档系统18个文档
│ ├── 01-项目入门/ # 👋 新人必读
│ ├── 02-开发规范/ # 📋 编码标准
│ ├── 03-技术实现/ # 🔧 开发指导
│ ├── 04-高级开发/ # 🚀 进阶技巧
│ ├── 05-部署运维/ # 🌐 发布部署
│ ├── 06-功能模块/ # 🎮 功能文档
│ └── AI_docs/ # 🤖 AI专用文档执行规范、代码模板
├── 🔧 _Core/ # ⚙️ 核心底层实现
│ ├── managers/ # 🎯 全局管理器(游戏状态、场景、网络等)
│ ├── systems/ # 🔄 系统组件(事件系统、输入系统等)
│ ├── components/ # 🧩 基础组件实现
│ ├── utils/ # <20> 核件心工具类(字符串处理、数学计算等)
│ ├── EventNames.gd # 📝 事件名称定义
│ └── ProjectPaths.gd # <20> 路径组统一管理
├── 🎬 scenes/ # 🎭 场景与视觉呈现
│ ├── maps/ # <20> 地图一场景(游戏关卡、世界地图)
│ ├── characters/ # 👤 人物场景角色、NPC、敌人
│ ├── ui/ # 🖼️ UI界面场景菜单、HUD、对话框
│ ├── effects/ # ✨ 特效场景(粒子效果、动画)
│ └── prefabs/ # 🧩 预制体组件
├── 🎨 assets/ # 🖼️ 静态资源存储
│ ├── sprites/ # 🎨 精灵图片(角色、物品、环境)
│ ├── audio/ # 🎵 音频资源(音乐、音效)
│ ├── fonts/ # 🔤 字体文件
│ ├── materials/ # 🎭 材质资源
│ ├── shaders/ # 🌈 着色器文件
│ ├── ui/ # 🖼️ UI素材按钮、图标、背景
│ └── icon/ # 📱 应用图标
├── ⚙️ Config/ # 📋 配置文件管理
│ ├── game_config.json # 🎮 游戏配置(难度、设置等)
│ ├── zh_CN.json # 🌐 本地化配置
│ └── environment/ # 🔧 环境配置(开发、测试、生产)
├── 🧪 tests/ # 🔬 测试文件系统
│ ├── unit/ # 🔍 单元测试(组件功能测试)
│ ├── integration/ # 🔗 集成测试(系统交互测试)
│ ├── performance/ # ⚡ 性能测试(帧率、内存优化)
│ └── api/ # 🌐 API接口测试
└── 🌐 web_assets/ # 🌍 Web导出资源
├── html/ # 📄 HTML模板文件
├── css/ # 🎨 样式文件
└── js/ # 📜 JavaScript脚本
```
### 🔧 核心架构说明
| 目录 | 作用 | 详细说明 |
|------|------|----------|
| **_Core** | 🔧 功能实现与组件实现 | 项目最基本的底层实现,包含所有核心系统和基础组件 |
| **scenes** | 🎭 场景与视觉呈现 | 包含地图场景、人物场景等一系列视觉呈现部分主要是UI的实现 |
| **assets** | 🎨 静态资源存储 | 所有静态资源的存储,包括图片、音乐、视频、贴图等素材 |
| **Config** | ⚙️ 配置文件管理 | 主要用来配置各类环境,包括游戏设置、本地化等配置 |
| **tests** | 🧪 测试文件系统 | 放置所有对应组件的测试代码,方便快速进行功能性与性能测试 |
| **web_assets** | 🌐 Web导出资源 | 专门用于Web平台导出的相关资源和配置文件 |
| **docs/AI_docs** | 🤖 AI专用文档 | 专门为AI编程助手准备的执行规范和代码模板提升vibe coding效率 |
### 🎮 核心组件
| 组件 | 位置 | 作用 | 文档链接 |
|------|------|------|----------|
| **EventSystem** | _Core/systems/ | 全局事件通信系统 | [架构规范](docs/02-开发规范/架构与通信规范.md) |
| **GameManager** | _Core/managers/ | 游戏状态管理器 | [实现细节](docs/03-技术实现/实现细节规范.md) |
| **SceneManager** | _Core/managers/ | 场景切换管理器 | [场景设计](docs/04-高级开发/场景设计规范.md) |
| **NetworkManager** | _Core/managers/ | 网络请求管理器 | [网络管理器](docs/03-技术实现/网络管理器设置.md) |
| **ProjectPaths** | _Core/ | 路径统一管理工具 | [项目结构](docs/01-项目入门/项目结构说明.md) |
---
## 🎮 核心功能
### 🔐 用户认证系统
**完整的用户管理功能**
- ✅ 用户注册(用户名+邮箱验证)
- ✅ 多方式登录(用户名/邮箱/验证码)
- ✅ 密码管理(修改/重置)
- ✅ 表单验证(实时验证+友好提示)
- ✅ 错误处理(网络异常+业务错误)
**技术特色**
- 📱 响应式UI设计
- 🔄 实时表单验证
- ⏰ 验证码冷却机制
- 🎨 流畅动画效果
### 🎮 游戏核心系统
**模块化游戏架构**
- 🎭 场景管理系统
- 🔄 事件通信系统
- 🎯 状态管理系统
- 🌐 网络通信系统
**开发友好特性**
- 🧩 高度模块化
- 📝 完整文档覆盖
- 🧪 测试用例齐全
- 🔧 开发工具完善
---
## 🧪 测试系统
### 🔬 测试类型
| 测试类型 | 工具 | 覆盖范围 | 文档 |
|----------|------|----------|------|
| **API测试** | Python脚本 | 17个接口全覆盖 | [测试指南](docs/03-技术实现/测试指南.md) |
| **UI测试** | Godot场景 | 认证流程完整测试 | [认证测试](docs/06-功能模块/auth/认证测试指南.md) |
| **单元测试** | GUT框架 | 核心组件测试 | [测试指南](docs/03-技术实现/测试指南.md) |
### 🚀 快速测试
```bash
# 🔌 API接口测试30秒
python tests/api/quick_test.py
# 🔍 完整功能测试2-3分钟
python tests/api/api_client_test.py
# 🎮 UI交互测试在Godot中运行
# 打开 tests/auth/auth_ui_test.tscn 场景
```
---
## 🚀 部署发布
### 🖥️ 桌面版本
```bash
# Windows
godot --export "Windows Desktop" build/WhaleTown.exe
# Linux
godot --export "Linux/X11" build/WhaleTown.x86_64
# macOS
godot --export "macOS" build/WhaleTown.app
```
### 🌐 Web版本
```bash
# 使用自动化脚本
scripts/build_web.bat # Windows
scripts/build_web.sh # Linux/macOS
# 本地测试
scripts/serve_web.bat # 启动本地服务器
```
**详细部署流程**: [Web部署指南](docs/05-部署运维/Web部署指南.md)
---
## 📊 项目统计
### 📚 文档系统
| 类别 | 文档数 | 完成度 |
|------|--------|--------|
| 项目入门 | 3 | 100% |
| 开发规范 | 5 | 100% |
| 技术实现 | 4 | 100% |
| 高级开发 | 3 | 100% |
| 部署运维 | 1 | 100% |
| 功能模块 | 2 | 100% |
| **总计** | **18** | **100%** |
### 🧪 测试覆盖
- **API接口**: 17个接口 ✅
- **认证流程**: 完整测试 ✅
- **错误处理**: 边界测试 ✅
- **性能监控**: 帧率/内存 ✅
---
## 🤝 参与贡献
### 🌟 贡献方式
1. **🐛 Bug修复** - 发现并修复问题
2. **✨ 新功能** - 添加有价值的功能
3. **📚 文档改进** - 完善项目文档
4. **🧪 测试用例** - 提高代码覆盖率
5. **🎨 UI/UX改进** - 提升用户体验
### 📋 贡献流程
```bash
# 1⃣ Fork项目到你的账户
# 2⃣ 克隆到本地
git clone <your-fork-url>
cd whale-town
# 3⃣ 创建功能分支
git checkout -b feature/your-feature
# 4⃣ 开发功能(遵循项目规范)
# 参考: docs/02-开发规范/
# 5⃣ 添加测试用例
# 参考: docs/03-技术实现/测试指南.md
# 6⃣ 提交代码
git commit -m "feat添加新功能"
# 参考: docs/02-开发规范/Git提交规范.md
# 7⃣ 推送分支
git push origin feature/your-feature
# 8⃣ 创建Pull Request
```
### 📖 开发规范
**必读文档**
- [命名规范](docs/02-开发规范/命名规范.md) - 代码命名标准
- [Git提交规范](docs/02-开发规范/Git提交规范.md) - 提交信息格式
- [代码注释规范](docs/02-开发规范/代码注释规范.md) - 注释标准
### 🙏 贡献者致谢
感谢所有为 WhaleTown 项目做出贡献的开发者们!详细的贡献者信息和统计请查看:
**[📖 贡献者详细信息](docs/CONTRIBUTORS.md)**
---
## 📞 获取帮助
### 🔍 问题解决
| 问题类型 | 解决方案 |
|----------|----------|
| **🤔 不知道从哪开始** | [项目入门总览](docs/01-项目入门/README.md) |
| **🏗️ 不理解项目架构** | [项目结构说明](docs/01-项目入门/项目结构说明.md) |
| **🔧 开发环境问题** | [项目设置指南](docs/01-项目入门/项目设置指南.md) |
| **📝 不知道怎么命名** | [命名规范](docs/02-开发规范/命名规范.md) |
| **🔄 组件通信问题** | [架构与通信规范](docs/02-开发规范/架构与通信规范.md) |
| **🌐 API调用问题** | [API接口文档](docs/03-技术实现/API接口文档.md) |
| **🧪 测试相关问题** | [测试指南](docs/03-技术实现/测试指南.md) |
| **🚀 部署发布问题** | [Web部署指南](docs/05-部署运维/Web部署指南.md) |
### 📚 文档导航
- **[📖 完整文档中心](docs/README.md)** - 所有文档的导航页面
- **[📋 文档更新日志](docs/CHANGELOG.md)** - 文档版本变更记录
### 💬 联系方式
- **项目地址**: [Gitea Repository](https://gitea.xinghangee.icu/datawhale/whale-town)
- **问题反馈**: [Issues](https://gitea.xinghangee.icu/datawhale/whale-town/issues)
- **功能建议**: [Discussions](https://gitea.xinghangee.icu/datawhale/whale-town/discussions)
---
## 📄 许可证
本项目采用 [MIT License](./LICENSE) 开源协议。
---
<div align="center">
**🐋 WhaleTown - 企业级像素游戏开发框架**
*让游戏开发更简单,让代码质量更优秀*
[⭐ Star](https://gitea.xinghangee.icu/datawhale/whale-town) | [🍴 Fork](https://gitea.xinghangee.icu/datawhale/whale-town/fork) | [📖 文档](./docs/) | [🐛 反馈](https://gitea.xinghangee.icu/datawhale/whale-town/issues)
**文档版本**: v1.2.0 | **最后更新**: 2025-12-31
</div>

60
_Core/EventNames.gd Normal file
View File

@@ -0,0 +1,60 @@
# ============================================================================
# 事件名称定义 - EventNames.gd
#
# 定义项目中所有事件的名称常量,确保事件名称的一致性和可维护性
#
# 使用方式:
# EventSystem.emit_event(EventNames.PLAYER_MOVED, data)
# EventSystem.connect_event(EventNames.INTERACT_PRESSED, callback)
# ============================================================================
class_name EventNames
# ============================================================================
# 玩家相关事件
# ============================================================================
const PLAYER_MOVED = "player_moved"
const PLAYER_SPAWNED = "player_spawned"
const PLAYER_HEALTH_CHANGED = "player_health_changed"
const PLAYER_DIED = "player_died"
const PLAYER_RESPAWNED = "player_respawned"
const PLAYER_ATTACK = "player_attack"
# ============================================================================
# 交互事件
# ============================================================================
const INTERACT_PRESSED = "interact_pressed"
const NPC_TALKED = "npc_talked"
const ITEM_COLLECTED = "item_collected"
const OBJECT_INTERACTED = "object_interacted"
# ============================================================================
# UI事件
# ============================================================================
const UI_BUTTON_CLICKED = "ui_button_clicked"
const DIALOG_OPENED = "dialog_opened"
const DIALOG_CLOSED = "dialog_closed"
const MENU_OPENED = "menu_opened"
const MENU_CLOSED = "menu_closed"
# ============================================================================
# 游戏状态事件
# ============================================================================
const GAME_PAUSED = "game_paused"
const GAME_RESUMED = "game_resumed"
const SCENE_CHANGED = "scene_changed"
const SCENE_DATA_TRANSFER = "scene_data_transfer"
# ============================================================================
# 系统事件
# ============================================================================
const TILEMAP_READY = "tilemap_ready"
const COMPONENT_MESSAGE = "component_message"
const POSITION_UPDATE = "position_update"
const GRID_POSITION_CHANGED = "grid_position_changed"
const GRID_SNAP_REQUESTED = "grid_snap_requested"
# ============================================================================
# 测试事件
# ============================================================================
const TEST_EVENT = "test_event"

1
_Core/EventNames.gd.uid Normal file
View File

@@ -0,0 +1 @@
uid://qn0imbklx1m0

118
_Core/ProjectPaths.gd Normal file
View File

@@ -0,0 +1,118 @@
# ============================================================================
# 项目路径配置 - ProjectPaths.gd
#
# 统一管理项目中所有路径常量,确保路径的一致性和可维护性
#
# 使用方式:
# var scene_path = ProjectPaths.SCENES_COMPONENTS + "ui/Button.tscn"
# var config_path = ProjectPaths.DATA_CONFIG + "game_config.json"
# ============================================================================
class_name ProjectPaths
# ============================================================================
# 核心系统路径
# ============================================================================
const CORE_ROOT = "res://_Core/"
const CORE_MANAGERS = CORE_ROOT + "managers/"
const CORE_SYSTEMS = CORE_ROOT + "systems/"
const CORE_COMPONENTS = CORE_ROOT + "components/"
const CORE_UTILS = CORE_ROOT + "utils/"
# 系统文件路径
const GRID_SYSTEM = CORE_SYSTEMS + "GridSystem.gd"
const EVENT_SYSTEM = CORE_SYSTEMS + "EventSystem.gd"
const TILE_SYSTEM = CORE_SYSTEMS + "TileSystem.gd"
# ============================================================================
# 场景路径
# ============================================================================
const SCENES_ROOT = "res://scenes/"
const SCENES_MAPS = SCENES_ROOT + "Maps/"
const SCENES_COMPONENTS = SCENES_ROOT + "Components/"
const SCENES_UI_COMPONENTS = SCENES_COMPONENTS + "ui/"
const SCENES_CHARACTER_COMPONENTS = SCENES_COMPONENTS + "characters/"
const SCENES_EFFECT_COMPONENTS = SCENES_COMPONENTS + "effects/"
const SCENES_ITEM_COMPONENTS = SCENES_COMPONENTS + "items/"
# ============================================================================
# UI路径
# ============================================================================
const UI_ROOT = "res://scenes/ui/"
const UI_WINDOWS = UI_ROOT
# ============================================================================
# 资源路径
# ============================================================================
const ASSETS_ROOT = "res://assets/"
const ASSETS_SPRITES = ASSETS_ROOT + "sprites/"
const ASSETS_AUDIO = ASSETS_ROOT + "audio/"
const ASSETS_FONTS = ASSETS_ROOT + "fonts/"
const ASSETS_MATERIALS = ASSETS_ROOT + "materials/"
const ASSETS_SHADERS = ASSETS_ROOT + "shaders/"
# 地形资源路径
const ASSETS_TERRAIN = ASSETS_SPRITES + "terrain/"
const ASSETS_GRASS = ASSETS_TERRAIN + "grass/"
# ============================================================================
# 数据路径
# ============================================================================
const DATA_ROOT = "res://data/"
const DATA_CONFIG = "res://Config/"
const DATA_SCENES = DATA_ROOT + "scenes/"
const DATA_LEVELS = DATA_ROOT + "levels/"
const DATA_DIALOGUES = DATA_ROOT + "dialogues/"
# ============================================================================
# Web资源路径
# ============================================================================
const WEB_ASSETS = "res://web_assets/"
# ============================================================================
# 测试路径
# ============================================================================
const TESTS_ROOT = "res://tests/"
const TESTS_UNIT = TESTS_ROOT + "unit/"
const TESTS_INTEGRATION = TESTS_ROOT + "integration/"
const TESTS_AUTH = TESTS_ROOT + "auth/"
# ============================================================================
# 工具路径
# ============================================================================
const UTILS_ROOT = "res://_Core/utils/"
# ============================================================================
# 模块路径
# ============================================================================
const MODULES_ROOT = "res://module/"
# ============================================================================
# 辅助方法
# ============================================================================
# 获取场景组件路径
static func get_component_path(category: String, component_name: String) -> String:
match category:
"ui":
return SCENES_UI_COMPONENTS + component_name + ".tscn"
"characters":
return SCENES_CHARACTER_COMPONENTS + component_name + ".tscn"
"effects":
return SCENES_EFFECT_COMPONENTS + component_name + ".tscn"
"items":
return SCENES_ITEM_COMPONENTS + component_name + ".tscn"
_:
return SCENES_COMPONENTS + component_name + ".tscn"
# 获取模块路径
static func get_module_path(module_name: String) -> String:
return MODULES_ROOT + module_name + "/"
# 获取模块配置路径
static func get_module_config_path(module_name: String) -> String:
return get_module_path(module_name) + "data/module_config.json"
# 获取场景数据路径
static func get_scene_data_path(scene_name: String) -> String:
return DATA_SCENES + scene_name.to_lower() + ".json"

View File

@@ -0,0 +1 @@
uid://dybcuscku7tyl

View File

@@ -0,0 +1,2 @@
# 基础组件实现目录
# 存放项目的基础组件类

View File

@@ -0,0 +1,589 @@
class_name AuthManager
# ============================================================================
# AuthManager.gd - 认证管理器
# ============================================================================
# 认证系统的业务逻辑管理器,负责处理所有认证相关的业务逻辑
#
# 核心职责:
# - 用户登录业务逻辑(密码登录 + 验证码登录)
# - 用户注册业务逻辑
# - 表单验证逻辑
# - 验证码管理逻辑
# - 网络请求管理
# - 响应处理和状态管理
#
# 使用方式:
# var auth_manager = AuthManager.new()
# auth_manager.login_success.connect(_on_login_success)
# auth_manager.execute_password_login(username, password)
#
# 注意事项:
# - 这是业务逻辑层不包含任何UI相关代码
# - 通过信号与UI层通信
# - 所有验证逻辑都在这里实现
# ============================================================================
extends RefCounted
# ============ 信号定义 ============
# 登录成功信号
signal login_success(username: String)
# 登录失败信号
signal login_failed(message: String)
# 注册成功信号
signal register_success(message: String)
# 注册失败信号
signal register_failed(message: String)
# 验证码发送成功信号
signal verification_code_sent(message: String)
# 验证码发送失败信号
signal verification_code_failed(message: String)
# 表单验证失败信号
signal form_validation_failed(field: String, message: String)
# 网络状态变化信号
signal network_status_changed(is_connected: bool, message: String)
# 按钮状态变化信号
signal button_state_changed(button_name: String, is_loading: bool, text: String)
# Toast消息信号
signal show_toast_message(message: String, is_success: bool)
# ============ 枚举定义 ============
# 登录模式枚举
enum LoginMode {
PASSWORD, # 密码登录模式
VERIFICATION # 验证码登录模式
}
# ============ 成员变量 ============
# 登录状态
var current_login_mode: LoginMode = LoginMode.PASSWORD
var is_processing: bool = false
# 验证码管理
var verification_codes_sent: Dictionary = {}
var code_cooldown: float = 60.0
var current_email: String = ""
# 网络请求管理
var active_request_ids: Array = []
# ============ 生命周期方法 ============
# 初始化管理器
func _init():
print("AuthManager 初始化完成")
# 清理资源
func cleanup():
# 取消所有活动的网络请求
for request_id in active_request_ids:
NetworkManager.cancel_request(request_id)
active_request_ids.clear()
# ============ 登录相关方法 ============
# 执行密码登录
#
# 参数:
# username: String - 用户名/邮箱
# password: String - 密码
#
# 功能:
# - 验证输入参数
# - 发送登录请求
# - 处理响应结果
func execute_password_login(username: String, password: String):
if is_processing:
show_toast_message.emit("请等待当前操作完成", false)
return
# 验证输入
var validation_result = validate_login_inputs(username, password)
if not validation_result.valid:
form_validation_failed.emit(validation_result.field, validation_result.message)
return
# 设置处理状态
is_processing = true
button_state_changed.emit("main_btn", true, "登录中...")
show_toast_message.emit("正在验证登录信息...", true)
# 发送网络请求
var request_id = NetworkManager.login(username, password, _on_login_response)
if request_id != "":
active_request_ids.append(request_id)
else:
_reset_login_state()
show_toast_message.emit("网络请求失败", false)
# 执行验证码登录
#
# 参数:
# identifier: String - 用户标识符
# verification_code: String - 验证码
func execute_verification_login(identifier: String, verification_code: String):
if is_processing:
show_toast_message.emit("请等待当前操作完成", false)
return
# 验证输入
if identifier.is_empty():
form_validation_failed.emit("username", "请输入用户名/手机/邮箱")
return
if verification_code.is_empty():
form_validation_failed.emit("verification", "请输入验证码")
return
# 设置处理状态
is_processing = true
button_state_changed.emit("main_btn", true, "登录中...")
show_toast_message.emit("正在验证验证码...", true)
# 发送网络请求
var request_id = NetworkManager.verification_code_login(identifier, verification_code, _on_verification_login_response)
if request_id != "":
active_request_ids.append(request_id)
else:
_reset_login_state()
show_toast_message.emit("网络请求失败", false)
# 切换登录模式
func toggle_login_mode():
if current_login_mode == LoginMode.PASSWORD:
current_login_mode = LoginMode.VERIFICATION
else:
current_login_mode = LoginMode.PASSWORD
# 获取当前登录模式
func get_current_login_mode() -> LoginMode:
return current_login_mode
# ============ 注册相关方法 ============
# 执行用户注册
#
# 参数:
# username: String - 用户名
# email: String - 邮箱
# password: String - 密码
# confirm_password: String - 确认密码
# verification_code: String - 邮箱验证码
func execute_register(username: String, email: String, password: String, confirm_password: String, verification_code: String):
if is_processing:
show_toast_message.emit("请等待当前操作完成", false)
return
# 验证注册表单
var validation_result = validate_register_form(username, email, password, confirm_password, verification_code)
if not validation_result.valid:
form_validation_failed.emit(validation_result.field, validation_result.message)
return
# 设置处理状态
is_processing = true
button_state_changed.emit("register_btn", true, "注册中...")
show_toast_message.emit("正在创建账户...", true)
# 发送注册请求
var request_id = NetworkManager.register(username, password, username, email, verification_code, _on_register_response)
if request_id != "":
active_request_ids.append(request_id)
else:
_reset_register_state()
show_toast_message.emit("网络请求失败", false)
# ============ 验证码相关方法 ============
# 发送邮箱验证码
#
# 参数:
# email: String - 邮箱地址
func send_email_verification_code(email: String):
# 验证邮箱格式
var email_validation = validate_email(email)
if not email_validation.valid:
form_validation_failed.emit("email", email_validation.message)
return
# 检查冷却时间
if not _can_send_verification_code(email):
var remaining = get_remaining_cooldown_time(email)
show_toast_message.emit("该邮箱请等待 %d 秒后再次发送" % remaining, false)
return
# 记录发送状态
_record_verification_code_sent(email)
# 发送请求
var request_id = NetworkManager.send_email_verification(email, _on_send_code_response)
if request_id != "":
active_request_ids.append(request_id)
else:
_reset_verification_code_state(email)
show_toast_message.emit("网络请求失败", false)
# 发送登录验证码
#
# 参数:
# identifier: String - 用户标识符
func send_login_verification_code(identifier: String):
if identifier.is_empty():
form_validation_failed.emit("username", "请先输入用户名/手机/邮箱")
return
button_state_changed.emit("get_code_btn", true, "发送中...")
show_toast_message.emit("正在发送登录验证码...", true)
var request_id = NetworkManager.send_login_verification_code(identifier, _on_send_login_code_response)
if request_id != "":
active_request_ids.append(request_id)
else:
button_state_changed.emit("get_code_btn", false, "获取验证码")
show_toast_message.emit("网络请求失败", false)
# 发送密码重置验证码
#
# 参数:
# identifier: String - 用户标识符
func send_password_reset_code(identifier: String):
if identifier.is_empty():
show_toast_message.emit("请先输入邮箱或手机号", false)
return
if not _is_valid_identifier(identifier):
show_toast_message.emit("请输入有效的邮箱或手机号", false)
return
button_state_changed.emit("forgot_password_btn", true, "发送中...")
show_toast_message.emit("正在发送密码重置验证码...", true)
var request_id = NetworkManager.forgot_password(identifier, _on_forgot_password_response)
if request_id != "":
active_request_ids.append(request_id)
else:
button_state_changed.emit("forgot_password_btn", false, "忘记密码")
show_toast_message.emit("网络请求失败", false)
# ============ 验证方法 ============
# 验证登录输入
func validate_login_inputs(username: String, password: String) -> Dictionary:
var result = {"valid": false, "field": "", "message": ""}
if username.is_empty():
result.field = "username"
result.message = "用户名不能为空"
return result
if password.is_empty():
result.field = "password"
result.message = "密码不能为空"
return result
result.valid = true
return result
# 验证注册表单
func validate_register_form(username: String, email: String, password: String, confirm_password: String, verification_code: String) -> Dictionary:
var result = {"valid": false, "field": "", "message": ""}
# 验证用户名
var username_validation = validate_username(username)
if not username_validation.valid:
result.field = "username"
result.message = username_validation.message
return result
# 验证邮箱
var email_validation = validate_email(email)
if not email_validation.valid:
result.field = "email"
result.message = email_validation.message
return result
# 验证密码
var password_validation = validate_password(password)
if not password_validation.valid:
result.field = "password"
result.message = password_validation.message
return result
# 验证确认密码
var confirm_validation = validate_confirm_password(password, confirm_password)
if not confirm_validation.valid:
result.field = "confirm"
result.message = confirm_validation.message
return result
# 验证验证码
var code_validation = validate_verification_code(verification_code)
if not code_validation.valid:
result.field = "verification"
result.message = code_validation.message
return result
# 检查是否已发送验证码
if not _has_sent_verification_code(email):
result.field = "verification"
result.message = "请先获取邮箱验证码"
return result
result.valid = true
return result
# 验证用户名
func validate_username(username: String) -> Dictionary:
var result = {"valid": false, "message": ""}
if username.is_empty():
result.message = "用户名不能为空"
return result
if not StringUtils.is_valid_username(username):
if username.length() > 50:
result.message = "用户名长度不能超过50字符"
else:
result.message = "用户名只能包含字母、数字和下划线"
return result
result.valid = true
return result
# 验证邮箱
func validate_email(email: String) -> Dictionary:
var result = {"valid": false, "message": ""}
if email.is_empty():
result.message = "邮箱不能为空"
return result
if not StringUtils.is_valid_email(email):
result.message = "请输入有效的邮箱地址"
return result
result.valid = true
return result
# 验证密码
func validate_password(password: String) -> Dictionary:
return StringUtils.validate_password_strength(password)
# 验证确认密码
func validate_confirm_password(password: String, confirm: String) -> Dictionary:
var result = {"valid": false, "message": ""}
if confirm.is_empty():
result.message = "确认密码不能为空"
return result
if password != confirm:
result.message = "两次输入的密码不一致"
return result
result.valid = true
return result
# 验证验证码
func validate_verification_code(code: String) -> Dictionary:
var result = {"valid": false, "message": ""}
if code.is_empty():
result.message = "验证码不能为空"
return result
if code.length() != 6:
result.message = "验证码必须是6位数字"
return result
for i in range(code.length()):
var character = code[i]
if not (character >= '0' and character <= '9'):
result.message = "验证码必须是6位数字"
return result
result.valid = true
return result
# ============ 网络响应处理 ============
# 处理登录响应
func _on_login_response(success: bool, data: Dictionary, error_info: Dictionary):
_reset_login_state()
var result = ResponseHandler.handle_login_response(success, data, error_info)
if result.should_show_toast:
show_toast_message.emit(result.message, result.success)
if result.success:
var username = ""
if data.has("data") and data.data.has("user") and data.data.user.has("username"):
username = data.data.user.username
# 延迟发送登录成功信号
await Engine.get_main_loop().create_timer(1.0).timeout
login_success.emit(username)
else:
login_failed.emit(result.message)
# 处理验证码登录响应
func _on_verification_login_response(success: bool, data: Dictionary, error_info: Dictionary):
_reset_login_state()
var result = ResponseHandler.handle_verification_code_login_response(success, data, error_info)
if result.should_show_toast:
show_toast_message.emit(result.message, result.success)
if result.success:
var username = ""
if data.has("data") and data.data.has("user") and data.data.user.has("username"):
username = data.data.user.username
await Engine.get_main_loop().create_timer(1.0).timeout
login_success.emit(username)
else:
login_failed.emit(result.message)
# 处理注册响应
func _on_register_response(success: bool, data: Dictionary, error_info: Dictionary):
_reset_register_state()
var result = ResponseHandler.handle_register_response(success, data, error_info)
if result.should_show_toast:
show_toast_message.emit(result.message, result.success)
if result.success:
register_success.emit(result.message)
else:
register_failed.emit(result.message)
# 处理发送验证码响应
func _on_send_code_response(success: bool, data: Dictionary, error_info: Dictionary):
var result = ResponseHandler.handle_send_verification_code_response(success, data, error_info)
if result.should_show_toast:
show_toast_message.emit(result.message, result.success)
if result.success:
verification_code_sent.emit(result.message)
else:
verification_code_failed.emit(result.message)
_reset_verification_code_state(current_email)
# 处理发送登录验证码响应
func _on_send_login_code_response(success: bool, data: Dictionary, error_info: Dictionary):
button_state_changed.emit("get_code_btn", false, "获取验证码")
var result = ResponseHandler.handle_send_login_code_response(success, data, error_info)
if result.should_show_toast:
show_toast_message.emit(result.message, result.success)
# 处理忘记密码响应
func _on_forgot_password_response(success: bool, data: Dictionary, error_info: Dictionary):
button_state_changed.emit("forgot_password_btn", false, "忘记密码")
var result = ResponseHandler.handle_send_login_code_response(success, data, error_info)
if result.should_show_toast:
show_toast_message.emit(result.message, result.success)
# ============ 网络测试 ============
# 测试网络连接
func test_network_connection():
var request_id = NetworkManager.get_app_status(_on_network_test_response)
if request_id != "":
active_request_ids.append(request_id)
# 处理网络测试响应
func _on_network_test_response(success: bool, data: Dictionary, error_info: Dictionary):
var result = ResponseHandler.handle_network_test_response(success, data, error_info)
network_status_changed.emit(result.success, result.message)
# ============ 私有辅助方法 ============
# 重置登录状态
func _reset_login_state():
is_processing = false
button_state_changed.emit("main_btn", false, "进入小镇")
# 重置注册状态
func _reset_register_state():
is_processing = false
button_state_changed.emit("register_btn", false, "注册")
# 检查是否可以发送验证码
func _can_send_verification_code(email: String) -> bool:
if not verification_codes_sent.has(email):
return true
var email_data = verification_codes_sent[email]
if not email_data.sent:
return true
var current_time = Time.get_time_dict_from_system()
var current_timestamp = current_time.hour * 3600 + current_time.minute * 60 + current_time.second
return (current_timestamp - email_data.time) >= code_cooldown
# 获取剩余冷却时间
func get_remaining_cooldown_time(email: String) -> int:
if not verification_codes_sent.has(email):
return 0
var email_data = verification_codes_sent[email]
var current_time = Time.get_time_dict_from_system()
var current_timestamp = current_time.hour * 3600 + current_time.minute * 60 + current_time.second
return int(code_cooldown - (current_timestamp - email_data.time))
# 记录验证码发送状态
func _record_verification_code_sent(email: String):
var current_time = Time.get_time_dict_from_system()
var current_timestamp = current_time.hour * 3600 + current_time.minute * 60 + current_time.second
if not verification_codes_sent.has(email):
verification_codes_sent[email] = {}
verification_codes_sent[email].sent = true
verification_codes_sent[email].time = current_timestamp
current_email = email
# 重置验证码状态
func _reset_verification_code_state(email: String):
if verification_codes_sent.has(email):
verification_codes_sent[email].sent = false
# 检查是否已发送验证码
func _has_sent_verification_code(email: String) -> bool:
if not verification_codes_sent.has(email):
return false
return verification_codes_sent[email].get("sent", false)
# 验证标识符格式
func _is_valid_identifier(identifier: String) -> bool:
return StringUtils.is_valid_email(identifier) or _is_valid_phone(identifier)
# 验证手机号格式
func _is_valid_phone(phone: String) -> bool:
var regex = RegEx.new()
regex.compile("^\\+?[1-9]\\d{1,14}$")
return regex.search(phone) != null

View File

@@ -0,0 +1 @@
uid://bpdyraefv0yta

View File

@@ -0,0 +1,142 @@
extends Node
# ============================================================================
# GameManager.gd - 游戏管理器
# ============================================================================
# 全局单例管理器,负责游戏状态管理和生命周期控制
#
# 核心职责:
# - 游戏状态切换 (加载、认证、游戏中、暂停等)
# - 用户信息管理
# - 全局配置访问
# - 系统初始化和清理
#
# 使用方式:
# GameManager.change_state(GameManager.GameState.IN_GAME)
# GameManager.set_current_user("player123")
#
# 注意事项:
# - 作为自动加载单例,全局可访问
# - 状态变更会触发 game_state_changed 信号
# - 状态切换应该通过 change_state() 方法进行
# ============================================================================
# ============ 信号定义 ============
# 游戏状态变更信号
# 参数: new_state - 新的游戏状态
signal game_state_changed(new_state: GameState)
# ============ 枚举定义 ============
# 游戏状态枚举
# 定义了游戏的各种运行状态
enum GameState {
LOADING, # 加载中 - 游戏启动时的初始化状态
AUTH, # 认证状态 - 用户登录/注册界面
MAIN_MENU, # 主菜单 - 游戏主界面
IN_GAME, # 游戏中 - 正在进行游戏
PAUSED, # 暂停 - 游戏暂停状态
SETTINGS # 设置 - 设置界面
}
# ============ 成员变量 ============
# 状态管理
var current_state: GameState = GameState.LOADING # 当前游戏状态
var previous_state: GameState = GameState.LOADING # 上一个游戏状态
# 用户信息
var current_user: String = "" # 当前登录用户名
# 游戏配置
var game_version: String = "1.0.0" # 游戏版本号
# ============ 生命周期方法 ============
# 初始化游戏管理器
# 在节点准备就绪时调用,设置初始状态
func _ready():
print("GameManager 初始化完成")
change_state(GameState.AUTH) # 启动时进入认证状态
# ============ 状态管理方法 ============
# 切换游戏状态
#
# 参数:
# new_state: GameState - 要切换到的新状态
#
# 功能:
# - 检查状态是否需要切换
# - 记录状态变更历史
# - 发送状态变更信号
# - 输出状态变更日志
func change_state(new_state: GameState):
# 避免重复切换到相同状态
if current_state == new_state:
return
# 记录状态变更
previous_state = current_state
current_state = new_state
# 输出状态变更日志
print("游戏状态变更: ", GameState.keys()[previous_state], " -> ", GameState.keys()[current_state])
# 发送状态变更信号
game_state_changed.emit(new_state)
# 获取当前游戏状态
#
# 返回值:
# GameState - 当前的游戏状态
func get_current_state() -> GameState:
return current_state
# 获取上一个游戏状态
#
# 返回值:
# GameState - 上一个游戏状态
#
# 使用场景:
# - 从暂停状态恢复时,返回到之前的状态
# - 错误处理时回退到安全状态
func get_previous_state() -> GameState:
return previous_state
# ============ 用户管理方法 ============
# 设置当前登录用户
#
# 参数:
# username: String - 用户名
#
# 功能:
# - 存储当前登录用户信息
# - 输出用户设置日志
#
# 注意事项:
# - 用户登录成功后调用此方法
# - 用户登出时应传入空字符串
func set_current_user(username: String):
current_user = username
print("当前用户设置为: ", username)
# 获取当前登录用户
#
# 返回值:
# String - 当前登录的用户名,未登录时为空字符串
func get_current_user() -> String:
return current_user
# 检查用户是否已登录
#
# 返回值:
# bool - true表示已登录false表示未登录
#
# 使用场景:
# - 进入需要登录的功能前检查
# - UI显示逻辑判断
func is_user_logged_in() -> bool:
return not current_user.is_empty()

View File

@@ -0,0 +1 @@
uid://cd8fn73ysjxh8

View File

@@ -0,0 +1,701 @@
extends Node
# ============================================================================
# NetworkManager.gd - 网络请求管理器
# ============================================================================
# 全局单例管理器统一处理所有HTTP请求
#
# 核心职责:
# - 统一的HTTP请求接口 (GET, POST, PUT, DELETE, PATCH)
# - 认证相关API封装 (登录、注册、验证码等)
# - 请求状态管理和错误处理
# - 支持API v1.1.1规范的响应处理
#
# 使用方式:
# NetworkManager.login("user@example.com", "password", callback)
# var request_id = NetworkManager.get_request("/api/data", callback)
#
# 注意事项:
# - 作为自动加载单例,全局可访问
# - 所有请求都是异步的,通过回调函数或信号处理结果
# - 支持请求超时和取消功能
# - 自动处理JSON序列化和反序列化
# ============================================================================
# ============ 信号定义 ============
# 请求完成信号
# 参数:
# request_id: String - 请求唯一标识符
# success: bool - 请求是否成功
# data: Dictionary - 响应数据
signal request_completed(request_id: String, success: bool, data: Dictionary)
# 请求失败信号
# 参数:
# request_id: String - 请求唯一标识符
# error_type: String - 错误类型名称
# message: String - 错误消息
signal request_failed(request_id: String, error_type: String, message: String)
# ============ 常量定义 ============
# API基础URL - 所有请求的根地址
const API_BASE_URL = "https://whaletownend.xinghangee.icu"
# 默认请求超时时间(秒)
const DEFAULT_TIMEOUT = 30.0
# ============ 枚举定义 ============
# HTTP请求方法枚举
enum RequestType {
GET, # 获取数据
POST, # 创建数据
PUT, # 更新数据
DELETE, # 删除数据
PATCH # 部分更新数据
}
# 错误类型枚举
# 用于分类不同类型的网络错误
enum ErrorType {
NETWORK_ERROR, # 网络连接错误 - 无法连接到服务器
TIMEOUT_ERROR, # 请求超时 - 服务器响应时间过长
PARSE_ERROR, # JSON解析错误 - 服务器返回格式错误
HTTP_ERROR, # HTTP状态码错误 - 4xx, 5xx状态码
BUSINESS_ERROR # 业务逻辑错误 - API返回的业务错误
}
# ============ 请求信息类 ============
# 请求信息封装类
# 存储单个HTTP请求的所有相关信息
class RequestInfo:
var id: String # 请求唯一标识符
var url: String # 完整的请求URL
var method: RequestType # HTTP请求方法
var headers: PackedStringArray # 请求头数组
var body: String # 请求体内容
var timeout: float # 超时时间(秒)
var start_time: float # 请求开始时间戳
var http_request: HTTPRequest # Godot HTTPRequest节点引用
var callback: Callable # 完成时的回调函数
# 构造函数
#
# 参数:
# request_id: String - 请求唯一标识符
# request_url: String - 请求URL
# request_method: RequestType - HTTP方法
# request_headers: PackedStringArray - 请求头(可选)
# request_body: String - 请求体(可选)
# request_timeout: float - 超时时间可选默认使用DEFAULT_TIMEOUT
func _init(request_id: String, request_url: String, request_method: RequestType,
request_headers: PackedStringArray = [], request_body: String = "",
request_timeout: float = DEFAULT_TIMEOUT):
id = request_id
url = request_url
method = request_method
headers = request_headers
body = request_body
timeout = request_timeout
# 记录请求开始时间(简化版时间戳)
start_time = Time.get_time_dict_from_system().hour * 3600 + Time.get_time_dict_from_system().minute * 60 + Time.get_time_dict_from_system().second
# ============ 成员变量 ============
# 活动请求管理
var active_requests: Dictionary = {} # 存储所有活动请求 {request_id: RequestInfo}
var request_counter: int = 0 # 请求计数器用于生成唯一ID
# ============ 生命周期方法 ============
# 初始化网络管理器
# 在节点准备就绪时调用
func _ready():
print("NetworkManager 已初始化")
# ============ 公共API接口 ============
# 发送GET请求
#
# 参数:
# endpoint: String - API端点路径如: "/api/users"
# callback: Callable - 完成时的回调函数(可选)
# timeout: float - 超时时间可选默认30秒
#
# 返回值:
# String - 请求ID可用于取消请求或跟踪状态
#
# 使用示例:
# var request_id = NetworkManager.get_request("/api/users", my_callback)
func get_request(endpoint: String, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
return send_request(endpoint, RequestType.GET, [], "", callback, timeout)
# 发送POST请求
#
# 参数:
# endpoint: String - API端点路径
# data: Dictionary - 要发送的数据将自动转换为JSON
# callback: Callable - 完成时的回调函数(可选)
# timeout: float - 超时时间(可选)
#
# 返回值:
# String - 请求ID
#
# 使用示例:
# var data = {"name": "张三", "age": 25}
# var request_id = NetworkManager.post_request("/api/users", data, my_callback)
func post_request(endpoint: String, data: Dictionary, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
var body = JSON.stringify(data)
var headers = ["Content-Type: application/json"]
return send_request(endpoint, RequestType.POST, headers, body, callback, timeout)
# 发送PUT请求
#
# 参数:
# endpoint: String - API端点路径
# data: Dictionary - 要更新的数据
# callback: Callable - 完成时的回调函数(可选)
# timeout: float - 超时时间(可选)
#
# 返回值:
# String - 请求ID
func put_request(endpoint: String, data: Dictionary, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
var body = JSON.stringify(data)
var headers = ["Content-Type: application/json"]
return send_request(endpoint, RequestType.PUT, headers, body, callback, timeout)
# 发送DELETE请求
#
# 参数:
# endpoint: String - API端点路径
# callback: Callable - 完成时的回调函数(可选)
# timeout: float - 超时时间(可选)
#
# 返回值:
# String - 请求ID
func delete_request(endpoint: String, callback: Callable = Callable(), timeout: float = DEFAULT_TIMEOUT) -> String:
return send_request(endpoint, RequestType.DELETE, [], "", callback, timeout)
# ============ 认证相关API ============
# 用户登录
#
# 参数:
# identifier: String - 用户标识符(邮箱或手机号)
# password: String - 用户密码
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 回调函数签名:
# func callback(success: bool, data: Dictionary, error_info: Dictionary)
#
# 使用示例:
# NetworkManager.login("user@example.com", "password123", func(success, data, error):
# if success:
# print("登录成功: ", data)
# else:
# print("登录失败: ", error.message)
# )
func login(identifier: String, password: String, callback: Callable = Callable()) -> String:
var data = {
"identifier": identifier,
"password": password
}
return post_request("/auth/login", data, callback)
# 验证码登录
#
# 参数:
# identifier: String - 用户标识符(邮箱或手机号)
# verification_code: String - 验证码
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 使用场景:
# - 用户忘记密码时的替代登录方式
# - 提供更安全的登录选项
func verification_code_login(identifier: String, verification_code: String, callback: Callable = Callable()) -> String:
var data = {
"identifier": identifier,
"verification_code": verification_code
}
return post_request("/auth/verification-code-login", data, callback)
# 发送登录验证码
#
# 参数:
# identifier: String - 用户标识符(邮箱或手机号)
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 向已注册用户发送登录验证码
# - 支持邮箱和手机号
# - 有频率限制保护
func send_login_verification_code(identifier: String, callback: Callable = Callable()) -> String:
var data = {"identifier": identifier}
return post_request("/auth/send-login-verification-code", data, callback)
# 用户注册
#
# 参数:
# username: String - 用户名
# password: String - 密码
# nickname: String - 昵称
# email: String - 邮箱地址(可选)
# email_verification_code: String - 邮箱验证码(可选)
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 注意事项:
# - 如果提供邮箱,建议同时提供验证码
# - 用户名和邮箱必须唯一
# - 密码需要符合安全要求
func register(username: String, password: String, nickname: String, email: String = "",
email_verification_code: String = "", callback: Callable = Callable()) -> String:
var data = {
"username": username,
"password": password,
"nickname": nickname
}
# 可选参数处理
if email != "":
data["email"] = email
if email_verification_code != "":
data["email_verification_code"] = email_verification_code
return post_request("/auth/register", data, callback)
# 发送邮箱验证码
#
# 参数:
# email: String - 邮箱地址
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 向指定邮箱发送验证码
# - 用于注册时的邮箱验证
# - 支持测试模式(开发环境)
func send_email_verification(email: String, callback: Callable = Callable()) -> String:
var data = {"email": email}
return post_request("/auth/send-email-verification", data, callback)
# 验证邮箱
#
# 参数:
# email: String - 邮箱地址
# verification_code: String - 验证码
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 验证邮箱验证码的有效性
# - 通常在注册流程中使用
func verify_email(email: String, verification_code: String, callback: Callable = Callable()) -> String:
var data = {
"email": email,
"verification_code": verification_code
}
return post_request("/auth/verify-email", data, callback)
# 获取应用状态
#
# 参数:
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 检查API服务器状态
# - 获取应用基本信息
# - 用于网络连接测试
func get_app_status(callback: Callable = Callable()) -> String:
return get_request("/", callback)
# 重新发送邮箱验证码
#
# 参数:
# email: String - 邮箱地址
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 使用场景:
# - 用户未收到验证码时重新发送
# - 验证码过期后重新获取
func resend_email_verification(email: String, callback: Callable = Callable()) -> String:
var data = {"email": email}
return post_request("/auth/resend-email-verification", data, callback)
# 忘记密码 - 发送重置验证码
#
# 参数:
# identifier: String - 用户标识符(邮箱或手机号)
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 向用户发送密码重置验证码
# - 用于密码找回流程的第一步
func forgot_password(identifier: String, callback: Callable = Callable()) -> String:
var data = {"identifier": identifier}
return post_request("/auth/forgot-password", data, callback)
# 重置密码
#
# 参数:
# identifier: String - 用户标识符
# verification_code: String - 重置验证码
# new_password: String - 新密码
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 使用验证码重置用户密码
# - 密码找回流程的第二步
func reset_password(identifier: String, verification_code: String, new_password: String, callback: Callable = Callable()) -> String:
var data = {
"identifier": identifier,
"verification_code": verification_code,
"new_password": new_password
}
return post_request("/auth/reset-password", data, callback)
# 修改密码
#
# 参数:
# user_id: String - 用户ID
# old_password: String - 旧密码
# new_password: String - 新密码
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 已登录用户修改密码
# - 需要验证旧密码
func change_password(user_id: String, old_password: String, new_password: String, callback: Callable = Callable()) -> String:
var data = {
"user_id": user_id,
"old_password": old_password,
"new_password": new_password
}
return put_request("/auth/change-password", data, callback)
# GitHub OAuth登录
#
# 参数:
# github_id: String - GitHub用户ID
# username: String - GitHub用户名
# nickname: String - 显示昵称
# email: String - GitHub邮箱
# avatar_url: String - 头像URL可选
# callback: Callable - 完成时的回调函数(可选)
#
# 返回值:
# String - 请求ID
#
# 功能:
# - 通过GitHub账号登录或注册
# - 支持第三方OAuth认证
func github_login(github_id: String, username: String, nickname: String, email: String, avatar_url: String = "", callback: Callable = Callable()) -> String:
var data = {
"github_id": github_id,
"username": username,
"nickname": nickname,
"email": email
}
# 可选头像URL
if avatar_url != "":
data["avatar_url"] = avatar_url
return post_request("/auth/github", data, callback)
# ============ 核心请求处理 ============
# 发送请求的核心方法
func send_request(endpoint: String, method: RequestType, headers: PackedStringArray,
body: String, callback: Callable, timeout: float) -> String:
# 生成请求ID
request_counter += 1
var request_id = "req_" + str(request_counter)
# 构建完整URL
var full_url = API_BASE_URL + endpoint
# 创建HTTPRequest节点
var http_request = HTTPRequest.new()
add_child(http_request)
# 设置超时
http_request.timeout = timeout
# 创建请求信息
var request_info = RequestInfo.new(request_id, full_url, method, headers, body, timeout)
request_info.http_request = http_request
request_info.callback = callback
# 存储请求信息
active_requests[request_id] = request_info
# 连接信号
http_request.request_completed.connect(func(result: int, response_code: int, response_headers: PackedStringArray, response_body: PackedByteArray):
_on_request_completed(request_id, result, response_code, response_headers, response_body)
)
# 发送请求
var godot_method = _convert_to_godot_method(method)
var error = http_request.request(full_url, headers, godot_method, body)
print("=== 发送网络请求 ===")
print("请求ID: ", request_id)
print("URL: ", full_url)
print("方法: ", RequestType.keys()[method])
print("Headers: ", headers)
print("Body: ", body if body.length() < 200 else body.substr(0, 200) + "...")
print("发送结果: ", error)
if error != OK:
print("请求发送失败,错误代码: ", error)
_handle_request_error(request_id, ErrorType.NETWORK_ERROR, "网络请求发送失败: " + str(error))
return ""
return request_id
# 请求完成回调
func _on_request_completed(request_id: String, result: int, response_code: int,
headers: PackedStringArray, body: PackedByteArray):
print("=== 网络请求完成 ===")
print("请求ID: ", request_id)
print("结果: ", result)
print("状态码: ", response_code)
print("响应头: ", headers)
# 获取请求信息
if not active_requests.has(request_id):
print("警告: 未找到请求ID ", request_id)
return
var _request_info = active_requests[request_id]
var response_text = body.get_string_from_utf8()
print("响应体长度: ", body.size(), " 字节")
print("响应内容: ", response_text if response_text.length() < 500 else response_text.substr(0, 500) + "...")
# 处理网络连接失败
if response_code == 0:
_handle_request_error(request_id, ErrorType.NETWORK_ERROR, "网络连接失败,请检查网络连接")
return
# 解析JSON响应
var json = JSON.new()
var parse_result = json.parse(response_text)
if parse_result != OK:
_handle_request_error(request_id, ErrorType.PARSE_ERROR, "服务器响应格式错误")
return
var response_data = json.data
# 处理响应
_handle_response(request_id, response_code, response_data)
# 处理响应 - 支持API v1.1.1的状态码
func _handle_response(request_id: String, response_code: int, data: Dictionary):
var request_info = active_requests[request_id]
# 检查业务成功标志
var success = data.get("success", true) # 默认true保持向后兼容
var error_code = data.get("error_code", "")
var message = data.get("message", "")
# 判断请求是否成功
var is_success = false
# HTTP成功状态码且业务成功
if (response_code >= 200 and response_code < 300) and success:
is_success = true
# 特殊情况206测试模式 - 根据API文档这是成功的测试模式响应
elif response_code == 206 and error_code == "TEST_MODE_ONLY":
is_success = true
print("🧪 测试模式响应: ", message)
# 201创建成功
elif response_code == 201:
is_success = true
if is_success:
print("✅ 请求成功: ", request_id)
# 发送成功信号
request_completed.emit(request_id, true, data)
# 调用回调函数
if request_info.callback.is_valid():
request_info.callback.call(true, data, {})
else:
print("❌ 请求失败: ", request_id, " - HTTP:", response_code, " 错误码:", error_code, " 消息:", message)
# 确定错误类型
var error_type = _determine_error_type(response_code, error_code)
# 发送失败信号
request_failed.emit(request_id, ErrorType.keys()[error_type], message)
# 调用回调函数
if request_info.callback.is_valid():
var error_info = {
"response_code": response_code,
"error_code": error_code,
"message": message,
"error_type": error_type
}
request_info.callback.call(false, data, error_info)
# 清理请求
_cleanup_request(request_id)
# 处理请求错误
func _handle_request_error(request_id: String, error_type: ErrorType, message: String):
print("❌ 请求错误: ", request_id, " - ", message)
# 发送错误信号
request_failed.emit(request_id, ErrorType.keys()[error_type], message)
# 调用回调函数
if active_requests.has(request_id):
var request_info = active_requests[request_id]
if request_info.callback.is_valid():
var error_info = {
"error_type": error_type,
"message": message
}
request_info.callback.call(false, {}, error_info)
# 清理请求
_cleanup_request(request_id)
# 确定错误类型 - 支持更多状态码
func _determine_error_type(response_code: int, error_code: String) -> ErrorType:
# 根据错误码判断
match error_code:
"SERVICE_UNAVAILABLE":
return ErrorType.BUSINESS_ERROR
"TOO_MANY_REQUESTS":
return ErrorType.BUSINESS_ERROR
"TEST_MODE_ONLY":
return ErrorType.BUSINESS_ERROR
"SEND_EMAIL_VERIFICATION_FAILED", "REGISTER_FAILED":
# 这些可能是409冲突或其他业务错误
return ErrorType.BUSINESS_ERROR
_:
# 根据HTTP状态码判断
match response_code:
409: # 资源冲突
return ErrorType.BUSINESS_ERROR
206: # 测试模式
return ErrorType.BUSINESS_ERROR
429: # 频率限制
return ErrorType.BUSINESS_ERROR
_:
if response_code >= 400 and response_code < 500:
return ErrorType.HTTP_ERROR
elif response_code >= 500:
return ErrorType.HTTP_ERROR
else:
return ErrorType.BUSINESS_ERROR
# 清理请求资源
func _cleanup_request(request_id: String):
if active_requests.has(request_id):
var request_info = active_requests[request_id]
# 移除HTTPRequest节点
if is_instance_valid(request_info.http_request):
request_info.http_request.queue_free()
# 从活动请求中移除
active_requests.erase(request_id)
print("🧹 清理请求: ", request_id)
# 转换请求方法
func _convert_to_godot_method(method: RequestType) -> HTTPClient.Method:
match method:
RequestType.GET:
return HTTPClient.METHOD_GET
RequestType.POST:
return HTTPClient.METHOD_POST
RequestType.PUT:
return HTTPClient.METHOD_PUT
RequestType.DELETE:
return HTTPClient.METHOD_DELETE
RequestType.PATCH:
return HTTPClient.METHOD_PATCH
_:
return HTTPClient.METHOD_GET
# ============ 工具方法 ============
# 取消请求
func cancel_request(request_id: String) -> bool:
if active_requests.has(request_id):
print("🚫 取消请求: ", request_id)
_cleanup_request(request_id)
return true
return false
# 取消所有请求
func cancel_all_requests():
print("🚫 取消所有请求")
var request_ids = active_requests.keys()
for request_id in request_ids:
cancel_request(request_id)
# 获取活动请求数量
func get_active_request_count() -> int:
return active_requests.size()
# 检查请求是否活动
func is_request_active(request_id: String) -> bool:
return active_requests.has(request_id)
# 获取请求信息
func get_request_info(request_id: String) -> Dictionary:
if active_requests.has(request_id):
var info = active_requests[request_id]
return {
"id": info.id,
"url": info.url,
"method": RequestType.keys()[info.method],
"start_time": info.start_time,
"timeout": info.timeout
}
return {}
func _notification(what):
if what == NOTIFICATION_WM_CLOSE_REQUEST:
# 应用关闭时取消所有请求
cancel_all_requests()

View File

@@ -0,0 +1 @@
uid://dr7v30wheetca

View File

@@ -0,0 +1,590 @@
extends Node
# 响应处理器 - 统一处理API响应和错误
# 响应处理结果
class ResponseResult:
var success: bool
var message: String
var toast_type: String # "success" 或 "error"
var data: Dictionary
var should_show_toast: bool
var custom_action: Callable
func _init():
success = false
message = ""
toast_type = "error"
data = {}
should_show_toast = true
custom_action = Callable()
# 错误码映射表 - 根据API v1.1.1更新
const ERROR_CODE_MESSAGES = {
# 登录相关
"LOGIN_FAILED": "登录失败",
"VERIFICATION_CODE_LOGIN_FAILED": "验证码错误或已过期",
"EMAIL_NOT_VERIFIED": "请先验证邮箱",
# 注册相关
"REGISTER_FAILED": "注册失败",
# 验证码相关
"SEND_CODE_FAILED": "发送验证码失败",
"SEND_LOGIN_CODE_FAILED": "发送登录验证码失败",
"SEND_EMAIL_VERIFICATION_FAILED": "发送邮箱验证码失败",
"RESEND_EMAIL_VERIFICATION_FAILED": "重新发送验证码失败",
"EMAIL_VERIFICATION_FAILED": "邮箱验证失败",
"RESET_PASSWORD_FAILED": "重置密码失败",
"CHANGE_PASSWORD_FAILED": "修改密码失败",
"VERIFICATION_CODE_EXPIRED": "验证码已过期",
"VERIFICATION_CODE_INVALID": "验证码无效",
"VERIFICATION_CODE_ATTEMPTS_EXCEEDED": "验证码尝试次数过多",
"VERIFICATION_CODE_RATE_LIMITED": "验证码发送过于频繁",
"VERIFICATION_CODE_HOURLY_LIMIT": "验证码每小时发送次数已达上限",
# 用户状态相关
"USER_NOT_FOUND": "用户不存在",
"INVALID_IDENTIFIER": "请输入有效的邮箱或手机号",
"USER_STATUS_UPDATE_FAILED": "用户状态更新失败",
# 系统状态相关
"TEST_MODE_ONLY": "测试模式",
"TOO_MANY_REQUESTS": "请求过于频繁,请稍后再试",
"SERVICE_UNAVAILABLE": "系统维护中,请稍后再试",
# 权限相关
"UNAUTHORIZED": "未授权访问",
"FORBIDDEN": "权限不足",
"ADMIN_LOGIN_FAILED": "管理员登录失败",
# 其他
"VALIDATION_FAILED": "参数验证失败",
"UNSUPPORTED_MEDIA_TYPE": "不支持的请求格式",
"REQUEST_TIMEOUT": "请求超时"
}
# HTTP状态码消息映射 - 根据API v1.1.1更新
const HTTP_STATUS_MESSAGES = {
200: "请求成功",
201: "创建成功",
206: "测试模式",
400: "请求参数错误",
401: "认证失败",
403: "权限不足",
404: "资源不存在",
408: "请求超时",
409: "资源冲突",
415: "不支持的媒体类型",
429: "请求过于频繁",
500: "服务器内部错误",
503: "服务不可用"
}
# ============ 主要处理方法 ============
# 处理登录响应
func handle_login_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
result.success = true
result.message = "登录成功!正在进入鲸鱼镇..."
result.toast_type = "success"
result.data = data
# 自定义动作:延迟发送登录成功信号
result.custom_action = func():
await Engine.get_main_loop().create_timer(1.0).timeout
# 这里可以发送登录成功信号或执行其他逻辑
else:
result = _handle_login_error(data, error_info)
return result
# 处理验证码登录响应
func handle_verification_code_login_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
result.success = true
result.message = "验证码登录成功!正在进入鲸鱼镇..."
result.toast_type = "success"
result.data = data
result.custom_action = func():
await Engine.get_main_loop().create_timer(1.0).timeout
# 登录成功后的处理逻辑
else:
result = _handle_verification_code_login_error(data, error_info)
return result
# 处理发送验证码响应 - 支持邮箱冲突检测
func handle_send_verification_code_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
var error_code = data.get("error_code", "")
if error_code == "TEST_MODE_ONLY":
result.success = true
result.message = "🧪 测试模式:验证码已生成,请查看控制台"
result.toast_type = "success"
# 在控制台显示验证码
if data.has("data") and data.data.has("verification_code"):
print("🔑 测试模式验证码: ", data.data.verification_code)
result.message += "\n验证码: " + str(data.data.verification_code)
else:
result.success = true
result.message = "📧 验证码已发送到您的邮箱,请查收"
result.toast_type = "success"
# 开发环境下显示验证码
if data.has("data") and data.data.has("verification_code"):
print("🔑 开发环境验证码: ", data.data.verification_code)
else:
result = _handle_send_code_error(data, error_info)
return result
# 处理发送登录验证码响应
func handle_send_login_code_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
var error_code = data.get("error_code", "")
if error_code == "TEST_MODE_ONLY":
result.success = true
result.message = "测试模式:登录验证码已生成,请查看控制台"
result.toast_type = "success"
if data.has("data") and data.data.has("verification_code"):
print("测试模式登录验证码: ", data.data.verification_code)
else:
result.success = true
result.message = "登录验证码已发送,请查收"
result.toast_type = "success"
if data.has("data") and data.data.has("verification_code"):
print("开发环境登录验证码: ", data.data.verification_code)
else:
result = _handle_send_login_code_error(data, error_info)
return result
# 处理注册响应
func handle_register_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
result.success = true
result.message = "注册成功!欢迎加入鲸鱼镇"
result.toast_type = "success"
result.data = data
# 自定义动作:清空表单,切换到登录界面
result.custom_action = func():
# 这里可以执行清空表单、切换界面等操作
pass
else:
result = _handle_register_error(data, error_info)
return result
# 处理邮箱验证响应
func handle_verify_email_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
result.success = true
result.message = "邮箱验证成功,正在注册..."
result.toast_type = "success"
result.data = data
else:
result = _handle_verify_email_error(data, error_info)
return result
# 处理重新发送邮箱验证码响应
func handle_resend_email_verification_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
var error_code = data.get("error_code", "")
if error_code == "TEST_MODE_ONLY":
result.success = true
result.message = "🧪 测试模式:验证码已重新生成,请查看控制台"
result.toast_type = "success"
if data.has("data") and data.data.has("verification_code"):
print("🔑 测试模式重新发送验证码: ", data.data.verification_code)
else:
result.success = true
result.message = "📧 验证码已重新发送到您的邮箱,请查收"
result.toast_type = "success"
if data.has("data") and data.data.has("verification_code"):
print("🔑 开发环境重新发送验证码: ", data.data.verification_code)
else:
result = _handle_resend_email_verification_error(data, error_info)
return result
# 处理忘记密码响应
func handle_forgot_password_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
var error_code = data.get("error_code", "")
if error_code == "TEST_MODE_ONLY":
result.success = true
result.message = "🧪 测试模式:重置验证码已生成,请查看控制台"
result.toast_type = "success"
if data.has("data") and data.data.has("verification_code"):
print("🔑 测试模式重置验证码: ", data.data.verification_code)
else:
result.success = true
result.message = "📧 重置验证码已发送,请查收"
result.toast_type = "success"
if data.has("data") and data.data.has("verification_code"):
print("🔑 开发环境重置验证码: ", data.data.verification_code)
else:
result = _handle_forgot_password_error(data, error_info)
return result
# 处理重置密码响应
func handle_reset_password_response(success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
result.success = true
result.message = "🔒 密码重置成功,请使用新密码登录"
result.toast_type = "success"
result.data = data
else:
result = _handle_reset_password_error(data, error_info)
return result
# ============ 错误处理方法 ============
# 处理登录错误
func _handle_login_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "登录失败")
match error_code:
"LOGIN_FAILED":
# 根据消息内容进一步判断用户状态
if "账户已锁定" in message or "locked" in message.to_lower():
result.message = "账户已被锁定,请联系管理员"
elif "账户已禁用" in message or "banned" in message.to_lower():
result.message = "账户已被禁用,请联系管理员"
elif "账户待审核" in message or "pending" in message.to_lower():
result.message = "账户待审核,请等待管理员审核"
elif "邮箱未验证" in message or "inactive" in message.to_lower():
result.message = "请先验证邮箱后再登录"
else:
result.message = "用户名或密码错误,请检查后重试"
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理验证码登录错误
func _handle_verification_code_login_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "验证码登录失败")
match error_code:
"VERIFICATION_CODE_LOGIN_FAILED":
result.message = "验证码错误或已过期"
"EMAIL_NOT_VERIFIED":
result.message = "邮箱未验证,请先验证邮箱后再使用验证码登录"
"USER_NOT_FOUND":
result.message = "用户不存在,请先注册"
"INVALID_IDENTIFIER":
result.message = "请输入有效的邮箱或手机号"
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理发送验证码错误 - 支持邮箱冲突检测和频率限制
func _handle_send_code_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "发送验证码失败")
var response_code = error_info.get("response_code", 0)
match error_code:
"SEND_EMAIL_VERIFICATION_FAILED":
# 检查是否是邮箱冲突409状态码
if response_code == 409:
result.message = "⚠️ 邮箱已被注册,请使用其他邮箱或直接登录"
result.toast_type = "error"
elif "邮箱格式" in message:
result.message = "📧 请输入有效的邮箱地址"
else:
result.message = message
"TOO_MANY_REQUESTS":
# 处理频率限制,提供重试建议
result.toast_type = "error"
# 如果有throttle_info显示更详细的信息
if data.has("throttle_info"):
var throttle_info = data.throttle_info
var reset_time = throttle_info.get("reset_time", "")
if reset_time != "":
var relative_time = StringUtils.get_relative_time_until(reset_time)
var local_time = StringUtils.format_utc_to_local_time(reset_time)
result.message = "⏰ 验证码发送过于频繁"
result.message += "\n" + relative_time + "再试"
result.message += "\n重试时间: " + local_time
else:
result.message = "⏰ 验证码发送过于频繁,请稍后再试"
else:
result.message = "⏰ 验证码发送过于频繁,请稍后再试"
"VERIFICATION_CODE_RATE_LIMITED":
result.message = "⏰ 验证码发送过于频繁,请稍后再试"
"VERIFICATION_CODE_HOURLY_LIMIT":
result.message = "⏰ 每小时发送次数已达上限,请稍后再试"
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理发送登录验证码错误
func _handle_send_login_code_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "发送登录验证码失败")
match error_code:
"SEND_LOGIN_CODE_FAILED":
if "用户不存在" in message:
result.message = "用户不存在,请先注册"
else:
result.message = "发送登录验证码失败"
"USER_NOT_FOUND":
result.message = "用户不存在,请先注册"
"INVALID_IDENTIFIER":
result.message = "请输入有效的邮箱或手机号"
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理注册错误 - 支持409冲突状态码
func _handle_register_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "注册失败")
var response_code = error_info.get("response_code", 0)
match error_code:
"REGISTER_FAILED":
# 检查409冲突状态码
if response_code == 409:
if "邮箱已存在" in message or "邮箱已被使用" in message:
result.message = "📧 邮箱已被注册,请使用其他邮箱或直接登录"
elif "用户名已存在" in message or "用户名已被使用" in message:
result.message = "👤 用户名已被使用,请换一个"
else:
result.message = "⚠️ 资源冲突:" + message
elif "邮箱验证码" in message or "verification_code" in message:
result.message = "🔑 请先获取并输入邮箱验证码"
elif "用户名" in message:
result.message = "👤 用户名格式不正确"
elif "邮箱" in message:
result.message = "📧 邮箱格式不正确"
elif "密码" in message:
result.message = "🔒 密码格式不符合要求"
elif "验证码" in message:
result.message = "🔑 验证码错误或已过期"
else:
result.message = message
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理邮箱验证错误
func _handle_verify_email_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "邮箱验证失败")
match error_code:
"EMAIL_VERIFICATION_FAILED":
if "验证码错误" in message:
result.message = "🔑 验证码错误"
elif "验证码已过期" in message:
result.message = "🔑 验证码已过期,请重新获取"
else:
result.message = message
"VERIFICATION_CODE_INVALID":
result.message = "🔑 验证码错误或已过期"
"VERIFICATION_CODE_EXPIRED":
result.message = "🔑 验证码已过期,请重新获取"
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理网络测试响应
func handle_network_test_response(success: bool, _data: Dictionary, _error_info: Dictionary = {}) -> ResponseResult:
var result = ResponseResult.new()
if success:
result.success = true
result.message = "🌐 网络连接正常"
result.toast_type = "success"
else:
result.success = false
result.message = "🌐 网络连接异常"
result.toast_type = "error"
return result
# 处理重新发送邮箱验证码错误
func _handle_resend_email_verification_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "重新发送验证码失败")
match error_code:
"RESEND_EMAIL_VERIFICATION_FAILED":
if "邮箱已验证" in message:
result.message = "📧 邮箱已验证,无需重复验证"
else:
result.message = message
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理忘记密码错误
func _handle_forgot_password_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "发送重置验证码失败")
match error_code:
"SEND_CODE_FAILED":
if "用户不存在" in message:
result.message = "👤 用户不存在,请检查邮箱或手机号"
else:
result.message = message
"USER_NOT_FOUND":
result.message = "👤 用户不存在,请检查邮箱或手机号"
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# 处理重置密码错误
func _handle_reset_password_error(data: Dictionary, error_info: Dictionary) -> ResponseResult:
var result = ResponseResult.new()
var error_code = data.get("error_code", "")
var message = data.get("message", "重置密码失败")
match error_code:
"RESET_PASSWORD_FAILED":
if "验证码" in message:
result.message = "🔑 验证码错误或已过期"
else:
result.message = message
_:
result.message = _get_error_message(error_code, message, error_info)
return result
# ============ 工具方法 ============
# 获取错误消息 - 支持更多状态码和错误处理
func _get_error_message(error_code: String, original_message: String, error_info: Dictionary) -> String:
# 优先使用错误码映射
if ERROR_CODE_MESSAGES.has(error_code):
return ERROR_CODE_MESSAGES[error_code]
# 处理频率限制
if error_code == "TOO_MANY_REQUESTS":
return _handle_rate_limit_message(original_message, error_info)
# 处理维护模式
if error_code == "SERVICE_UNAVAILABLE":
return _handle_maintenance_message(original_message, error_info)
# 处理测试模式
if error_code == "TEST_MODE_ONLY":
return "🧪 测试模式:" + original_message
# 根据HTTP状态码处理
if error_info.has("response_code"):
var response_code = error_info.response_code
match response_code:
409:
return "⚠️ 资源冲突:" + original_message
206:
return "🧪 测试模式:" + original_message
429:
return "⏰ 请求过于频繁,请稍后再试"
_:
if HTTP_STATUS_MESSAGES.has(response_code):
return HTTP_STATUS_MESSAGES[response_code] + "" + original_message
# 返回原始消息
return original_message if original_message != "" else "操作失败"
# 处理频率限制消息
func _handle_rate_limit_message(message: String, _error_info: Dictionary) -> String:
# 可以根据throttle_info提供更详细的信息
return message + ",请稍后再试"
# 处理维护模式消息
func _handle_maintenance_message(_message: String, _error_info: Dictionary) -> String:
# 可以根据maintenance_info提供更详细的信息
return "系统维护中,请稍后再试"
# 通用响应处理器 - 支持更多操作类型
func handle_response(operation_type: String, success: bool, data: Dictionary, error_info: Dictionary = {}) -> ResponseResult:
match operation_type:
"login":
return handle_login_response(success, data, error_info)
"verification_code_login":
return handle_verification_code_login_response(success, data, error_info)
"send_code":
return handle_send_verification_code_response(success, data, error_info)
"send_login_code":
return handle_send_login_code_response(success, data, error_info)
"register":
return handle_register_response(success, data, error_info)
"verify_email":
return handle_verify_email_response(success, data, error_info)
"resend_email_verification":
return handle_resend_email_verification_response(success, data, error_info)
"forgot_password":
return handle_forgot_password_response(success, data, error_info)
"reset_password":
return handle_reset_password_response(success, data, error_info)
"network_test":
return handle_network_test_response(success, data, error_info)
_:
# 通用处理
var result = ResponseResult.new()
if success:
result.success = true
result.message = "✅ 操作成功"
result.toast_type = "success"
else:
result.success = false
result.message = _get_error_message(data.get("error_code", ""), data.get("message", "操作失败"), error_info)
result.toast_type = "error"
return result

View File

@@ -0,0 +1 @@
uid://nseguk2ytiw6

View File

@@ -0,0 +1,187 @@
extends Node
# ============================================================================
# SceneManager.gd - 场景管理器
# ============================================================================
# 全局单例管理器,负责场景切换和管理
#
# 核心职责:
# - 场景切换的统一接口
# - 场景路径映射管理
# - 场景切换过渡效果
# - 场景状态跟踪
#
# 使用方式:
# SceneManager.change_scene("main")
# SceneManager.register_scene("custom", "res://scenes/custom.tscn")
#
# 注意事项:
# - 作为自动加载单例,全局可访问
# - 场景切换是异步操作,支持过渡效果
# - 场景名称必须在 scene_paths 中注册
# ============================================================================
# ============ 信号定义 ============
# 场景切换完成信号
# 参数: scene_name - 切换到的场景名称
signal scene_changed(scene_name: String)
# 场景切换开始信号
# 参数: scene_name - 即将切换到的场景名称
signal scene_change_started(scene_name: String)
# ============ 成员变量 ============
# 场景状态
var current_scene_name: String = "" # 当前场景名称
var is_changing_scene: bool = false # 是否正在切换场景
# 场景路径映射表
# 将场景名称映射到实际的文件路径
# 便于统一管理和修改场景路径
var scene_paths: Dictionary = {
"main": "res://scenes/MainScene.tscn", # 主场景 - 游戏入口
"auth": "res://scenes/ui/LoginWindow.tscn", # 认证场景 - 登录窗口
"game": "res://scenes/maps/game_scene.tscn", # 游戏场景 - 主要游戏内容
"battle": "res://scenes/maps/battle_scene.tscn", # 战斗场景 - 战斗系统
"inventory": "res://scenes/ui/InventoryWindow.tscn", # 背包界面
"shop": "res://scenes/ui/ShopWindow.tscn", # 商店界面
"settings": "res://scenes/ui/SettingsWindow.tscn" # 设置界面
}
# ============ 生命周期方法 ============
# 初始化场景管理器
# 在节点准备就绪时调用
func _ready():
print("SceneManager 初始化完成")
# ============ 场景切换方法 ============
# 切换到指定场景
#
# 参数:
# scene_name: String - 要切换到的场景名称必须在scene_paths中注册
# use_transition: bool - 是否使用过渡效果默认为true
#
# 返回值:
# bool - 切换是否成功
#
# 功能:
# - 检查场景切换状态和场景是否存在
# - 显示过渡效果(可选)
# - 执行场景切换
# - 更新当前场景状态
# - 发送相关信号
#
# 使用示例:
# var success = SceneManager.change_scene("main", true)
# if success:
# print("场景切换成功")
#
# 注意事项:
# - 场景切换是异步操作
# - 切换过程中会阻止新的切换请求
# - 场景名称必须预先注册
func change_scene(scene_name: String, use_transition: bool = true):
# 防止重复切换
if is_changing_scene:
print("场景切换中,忽略新的切换请求")
return false
# 检查场景是否存在
if not scene_paths.has(scene_name):
print("错误: 未找到场景 ", scene_name)
return false
var scene_path = scene_paths[scene_name]
print("开始切换场景: ", current_scene_name, " -> ", scene_name)
# 设置切换状态
is_changing_scene = true
scene_change_started.emit(scene_name)
# 显示过渡效果
if use_transition:
await show_transition()
# 执行场景切换
var error = get_tree().change_scene_to_file(scene_path)
if error != OK:
print("场景切换失败: ", error)
is_changing_scene = false
return false
# 更新状态
current_scene_name = scene_name
is_changing_scene = false
scene_changed.emit(scene_name)
# 隐藏过渡效果
if use_transition:
await hide_transition()
print("场景切换完成: ", scene_name)
return true
# ============ 查询方法 ============
# 获取当前场景名称
#
# 返回值:
# String - 当前场景的名称
func get_current_scene_name() -> String:
return current_scene_name
# ============ 场景注册方法 ============
# 注册新场景
#
# 参数:
# scene_name: String - 场景名称(用于切换时引用)
# scene_path: String - 场景文件路径
#
# 功能:
# - 将场景名称和路径添加到映射表
# - 支持运行时动态注册场景
#
# 使用示例:
# SceneManager.register_scene("boss_battle", "res://scenes/boss/boss_battle.tscn")
func register_scene(scene_name: String, scene_path: String):
scene_paths[scene_name] = scene_path
print("注册场景: ", scene_name, " -> ", scene_path)
# ============ 过渡效果方法 ============
# 显示场景切换过渡效果
#
# 功能:
# - 显示场景切换时的过渡动画
# - 为用户提供视觉反馈
#
# 注意事项:
# - 这是异步方法需要await等待完成
# - 当前实现为简单的延时,可扩展为复杂动画
#
# TODO: 实现淡入淡出、滑动等过渡效果
func show_transition():
# TODO: 实现场景切换过渡效果
print("显示场景切换过渡效果")
await get_tree().create_timer(0.2).timeout
# 隐藏场景切换过渡效果
#
# 功能:
# - 隐藏场景切换完成后的过渡动画
# - 恢复正常的游戏显示
#
# 注意事项:
# - 这是异步方法需要await等待完成
# - 与show_transition()配对使用
#
# TODO: 实现与show_transition()对应的隐藏效果
func hide_transition():
# TODO: 隐藏场景切换过渡效果
print("隐藏场景切换过渡效果")
await get_tree().create_timer(0.2).timeout

View File

@@ -0,0 +1 @@
uid://d3l286ti5gqhw

View File

@@ -0,0 +1,234 @@
class_name ToastManager
# ============================================================================
# ToastManager.gd - Toast消息管理器
# ============================================================================
# 负责创建和管理Toast消息的显示
#
# 核心功能:
# - 创建Toast消息实例
# - 管理Toast动画和生命周期
# - 支持多个Toast同时显示
# - 自动排列和清理Toast
# - 支持中文字体显示
#
# 使用方式:
# var toast_manager = ToastManager.new()
# toast_manager.setup(toast_container)
# toast_manager.show_toast("消息内容", true)
#
# 注意事项:
# - 需要提供一个容器节点来承载Toast
# - 自动处理Toast的位置计算和动画
# - 支持Web平台的字体处理
# ============================================================================
extends RefCounted
# ============ 成员变量 ============
# Toast容器和管理
var toast_container: Control # Toast消息容器
var active_toasts: Array = [] # 当前显示的Toast消息列表
var toast_counter: int = 0 # Toast计数器用于生成唯一ID
# ============ 初始化方法 ============
# 设置Toast管理器
#
# 参数:
# container: Control - Toast消息的容器节点
func setup(container: Control):
toast_container = container
print("ToastManager 初始化完成")
# ============ 公共方法 ============
# 显示Toast消息
#
# 参数:
# message: String - 消息内容
# is_success: bool - 是否为成功消息(影响颜色)
func show_toast(message: String, is_success: bool = true):
if toast_container == null:
print("错误: toast_container 节点不存在")
return
print("显示Toast消息: ", message, " 成功: ", is_success)
_create_toast_instance(message, is_success)
# 清理所有Toast
func clear_all_toasts():
for toast in active_toasts:
if is_instance_valid(toast):
toast.queue_free()
active_toasts.clear()
# ============ 私有方法 ============
# 创建Toast实例
func _create_toast_instance(message: String, is_success: bool):
toast_counter += 1
# Web平台字体处理
var is_web = OS.get_name() == "Web"
# 1. 创建Toast Panel方框UI
var toast_panel = Panel.new()
toast_panel.name = "Toast_" + str(toast_counter)
# 设置Toast样式
var style = StyleBoxFlat.new()
if is_success:
style.bg_color = Color(0.15, 0.7, 0.15, 0.95)
style.border_color = Color(0.2, 0.9, 0.2, 0.9)
else:
style.bg_color = Color(0.7, 0.15, 0.15, 0.95)
style.border_color = Color(0.9, 0.2, 0.2, 0.9)
style.border_width_left = 3
style.border_width_top = 3
style.border_width_right = 3
style.border_width_bottom = 3
style.corner_radius_top_left = 12
style.corner_radius_top_right = 12
style.corner_radius_bottom_left = 12
style.corner_radius_bottom_right = 12
style.shadow_color = Color(0, 0, 0, 0.3)
style.shadow_size = 4
style.shadow_offset = Vector2(2, 2)
toast_panel.add_theme_stylebox_override("panel", style)
# 设置Toast基本尺寸
var toast_width = 320
toast_panel.size = Vector2(toast_width, 60)
# 2. 创建VBoxContainer
var vbox = VBoxContainer.new()
vbox.add_theme_constant_override("separation", 0)
vbox.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
vbox.alignment = BoxContainer.ALIGNMENT_CENTER
# 3. 创建CenterContainer
var center_container = CenterContainer.new()
center_container.size_flags_horizontal = Control.SIZE_EXPAND_FILL
center_container.size_flags_vertical = Control.SIZE_SHRINK_CENTER
# 4. 创建Label文字控件
var text_label = Label.new()
text_label.text = message
text_label.add_theme_color_override("font_color", Color(1, 1, 1, 1))
text_label.add_theme_font_size_override("font_size", 14)
# 平台特定的字体处理
if is_web:
print("Web平台Toast字体处理")
# Web平台使用主题文件
var chinese_theme = load("res://assets/ui/chinese_theme.tres")
if chinese_theme:
text_label.theme = chinese_theme
print("Web平台应用中文主题")
else:
print("Web平台中文主题加载失败")
else:
print("桌面平台Toast字体处理")
# 桌面平台直接加载中文字体
var desktop_chinese_font = load("res://assets/fonts/msyh.ttc")
if desktop_chinese_font:
text_label.add_theme_font_override("font", desktop_chinese_font)
print("桌面平台使用中文字体")
text_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
text_label.custom_minimum_size = Vector2(280, 0)
text_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
text_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
# 组装控件层级
center_container.add_child(text_label)
vbox.add_child(center_container)
toast_panel.add_child(vbox)
# 计算位置
var margin = 20
var start_x = toast_container.get_viewport().get_visible_rect().size.x
var final_x = toast_container.get_viewport().get_visible_rect().size.x - toast_width - margin
# 计算Y位置
var y_position = margin
for existing_toast in active_toasts:
if is_instance_valid(existing_toast):
y_position += existing_toast.size.y + 15
# 设置初始位置
toast_panel.position = Vector2(start_x, y_position)
# 添加到容器
toast_container.add_child(toast_panel)
active_toasts.append(toast_panel)
# 等待一帧让布局系统计算尺寸
await toast_container.get_tree().process_frame
# 让Toast高度自适应内容
var content_size = vbox.get_combined_minimum_size()
var final_height = max(60, content_size.y + 20) # 最小60加20像素边距
toast_panel.size.y = final_height
# 重新排列所有Toast
_rearrange_toasts()
# 开始动画
_animate_toast_in(toast_panel, final_x)
# Toast入场动画
func _animate_toast_in(toast_panel: Panel, final_x: float):
var tween = toast_container.create_tween()
tween.set_ease(Tween.EASE_OUT)
tween.set_trans(Tween.TRANS_BACK)
tween.parallel().tween_property(toast_panel, "position:x", final_x, 0.6)
tween.parallel().tween_property(toast_panel, "modulate:a", 1.0, 0.4)
toast_panel.modulate.a = 0.0
# 等待3秒后开始退场动画
await toast_container.get_tree().create_timer(3.0).timeout
_animate_toast_out(toast_panel)
# Toast退场动画
func _animate_toast_out(toast_panel: Panel):
if not is_instance_valid(toast_panel):
return
var tween = toast_container.create_tween()
tween.set_ease(Tween.EASE_IN)
tween.set_trans(Tween.TRANS_QUART)
var end_x = toast_container.get_viewport().get_visible_rect().size.x + 50
tween.parallel().tween_property(toast_panel, "position:x", end_x, 0.4)
tween.parallel().tween_property(toast_panel, "modulate:a", 0.0, 0.3)
await tween.finished
_cleanup_toast(toast_panel)
# 清理Toast
func _cleanup_toast(toast_panel: Panel):
if not is_instance_valid(toast_panel):
return
active_toasts.erase(toast_panel)
_rearrange_toasts()
toast_panel.queue_free()
# 重新排列Toast位置
func _rearrange_toasts():
var margin = 20
var current_y = margin
for i in range(active_toasts.size()):
var toast = active_toasts[i]
if is_instance_valid(toast):
var tween = toast_container.create_tween()
tween.tween_property(toast, "position:y", current_y, 0.2)
current_y += toast.size.y + 15

View File

@@ -0,0 +1 @@
uid://buk7d21cag262

View File

@@ -0,0 +1,195 @@
extends Node
# ============================================================================
# EventSystem.gd - 全局事件系统
# ============================================================================
# 全局单例管理器,提供解耦的事件通信机制
#
# 核心职责:
# - 事件监听器注册和管理
# - 事件发送和分发
# - 自动清理无效监听器
# - 支持带参数的事件通信
#
# 使用方式:
# EventSystem.connect_event("player_moved", _on_player_moved)
# EventSystem.emit_event("player_moved", {"position": Vector2(100, 200)})
#
# 注意事项:
# - 作为自动加载单例,全局可访问
# - 监听器会自动检查目标节点的有效性
# - 建议使用EventNames类中定义的事件名称常量
# ============================================================================
# ============ 成员变量 ============
# 事件监听器存储
# 结构: {event_name: [{"callback": Callable, "target": Node}, ...]}
var event_listeners: Dictionary = {}
# ============ 生命周期方法 ============
# 初始化事件系统
# 在节点准备就绪时调用
func _ready():
print("EventSystem 初始化完成")
# ============ 事件监听器管理 ============
# 注册事件监听器
#
# 参数:
# event_name: String - 事件名称建议使用EventNames中的常量
# callback: Callable - 回调函数
# target: Node - 目标节点(可选,用于自动清理)
#
# 功能:
# - 将回调函数注册到指定事件
# - 支持同一事件多个监听器
# - 自动管理监听器生命周期
#
# 使用示例:
# EventSystem.connect_event(EventNames.PLAYER_MOVED, _on_player_moved, self)
#
# 注意事项:
# - 如果提供target参数当target节点被销毁时会自动清理监听器
# - 同一个callback可以监听多个事件
func connect_event(event_name: String, callback: Callable, target: Node = null):
# 初始化事件监听器数组
if not event_listeners.has(event_name):
event_listeners[event_name] = []
# 创建监听器信息
var listener_info = {
"callback": callback,
"target": target
}
# 添加到监听器列表
event_listeners[event_name].append(listener_info)
print("注册事件监听器: ", event_name, " -> ", callback)
# 移除事件监听器
#
# 参数:
# event_name: String - 事件名称
# callback: Callable - 要移除的回调函数
# target: Node - 目标节点(可选,用于精确匹配)
#
# 功能:
# - 从指定事件中移除特定的监听器
# - 支持精确匹配callback + target
#
# 使用示例:
# EventSystem.disconnect_event(EventNames.PLAYER_MOVED, _on_player_moved, self)
func disconnect_event(event_name: String, callback: Callable, target: Node = null):
if not event_listeners.has(event_name):
return
var listeners = event_listeners[event_name]
# 从后往前遍历,避免删除元素时索引问题
for i in range(listeners.size() - 1, -1, -1):
var listener = listeners[i]
# 匹配callback和target
if listener.callback == callback and listener.target == target:
listeners.remove_at(i)
print("移除事件监听器: ", event_name, " -> ", callback)
break
# ============ 事件发送 ============
# 发送事件
#
# 参数:
# event_name: String - 事件名称
# data: Variant - 事件数据(可选)
#
# 功能:
# - 向所有注册的监听器发送事件
# - 自动跳过无效的监听器
# - 支持任意类型的事件数据
#
# 使用示例:
# EventSystem.emit_event(EventNames.PLAYER_MOVED, {"position": Vector2(100, 200)})
# EventSystem.emit_event(EventNames.GAME_PAUSED) # 无数据事件
#
# 注意事项:
# - 事件发送是同步的,所有监听器会立即执行
# - 如果监听器执行出错,不会影响其他监听器
func emit_event(event_name: String, data: Variant = null):
print("发送事件: ", event_name, " 数据: ", data)
# 检查是否有监听器
if not event_listeners.has(event_name):
return
var listeners = event_listeners[event_name]
for listener_info in listeners:
var target = listener_info.target
var callback = listener_info.callback
# 检查目标节点是否仍然有效
if target != null and not is_instance_valid(target):
continue
# 调用回调函数
if data != null:
callback.call(data)
else:
callback.call()
# ============ 维护方法 ============
# 清理无效的监听器
#
# 功能:
# - 遍历所有监听器,移除已销毁节点的监听器
# - 防止内存泄漏
# - 建议定期调用或在场景切换时调用
#
# 使用场景:
# - 场景切换时清理
# - 定期维护(如每分钟一次)
# - 内存优化时调用
func cleanup_invalid_listeners():
for event_name in event_listeners.keys():
var listeners = event_listeners[event_name]
# 从后往前遍历,避免删除元素时索引问题
for i in range(listeners.size() - 1, -1, -1):
var listener = listeners[i]
var target = listener.target
# 如果目标节点无效,移除监听器
if target != null and not is_instance_valid(target):
listeners.remove_at(i)
print("清理无效监听器: ", event_name)
# ============ 查询方法 ============
# 获取事件监听器数量
#
# 参数:
# event_name: String - 事件名称
#
# 返回值:
# int - 监听器数量
#
# 使用场景:
# - 调试时检查监听器数量
# - 性能分析
func get_listener_count(event_name: String) -> int:
if not event_listeners.has(event_name):
return 0
return event_listeners[event_name].size()
# 清空所有事件监听器
#
# 功能:
# - 移除所有已注册的事件监听器
# - 通常在游戏重置或退出时使用
#
# 警告:
# - 这是一个危险操作,会影响所有模块
# - 使用前请确保所有模块都能正确处理监听器丢失
func clear_all_listeners():
event_listeners.clear()
print("清空所有事件监听器")

View File

@@ -0,0 +1 @@
uid://bfheblucmti24

143
_Core/systems/GridSystem.gd Normal file
View File

@@ -0,0 +1,143 @@
# ============================================================================
# 网格系统 - GridSystem.gd
#
# 提供32x32像素的最小网格单元控制用于规范地图大小和位置计算
#
# 使用方式:
# var grid_pos = GridSystem.world_to_grid(world_position)
# var world_pos = GridSystem.grid_to_world(grid_position)
# var snapped_pos = GridSystem.snap_to_grid(position)
# ============================================================================
class_name GridSystem
extends RefCounted
# ============================================================================
# 常量定义
# ============================================================================
const GRID_SIZE: int = 32 # 网格单元大小 32x32 像素
const HALF_GRID_SIZE: float = GRID_SIZE * 0.5 # 网格中心偏移
# ============================================================================
# 坐标转换方法
# ============================================================================
# 世界坐标转换为网格坐标
static func world_to_grid(world_pos: Vector2) -> Vector2i:
return Vector2i(
int(world_pos.x / GRID_SIZE),
int(world_pos.y / GRID_SIZE)
)
# 网格坐标转换为世界坐标(返回网格左上角)
static func grid_to_world(grid_pos: Vector2i) -> Vector2:
return Vector2(
grid_pos.x * GRID_SIZE,
grid_pos.y * GRID_SIZE
)
# 网格坐标转换为世界坐标(返回网格中心)
static func grid_to_world_center(grid_pos: Vector2i) -> Vector2:
return Vector2(
grid_pos.x * GRID_SIZE + HALF_GRID_SIZE,
grid_pos.y * GRID_SIZE + HALF_GRID_SIZE
)
# 将位置吸附到最近的网格点(左上角)
static func snap_to_grid(position: Vector2) -> Vector2:
return Vector2(
floor(position.x / GRID_SIZE) * GRID_SIZE,
floor(position.y / GRID_SIZE) * GRID_SIZE
)
# 将位置吸附到最近的网格中心
static func snap_to_grid_center(position: Vector2) -> Vector2:
var grid_pos = world_to_grid(position)
return grid_to_world_center(grid_pos)
# ============================================================================
# 距离和区域计算
# ============================================================================
# 计算两个网格坐标之间的曼哈顿距离
static func grid_distance_manhattan(grid_pos1: Vector2i, grid_pos2: Vector2i) -> int:
return abs(grid_pos1.x - grid_pos2.x) + abs(grid_pos1.y - grid_pos2.y)
# 计算两个网格坐标之间的欧几里得距离
static func grid_distance_euclidean(grid_pos1: Vector2i, grid_pos2: Vector2i) -> float:
var diff = grid_pos1 - grid_pos2
return sqrt(diff.x * diff.x + diff.y * diff.y)
# 获取指定网格坐标周围的邻居网格4方向
static func get_grid_neighbors_4(grid_pos: Vector2i) -> Array[Vector2i]:
return [
Vector2i(grid_pos.x, grid_pos.y - 1), # 上
Vector2i(grid_pos.x + 1, grid_pos.y), # 右
Vector2i(grid_pos.x, grid_pos.y + 1), # 下
Vector2i(grid_pos.x - 1, grid_pos.y) # 左
]
# 获取指定网格坐标周围的邻居网格8方向
static func get_grid_neighbors_8(grid_pos: Vector2i) -> Array[Vector2i]:
var neighbors: Array[Vector2i] = []
for x in range(-1, 2):
for y in range(-1, 2):
if x == 0 and y == 0:
continue
neighbors.append(Vector2i(grid_pos.x + x, grid_pos.y + y))
return neighbors
# ============================================================================
# 区域和边界检查
# ============================================================================
# 检查网格坐标是否在指定矩形区域内
static func is_grid_in_bounds(grid_pos: Vector2i, min_grid: Vector2i, max_grid: Vector2i) -> bool:
return (grid_pos.x >= min_grid.x and grid_pos.x <= max_grid.x and
grid_pos.y >= min_grid.y and grid_pos.y <= max_grid.y)
# 获取矩形区域内的所有网格坐标
static func get_grids_in_rect(min_grid: Vector2i, max_grid: Vector2i) -> Array[Vector2i]:
var grids: Array[Vector2i] = []
for x in range(min_grid.x, max_grid.x + 1):
for y in range(min_grid.y, max_grid.y + 1):
grids.append(Vector2i(x, y))
return grids
# ============================================================================
# 地图尺寸规范化
# ============================================================================
# 将像素尺寸规范化为网格尺寸的倍数
static func normalize_size_to_grid(pixel_size: Vector2i) -> Vector2i:
return Vector2i(
int(ceil(float(pixel_size.x) / GRID_SIZE)) * GRID_SIZE,
int(ceil(float(pixel_size.y) / GRID_SIZE)) * GRID_SIZE
)
# 计算指定像素尺寸需要多少个网格单元
static func get_grid_count(pixel_size: Vector2i) -> Vector2i:
return Vector2i(
int(ceil(float(pixel_size.x) / GRID_SIZE)),
int(ceil(float(pixel_size.y) / GRID_SIZE))
)
# ============================================================================
# 调试和可视化辅助
# ============================================================================
# 获取网格的边界矩形(用于调试绘制)
static func get_grid_rect(grid_pos: Vector2i) -> Rect2:
var world_pos = grid_to_world(grid_pos)
return Rect2(world_pos, Vector2(GRID_SIZE, GRID_SIZE))
# 打印网格信息(调试用)
static func print_grid_info(world_pos: Vector2) -> void:
var grid_pos = world_to_grid(world_pos)
var snapped_pos = snap_to_grid(world_pos)
var center_pos = grid_to_world_center(grid_pos)
print("世界坐标: ", world_pos)
print("网格坐标: ", grid_pos)
print("吸附位置: ", snapped_pos)
print("网格中心: ", center_pos)

View File

@@ -0,0 +1 @@
uid://dceqpffgti4jb

2
_Core/utils/.gitkeep Normal file
View File

@@ -0,0 +1,2 @@
# 核心工具类目录
# 存放字符串处理、数学计算等工具类

386
_Core/utils/StringUtils.gd Normal file
View File

@@ -0,0 +1,386 @@
class_name StringUtils
# ============================================================================
# StringUtils.gd - 字符串工具类
# ============================================================================
# 静态工具类,提供常用的字符串处理功能
#
# 核心功能:
# - 输入验证(邮箱、用户名、密码)
# - 字符串格式化和转换
# - 时间格式化和相对时间计算
# - 文件大小格式化
#
# 使用方式:
# var is_valid = StringUtils.is_valid_email("user@example.com")
# var formatted_time = StringUtils.format_utc_to_local_time(utc_string)
#
# 注意事项:
# - 所有方法都是静态的,无需实例化
# - 验证方法返回布尔值或包含详细信息的字典
# - 时间处理方法支持UTC到本地时间的转换
# ============================================================================
# ============ 输入验证方法 ============
# 验证邮箱格式
#
# 参数:
# email: String - 待验证的邮箱地址
#
# 返回值:
# bool - true表示格式正确false表示格式错误
#
# 验证规则:
# - 必须包含@符号
# - @前后都必须有内容
# - 域名部分必须包含至少一个点
# - 顶级域名至少2个字符
#
# 使用示例:
# if StringUtils.is_valid_email("user@example.com"):
# print("邮箱格式正确")
static func is_valid_email(email: String) -> bool:
var regex = RegEx.new()
regex.compile("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$")
return regex.search(email) != null
# 验证用户名格式
#
# 参数:
# username: String - 待验证的用户名
#
# 返回值:
# bool - true表示格式正确false表示格式错误
#
# 验证规则:
# - 只能包含字母、数字、下划线
# - 长度不能为空且不超过50个字符
# - 不能包含空格或特殊字符
#
# 使用示例:
# if StringUtils.is_valid_username("user_123"):
# print("用户名格式正确")
static func is_valid_username(username: String) -> bool:
# 检查长度
if username.is_empty() or username.length() > 50:
return false
# 检查字符组成
var regex = RegEx.new()
regex.compile("^[a-zA-Z0-9_]+$")
return regex.search(username) != null
# 验证密码强度
#
# 参数:
# password: String - 待验证的密码
#
# 返回值:
# Dictionary - 包含验证结果的详细信息
# {
# "valid": bool, # 是否符合最低要求
# "message": String, # 验证结果消息
# "strength": int # 强度等级 (1-4)
# }
#
# 验证规则:
# - 最少8位最多128位
# - 必须包含字母和数字
# - 强度评级:包含字母(+1)、数字(+1)、特殊字符(+1)、长度>=12(+1)
#
# 使用示例:
# var result = StringUtils.validate_password_strength("MyPass123!")
# if result.valid:
# print("密码强度: ", result.message)
static func validate_password_strength(password: String) -> Dictionary:
var result = {"valid": false, "message": "", "strength": 0}
# 检查长度限制
if password.length() < 8:
result.message = "密码长度至少8位"
return result
if password.length() > 128:
result.message = "密码长度不能超过128位"
return result
# 检查字符类型
var has_letter = false # 是否包含字母
var has_digit = false # 是否包含数字
var has_special = false # 是否包含特殊字符
for i in range(password.length()):
var character = password[i]
if character >= 'a' and character <= 'z' or character >= 'A' and character <= 'Z':
has_letter = true
elif character >= '0' and character <= '9':
has_digit = true
elif character in "!@#$%^&*()_+-=[]{}|;:,.<>?":
has_special = true
# 计算强度等级
var strength = 0
if has_letter:
strength += 1
if has_digit:
strength += 1
if has_special:
strength += 1
if password.length() >= 12:
strength += 1
result.strength = strength
# 检查最低要求
if not (has_letter and has_digit):
result.message = "密码必须包含字母和数字"
return result
# 密码符合要求
result.valid = true
result.message = "密码强度: " + ["", "", "", "很强"][min(strength - 1, 3)]
return result
# ============ 字符串格式化方法 ============
# 截断字符串
#
# 参数:
# text: String - 原始字符串
# max_length: int - 最大长度
# suffix: String - 截断后缀(默认为"..."
#
# 返回值:
# String - 截断后的字符串
#
# 功能:
# - 如果字符串长度超过限制,截断并添加后缀
# - 如果字符串长度未超过限制,返回原字符串
#
# 使用示例:
# var short_text = StringUtils.truncate("这是一个很长的文本", 10, "...")
# # 结果: "这是一个很长..."
static func truncate(text: String, max_length: int, suffix: String = "...") -> String:
if text.length() <= max_length:
return text
return text.substr(0, max_length - suffix.length()) + suffix
# 首字母大写
#
# 参数:
# text: String - 原始字符串
#
# 返回值:
# String - 首字母大写的字符串
#
# 使用示例:
# var capitalized = StringUtils.capitalize_first("hello world")
# # 结果: "Hello world"
static func capitalize_first(text: String) -> String:
if text.is_empty():
return text
return text[0].to_upper() + text.substr(1)
# 转换为标题格式
#
# 参数:
# text: String - 原始字符串
#
# 返回值:
# String - 每个单词首字母大写的字符串
#
# 功能:
# - 将每个单词的首字母转换为大写
# - 其余字母转换为小写
# - 以空格分隔单词
#
# 使用示例:
# var title = StringUtils.to_title_case("hello world game")
# # 结果: "Hello World Game"
static func to_title_case(text: String) -> String:
var words = text.split(" ")
var result = []
for word in words:
if not word.is_empty():
result.append(capitalize_first(word.to_lower()))
return " ".join(result)
# 移除HTML标签
#
# 参数:
# html: String - 包含HTML标签的字符串
#
# 返回值:
# String - 移除HTML标签后的纯文本
#
# 功能:
# - 使用正则表达式移除所有HTML标签
# - 保留标签之间的文本内容
#
# 使用示例:
# var plain_text = StringUtils.strip_html_tags("<p>Hello <b>World</b></p>")
# # 结果: "Hello World"
static func strip_html_tags(html: String) -> String:
var regex = RegEx.new()
regex.compile("<[^>]*>")
return regex.sub(html, "", true)
# 格式化文件大小
#
# 参数:
# bytes: int - 文件大小(字节)
#
# 返回值:
# String - 格式化后的文件大小字符串
#
# 功能:
# - 自动选择合适的单位B, KB, MB, GB, TB
# - 保留一位小数(除了字节)
# - 使用1024作为换算基数
#
# 使用示例:
# var size_text = StringUtils.format_file_size(1536)
# # 结果: "1.5 KB"
static func format_file_size(bytes: int) -> String:
var units = ["B", "KB", "MB", "GB", "TB"]
var size = float(bytes)
var unit_index = 0
# 自动选择合适的单位
while size >= 1024.0 and unit_index < units.size() - 1:
size /= 1024.0
unit_index += 1
# 格式化输出
if unit_index == 0:
return str(int(size)) + " " + units[unit_index]
else:
return "%.1f %s" % [size, units[unit_index]]
# ============ 时间处理方法 ============
# 将UTC时间字符串转换为本地时间显示
#
# 参数:
# utc_time_str: String - UTC时间字符串格式: 2025-12-25T11:23:52.175Z
#
# 返回值:
# String - 格式化的本地时间字符串
#
# 功能:
# - 解析ISO 8601格式的UTC时间
# - 转换为本地时区时间
# - 格式化为易读的中文时间格式
#
# 使用示例:
# var local_time = StringUtils.format_utc_to_local_time("2025-12-25T11:23:52.175Z")
# # 结果: "2025年12月25日 19:23:52" (假设本地时区为UTC+8)
static func format_utc_to_local_time(utc_time_str: String) -> String:
# 解析UTC时间字符串 (格式: 2025-12-25T11:23:52.175Z)
var regex = RegEx.new()
regex.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})")
var result = regex.search(utc_time_str)
if result == null:
return utc_time_str # 如果解析失败,返回原字符串
# 提取时间组件
var year = int(result.get_string(1))
var month = int(result.get_string(2))
var day = int(result.get_string(3))
var hour = int(result.get_string(4))
var minute = int(result.get_string(5))
var second = int(result.get_string(6))
# 创建UTC时间字典
var utc_dict = {
"year": year,
"month": month,
"day": day,
"hour": hour,
"minute": minute,
"second": second
}
# 转换为Unix时间戳UTC
var utc_timestamp = Time.get_unix_time_from_datetime_dict(utc_dict)
# 获取本地时间Godot会自动处理时区转换
var local_dict = Time.get_datetime_dict_from_unix_time(utc_timestamp)
# 格式化为易读的本地时间
return "%04d%02d%02d%02d:%02d:%02d" % [
local_dict.year,
local_dict.month,
local_dict.day,
local_dict.hour,
local_dict.minute,
local_dict.second
]
# 获取相对时间描述
#
# 参数:
# utc_time_str: String - UTC时间字符串
#
# 返回值:
# String - 相对时间描述(如"5分钟后"、"2小时30分钟后"
#
# 功能:
# - 计算指定时间与当前时间的差值
# - 返回人性化的相对时间描述
# - 支持秒、分钟、小时的组合显示
#
# 使用示例:
# var relative_time = StringUtils.get_relative_time_until("2025-12-25T12:00:00Z")
# # 结果: "30分钟后" 或 "现在可以重试"
static func get_relative_time_until(utc_time_str: String) -> String:
# 解析UTC时间字符串
var regex = RegEx.new()
regex.compile("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})")
var result = regex.search(utc_time_str)
if result == null:
return "时间格式错误"
# 提取时间组件
var year = int(result.get_string(1))
var month = int(result.get_string(2))
var day = int(result.get_string(3))
var hour = int(result.get_string(4))
var minute = int(result.get_string(5))
var second = int(result.get_string(6))
# 创建UTC时间字典
var utc_dict = {
"year": year,
"month": month,
"day": day,
"hour": hour,
"minute": minute,
"second": second
}
# 转换为Unix时间戳
var target_timestamp = Time.get_unix_time_from_datetime_dict(utc_dict)
var current_timestamp = Time.get_unix_time_from_system()
# 计算时间差(秒)
var diff_seconds = target_timestamp - current_timestamp
# 格式化相对时间
if diff_seconds <= 0:
return "现在可以重试"
elif diff_seconds < 60:
return "%d秒后" % diff_seconds
elif diff_seconds < 3600:
var minutes = int(diff_seconds / 60)
return "%d分钟后" % minutes
else:
var hours = int(diff_seconds / 3600)
var minutes = int((diff_seconds % 3600) / 60)
if minutes > 0:
return "%d小时%d分钟后" % [hours, minutes]
else:
return "%d小时后" % hours

View File

@@ -0,0 +1 @@
uid://bu8onmk6q8wic

View File

View File

@@ -0,0 +1 @@
# 保持目录结构 - 音乐资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 音效资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 语音资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 音乐资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 音效资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 语音资源目录

1
assets/fonts/.gitkeep Normal file
View File

@@ -0,0 +1 @@
# 保持目录结构 - 字体资源目录

BIN
assets/fonts/msyh.ttc Normal file

Binary file not shown.

View File

@@ -0,0 +1,41 @@
[remap]
importer="font_data_dynamic"
type="FontFile"
uid="uid://ce7ujbeobblyr"
path="res://.godot/imported/msyh.ttc-1f7944f6d1cff8092894a3525ec5156c.fontdata"
[deps]
source_file="res://assets/fonts/msyh.ttc"
dest_files=["res://.godot/imported/msyh.ttc-1f7944f6d1cff8092894a3525ec5156c.fontdata"]
[params]
Rendering=null
antialiasing=1
generate_mipmaps=false
disable_embedded_bitmaps=true
multichannel_signed_distance_field=false
msdf_pixel_range=8
msdf_size=48
allow_system_fallback=true
force_autohinter=false
modulate_color_glyphs=false
hinting=1
subpixel_positioning=4
keep_rounding_remainders=true
oversampling=0.0
Fallbacks=null
fallbacks=[]
Compress=null
compress=false
preload=[{
"chars": "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_+-=[]{}|;':\",./<>?`~一二三四五六七八九十百千万亿用户名密码登录注册验证码邮箱小镇鲸鱼欢迎来到开始你的之旅请输入不能为空获取发送忘记返回居民身份确认再次已被使用换个等待分钟后试稍后正在创建账户测试模式生成查看控制台网络连接失败系统维护中升级稍后再试频繁联系管理员禁用审核先邮箱后使用成功进入镇错误或过期未找到存在",
"glyphs": [],
"name": "Web预加载",
"size": Vector2i(16, 0)
}]
language_support={}
script_support={}
opentype_features={}

BIN
assets/icon/icon144.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -2,16 +2,16 @@
importer="texture" importer="texture"
type="CompressedTexture2D" type="CompressedTexture2D"
uid="uid://byw73r2dt6xb8" uid="uid://bwy5r7soxi76a"
path="res://.godot/imported/login-bg.png-3f4c0c8160ab08ab0791dc1de267dd7a.ctex" path="res://.godot/imported/icon144.png-ae9d1f30a88beaab449c2cad89283dd3.ctex"
metadata={ metadata={
"vram_texture": false "vram_texture": false
} }
[deps] [deps]
source_file="res://assets/login/login-bg.png" source_file="res://assets/icon/icon144.png"
dest_files=["res://.godot/imported/login-bg.png-3f4c0c8160ab08ab0791dc1de267dd7a.ctex"] dest_files=["res://.godot/imported/icon144.png-ae9d1f30a88beaab449c2cad89283dd3.ctex"]
[params] [params]

BIN
assets/icon/icon16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 644 B

View File

@@ -2,16 +2,16 @@
importer="texture" importer="texture"
type="CompressedTexture2D" type="CompressedTexture2D"
uid="uid://bqvel7n6dfo1d" uid="uid://bqg5e8qn1j74u"
path="res://.godot/imported/whaletown.png-c44c9408e8b817d0db57fd8eec9de194.ctex" path="res://.godot/imported/icon16.png-3099ad8a609f90c382508b9c073ffd76.ctex"
metadata={ metadata={
"vram_texture": false "vram_texture": false
} }
[deps] [deps]
source_file="res://assets/login/whaletown.png" source_file="res://assets/icon/icon16.png"
dest_files=["res://.godot/imported/whaletown.png-c44c9408e8b817d0db57fd8eec9de194.ctex"] dest_files=["res://.godot/imported/icon16.png-3099ad8a609f90c382508b9c073ffd76.ctex"]
[params] [params]

BIN
assets/icon/icon180.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://drpllpsjdiaex"
path="res://.godot/imported/icon180.png-20a9d7b98bfb315dd470e3635f315a17.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/icon/icon180.png"
dest_files=["res://.godot/imported/icon180.png-20a9d7b98bfb315dd470e3635f315a17.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

BIN
assets/icon/icon32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://dt24j6p0cijqo"
path="res://.godot/imported/icon32.png-9a0aceb23d191139c34540a188bf8c91.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/icon/icon32.png"
dest_files=["res://.godot/imported/icon32.png-9a0aceb23d191139c34540a188bf8c91.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

BIN
assets/icon/icon512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://dt817lem3dwee"
path="res://.godot/imported/icon512.png-1c1c4b424489de87a542c89bec6eb15b.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/icon/icon512.png"
dest_files=["res://.godot/imported/icon512.png-1c1c4b424489de87a542c89bec6eb15b.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

BIN
assets/icon/icon64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://ci42rd5qe6icl"
path="res://.godot/imported/icon64.png-da8a1a20e3bf4dcf06c8ff6c558caaff.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/icon/icon64.png"
dest_files=["res://.godot/imported/icon64.png-da8a1a20e3bf4dcf06c8ff6c558caaff.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

BIN
assets/icon/image(1).png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://cnw6e3wmy0ea4"
path="res://.godot/imported/image(1).png-c89cc92103e50aaba40bf38c797be77f.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/icon/image(1).png"
dest_files=["res://.godot/imported/image(1).png-c89cc92103e50aaba40bf38c797be77f.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

BIN
assets/icon/image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

View File

@@ -2,16 +2,16 @@
importer="texture" importer="texture"
type="CompressedTexture2D" type="CompressedTexture2D"
uid="uid://cswuqnhiiypb2" uid="uid://c7v22i1hgo1x6"
path="res://.godot/imported/enter.png-ed3d67e95e66053ad0fb61054985bfb8.ctex" path="res://.godot/imported/image.png-3f16548595ba9fb08c5e50ef3251d148.ctex"
metadata={ metadata={
"vram_texture": false "vram_texture": false
} }
[deps] [deps]
source_file="res://assets/login/enter.png" source_file="res://assets/icon/image.png"
dest_files=["res://.godot/imported/enter.png-ed3d67e95e66053ad0fb61054985bfb8.ctex"] dest_files=["res://.godot/imported/image.png-3f16548595ba9fb08c5e50ef3251d148.ctex"]
[params] [params]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 840 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 218 KiB

View File

@@ -0,0 +1 @@
# 保持目录结构 - 材质资源目录

1
assets/shaders/.gitkeep Normal file
View File

@@ -0,0 +1 @@
# 保持目录结构 - 着色器资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 角色精灵资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 特效精灵资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 环境精灵资源目录

Binary file not shown.

After

Width:  |  Height:  |  Size: 351 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://b2gci3tcylfiw"
path="res://.godot/imported/curb.png-aea973bea0e48d7135256b05941024a3.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/curb.png"
dest_files=["res://.godot/imported/curb.png-aea973bea0e48d7135256b05941024a3.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 MiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://djmpsp6t8vbra"
path="res://.godot/imported/download_1767426187137.png-a7252aa9f644c4f3ab14cefb1a59847c.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/download_1767426187137.png"
dest_files=["res://.godot/imported/download_1767426187137.png-a7252aa9f644c4f3ab14cefb1a59847c.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://c3yr7cietnip3"
path="res://.godot/imported/floor_tile.png-922ec9c726f71491a3ebe25e6696192d.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/floor_tile.png"
dest_files=["res://.godot/imported/floor_tile.png-922ec9c726f71491a3ebe25e6696192d.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 475 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://7o0xyqmqbvov"
path="res://.godot/imported/square.png-f3b8edd32d9382a7b98d24fd60e1b771.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/square.png"
dest_files=["res://.godot/imported/square.png-f3b8edd32d9382a7b98d24fd60e1b771.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 523 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://dt33hewme0p1k"
path="res://.godot/imported/square1.png-5d845f041b32e4a2880ddc03c7e210e2.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/square1.png"
dest_files=["res://.godot/imported/square1.png-5d845f041b32e4a2880ddc03c7e210e2.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://ignbtjvnp5k7"
path="res://.godot/imported/广场瓦片集.png-b224b40553b9f690e690f67a89e2b520.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/广场瓦片集.png"
dest_files=["res://.godot/imported/广场瓦片集.png-b224b40553b9f690e690f67a89e2b520.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://dvsb51jintro"
path="res://.godot/imported/草地.png-2fa7f2346d7dc837788dd21e5693cec7.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/sprites/environment/草地.png"
dest_files=["res://.godot/imported/草地.png-2fa7f2346d7dc837788dd21e5693cec7.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

View File

@@ -0,0 +1 @@
# 保持目录结构 - 材质资源目录

View File

@@ -0,0 +1 @@
# 保持目录结构 - 着色器资源目录

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 MiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://bx17oy8lvaca4"
path="res://.godot/imported/bg_auth_scene.png-818065fcc20397e855c75507c1313623.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/ui/auth/bg_auth_scene.png"
dest_files=["res://.godot/imported/bg_auth_scene.png-818065fcc20397e855c75507c1313623.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 587 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://de4q4s1gxivtf"
path="res://.godot/imported/login_frame_smart_transparent.png-e5d0fd05b4713ddd3beae8223f2abb80.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/ui/auth/login_frame_smart_transparent.png"
dest_files=["res://.godot/imported/login_frame_smart_transparent.png-e5d0fd05b4713ddd3beae8223f2abb80.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

View File

@@ -0,0 +1,7 @@
[gd_resource type="Theme" load_steps=2 format=3 uid="uid://cp7t8tu7rmyad"]
[ext_resource type="FontFile" uid="uid://ce7ujbeobblyr" path="res://assets/fonts/msyh.ttc" id="1_ftb5w"]
[resource]
resource_local_to_scene = true
default_font = ExtResource("1_ftb5w")

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://gr7vud1lee4m"
path="res://.godot/imported/datawhale_logo.png-ddb5e2c04419eb84cfa8605bcbf64fbd.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://assets/ui/datawhale_logo.png"
dest_files=["res://.godot/imported/datawhale_logo.png-ddb5e2c04419eb84cfa8605bcbf64fbd.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

161
claude.md Normal file
View File

@@ -0,0 +1,161 @@
# 🎯 CLAUDE.md - WhaleTown Project Instructions
## 1. Project Vision & Context
- **Project**: "WhaleTown" - A 2D top-down pixel art RPG.
- **Engine**: Godot 4.5+ (Strictly NO Godot 3.x syntax).
- **Architecture**: Strictly layered: `_Core` (Framework), `Scenes` (Gameplay), `UI` (Interface).
- **Core Principle**: "Signal Up, Call Down". High decoupling via `EventSystem`.
## 2. 🛠 Command Reference & Setup
- **Input Map (Required Configuration)**:
- `move_left`, `move_right`, `move_up`, `move_down` (WASD / Arrows)
- `interact` (E Key / Space)
- `pause` (ESC)
- **Run Game**: `godot --path .`
- **Run Tests (GUT)**: `godot --headless -s addons/gut/gut_cmdline.gd -gdir=res://tests/ -ginclude_subdirs`
- **Init Structure**: `mkdir -p _Core/managers _Core/systems Scenes/Maps Scenes/Entities Scenes/Components UI/Windows UI/HUD Assets/Sprites tests/unit tests/integration`
## 3. 📂 File Path Rules (STRICT LOWERCASE)
*Claude: Root folders MUST be lowercase. Scripts and Scenes MUST stay together.*
- **Core Managers**: `_Core/managers/[Name].gd`
- **Core Systems**: `_Core/systems/[Name].gd`
- **Entities**: `Scenes/Entities/[EntityName]/[EntityName].tscn` (Script `.gd` in same folder).
- **Maps**: `Scenes/Maps/[map_name].tscn`
- **Components**: `Scenes/Components/[ComponentName].gd` (Reusable logic nodes).
- **UI Windows**: `UI/Windows/[WindowName].tscn`
- **Tests**: `tests/[unit|integration]/test_[name].gd` (Folder is lowercase `tests`).
## 4. 📋 Coding Standards (The Law)
- **Type Safety**: ALWAYS use strict static typing: `var speed: float = 100.0`, `func _ready() -> void`.
- **Naming Conventions**:
- `class_name PascalCase` at the top of every script.
- Variables/Functions: `camelCase` (e.g., `var moveSpeed`, `func updateMovement()`). Constants: `UPPER_CASE`.
- Private members: Prefix with underscore `_` (e.g., `var _velocity: Vector2`).
- **Node Access**: Use `%UniqueName` for UI and internal scene components.
- **Signals**: Use "Signal Up, Call Down". Parent calls child methods; Child emits signals.
- **Forbidden Patterns**:
- ❌ NO `yield()` -> Use `await`.
- ❌ NO `get_node()` in `_process` -> Cache with `@onready`.
- ❌ NO Linear Filter -> All Sprite2D/TileMap resources MUST use **Nearest** filter.
## 5. 🏛 Architecture & Communication
- **EventSystem**: Use `_Core/systems/EventSystem.gd` for cross-module messaging.
- **Event Registry**: Use `class_name EventNames` in `_Core/EventNames.gd`.
```gdscript
class_name EventNames
const PLAYER_MOVED = "player_moved"
const INTERACT_PRESSED = "interact_pressed"
const NPC_TALKED = "npc_talked"
```
- **Singletons**: Only GameManager, SceneManager, EventSystem allowed as Autoloads.
- **Decoupling**: Low-level entities MUST NOT reference GameManager. Use events.
## 6. 🏗 Implementation Details
- **Player**: CharacterBody2D. Must include Camera2D with `position_smoothing_enabled = true`.
- **NPC/Interactables**: Use Area2D named InteractionArea. Trigger via EventSystem.
- **TileMap Layers**:
- Layer 0: Ground (No collision).
- Layer 1: Obstacles (Physics Layer enabled).
- Layer 2: Decoration (Y-Sort enabled).
- **Camera**: Must auto-calculate limits via `TileMap.get_used_rect()`.
## 7. 🧪 Testing Requirements (MANDATORY)
- **Coverage**: Every Manager/System in `_Core/` MUST have a GUT test.
- **Naming**: Test files must start with `test_` and extend GutTest.
- **Example**:
```gdscript
extends GutTest
func test_event_emission():
var sender = Node.new()
watch_signals(EventSystem)
EventSystem.emit_event(EventNames.PLAYER_MOVED, {})
assert_signal_emitted(EventSystem, "event_raised")
```
## 🔄 8. Standard Development Workflow (MANDATORY)
**CRITICAL**: When performing ANY development task (implementing features, fixing bugs, creating scenes), you MUST follow this 7-step standardized workflow:
### Quick Start: Use the Skill (Recommended) ⭐
```bash
/whaletown-developer [任务描述]
```
Example: `/whaletown-developer 实现玩家二段跳功能`
The skill automates the entire 7-step process and enforces all quality standards.
### The 7-Step Workflow
```
Step 1: Architecture Analysis → Read docs/02-开发规范/架构与通信规范.md
Step 2: Implementation → Follow layered architecture, type safety, EventSystem
Step 3: Comment Validation → Read docs/02-开发规范/代码注释规范.md
Step 4: Naming Validation → Read docs/02-开发规范/命名规范.md
Step 5: Test Writing → Read docs/03-技术实现/测试指南.md
Step 6: Test Execution → Run: godot --headless -s addons/gut/gut_cmdline.gd
Step 7: Git Commit → Read docs/02-开发规范/Git提交规范.md
```
### Workflow Enforcement Rules
1. **Never Skip Steps**: All 7 steps are mandatory for every development task
2. **Read Specs First**: Each step requires reading the corresponding specification document
3. **Use TodoWrite**: Track progress through all 7 steps using TodoWrite tool
4. **Mark Completed**: Mark each step as completed immediately after finishing
5. **Quality Gates**: Cannot proceed to next step until current step passes validation
### Naming Convention Clarification
**IMPORTANT**: The project uses **camelCase** for variables/functions, NOT snake_case:
- ✅ Correct: `var moveSpeed: float`, `func updateMovement()`
- ❌ Incorrect: `var move_speed: float`, `func update_movement()`
See `docs/02-开发规范/命名规范.md` for complete details.
### Quality Checklist (Every Development Task)
- [ ] File location follows layered architecture (_Core, scenes, UI)
- [ ] Uses EventSystem for cross-module communication
- [ ] Event names added to EventNames.gd
- [ ] All variables/functions have type annotations
- [ ] Naming: PascalCase (classes), camelCase (vars/funcs), UPPER_CASE (constants)
- [ ] File header comment complete
- [ ] Public functions have complete documentation
- [ ] Unit tests created and passing
- [ ] Git commit message follows specification
- [ ] No Godot 3.x syntax (await not yield, @onready cached)
### Reference Documents
- **Full Workflow**: `docs/AI_docs/workflows/standard_development_workflow.md`
- **Quick Checklist**: `.claude/skills/whaletown-developer/references/checklist.md`
- **Skill Definition**: `.claude/skills/whaletown-developer/SKILL.md`
**Remember**: Consistency through automation. Use `/whaletown-developer` to ensure no steps are missed.
## 9. 🧘 The Zen of Development
- **Juice or Death**: Every interaction (UI popup, NPC talk) MUST have a Tween placeholder.
- **Zero Magic Numbers**: All speeds/timers MUST be `@export` or defined in `Config/`.
- **Simplicity**: If a function does two things, split it.
- **Back of the Fence**: Hidden logic (like ResponseHandler.gd) must be as clean as the HUD.
## 10. 📝 Code Template (Entity Pattern)
```gdscript
extends CharacterBody2D
class_name Player
# 1. Exports & Constants
@export var move_speed: float = 200.0
# 2. Node References
@onready var sprite: Sprite2D = %Sprite2D
# 3. Lifecycle
func _physics_process(delta: float) -> void:
_move(delta)
# 4. Private Methods
func _move(_delta: float) -> void:
var dir := Input.get_vector("move_left", "move_right", "move_up", "move_down")
velocity = dir * move_speed
move_and_slide()

View File

View File

View File

@@ -0,0 +1,85 @@
# 📖 项目入门
> **适用人群**: 新加入项目的开发者
> **使用时机**: 项目开始前,环境搭建阶段
> **质量等级**: A级 ⭐⭐⭐⭐⭐
这个目录包含了新人入门必读的基础文档,帮助你快速了解项目并搭建开发环境。
## 📋 阅读顺序
### 第一步:了解项目 🏗️
**[项目结构说明.md](项目结构说明.md)**
- 项目整体架构设计
- 目录组织规则和命名规范
- 各层级职责说明
- 核心组件介绍
### 第二步:配置环境 ⚙️
**[项目设置指南.md](项目设置指南.md)**
- Godot编辑器配置
- AutoLoad单例设置
- 输入映射配置(已预配置)
- 开发环境验证
## ✅ 完成检查
阅读完本目录的文档后,你应该能够:
- [ ] 理解项目的整体架构和设计理念
- [ ] 成功配置Godot开发环境
- [ ] 了解核心组件的作用和使用方式
- [ ] 运行项目并进行基本测试
- [ ] 验证所有AutoLoad单例正常工作
- [ ] 确认游戏输入控制正常响应
## 🎮 输入控制说明
项目已预配置以下输入映射:
- **移动控制**: `move_left` (A/←), `move_right` (D/→), `move_up` (W/↑), `move_down` (S/↓)
- **交互控制**: `interact` (E键), `jump` (空格键)
这些输入映射已经在 `project.godot` 中配置完成,无需额外设置。
## 🚨 常见启动问题
### 问题1: 游戏无法响应输入
**原因**: 项目文件损坏或配置丢失
**解决**: 重新克隆项目,确保 `project.godot` 文件完整
### 问题2: 控制台出现"Invalid action"错误
**原因**: 输入映射配置丢失
**解决**: 检查 `project.godot` 文件中的 `[input]` 部分是否完整
### 问题3: AutoLoad单例报错
**原因**: AutoLoad配置不正确或文件路径错误
**解决**: 参考 [项目设置指南.md](项目设置指南.md) 验证配置
### 问题4: EventSystem相关错误
**原因**: 缺少 `_Core/EventNames.gd` 文件
**解决**: 确保项目包含完整的 `_Core` 目录结构
## 🔗 下一步
完成项目入门后,建议继续阅读:
- [02-开发规范](../02-开发规范/) - 学习编码标准和架构规范
- [03-技术实现](../03-技术实现/) - 开始具体功能开发
## 💡 小贴士
- **项目已预配置完成** - 输入映射和核心组件都已设置好
- 遇到问题时,先查看对应文档的"常见问题"部分
- 建议在实际操作中边读边做,加深理解
- 可以将重要的配置信息做笔记备用
- 完成每个步骤后,建议运行项目验证配置是否正确
- 重点关注 `_Core` 目录中的核心组件,它们是项目的基础
## 🛠️ 核心组件预览
项目包含以下核心组件,在后续开发中会频繁使用:
- **EventSystem** - 全局事件通信系统
- **GameManager** - 游戏状态管理
- **SceneManager** - 场景切换管理
- **NetworkManager** - 网络请求管理
- **ProjectPaths** - 统一路径管理
详细使用方法请参考 [架构与通信规范](../02-开发规范/架构与通信规范.md)。

View File

@@ -0,0 +1,157 @@
# 输入映射配置指南
本文档说明了WhaleTown项目的输入映射配置要求和设置方法。
## 🎮 必需的输入映射
### 基础移动控制
- **`move_left`** - 向左移动
- 推荐按键A键、左方向键
- **`move_right`** - 向右移动
- 推荐按键D键、右方向键
- **`move_up`** - 向上移动
- 推荐按键W键、上方向键
- **`move_down`** - 向下移动
- 推荐按键S键、下方向键
### 交互控制
- **`interact`** - 交互动作
- 推荐按键E键、空格键
- **`pause`** - 暂停游戏
- 推荐按键ESC键
## ⚙️ Godot编辑器配置步骤
### 1. 打开输入映射设置
1. 在Godot编辑器中打开 `Project``Project Settings`
2. 切换到 `Input Map` 标签
### 2. 添加输入动作
对于每个必需的输入动作:
1.`Action` 输入框中输入动作名称(如 `move_left`
2. 点击 `Add` 按钮
3. 点击新添加动作右侧的 `+` 按钮
4. 按下对应的按键进行绑定
5. 重复步骤3-4添加备用按键
### 3. 配置示例
```
move_left:
- Key: A
- Key: Left Arrow
move_right:
- Key: D
- Key: Right Arrow
move_up:
- Key: W
- Key: Up Arrow
move_down:
- Key: S
- Key: Down Arrow
interact:
- Key: E
- Key: Space
pause:
- Key: Escape
```
## 🔧 代码中的使用方法
### 移动输入检测
```gdscript
func _physics_process(delta: float) -> void:
# 获取移动向量
var direction := Input.get_vector(
"move_left", "move_right",
"move_up", "move_down"
)
# 应用移动
velocity = direction * move_speed
move_and_slide()
```
### 交互输入检测
```gdscript
func _input(event: InputEvent) -> void:
if event.is_action_pressed("interact"):
_handle_interaction()
if event.is_action_pressed("pause"):
_toggle_pause()
```
### 连续输入检测
```gdscript
func _process(delta: float) -> void:
# 检测持续按下的按键
if Input.is_action_pressed("interact"):
_continuous_interaction(delta)
```
## 📱 手柄支持(可选)
### 推荐手柄映射
- **左摇杆** - 移动控制
- **A按钮/X按钮** - 交互
- **Start按钮** - 暂停
### 配置方法
1. 在Input Map中为每个动作添加手柄输入
2. 使用 `Joypad Button``Joypad Axis` 进行绑定
## ✅ 验证配置
### 测试脚本
创建一个简单的测试脚本验证输入配置:
```gdscript
extends Node
func _ready() -> void:
print("输入映射测试开始...")
_test_input_actions()
func _test_input_actions() -> void:
var required_actions = [
"move_left", "move_right", "move_up", "move_down",
"interact", "pause"
]
for action in required_actions:
if InputMap.has_action(action):
print("", action, " - 已配置")
else:
print("", action, " - 未配置")
func _input(event: InputEvent) -> void:
# 实时显示输入事件
for action in InputMap.get_actions():
if event.is_action_pressed(action):
print("按下: ", action)
```
## 🚨 常见问题
### Q: 输入没有响应怎么办?
A: 检查以下几点:
1. 确认输入动作名称拼写正确
2. 验证按键是否正确绑定
3. 检查代码中是否正确使用了动作名称
### Q: 如何添加自定义输入?
A: 按照相同步骤在Input Map中添加新的动作并在代码中使用对应的动作名称。
### Q: 手柄不工作怎么办?
A: 确保手柄已连接并在Input Map中正确配置了手柄按钮映射。
---
**注意:输入映射配置是游戏正常运行的基础,请确保所有必需的输入动作都已正确配置!**

View File

@@ -0,0 +1,393 @@
# WhaleTown 项目结构说明
本文档详细说明了 WhaleTown 项目的文件结构设计,采用分层架构模式,确保团队协作高效且代码结构清晰。
## 🎯 设计理念
### 核心原则
- **分层架构**:框架层、游戏层、界面层明确分离
- **团队协作**:策划、美术、开发三类角色各司其职
- **高度解耦**:通过事件系统实现组件间通信
- **组件复用**:可复用组件统一管理
- **标准化**:统一的命名规范和目录结构
### 团队协作模式
- **🎮 开发团队** - 主要工作在 `_Core/``scenes/``UI/``Utils/`
- **🎨 美术团队** - 主要工作在 `assets/`
- **📋 策划团队** - 主要工作在 `Config/`
## 🏗️ 项目架构概览
```
WhaleTown/
├── 🔧 _Core/ # [核心层] 功能实现与组件实现,项目最基本的底层实现
├── 🎬 scenes/ # [场景层] 场景与视觉呈现,包含地图、人物等视觉部分
├── 🎨 assets/ # [资源层] 静态资源存储,包括图片、音乐、视频、贴图等
├── ⚙️ Config/ # [配置层] 配置文件管理,用于配置各类环境
├── 🧪 tests/ # [测试层] 测试文件系统,放置所有组件的测试代码
├── 🌐 web_assets/ # [发布层] Web导出资源专门用于Web平台导出
└── 📚 docs/ # [文档层] 项目文档
```
---
## 📁 详细目录结构
### 1. 🔧 核心层 (_Core/)
> **负责团队**: 开发团队
> **职责**: 功能实现与组件实现,项目最基本的底层实现
```
_Core/
├── managers/ # 全局管理器
│ ├── GameManager.gd # 游戏状态管理
│ ├── SceneManager.gd # 场景切换管理
│ ├── NetworkManager.gd # 网络通信管理
│ └── ResponseHandler.gd # API响应处理
├── systems/ # 核心系统
│ └── EventSystem.gd # 全局事件系统
├── components/ # 基础组件实现
│ ├── BaseCharacter.gd # 基础角色组件
│ ├── BaseItem.gd # 基础物品组件
│ └── BaseUI.gd # 基础UI组件
├── utils/ # 🔨 核心工具类
│ ├── StringUtils.gd # 字符串处理工具
│ ├── MathUtils.gd # 数学计算工具
│ └── PixelUtils.gd # 像素风游戏专用工具
├── EventNames.gd # 事件名称定义
└── ProjectPaths.gd # 路径统一管理
```
**特点**:
- 自动加载 (AutoLoad) 单例
- 全局可访问的核心功能
- 与具体游戏逻辑无关的底层实现
- 提供基础服务和组件框架
**使用示例**:
```gdscript
# 游戏状态管理
GameManager.change_state(GameManager.GameState.IN_GAME)
# 场景切换
SceneManager.change_scene("main")
# 事件通信
EventSystem.emit_event("player_moved", {"position": Vector2(100, 200)})
```
### 2. 🎬 场景层 (scenes/)
> **负责团队**: 开发团队
> **职责**: 场景与视觉呈现,包含地图场景、人物场景等一系列视觉呈现的部分
```
scenes/
├── MainScene.tscn # 🎯 主入口场景 - 所有图像显示的入口文件
├── MainScene.gd # 主场景控制器脚本
├── maps/ # 地图场景
│ ├── main_world.tscn # 主世界地图
│ ├── dungeon_01.tscn # 地牢场景
│ └── town_center.tscn # 城镇中心
├── characters/ # 人物场景
│ ├── player/ # 玩家角色
│ │ ├── Player.tscn # 玩家场景
│ │ └── Player.gd # 玩家脚本
│ ├── npcs/ # NPC角色
│ └── enemies/ # 敌人角色
├── ui/ # UI界面场景
│ ├── menus/ # 菜单界面
│ ├── hud/ # 游戏HUD
│ └── dialogs/ # 对话框
├── effects/ # 特效场景
│ ├── particles/ # 粒子效果
│ └── animations/ # 动画效果
└── prefabs/ # 预制体组件
├── items/ # 物品预制体
└── interactive/ # 交互对象预制体
```
**设计原则**:
- **场景内聚**: 脚本紧邻场景文件存放
- **分类明确**: 按功能类型地图、人物、UI、特效分类
- **模块化**: 可复用的预制体统一管理
- **视觉导向**: 主要负责游戏的视觉呈现和UI实现
### 3. 🎨 资源层 (assets/)
> **负责团队**: 美术团队
> **职责**: 所有静态资源的存储,包括图片、音乐、视频、贴图等素材
```
assets/
├── sprites/ # 精灵图片资源
│ ├── characters/ # 角色精灵玩家、NPC、敌人
│ ├── environment/ # 环境精灵(地形、建筑、装饰)
│ ├── items/ # 物品精灵(道具、装备、收集品)
│ ├── effects/ # 特效精灵(爆炸、魔法、粒子)
│ └── ui/ # UI精灵按钮、图标、边框
├── audio/ # 音频资源
│ ├── music/ # 背景音乐BGM
│ ├── sounds/ # 音效SFX
│ └── voice/ # 语音(对话、旁白)
├── fonts/ # 字体文件
│ ├── pixel_fonts/ # 像素风字体
│ └── ui_fonts/ # UI专用字体
├── materials/ # 材质资源
│ ├── pixel_materials/ # 像素风材质
│ └── shader_materials/ # 着色器材质
├── shaders/ # 着色器文件
│ ├── pixel_shaders/ # 像素风着色器
│ └── effect_shaders/ # 特效着色器
├── ui/ # UI专用资源
│ ├── themes/ # UI主题
│ ├── icons/ # 图标资源
│ └── backgrounds/ # 背景图片
└── icon/ # 应用图标
├── icon.svg # 矢量图标
└── icon.png # 位图图标
```
**像素风游戏资源特点**:
- **像素完美**: 所有精灵使用像素完美设置Filter: Off, Mipmaps: Off
- **统一风格**: 保持一致的像素密度和调色板
- **分辨率标准**: 建议使用16x16、32x32等标准像素尺寸
- **动画帧**: 角色动画使用精灵表Sprite Sheet组织
### 4. ⚙️ 配置层 (Config/)
> **负责团队**: 策划团队
> **职责**: 配置文件管理,主要用来配置各类环境
```
Config/
├── game_config.json # 游戏主配置
├── zh_CN.json # 中文本地化
├── environment/ # 环境配置
│ ├── development.json # 开发环境配置
│ ├── testing.json # 测试环境配置
│ └── production.json # 生产环境配置
├── gameplay/ # 游戏玩法配置
│ ├── character_stats.json # 角色属性配置
│ ├── item_database.json # 物品数据库
│ └── level_config.json # 关卡配置
└── localization/ # 本地化配置
├── en_US.json # 英文本地化
├── zh_CN.json # 中文本地化
└── ja_JP.json # 日文本地化
```
**配置文件特点**:
- **环境分离**: 开发、测试、生产环境配置分离
- **数据驱动**: 游戏数值通过配置文件控制
- **本地化支持**: 多语言文本管理
- **热更新**: 支持运行时配置更新
### 5. 🧪 测试层 (tests/)
> **负责团队**: 开发团队
> **职责**: 测试文件系统,放置所有对应组件的测试代码,方便快速进行功能性与性能测试
```
tests/
├── unit/ # 单元测试
│ ├── core/ # 核心组件测试
│ ├── characters/ # 角色组件测试
│ └── systems/ # 系统功能测试
├── integration/ # 集成测试
│ ├── scene_transitions/ # 场景切换测试
│ ├── save_load/ # 存档系统测试
│ └── network/ # 网络功能测试
├── performance/ # 性能测试
│ ├── framerate/ # 帧率测试
│ ├── memory/ # 内存使用测试
│ └── loading_times/ # 加载时间测试
├── api/ # API接口测试
│ ├── auth_tests.py # 认证接口测试
│ └── game_api_tests.py # 游戏API测试
└── ui/ # UI功能测试
├── menu_tests/ # 菜单测试
└── dialog_tests/ # 对话框测试
```
**测试类型说明**:
- **单元测试**: 测试单个组件的功能正确性
- **集成测试**: 测试组件间的交互和协作
- **性能测试**: 监控游戏性能指标,确保流畅运行
- **API测试**: 验证网络接口的正确性和稳定性
- **UI测试**: 测试用户界面的交互和响应
### 6. 🌐 Web导出层 (web_assets/)
> **负责团队**: 自动生成
> **职责**: Web导出资源专门用于Web平台导出的相关资源和配置文件
```
web_assets/
├── html/ # HTML模板文件
│ ├── index.html # Web版本入口页面
│ └── loading.html # 加载页面模板
├── css/ # 样式文件
│ ├── game.css # 游戏样式
│ └── loading.css # 加载样式
├── js/ # JavaScript脚本
│ ├── game_loader.js # 游戏加载器
│ └── utils.js # 工具函数
├── icons/ # Web应用图标
│ ├── favicon.ico # 网站图标
│ └── app_icons/ # PWA应用图标
└── config/ # Web配置文件
├── manifest.json # PWA清单文件
└── service-worker.js # 服务工作者
```
**Web导出特点**:
- **PWA支持**: 支持渐进式Web应用功能
- **响应式设计**: 适配不同屏幕尺寸
- **加载优化**: 优化资源加载和缓存策略
- **跨平台兼容**: 确保在各种浏览器中正常运行
### 7. 📚 文档层 (docs/)
> **负责团队**: 全体团队
> **职责**: 项目文档和开发指南
```
docs/
├── 01-项目入门/ # 新人必读文档
├── 02-开发规范/ # 编码标准文档
├── 03-技术实现/ # 开发指导文档
├── 04-高级开发/ # 进阶技巧文档
├── 05-部署运维/ # 发布部署文档
├── 06-功能模块/ # 功能文档
└── AI_docs/ # 🤖 AI专用文档
├── README.md # AI文档总览
├── architecture_guide.md # 架构执行指南
├── coding_standards.md # 代码风格规范
├── templates/ # 代码模板库
│ ├── components.md # 组件模板集合
│ ├── managers.md # 管理器模板集合
│ └── ui_templates.md # UI模板集合
├── workflows/ # 工作流程指南
│ ├── feature_development.md # 功能开发流程
│ ├── bug_fixing.md # Bug修复流程
│ └── testing_workflow.md # 测试执行流程
└── quick_reference/ # 快速参考手册
├── code_snippets.md # 常用代码片段
├── api_reference.md # API快速参考
└── troubleshooting.md # 故障排除指南
```
**AI_docs特点**:
- **结构化执行**: 每个文档都包含可直接执行的步骤和代码模板
- **标准化规范**: 为AI编程助手提供统一的开发标准和最佳实践
- **模板驱动**: 提供完整的代码模板,确保代码一致性和质量
- **工作流导向**: 包含详细的开发工作流程提升AI协作效率
```
docs/
├── 01-项目入门/ # 新人必读
├── 02-开发规范/ # 编码标准
├── 03-技术实现/ # 开发指导
├── 04-高级开发/ # 进阶技巧
├── 05-部署运维/ # 发布部署
└── 06-功能模块/ # 功能文档
```
---
## 🤝 团队协作指南
### 开发团队 🎮
**主要工作区域**: `_Core/`, `scenes/`, `tests/`
**日常工作流程**:
1.`_Core/` 中开发核心系统、管理器、基础组件和工具类
2.`scenes/` 中创建游戏场景、角色、UI界面和特效
3.`tests/` 中编写各类测试用例确保代码质量
**协作要点**:
- 遵循架构设计原则,使用事件系统进行模块通信
- 保持代码模块化和可复用性
- 将通用工具类放在 `_Core/utils/` 中统一管理
- 针对像素风游戏特点优化性能
- 及时编写测试和文档
### 美术团队 🎨
**主要工作区域**: `assets/`
**日常工作流程**:
1. 按分类整理美术资源到 `assets/` 对应目录
2. 确保像素艺术风格的一致性和像素完美
3. 配置正确的Godot导入设置关闭过滤、禁用Mipmaps
4. 与开发团队协作调整UI和游戏资源
**像素风游戏特殊要求**:
- 严格遵循像素完美原则
- 保持统一的像素密度和调色板
- 使用标准像素尺寸16x16、32x32等
- 精灵动画使用精灵表组织
### 策划团队 📋
**主要工作区域**: `Config/`
**日常工作流程**:
1.`Config/` 中维护游戏配置和数值平衡
2. 管理多环境配置(开发、测试、生产)
3. 负责本地化文本的翻译和维护
4. 设计游戏玩法和关卡数据
**协作要点**:
- 使用JSON格式编写配置文件
- 保持配置文件的结构清晰和可维护性
- 及时更新本地化文本
- 与开发团队协作实现数据驱动的游戏功能
---
## 🔄 开发工作流
### 新功能开发流程
1. **需求分析** - 明确功能需求和设计方案
2. **架构设计** - 确定涉及的模块和接口
3. **资源准备** - 美术团队准备相关资源
4. **配置设置** - 策划团队配置相关数据
5. **代码实现** - 开发团队实现功能逻辑
6. **测试验证** - 编写测试用例验证功能
7. **文档更新** - 更新相关文档说明
### 版本发布流程
1. **功能完成** - 所有计划功能开发完成
2. **测试通过** - 所有测试用例通过
3. **资源整理** - 美术资源整理完成
4. **配置确认** - 策划配置确认无误
5. **构建发布** - 使用 `tools/` 中的脚本构建
6. **部署上线** - 部署到目标环境
---
## 📋 最佳实践
### 目录命名规范
- **文件夹**: 使用 PascalCase (如: `Config/`, `Utils/`)
- **文件**: 使用 snake_case (如: `main_scene.tscn`, `game_config.json`)
- **脚本类**: 使用 PascalCase (如: `GameManager.gd`)
### 资源管理规范
- 所有资源必须放在 `assets/` 对应分类目录下
- 使用描述性的文件名,避免使用数字编号
- **像素艺术资源必须关闭过滤** (Filter: Off, Mipmaps: Off)
- 保持统一的像素密度和调色板
- 使用标准像素尺寸16x16、32x32、64x64等
- 及时清理不使用的资源文件
### 代码组织规范
- 脚本文件与场景文件放在同一目录
- 使用事件系统实现模块间通信,避免直接引用
- 保持单一职责原则,避免过度耦合
- 针对像素风游戏优化性能(避免浮点数位置、使用整数坐标)
- 及时编写注释和文档
### 像素风游戏特殊规范
- **像素完美**: 确保所有精灵在整数坐标上渲染
- **统一风格**: 保持一致的像素密度和艺术风格
- **性能优化**: 使用对象池管理频繁创建销毁的对象
- **分辨率适配**: 使用像素完美的缩放方式适配不同分辨率
---
**记住:良好的项目结构是团队协作成功的基础!**

View File

@@ -0,0 +1,142 @@
# 项目设置指南
本文档指导你完成WhaleTown项目的Godot编辑器配置确保开发环境正确设置。
## 🎯 AutoLoad 配置
项目已经预配置了以下AutoLoad单例你可以验证配置是否正确
### 1. 打开项目设置
1. 在Godot编辑器中打开 `Project``Project Settings`
2. 切换到 `AutoLoad` 标签
### 2. 验证AutoLoad配置
确认以下单例已正确配置:
| 名称 | 路径 | 单例 |
|------|------|------|
| GameManager | `res://_Core/managers/GameManager.gd` | ✅ |
| SceneManager | `res://_Core/managers/SceneManager.gd` | ✅ |
| EventSystem | `res://_Core/systems/EventSystem.gd` | ✅ |
| NetworkManager | `res://_Core/managers/NetworkManager.gd` | ✅ |
| ResponseHandler | `res://_Core/managers/ResponseHandler.gd` | ✅ |
### 3. 如果需要手动添加AutoLoad
如果某个AutoLoad缺失可以手动添加
1. 点击 `Add` 按钮
2. 设置以下信息:
- **Path**: 对应的脚本路径
- **Name**: 单例名称
- **Singleton**: ✅ 勾选
3. 点击 `Add` 确认
## ⚙️ 其他重要设置
### 主题配置
项目使用自定义中文主题:
- **路径**: `assets/ui/chinese_theme.tres`
- **字体**: 微软雅黑 (`assets/fonts/msyh.ttc`)
### 主场景设置
- **主场景**: `res://Scenes/Maps/main_scene.tscn`
- **窗口大小**: 1376x768
- **窗口模式**: 全屏模式
### 渲染设置
- **渲染器**: GL Compatibility (兼容性优先)
- **拉伸模式**: Canvas Items
- **拉伸比例**: Expand
## 🧪 验证设置
### 1. 测试AutoLoad单例
在任何脚本中可以直接使用:
```gdscript
func _ready():
# 测试GameManager
print("游戏状态: ", GameManager.get_current_state())
# 测试SceneManager
print("当前场景: ", SceneManager.get_current_scene_name())
# 测试EventSystem
EventSystem.emit_event("test_event", {"message": "Hello World"})
# 测试NetworkManager
var request_id = NetworkManager.login("test_user", "test_password")
print("网络请求ID: ", request_id)
```
### 2. 检查控制台输出
运行项目后,检查控制台是否有以下信息:
- ✅ 没有AutoLoad相关错误
- ✅ 各个管理器初始化成功
- ✅ 主题和字体加载正常
### 3. 测试场景切换
```gdscript
# 测试场景管理器
func test_scene_manager():
# 切换到主场景
SceneManager.change_scene("main")
```
## 🔧 常见问题排查
### 问题1: AutoLoad脚本找不到
**症状**: 控制台显示"Cannot load script"错误
**解决方案**:
1. 检查脚本文件是否存在于指定路径
2. 确认脚本文件没有语法错误
3. 重新导入项目 (`Project``Reload Current Project`)
### 问题2: 单例无法访问
**症状**: 代码中无法访问GameManager等单例
**解决方案**:
1. 确认AutoLoad配置中勾选了"Singleton"
2. 重启Godot编辑器
3. 检查脚本中是否有拼写错误
### 问题3: 主题显示异常
**症状**: 界面字体或样式显示不正确
**解决方案**:
1. 检查 `assets/ui/chinese_theme.tres` 文件是否存在
2. 确认字体文件 `assets/fonts/msyh.ttc` 已正确导入
3. 在项目设置中重新设置自定义主题
### 问题4: 网络请求失败
**症状**: NetworkManager调用失败
**解决方案**:
1. 检查网络连接
2. 确认API地址配置正确
3. 查看ResponseHandler是否正常工作
## 📋 配置检查清单
完成设置后,请检查以下项目:
- [ ] 所有AutoLoad单例配置正确
- [ ] 主场景可以正常启动
- [ ] 控制台没有错误信息
- [ ] 自定义主题加载正常
- [ ] 中文字体显示正确
- [ ] 网络管理器可以正常调用
- [ ] 事件系统工作正常
- [ ] 场景管理器可以切换场景
## 🚀 下一步
配置完成后,建议继续阅读:
- [输入映射配置](输入映射配置.md) - 设置游戏控制
- [命名规范](../02-开发规范/命名规范.md) - 学习编码规范
- [架构与通信规范](../02-开发规范/架构与通信规范.md) - 理解项目架构
---
**💡 提示**: 如果遇到问题,可以参考 [测试指南](../03-技术实现/测试指南.md) 进行更详细的功能验证。

View File

@@ -0,0 +1,105 @@
# 📋 开发规范
> **适用人群**: 所有开发者
> **使用时机**: 编码过程中,代码审查时
这个目录包含了项目的所有编码标准和开发规范,确保团队代码风格一致,架构设计统一。
## 📚 规范文档
### 基础规范 📝
**[命名规范.md](命名规范.md)**
- 文件、类、变量、函数命名标准
- 资源文件命名规则
- 目录结构命名约定
**[代码注释规范.md](代码注释规范.md)**
- 注释格式和标准
- 文档生成规范
- AI辅助开发指南
**[Git提交规范.md](Git提交规范.md)**
- 提交信息格式标准
- 分支管理策略
- 代码审查流程
### 架构规范 🏗️
**[架构与通信规范.md](架构与通信规范.md)**
- 分层架构设计原则
- EventSystem事件系统使用
- 组件间通信标准
- 单例管理规范
### 质量标准 ⭐
**[开发哲学与最佳实践.md](开发哲学与最佳实践.md)**
- 项目开发理念
- 代码质量标准
- 最佳实践指导
- 代码审查清单
## 🎯 使用指南
### 新人学习路径
1. **命名规范** - 学会正确命名
2. **架构与通信规范** - 理解项目架构
3. **开发哲学与最佳实践** - 掌握质量标准
4. **代码注释规范** - 学会写好注释
5. **Git提交规范** - 规范版本控制
### 日常开发参考
- 编码时参考 **命名规范****架构规范**
- 提交代码前检查 **最佳实践** 清单
- 写注释时遵循 **注释规范**
- 提交时遵循 **Git规范**
### 代码审查要点
- [ ] 命名是否符合规范
- [ ] 架构设计是否合理
- [ ] 代码质量是否达标
- [ ] 注释是否完整清晰
- [ ] 提交信息是否规范
## ⚠️ 重要提醒
### 强制性规范
以下规范是**强制性**的,必须严格遵守:
- 文件和目录命名规范
- EventSystem通信规范
- 类型安全要求
- Git提交格式
### 建议性规范
以下规范是**建议性**的,推荐遵循:
- 代码注释的详细程度
- 函数长度和复杂度
- 性能优化建议
## 🔄 规范更新
### 更新原则
- 规范变更需要团队讨论
- 重大变更需要文档化说明
- 保持向后兼容性
### 更新流程
1. 提出规范变更建议
2. 团队讨论和评审
3. 更新相关文档
4. 通知所有开发者
## 🤝 团队协作
### 规范执行
- 代码审查时严格检查规范遵循情况
- 定期进行规范培训和分享
- 鼓励团队成员提出改进建议
### 问题反馈
如果发现规范问题或有改进建议:
- 创建Issue讨论
- 在团队会议中提出
- 通过PR提交改进方案
---
**记住:规范不是束缚,而是团队协作的基础!**

Some files were not shown because too many files have changed in this diff Show More