forked from datawhale/whale-town-front
refactor:实现新的项目结构组织
- 添加 _Core/components/ 和 _Core/utils/ 目录 - 重新组织 scenes/ 目录结构,按功能分类 - 迁移 StringUtils.gd 到新的 _Core/utils/ 位置 - 迁移 AuthScene.gd 到新的 scenes/ui/ 位置 - 添加 AI 文档支持目录 docs/AI_docs/ - 添加开发参考文档 claude.md
This commit is contained in:
0
docs/AI_docs/.gitkeep
Normal file
0
docs/AI_docs/.gitkeep
Normal file
238
docs/AI_docs/quick_reference/troubleshooting.md
Normal file
238
docs/AI_docs/quick_reference/troubleshooting.md
Normal file
@@ -0,0 +1,238 @@
|
||||
# 🔧 故障排除指南
|
||||
|
||||
> AI编程助手专用:常见问题的快速解决方案
|
||||
|
||||
## 🚨 常见错误及解决方案
|
||||
|
||||
### 1. UID无效警告
|
||||
|
||||
**错误信息**:
|
||||
```
|
||||
WARNING: scene/resources/resource_format_text.cpp:444 - res://path/to/file.tscn:X - ext_resource, invalid UID: uid://xxxxx - using text path instead: res://path/to/script.gd
|
||||
```
|
||||
|
||||
**原因**: 文件移动后,Godot的UID缓存没有更新,导致UID引用失效。
|
||||
|
||||
**解决方案**:
|
||||
```gdscript
|
||||
# 方法1: 移除无效的UID,使用文本路径
|
||||
# 将这行:
|
||||
[ext_resource type="Script" uid="uid://invalid_uid" path="res://path/to/script.gd" id="1_script"]
|
||||
|
||||
# 改为:
|
||||
[ext_resource type="Script" path="res://path/to/script.gd" id="1_script"]
|
||||
```
|
||||
|
||||
**预防措施**:
|
||||
- 移动文件时使用Godot编辑器的文件系统面板
|
||||
- 避免直接在文件系统中移动.gd和.tscn文件
|
||||
- 移动文件后重新导入项目
|
||||
|
||||
### 2. 脚本路径错误
|
||||
|
||||
**错误信息**:
|
||||
```
|
||||
ERROR: Failed to load script "res://old/path/Script.gd" with error "File not found".
|
||||
```
|
||||
|
||||
**解决方案**:
|
||||
```gdscript
|
||||
# 检查并更新所有.tscn文件中的脚本路径
|
||||
# 使用搜索替换功能批量更新:
|
||||
|
||||
# 旧路径 → 新路径
|
||||
"res://UI/Windows/" → "res://scenes/ui/"
|
||||
"res://Utils/" → "res://_Core/utils/"
|
||||
"res://Scenes/Maps/" → "res://scenes/maps/"
|
||||
```
|
||||
|
||||
### 3. AutoLoad路径错误
|
||||
|
||||
**错误信息**:
|
||||
```
|
||||
ERROR: Cannot load autoload: res://old/path/Manager.gd
|
||||
```
|
||||
|
||||
**解决方案**:
|
||||
```ini
|
||||
# 在 project.godot 中更新 AutoLoad 路径
|
||||
[autoload]
|
||||
GameManager="*res://_Core/managers/GameManager.gd"
|
||||
SceneManager="*res://_Core/managers/SceneManager.gd"
|
||||
EventSystem="*res://_Core/systems/EventSystem.gd"
|
||||
```
|
||||
|
||||
### 4. 资源加载失败
|
||||
|
||||
**错误信息**:
|
||||
```
|
||||
ERROR: Failed to load resource "res://old/path/resource.png".
|
||||
```
|
||||
|
||||
**解决方案**:
|
||||
```gdscript
|
||||
# 检查资源路径是否正确
|
||||
# 使用 ResourceLoader.exists() 验证路径
|
||||
func load_resource_safely(path: String):
|
||||
if not ResourceLoader.exists(path):
|
||||
push_error("Resource not found: %s" % path)
|
||||
return null
|
||||
|
||||
return load(path)
|
||||
```
|
||||
|
||||
## 🔍 调试技巧
|
||||
|
||||
### 1. 路径验证
|
||||
```gdscript
|
||||
# 验证文件是否存在
|
||||
func verify_file_exists(file_path: String) -> bool:
|
||||
return FileAccess.file_exists(file_path)
|
||||
|
||||
# 验证资源是否存在
|
||||
func verify_resource_exists(resource_path: String) -> bool:
|
||||
return ResourceLoader.exists(resource_path)
|
||||
|
||||
# 打印当前工作目录
|
||||
func print_current_directory():
|
||||
print("Current directory: ", OS.get_executable_path().get_base_dir())
|
||||
```
|
||||
|
||||
### 2. 场景加载调试
|
||||
```gdscript
|
||||
# 安全的场景加载
|
||||
func load_scene_safely(scene_path: String) -> PackedScene:
|
||||
if not ResourceLoader.exists(scene_path):
|
||||
push_error("Scene file not found: %s" % scene_path)
|
||||
return null
|
||||
|
||||
var scene = load(scene_path) as PackedScene
|
||||
if scene == null:
|
||||
push_error("Failed to load scene: %s" % scene_path)
|
||||
return null
|
||||
|
||||
return scene
|
||||
```
|
||||
|
||||
### 3. 节点引用调试
|
||||
```gdscript
|
||||
# 安全的节点获取
|
||||
func get_node_safely(node_path: String) -> Node:
|
||||
var node = get_node_or_null(node_path)
|
||||
if node == null:
|
||||
push_warning("Node not found: %s" % node_path)
|
||||
return node
|
||||
|
||||
# 检查@onready变量是否正确初始化
|
||||
func _ready():
|
||||
# 验证所有@onready节点
|
||||
if not some_button:
|
||||
push_error("some_button not found - check node path")
|
||||
if not some_label:
|
||||
push_error("some_label not found - check node path")
|
||||
```
|
||||
|
||||
## 🛠️ 项目结构问题
|
||||
|
||||
### 1. 文件移动后的检查清单
|
||||
- [ ] 更新.tscn文件中的脚本路径
|
||||
- [ ] 更新project.godot中的AutoLoad路径
|
||||
- [ ] 更新代码中的硬编码路径
|
||||
- [ ] 清理Godot缓存文件
|
||||
- [ ] 重新导入项目
|
||||
|
||||
### 2. 缓存清理命令
|
||||
```bash
|
||||
# Windows PowerShell
|
||||
Remove-Item -Recurse -Force ".godot\uid_cache.bin"
|
||||
Remove-Item -Recurse -Force ".godot\global_script_class_cache.cfg"
|
||||
|
||||
# Linux/macOS
|
||||
rm -rf .godot/uid_cache.bin
|
||||
rm -rf .godot/global_script_class_cache.cfg
|
||||
```
|
||||
|
||||
### 3. 路径常量管理
|
||||
```gdscript
|
||||
# 在 _Core/ProjectPaths.gd 中定义所有路径
|
||||
class_name ProjectPaths
|
||||
|
||||
# 核心路径
|
||||
const CORE_ROOT = "res://_Core/"
|
||||
const MANAGERS_PATH = CORE_ROOT + "managers/"
|
||||
const SYSTEMS_PATH = CORE_ROOT + "systems/"
|
||||
const UTILS_PATH = CORE_ROOT + "utils/"
|
||||
|
||||
# 场景路径
|
||||
const SCENES_ROOT = "res://scenes/"
|
||||
const UI_PATH = SCENES_ROOT + "ui/"
|
||||
const MAPS_PATH = SCENES_ROOT + "maps/"
|
||||
|
||||
# 使用示例
|
||||
var scene_path = ProjectPaths.UI_PATH + "LoginWindow.tscn"
|
||||
```
|
||||
|
||||
## 🎯 性能问题
|
||||
|
||||
### 1. 内存泄漏检测
|
||||
```gdscript
|
||||
# 监控节点数量
|
||||
func _ready():
|
||||
print("Initial node count: ", get_tree().get_node_count())
|
||||
|
||||
func _exit_tree():
|
||||
print("Final node count: ", get_tree().get_node_count())
|
||||
|
||||
# 检查未释放的资源
|
||||
func check_resource_leaks():
|
||||
print("Resource count: ", ResourceLoader.get_resource_list().size())
|
||||
```
|
||||
|
||||
### 2. 帧率监控
|
||||
```gdscript
|
||||
# 在 _Core/managers/PerformanceManager.gd
|
||||
extends Node
|
||||
|
||||
var frame_count: int = 0
|
||||
var fps_timer: float = 0.0
|
||||
|
||||
func _process(delta: float):
|
||||
frame_count += 1
|
||||
fps_timer += delta
|
||||
|
||||
if fps_timer >= 1.0:
|
||||
var fps = frame_count / fps_timer
|
||||
if fps < 30:
|
||||
push_warning("Low FPS detected: %.1f" % fps)
|
||||
|
||||
frame_count = 0
|
||||
fps_timer = 0.0
|
||||
```
|
||||
|
||||
## 🔧 开发工具问题
|
||||
|
||||
### 1. Godot编辑器崩溃
|
||||
**解决方案**:
|
||||
1. 备份项目文件
|
||||
2. 删除.godot文件夹
|
||||
3. 重新打开项目
|
||||
4. 重新导入所有资源
|
||||
|
||||
### 2. 脚本编辑器问题
|
||||
**解决方案**:
|
||||
```gdscript
|
||||
# 检查脚本语法
|
||||
# 使用 Godot 内置的语法检查器
|
||||
# 或者在命令行中运行:
|
||||
# godot --check-only script.gd
|
||||
```
|
||||
|
||||
### 3. 场景编辑器问题
|
||||
**解决方案**:
|
||||
- 检查场景文件是否损坏
|
||||
- 重新创建有问题的场景
|
||||
- 使用版本控制恢复到工作版本
|
||||
|
||||
---
|
||||
|
||||
**💡 提示**: 遇到问题时,首先检查Godot的输出面板和调试器,它们通常会提供详细的错误信息和解决建议。
|
||||
617
docs/AI_docs/templates/managers.md
Normal file
617
docs/AI_docs/templates/managers.md
Normal file
@@ -0,0 +1,617 @@
|
||||
# 🎯 管理器模板集合
|
||||
|
||||
> AI编程助手专用:各类管理器的标准化代码模板
|
||||
|
||||
## 🎮 游戏管理器模板
|
||||
|
||||
### 基础游戏管理器
|
||||
```gdscript
|
||||
# _Core/managers/GameManager.gd
|
||||
extends Node
|
||||
|
||||
## 游戏状态管理器
|
||||
## 负责管理游戏的全局状态、玩家数据和游戏流程
|
||||
|
||||
# 信号定义
|
||||
signal game_state_changed(old_state: GameState, new_state: GameState)
|
||||
signal player_data_updated(data: Dictionary)
|
||||
signal game_paused()
|
||||
signal game_resumed()
|
||||
|
||||
# 游戏状态枚举
|
||||
enum GameState {
|
||||
LOADING,
|
||||
MENU,
|
||||
PLAYING,
|
||||
PAUSED,
|
||||
GAME_OVER,
|
||||
SETTINGS
|
||||
}
|
||||
|
||||
# 常量定义
|
||||
const SAVE_FILE_PATH: String = "user://game_save.dat"
|
||||
const CONFIG_FILE_PATH: String = "res://Config/game_config.json"
|
||||
|
||||
# 导出变量
|
||||
@export var debug_mode: bool = false
|
||||
@export var auto_save_interval: float = 30.0
|
||||
|
||||
# 公共变量
|
||||
var current_state: GameState = GameState.LOADING
|
||||
var is_paused: bool = false
|
||||
var game_time: float = 0.0
|
||||
|
||||
# 玩家数据
|
||||
var player_data: Dictionary = {
|
||||
"level": 1,
|
||||
"experience": 0,
|
||||
"coins": 100,
|
||||
"health": 100,
|
||||
"max_health": 100,
|
||||
"energy": 100,
|
||||
"max_energy": 100
|
||||
}
|
||||
|
||||
# 私有变量
|
||||
var _auto_save_timer: Timer
|
||||
var _game_config: Dictionary = {}
|
||||
|
||||
func _ready() -> void:
|
||||
_initialize_manager()
|
||||
_setup_auto_save()
|
||||
_load_game_config()
|
||||
change_state(GameState.MENU)
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if current_state == GameState.PLAYING and not is_paused:
|
||||
game_time += delta
|
||||
|
||||
## 改变游戏状态
|
||||
func change_state(new_state: GameState) -> void:
|
||||
if current_state == new_state:
|
||||
return
|
||||
|
||||
var old_state = current_state
|
||||
_exit_state(old_state)
|
||||
current_state = new_state
|
||||
_enter_state(new_state)
|
||||
|
||||
game_state_changed.emit(old_state, new_state)
|
||||
|
||||
if debug_mode:
|
||||
print("[GameManager] State changed: %s -> %s" % [old_state, new_state])
|
||||
|
||||
## 暂停游戏
|
||||
func pause_game() -> void:
|
||||
if current_state != GameState.PLAYING:
|
||||
return
|
||||
|
||||
is_paused = true
|
||||
get_tree().paused = true
|
||||
game_paused.emit()
|
||||
|
||||
## 恢复游戏
|
||||
func resume_game() -> void:
|
||||
if not is_paused:
|
||||
return
|
||||
|
||||
is_paused = false
|
||||
get_tree().paused = false
|
||||
game_resumed.emit()
|
||||
|
||||
## 更新玩家数据
|
||||
func update_player_data(key: String, value) -> void:
|
||||
if not player_data.has(key):
|
||||
push_warning("Unknown player data key: %s" % key)
|
||||
return
|
||||
|
||||
player_data[key] = value
|
||||
player_data_updated.emit(player_data)
|
||||
|
||||
if debug_mode:
|
||||
print("[GameManager] Player data updated: %s = %s" % [key, value])
|
||||
|
||||
## 获取玩家数据
|
||||
func get_player_data(key: String = ""):
|
||||
if key.is_empty():
|
||||
return player_data.duplicate()
|
||||
|
||||
return player_data.get(key, null)
|
||||
|
||||
## 保存游戏数据
|
||||
func save_game() -> bool:
|
||||
var save_data = {
|
||||
"player_data": player_data,
|
||||
"game_time": game_time,
|
||||
"current_state": current_state,
|
||||
"timestamp": Time.get_unix_time_from_system()
|
||||
}
|
||||
|
||||
var file = FileAccess.open(SAVE_FILE_PATH, FileAccess.WRITE)
|
||||
if file == null:
|
||||
push_error("Failed to open save file for writing")
|
||||
return false
|
||||
|
||||
file.store_string(JSON.stringify(save_data))
|
||||
file.close()
|
||||
|
||||
if debug_mode:
|
||||
print("[GameManager] Game saved successfully")
|
||||
|
||||
return true
|
||||
|
||||
## 加载游戏数据
|
||||
func load_game() -> bool:
|
||||
if not FileAccess.file_exists(SAVE_FILE_PATH):
|
||||
if debug_mode:
|
||||
print("[GameManager] No save file found")
|
||||
return false
|
||||
|
||||
var file = FileAccess.open(SAVE_FILE_PATH, FileAccess.READ)
|
||||
if file == null:
|
||||
push_error("Failed to open save file for reading")
|
||||
return false
|
||||
|
||||
var json_text = file.get_as_text()
|
||||
file.close()
|
||||
|
||||
var json = JSON.new()
|
||||
var parse_result = json.parse(json_text)
|
||||
if parse_result != OK:
|
||||
push_error("Failed to parse save file JSON")
|
||||
return false
|
||||
|
||||
var save_data = json.data
|
||||
|
||||
# 恢复玩家数据
|
||||
if save_data.has("player_data"):
|
||||
player_data = save_data.player_data
|
||||
player_data_updated.emit(player_data)
|
||||
|
||||
# 恢复游戏时间
|
||||
if save_data.has("game_time"):
|
||||
game_time = save_data.game_time
|
||||
|
||||
if debug_mode:
|
||||
print("[GameManager] Game loaded successfully")
|
||||
|
||||
return true
|
||||
|
||||
# 私有方法
|
||||
func _initialize_manager() -> void:
|
||||
# 设置进程模式为总是处理(即使暂停时也能工作)
|
||||
process_mode = Node.PROCESS_MODE_ALWAYS
|
||||
|
||||
func _setup_auto_save() -> void:
|
||||
_auto_save_timer = Timer.new()
|
||||
add_child(_auto_save_timer)
|
||||
_auto_save_timer.wait_time = auto_save_interval
|
||||
_auto_save_timer.timeout.connect(_on_auto_save_timeout)
|
||||
_auto_save_timer.start()
|
||||
|
||||
func _load_game_config() -> void:
|
||||
if not FileAccess.file_exists(CONFIG_FILE_PATH):
|
||||
push_warning("Game config file not found")
|
||||
return
|
||||
|
||||
var file = FileAccess.open(CONFIG_FILE_PATH, FileAccess.READ)
|
||||
if file == null:
|
||||
push_error("Failed to open game config file")
|
||||
return
|
||||
|
||||
var json_text = file.get_as_text()
|
||||
file.close()
|
||||
|
||||
var json = JSON.new()
|
||||
var parse_result = json.parse(json_text)
|
||||
if parse_result != OK:
|
||||
push_error("Failed to parse game config JSON")
|
||||
return
|
||||
|
||||
_game_config = json.data
|
||||
|
||||
func _enter_state(state: GameState) -> void:
|
||||
match state:
|
||||
GameState.LOADING:
|
||||
# 加载游戏资源
|
||||
pass
|
||||
GameState.MENU:
|
||||
# 显示主菜单
|
||||
pass
|
||||
GameState.PLAYING:
|
||||
# 开始游戏逻辑
|
||||
_auto_save_timer.start()
|
||||
GameState.PAUSED:
|
||||
# 暂停游戏
|
||||
_auto_save_timer.stop()
|
||||
GameState.GAME_OVER:
|
||||
# 游戏结束处理
|
||||
save_game()
|
||||
GameState.SETTINGS:
|
||||
# 显示设置界面
|
||||
pass
|
||||
|
||||
func _exit_state(state: GameState) -> void:
|
||||
match state:
|
||||
GameState.PLAYING:
|
||||
# 退出游戏时自动保存
|
||||
save_game()
|
||||
|
||||
func _on_auto_save_timeout() -> void:
|
||||
if current_state == GameState.PLAYING:
|
||||
save_game()
|
||||
```
|
||||
|
||||
## 🌐 网络管理器模板
|
||||
|
||||
### HTTP请求管理器
|
||||
```gdscript
|
||||
# _Core/managers/NetworkManager.gd
|
||||
extends Node
|
||||
|
||||
## 网络请求管理器
|
||||
## 负责处理所有HTTP请求和网络通信
|
||||
|
||||
# 信号定义
|
||||
signal request_completed(request_id: String, success: bool, data: Dictionary)
|
||||
signal connection_status_changed(is_connected: bool)
|
||||
|
||||
# 常量定义
|
||||
const BASE_URL: String = "https://api.example.com"
|
||||
const TIMEOUT_DURATION: float = 10.0
|
||||
const MAX_RETRIES: int = 3
|
||||
|
||||
# 请求状态枚举
|
||||
enum RequestStatus {
|
||||
PENDING,
|
||||
SUCCESS,
|
||||
FAILED,
|
||||
TIMEOUT,
|
||||
CANCELLED
|
||||
}
|
||||
|
||||
# 公共变量
|
||||
var is_connected: bool = false
|
||||
var active_requests: Dictionary = {}
|
||||
|
||||
# 私有变量
|
||||
var _http_client: HTTPClient
|
||||
var _request_counter: int = 0
|
||||
|
||||
func _ready() -> void:
|
||||
_initialize_network()
|
||||
_check_connection()
|
||||
|
||||
## 发送GET请求
|
||||
func send_get_request(endpoint: String, headers: Dictionary = {}) -> String:
|
||||
return _send_request(HTTPClient.METHOD_GET, endpoint, "", headers)
|
||||
|
||||
## 发送POST请求
|
||||
func send_post_request(endpoint: String, data: Dictionary, headers: Dictionary = {}) -> String:
|
||||
var json_data = JSON.stringify(data)
|
||||
return _send_request(HTTPClient.METHOD_POST, endpoint, json_data, headers)
|
||||
|
||||
## 发送PUT请求
|
||||
func send_put_request(endpoint: String, data: Dictionary, headers: Dictionary = {}) -> String:
|
||||
var json_data = JSON.stringify(data)
|
||||
return _send_request(HTTPClient.METHOD_PUT, endpoint, json_data, headers)
|
||||
|
||||
## 发送DELETE请求
|
||||
func send_delete_request(endpoint: String, headers: Dictionary = {}) -> String:
|
||||
return _send_request(HTTPClient.METHOD_DELETE, endpoint, "", headers)
|
||||
|
||||
## 取消请求
|
||||
func cancel_request(request_id: String) -> bool:
|
||||
if not active_requests.has(request_id):
|
||||
return false
|
||||
|
||||
var request_data = active_requests[request_id]
|
||||
if request_data.http_request:
|
||||
request_data.http_request.cancel_request()
|
||||
|
||||
_cleanup_request(request_id, RequestStatus.CANCELLED)
|
||||
return true
|
||||
|
||||
## 检查网络连接状态
|
||||
func check_connection() -> void:
|
||||
_check_connection()
|
||||
|
||||
# 私有方法
|
||||
func _initialize_network() -> void:
|
||||
_http_client = HTTPClient.new()
|
||||
|
||||
func _send_request(method: HTTPClient.Method, endpoint: String, data: String, headers: Dictionary) -> String:
|
||||
var request_id = _generate_request_id()
|
||||
var full_url = BASE_URL + endpoint
|
||||
|
||||
# 创建HTTP请求节点
|
||||
var http_request = HTTPRequest.new()
|
||||
add_child(http_request)
|
||||
|
||||
# 设置请求超时
|
||||
http_request.timeout = TIMEOUT_DURATION
|
||||
|
||||
# 连接完成信号
|
||||
http_request.request_completed.connect(_on_request_completed.bind(request_id))
|
||||
|
||||
# 准备请求头
|
||||
var request_headers = ["Content-Type: application/json"]
|
||||
for key in headers:
|
||||
request_headers.append("%s: %s" % [key, headers[key]])
|
||||
|
||||
# 存储请求信息
|
||||
active_requests[request_id] = {
|
||||
"http_request": http_request,
|
||||
"method": method,
|
||||
"url": full_url,
|
||||
"status": RequestStatus.PENDING,
|
||||
"retry_count": 0,
|
||||
"start_time": Time.get_time_dict_from_system()
|
||||
}
|
||||
|
||||
# 发送请求
|
||||
var error = http_request.request(full_url, request_headers, method, data)
|
||||
if error != OK:
|
||||
push_error("Failed to send HTTP request: %d" % error)
|
||||
_cleanup_request(request_id, RequestStatus.FAILED)
|
||||
return ""
|
||||
|
||||
return request_id
|
||||
|
||||
func _generate_request_id() -> String:
|
||||
_request_counter += 1
|
||||
return "req_%d_%d" % [Time.get_time_dict_from_system().hour * 3600 + Time.get_time_dict_from_system().minute * 60 + Time.get_time_dict_from_system().second, _request_counter]
|
||||
|
||||
func _on_request_completed(request_id: String, result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) -> void:
|
||||
if not active_requests.has(request_id):
|
||||
return
|
||||
|
||||
var request_data = active_requests[request_id]
|
||||
var success = false
|
||||
var response_data = {}
|
||||
|
||||
# 解析响应
|
||||
if response_code >= 200 and response_code < 300:
|
||||
success = true
|
||||
var body_text = body.get_string_from_utf8()
|
||||
|
||||
if not body_text.is_empty():
|
||||
var json = JSON.new()
|
||||
var parse_result = json.parse(body_text)
|
||||
if parse_result == OK:
|
||||
response_data = json.data
|
||||
else:
|
||||
response_data = {"raw_response": body_text}
|
||||
else:
|
||||
# 处理错误响应
|
||||
var body_text = body.get_string_from_utf8()
|
||||
response_data = {
|
||||
"error": "HTTP Error %d" % response_code,
|
||||
"response_code": response_code,
|
||||
"raw_response": body_text
|
||||
}
|
||||
|
||||
# 发送完成信号
|
||||
request_completed.emit(request_id, success, response_data)
|
||||
|
||||
# 清理请求
|
||||
_cleanup_request(request_id, RequestStatus.SUCCESS if success else RequestStatus.FAILED)
|
||||
|
||||
func _cleanup_request(request_id: String, status: RequestStatus) -> void:
|
||||
if not active_requests.has(request_id):
|
||||
return
|
||||
|
||||
var request_data = active_requests[request_id]
|
||||
|
||||
# 移除HTTP请求节点
|
||||
if request_data.http_request:
|
||||
request_data.http_request.queue_free()
|
||||
|
||||
# 从活动请求中移除
|
||||
active_requests.erase(request_id)
|
||||
|
||||
func _check_connection() -> void:
|
||||
# 简单的连接检查(可以改为ping服务器)
|
||||
var old_status = is_connected
|
||||
is_connected = true # 这里可以实现实际的连接检查逻辑
|
||||
|
||||
if old_status != is_connected:
|
||||
connection_status_changed.emit(is_connected)
|
||||
```
|
||||
|
||||
## 🎵 音频管理器模板
|
||||
|
||||
### 音频系统管理器
|
||||
```gdscript
|
||||
# _Core/managers/AudioManager.gd
|
||||
extends Node
|
||||
|
||||
## 音频管理器
|
||||
## 负责管理游戏中的音乐和音效播放
|
||||
|
||||
# 信号定义
|
||||
signal music_finished()
|
||||
signal sound_effect_finished(sound_name: String)
|
||||
|
||||
# 音频类型枚举
|
||||
enum AudioType {
|
||||
MUSIC,
|
||||
SOUND_EFFECT,
|
||||
UI_SOUND,
|
||||
VOICE
|
||||
}
|
||||
|
||||
# 常量定义
|
||||
const MUSIC_PATH: String = "res://assets/audio/music/"
|
||||
const SOUND_PATH: String = "res://assets/audio/sounds/"
|
||||
const VOICE_PATH: String = "res://assets/audio/voice/"
|
||||
|
||||
# 导出变量
|
||||
@export var master_volume: float = 1.0
|
||||
@export var music_volume: float = 0.7
|
||||
@export var sfx_volume: float = 0.8
|
||||
@export var voice_volume: float = 0.9
|
||||
|
||||
# 音频播放器
|
||||
var music_player: AudioStreamPlayer
|
||||
var sfx_players: Array[AudioStreamPlayer] = []
|
||||
var voice_player: AudioStreamPlayer
|
||||
|
||||
# 当前播放状态
|
||||
var current_music: String = ""
|
||||
var is_music_playing: bool = false
|
||||
var active_sounds: Dictionary = {}
|
||||
|
||||
func _ready() -> void:
|
||||
_initialize_audio_players()
|
||||
_load_audio_settings()
|
||||
|
||||
## 播放背景音乐
|
||||
func play_music(music_name: String, fade_in: bool = true) -> void:
|
||||
var music_path = MUSIC_PATH + music_name + ".ogg"
|
||||
|
||||
if not ResourceLoader.exists(music_path):
|
||||
push_warning("Music file not found: %s" % music_path)
|
||||
return
|
||||
|
||||
# 停止当前音乐
|
||||
if is_music_playing:
|
||||
stop_music(fade_in)
|
||||
await get_tree().create_timer(0.5).timeout
|
||||
|
||||
# 加载并播放新音乐
|
||||
var audio_stream = load(music_path)
|
||||
music_player.stream = audio_stream
|
||||
music_player.volume_db = linear_to_db(music_volume * master_volume)
|
||||
|
||||
if fade_in:
|
||||
_fade_in_music()
|
||||
else:
|
||||
music_player.play()
|
||||
|
||||
current_music = music_name
|
||||
is_music_playing = true
|
||||
|
||||
## 停止背景音乐
|
||||
func stop_music(fade_out: bool = true) -> void:
|
||||
if not is_music_playing:
|
||||
return
|
||||
|
||||
if fade_out:
|
||||
_fade_out_music()
|
||||
else:
|
||||
music_player.stop()
|
||||
is_music_playing = false
|
||||
current_music = ""
|
||||
|
||||
## 播放音效
|
||||
func play_sound_effect(sound_name: String, volume_override: float = -1.0) -> void:
|
||||
var sound_path = SOUND_PATH + sound_name + ".ogg"
|
||||
|
||||
if not ResourceLoader.exists(sound_path):
|
||||
push_warning("Sound file not found: %s" % sound_path)
|
||||
return
|
||||
|
||||
# 获取可用的音效播放器
|
||||
var player = _get_available_sfx_player()
|
||||
if player == null:
|
||||
push_warning("No available sound effect player")
|
||||
return
|
||||
|
||||
# 加载并播放音效
|
||||
var audio_stream = load(sound_path)
|
||||
player.stream = audio_stream
|
||||
|
||||
var final_volume = volume_override if volume_override > 0 else sfx_volume
|
||||
player.volume_db = linear_to_db(final_volume * master_volume)
|
||||
|
||||
player.play()
|
||||
active_sounds[sound_name] = player
|
||||
|
||||
## 设置主音量
|
||||
func set_master_volume(volume: float) -> void:
|
||||
master_volume = clamp(volume, 0.0, 1.0)
|
||||
_update_all_volumes()
|
||||
|
||||
## 设置音乐音量
|
||||
func set_music_volume(volume: float) -> void:
|
||||
music_volume = clamp(volume, 0.0, 1.0)
|
||||
if is_music_playing:
|
||||
music_player.volume_db = linear_to_db(music_volume * master_volume)
|
||||
|
||||
## 设置音效音量
|
||||
func set_sfx_volume(volume: float) -> void:
|
||||
sfx_volume = clamp(volume, 0.0, 1.0)
|
||||
_update_sfx_volumes()
|
||||
|
||||
# 私有方法
|
||||
func _initialize_audio_players() -> void:
|
||||
# 创建音乐播放器
|
||||
music_player = AudioStreamPlayer.new()
|
||||
add_child(music_player)
|
||||
music_player.finished.connect(_on_music_finished)
|
||||
|
||||
# 创建多个音效播放器(支持同时播放多个音效)
|
||||
for i in range(8):
|
||||
var sfx_player = AudioStreamPlayer.new()
|
||||
add_child(sfx_player)
|
||||
sfx_players.append(sfx_player)
|
||||
|
||||
# 创建语音播放器
|
||||
voice_player = AudioStreamPlayer.new()
|
||||
add_child(voice_player)
|
||||
|
||||
func _get_available_sfx_player() -> AudioStreamPlayer:
|
||||
for player in sfx_players:
|
||||
if not player.playing:
|
||||
return player
|
||||
return null
|
||||
|
||||
func _fade_in_music() -> void:
|
||||
music_player.volume_db = linear_to_db(0.01)
|
||||
music_player.play()
|
||||
|
||||
var tween = create_tween()
|
||||
tween.tween_method(_set_music_volume_db, 0.01, music_volume * master_volume, 1.0)
|
||||
|
||||
func _fade_out_music() -> void:
|
||||
var tween = create_tween()
|
||||
tween.tween_method(_set_music_volume_db, music_volume * master_volume, 0.01, 1.0)
|
||||
tween.tween_callback(_stop_music_after_fade)
|
||||
|
||||
func _set_music_volume_db(volume: float) -> void:
|
||||
music_player.volume_db = linear_to_db(volume)
|
||||
|
||||
func _stop_music_after_fade() -> void:
|
||||
music_player.stop()
|
||||
is_music_playing = false
|
||||
current_music = ""
|
||||
|
||||
func _update_all_volumes() -> void:
|
||||
if is_music_playing:
|
||||
music_player.volume_db = linear_to_db(music_volume * master_volume)
|
||||
_update_sfx_volumes()
|
||||
|
||||
func _update_sfx_volumes() -> void:
|
||||
for player in sfx_players:
|
||||
if player.playing:
|
||||
player.volume_db = linear_to_db(sfx_volume * master_volume)
|
||||
|
||||
func _load_audio_settings() -> void:
|
||||
# 从配置文件加载音频设置
|
||||
pass
|
||||
|
||||
func _on_music_finished() -> void:
|
||||
is_music_playing = false
|
||||
current_music = ""
|
||||
music_finished.emit()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**🎯 使用说明**:
|
||||
1. 选择合适的管理器模板
|
||||
2. 根据具体需求修改类名和功能
|
||||
3. 确保在project.godot中配置为AutoLoad
|
||||
4. 遵循项目的命名规范和代码风格
|
||||
5. 添加必要的错误处理和日志记录
|
||||
363
docs/AI_docs/workflows/feature_development.md
Normal file
363
docs/AI_docs/workflows/feature_development.md
Normal file
@@ -0,0 +1,363 @@
|
||||
# 🚀 功能开发流程
|
||||
|
||||
> AI编程助手专用:新功能开发的标准化工作流程
|
||||
|
||||
## 🎯 开发流程概览
|
||||
|
||||
### 阶段1: 需求分析 → 阶段2: 架构设计 → 阶段3: 代码实现 → 阶段4: 测试验证 → 阶段5: 文档更新
|
||||
|
||||
---
|
||||
|
||||
## 📋 阶段1: 需求分析
|
||||
|
||||
### 1.1 理解需求
|
||||
```markdown
|
||||
**必须明确的问题:**
|
||||
- 功能的具体作用是什么?
|
||||
- 涉及哪些用户交互?
|
||||
- 需要哪些数据和状态管理?
|
||||
- 与现有功能的关系如何?
|
||||
```
|
||||
|
||||
### 1.2 需求分类
|
||||
```gdscript
|
||||
# 功能类型分类
|
||||
enum FeatureType {
|
||||
CORE_SYSTEM, # 核心系统功能 → 放在 _Core/
|
||||
GAME_SCENE, # 游戏场景功能 → 放在 scenes/
|
||||
UI_COMPONENT, # UI组件功能 → 放在 scenes/ui/
|
||||
ASSET_RELATED, # 资源相关功能 → 涉及 assets/
|
||||
CONFIG_DRIVEN # 配置驱动功能 → 涉及 Config/
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3 依赖分析
|
||||
- 需要哪些现有管理器?
|
||||
- 需要创建新的管理器吗?
|
||||
- 需要新的事件定义吗?
|
||||
- 需要新的配置文件吗?
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 阶段2: 架构设计
|
||||
|
||||
### 2.1 确定文件位置
|
||||
```gdscript
|
||||
# 根据功能类型确定文件位置
|
||||
match feature_type:
|
||||
FeatureType.CORE_SYSTEM:
|
||||
# _Core/managers/ 或 _Core/systems/
|
||||
var file_path = "_Core/managers/YourManager.gd"
|
||||
|
||||
FeatureType.GAME_SCENE:
|
||||
# scenes/maps/, scenes/characters/, scenes/effects/
|
||||
var file_path = "scenes/characters/YourCharacter.gd"
|
||||
|
||||
FeatureType.UI_COMPONENT:
|
||||
# scenes/ui/
|
||||
var file_path = "scenes/ui/YourWindow.gd"
|
||||
```
|
||||
|
||||
### 2.2 设计接口
|
||||
```gdscript
|
||||
# 定义公共接口
|
||||
class_name YourFeature
|
||||
|
||||
# 信号定义(对外通信)
|
||||
signal feature_initialized()
|
||||
signal feature_state_changed(new_state: String)
|
||||
|
||||
# 公共方法(供其他模块调用)
|
||||
func initialize(config: Dictionary) -> bool
|
||||
func get_state() -> String
|
||||
func cleanup() -> void
|
||||
```
|
||||
|
||||
### 2.3 事件设计
|
||||
```gdscript
|
||||
# 在 _Core/EventNames.gd 中添加新事件
|
||||
const YOUR_FEATURE_STARTED: String = "your_feature_started"
|
||||
const YOUR_FEATURE_COMPLETED: String = "your_feature_completed"
|
||||
const YOUR_FEATURE_ERROR: String = "your_feature_error"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💻 阶段3: 代码实现
|
||||
|
||||
### 3.1 创建基础结构
|
||||
```gdscript
|
||||
# 使用标准模板创建文件
|
||||
# 参考: docs/AI_docs/templates/components.md
|
||||
|
||||
extends Node # 或其他合适的基类
|
||||
|
||||
## [功能描述]
|
||||
## 负责[具体职责]
|
||||
|
||||
# 信号定义
|
||||
signal feature_ready()
|
||||
|
||||
# 枚举定义
|
||||
enum FeatureState {
|
||||
UNINITIALIZED,
|
||||
INITIALIZING,
|
||||
READY,
|
||||
ERROR
|
||||
}
|
||||
|
||||
# 常量定义
|
||||
const CONFIG_PATH: String = "res://Config/your_feature_config.json"
|
||||
|
||||
# 导出变量
|
||||
@export var debug_mode: bool = false
|
||||
|
||||
# 公共变量
|
||||
var current_state: FeatureState = FeatureState.UNINITIALIZED
|
||||
|
||||
# 私有变量
|
||||
var _config_data: Dictionary = {}
|
||||
|
||||
func _ready() -> void:
|
||||
initialize()
|
||||
```
|
||||
|
||||
### 3.2 实现核心逻辑
|
||||
```gdscript
|
||||
## 初始化功能
|
||||
func initialize() -> bool:
|
||||
if current_state != FeatureState.UNINITIALIZED:
|
||||
push_warning("Feature already initialized")
|
||||
return false
|
||||
|
||||
current_state = FeatureState.INITIALIZING
|
||||
|
||||
# 加载配置
|
||||
if not _load_config():
|
||||
current_state = FeatureState.ERROR
|
||||
return false
|
||||
|
||||
# 连接事件
|
||||
_connect_events()
|
||||
|
||||
# 执行初始化逻辑
|
||||
_perform_initialization()
|
||||
|
||||
current_state = FeatureState.READY
|
||||
feature_ready.emit()
|
||||
return true
|
||||
|
||||
func _load_config() -> bool:
|
||||
# 配置加载逻辑
|
||||
return true
|
||||
|
||||
func _connect_events() -> void:
|
||||
# 事件连接逻辑
|
||||
EventSystem.connect_event("related_event", _on_related_event)
|
||||
|
||||
func _perform_initialization() -> void:
|
||||
# 具体初始化逻辑
|
||||
pass
|
||||
```
|
||||
|
||||
### 3.3 错误处理
|
||||
```gdscript
|
||||
func _handle_error(error_message: String) -> void:
|
||||
push_error("[YourFeature] %s" % error_message)
|
||||
current_state = FeatureState.ERROR
|
||||
|
||||
# 发送错误事件
|
||||
EventSystem.emit_event(EventNames.YOUR_FEATURE_ERROR, {
|
||||
"message": error_message,
|
||||
"timestamp": Time.get_unix_time_from_system()
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 阶段4: 测试验证
|
||||
|
||||
### 4.1 创建测试文件
|
||||
```gdscript
|
||||
# tests/unit/test_your_feature.gd
|
||||
extends "res://addons/gut/test.gd"
|
||||
|
||||
## YourFeature 单元测试
|
||||
|
||||
var your_feature: YourFeature
|
||||
|
||||
func before_each():
|
||||
your_feature = preload("res://_Core/managers/YourFeature.gd").new()
|
||||
add_child(your_feature)
|
||||
|
||||
func after_each():
|
||||
your_feature.queue_free()
|
||||
|
||||
func test_initialization():
|
||||
# 测试初始化
|
||||
var result = your_feature.initialize()
|
||||
assert_true(result, "Feature should initialize successfully")
|
||||
assert_eq(your_feature.current_state, YourFeature.FeatureState.READY)
|
||||
|
||||
func test_error_handling():
|
||||
# 测试错误处理
|
||||
# 模拟错误条件
|
||||
pass
|
||||
```
|
||||
|
||||
### 4.2 集成测试
|
||||
```gdscript
|
||||
# tests/integration/test_your_feature_integration.gd
|
||||
extends "res://addons/gut/test.gd"
|
||||
|
||||
## YourFeature 集成测试
|
||||
|
||||
func test_feature_with_event_system():
|
||||
# 测试与事件系统的集成
|
||||
var event_received = false
|
||||
|
||||
EventSystem.connect_event("your_feature_started", func(data): event_received = true)
|
||||
|
||||
# 触发功能
|
||||
# 验证事件是否正确发送
|
||||
assert_true(event_received, "Event should be emitted")
|
||||
```
|
||||
|
||||
### 4.3 性能测试
|
||||
```gdscript
|
||||
# tests/performance/test_your_feature_performance.gd
|
||||
extends "res://addons/gut/test.gd"
|
||||
|
||||
## YourFeature 性能测试
|
||||
|
||||
func test_initialization_performance():
|
||||
var start_time = Time.get_time_dict_from_system()
|
||||
|
||||
# 执行功能
|
||||
your_feature.initialize()
|
||||
|
||||
var end_time = Time.get_time_dict_from_system()
|
||||
var duration = _calculate_duration(start_time, end_time)
|
||||
|
||||
# 验证性能要求(例如:初始化应在100ms内完成)
|
||||
assert_lt(duration, 0.1, "Initialization should complete within 100ms")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 阶段5: 文档更新
|
||||
|
||||
### 5.1 更新API文档
|
||||
```markdown
|
||||
# 在 docs/AI_docs/quick_reference/api_reference.md 中添加
|
||||
|
||||
## YourFeature API
|
||||
|
||||
### 初始化
|
||||
```gdscript
|
||||
var feature = YourFeature.new()
|
||||
feature.initialize(config_dict)
|
||||
```
|
||||
|
||||
### 主要方法
|
||||
- `initialize(config: Dictionary) -> bool` - 初始化功能
|
||||
- `get_state() -> FeatureState` - 获取当前状态
|
||||
- `cleanup() -> void` - 清理资源
|
||||
|
||||
### 事件
|
||||
- `feature_ready` - 功能准备就绪
|
||||
- `feature_state_changed(new_state)` - 状态改变
|
||||
```
|
||||
|
||||
### 5.2 更新使用示例
|
||||
```gdscript
|
||||
# 在 docs/AI_docs/quick_reference/code_snippets.md 中添加
|
||||
|
||||
## YourFeature 使用示例
|
||||
|
||||
### 基本使用
|
||||
```gdscript
|
||||
# 创建和初始化
|
||||
var feature = YourFeature.new()
|
||||
add_child(feature)
|
||||
|
||||
# 连接信号
|
||||
feature.feature_ready.connect(_on_feature_ready)
|
||||
|
||||
# 初始化
|
||||
var config = {"setting1": "value1"}
|
||||
feature.initialize(config)
|
||||
|
||||
func _on_feature_ready():
|
||||
print("Feature is ready to use")
|
||||
```
|
||||
```
|
||||
|
||||
### 5.3 更新架构文档
|
||||
```markdown
|
||||
# 在 docs/AI_docs/architecture_guide.md 中更新
|
||||
|
||||
## 新增功能: YourFeature
|
||||
|
||||
### 位置
|
||||
- 文件路径: `_Core/managers/YourFeature.gd`
|
||||
- AutoLoad: 是/否
|
||||
- 依赖: EventSystem, ConfigManager
|
||||
|
||||
### 职责
|
||||
- 负责[具体职责描述]
|
||||
- 管理[相关数据/状态]
|
||||
- 提供[对外接口]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ✅ 开发检查清单
|
||||
|
||||
### 代码质量检查
|
||||
- [ ] 遵循命名规范(PascalCase类名,snake_case变量名)
|
||||
- [ ] 所有变量和函数都有类型注解
|
||||
- [ ] 添加了适当的注释和文档字符串
|
||||
- [ ] 实现了错误处理和边界检查
|
||||
- [ ] 使用事件系统进行模块间通信
|
||||
|
||||
### 架构一致性检查
|
||||
- [ ] 文件放在正确的目录中
|
||||
- [ ] 如果是管理器,已配置AutoLoad
|
||||
- [ ] 事件名称已添加到EventNames.gd
|
||||
- [ ] 配置文件已放在Config/目录
|
||||
- [ ] 遵循项目的架构原则
|
||||
|
||||
### 测试覆盖检查
|
||||
- [ ] 编写了单元测试
|
||||
- [ ] 编写了集成测试(如果需要)
|
||||
- [ ] 编写了性能测试(如果是核心功能)
|
||||
- [ ] 所有测试都能通过
|
||||
- [ ] 测试覆盖了主要功能和边界情况
|
||||
|
||||
### 文档更新检查
|
||||
- [ ] 更新了API参考文档
|
||||
- [ ] 添加了使用示例
|
||||
- [ ] 更新了架构文档
|
||||
- [ ] 更新了相关的工作流程文档
|
||||
|
||||
---
|
||||
|
||||
## 🔄 迭代优化
|
||||
|
||||
### 代码审查要点
|
||||
1. **功能完整性**: 是否满足所有需求?
|
||||
2. **性能表现**: 是否存在性能瓶颈?
|
||||
3. **错误处理**: 是否处理了所有可能的错误情况?
|
||||
4. **代码可读性**: 代码是否清晰易懂?
|
||||
5. **测试覆盖**: 测试是否充分?
|
||||
|
||||
### 持续改进
|
||||
- 收集用户反馈
|
||||
- 监控性能指标
|
||||
- 定期重构优化
|
||||
- 更新文档和示例
|
||||
|
||||
---
|
||||
|
||||
**🎯 记住**: 这个流程确保了功能开发的质量和一致性。严格遵循每个阶段的要求,将大大提高开发效率和代码质量。
|
||||
Reference in New Issue
Block a user