class_name PlayerProgressStore extends Node ## Unico estado entre escenas: catalogo y objetos confirmados en el disco local. ## Los hallazgos del intento pertenecen a LevelRoot; nunca se guardan aqui pendientes. signal collection_changed const SAVE_VERSION: int = 1 const BONUS_PROPERTIES: Array[StringName] = [ &"special_damage_bonus", &"basic_damage_bonus", &"max_health_bonus" ] ## Edita el catalogo en game/player_progress.tscn. Un Id identifica una unica recompensa. @export var rare_items: Array[RareItemData] = [] ## Las pruebas pueden usar otra ruta antes de entrar al arbol, sin tocar el perfil real. var save_path: String = "user://player_progress.json" var last_error: String = "" var _catalog: Dictionary = {} var _owned_ids: Dictionary = {} var _save_blocked: bool = false var _primary_is_valid: bool = false func _ready() -> void: for item: RareItemData in rare_items: if item == null or item.id == &"" or _catalog.has(item.id): push_warning("Catalogo raro: recurso nulo, Id vacio o Id duplicado; entrada ignorada.") continue _catalog[item.id] = item _load_progress() func get_items() -> Array[RareItemData]: var items: Array[RareItemData] = [] for item: RareItemData in _catalog.values(): items.append(item) return items func get_item(item_id: StringName) -> RareItemData: return _catalog.get(item_id) as RareItemData func has_item(item_id: StringName) -> bool: return _owned_ids.has(item_id) ## Las bonificaciones se suman por Id, sin modificar recursos compartidos de personaje. func get_total_bonus(property: StringName) -> float: if property not in BONUS_PROPERTIES: return 0.0 var total: float = 0.0 for item: RareItemData in get_items(): if has_item(item.id): total += maxf(float(item.get(property)), 0.0) return total ## Confirma todas las recompensas de una meta, o ninguna si falla la escritura. ## Repetir un nivel o encontrar duplicados nunca vuelve a sumar el mismo objeto. func unlock_items(item_ids: Array[StringName]) -> Error: var candidate: Dictionary = _owned_ids.duplicate() for item_id: StringName in item_ids: if not _catalog.has(item_id): last_error = "Objeto no registrado en el catalogo: " + String(item_id) return ERR_INVALID_PARAMETER candidate[item_id] = true if candidate == _owned_ids: return OK if _save_blocked: return ERR_FILE_CORRUPT var error: Error = _write_progress(candidate) if error != OK: return error _owned_ids = candidate last_error = "" collection_changed.emit() return OK ## JSON plano: solo version e identificadores. Nunca deserializa objetos ejecutables. ## Los Id desconocidos se conservan por compatibilidad, pero no aportan atributos. func _read_progress(path: String) -> Dictionary: var file: FileAccess = FileAccess.open(path, FileAccess.READ) if file == null: return {"error": "No se pudo leer " + path + ": " + error_string(FileAccess.get_open_error())} if file.get_length() > 1048576: file.close() return {"error": "El guardado supera el tamano admitido."} var content: String = file.get_as_text() file.close() var json := JSON.new() if json.parse(content) != OK or not json.data is Dictionary: return {"error": "El guardado no contiene un JSON valido."} var data: Dictionary = json.data var version: Variant = data.get("version") if not (version is int or version is float): return {"error": "Version de guardado no valida."} if version != SAVE_VERSION: # No sobrescribir con un formato viejo un perfil de una version futura. return {"error": "Version de guardado no compatible.", "unsupported": true} var ids: Variant = data.get("rare_items") if not ids is Array: return {"error": "Lista de objetos no valida."} var owned: Dictionary = {} for item_id: Variant in ids: if not item_id is String or String(item_id).is_empty(): return {"error": "El guardado contiene un identificador no valido."} owned[StringName(item_id)] = true return {"owned": owned} func _load_progress() -> void: var backup_path: String = save_path + ".bak" if not FileAccess.file_exists(save_path) and not FileAccess.file_exists(backup_path): return var result: Dictionary = {"error": "Falta el archivo principal."} if FileAccess.file_exists(save_path): result = _read_progress(save_path) if result.has("owned"): _owned_ids = result["owned"] _primary_is_valid = true return if not result.get("unsupported", false) and FileAccess.file_exists(backup_path): var backup: Dictionary = _read_progress(backup_path) if backup.has("owned"): _owned_ids = backup["owned"] last_error = "Se ha recuperado la coleccion desde la copia de seguridad." return _save_blocked = true last_error = String(result.get("error", "Guardado no valido.")) + " Se conserva el archivo; revisalo antes de guardar de nuevo." push_warning(last_error) ## Escribe primero un temporal, conserva la version anterior y sustituye al final. ## Nunca borra el principal antes del renombrado; un fallo deja el estado en memoria intacto. func _write_progress(owned: Dictionary) -> Error: var ids: Array[String] = [] for item_id: StringName in owned: ids.append(String(item_id)) ids.sort() var temporary_path: String = save_path + ".tmp" var file: FileAccess = FileAccess.open(temporary_path, FileAccess.WRITE) if file == null: return _save_error(FileAccess.get_open_error()) file.store_string(JSON.stringify({"version": SAVE_VERSION, "rare_items": ids}, "\t")) file.flush() var write_error: Error = file.get_error() file.close() if write_error != OK: return _save_error(write_error) if _primary_is_valid and FileAccess.file_exists(save_path): var backup_error: Error = DirAccess.copy_absolute( ProjectSettings.globalize_path(save_path), ProjectSettings.globalize_path(save_path + ".bak")) if backup_error != OK: return _save_error(backup_error) var rename_error: Error = DirAccess.rename_absolute( ProjectSettings.globalize_path(temporary_path), ProjectSettings.globalize_path(save_path)) if rename_error != OK: return _save_error(rename_error) _primary_is_valid = true return OK func _save_error(error: Error) -> Error: last_error = "No se pudo guardar la coleccion: " + error_string(error) push_warning(last_error) return error