86 lines
2.1 KiB
GDScript
86 lines
2.1 KiB
GDScript
extends Node
|
|
class_name GameStateManager
|
|
## 游戏状态管理器
|
|
## 负责管理游戏的全局状态和场景切换
|
|
|
|
# 游戏状态枚举
|
|
enum GameState {
|
|
LOGIN, # 登录状态
|
|
CHARACTER_CREATION, # 角色创建状态
|
|
IN_GAME, # 游戏中
|
|
DISCONNECTED # 断线状态
|
|
}
|
|
|
|
# 信号定义
|
|
signal state_changed(old_state: GameState, new_state: GameState)
|
|
|
|
# 当前状态
|
|
var current_state: GameState = GameState.LOGIN
|
|
|
|
# 玩家数据
|
|
var player_data: Dictionary = {}
|
|
|
|
# 数据文件路径
|
|
const SAVE_PATH = "user://player_data.json"
|
|
|
|
func _ready():
|
|
print("GameStateManager initialized")
|
|
print("Initial state: ", GameState.keys()[current_state])
|
|
|
|
# 尝试加载玩家数据
|
|
load_player_data()
|
|
|
|
func change_state(new_state: GameState) -> void:
|
|
"""切换游戏状态"""
|
|
if new_state == current_state:
|
|
return
|
|
|
|
var old_state = current_state
|
|
current_state = new_state
|
|
|
|
print("State changed: ", GameState.keys()[old_state], " -> ", GameState.keys()[new_state])
|
|
state_changed.emit(old_state, new_state)
|
|
|
|
func save_player_data() -> void:
|
|
"""保存玩家数据到本地"""
|
|
var file = FileAccess.open(SAVE_PATH, FileAccess.WRITE)
|
|
if file:
|
|
var json_string = JSON.stringify(player_data)
|
|
file.store_string(json_string)
|
|
file.close()
|
|
print("Player data saved")
|
|
else:
|
|
print("Failed to save player data")
|
|
|
|
func load_player_data() -> Dictionary:
|
|
"""从本地加载玩家数据"""
|
|
if not FileAccess.file_exists(SAVE_PATH):
|
|
print("No saved player data found")
|
|
return {}
|
|
|
|
var file = FileAccess.open(SAVE_PATH, FileAccess.READ)
|
|
if file:
|
|
var json_string = file.get_as_text()
|
|
file.close()
|
|
|
|
var json = JSON.new()
|
|
var parse_result = json.parse(json_string)
|
|
|
|
if parse_result == OK:
|
|
player_data = json.data
|
|
print("Player data loaded: ", player_data.keys())
|
|
return player_data
|
|
else:
|
|
print("Failed to parse player data")
|
|
else:
|
|
print("Failed to open player data file")
|
|
|
|
return {}
|
|
|
|
func clear_player_data() -> void:
|
|
"""清除玩家数据"""
|
|
player_data.clear()
|
|
if FileAccess.file_exists(SAVE_PATH):
|
|
DirAccess.remove_absolute(SAVE_PATH)
|
|
print("Player data cleared")
|