ThreeKingdomsSlingshot/Assets/Scripts/OutGame/SaveData.cs

482 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using UnityEngine;
namespace TKS.OutGame
{
// 세이브 = 로컬 JSON 1장(기획서 §11 · Application.persistentDataPath/save.json · 버전 필드 · 변경 즉시 저장).
// §11 의 「id → 값」 맵은 JsonUtility 가 Dictionary 를 못 읽어 「id 필드를 가진 배열」로 둔다(필드 이름·뜻은 §11 그대로).
[Serializable]
public class LevelState
{
public string id;
public int lv = 1;
public int exp;
}
[Serializable]
public class HeroState : LevelState
{
public string grade = "";
[Tooltip("승급 장비 6칸(장착한 gear id · 빈 칸 = \"\")")]
public List<string> gear = new List<string>();
[Tooltip("지금까지 장착한 장비 누적 수(gear_bonus)")]
public int gearTotal;
public int star = 1;
public int shards;
public int[] skillLv = { 1, 1 };
[Tooltip("각성 줄(2026-11-20 · 열린 칸 = 승급 장비 등급 awaken_slots) — 등급 · 능력치 · 값 · 잠금")]
public List<AwakenLine> awaken = new List<AwakenLine>();
[Tooltip("착용 꾸미기(2026-11-20 외형 · 부위마다 1개 · costume_items s_id)")]
public List<string> costume = new List<string>();
}
/// <summary>각성 1줄(awaken_grades 등급 · awaken_stats 능력치 · 그 등급 범위 안 값 · 잠금).</summary>
[Serializable]
public class AwakenLine
{
public string grade = "";
public string stat = "";
public float value;
public bool locked;
}
[Serializable]
public class UnitState : LevelState
{
public int count = 1;
}
[Serializable]
public class Preset
{
[Tooltip("자리 0~2 = 전열 · 3~4 = 후열(playerSpawnPoints 순서) · 빈 칸 = \"\"")]
public List<string> slots = new List<string>();
}
[Serializable]
public class StageState
{
[Tooltip("<chapter>-<stage>")]
public string key;
public int stars;
public int clears;
}
/// <summary>출정 하드 난이도의 스테이지별 하루 도전 수(날짜가 바뀌면 통째로 새로 · 칸 = 「장-판」 · 2026-11-24).</summary>
[Serializable]
public class HardDaily
{
public string day = "";
public List<CountEntry> counts = new List<CountEntry>();
}
[Serializable]
public class CountEntry
{
public string id;
public int n;
}
[Serializable]
public class Books
{
public int exp; // 스킬서(skill)는 폐기(PD 2026-11-24 ③) — 옛 세이브의 값은 읽을 때 버려진다
}
[Serializable]
public class Inventory
{
public List<CountEntry> gear = new List<CountEntry>();
public Books books = new Books();
public int blueprint;
public int iron;
// 보물(PD #1093 C · §11 inv.chests · inv.treasures) — 상자 보유 수 · 상자 포인트(명장 상자 게이지) · 수집품
public List<CountEntry> chests = new List<CountEntry>();
public int chestPoints;
public List<TreasureState> treasures = new List<TreasureState>();
[Tooltip("새 재화(2026-11-20 goods_awaken_evolve · s_key → 수) — 각성석 · 진영 비서 16 · 등용권")]
public List<CountEntry> goods = new List<CountEntry>();
public TreasureState Treasure(string id)
{
foreach (var t in treasures)
if (t.id == id) return t;
return null;
}
public int GearCount(string id)
{
foreach (var e in gear)
if (e.id == id) return e.n;
return 0;
}
public void AddGear(string id, int n)
{
foreach (var e in gear)
{
if (e.id != id) continue;
e.n = Mathf.Max(0, e.n + n);
if (e.n == 0) gear.Remove(e);
return;
}
if (n > 0) gear.Add(new CountEntry { id = id, n = n });
}
}
[Serializable]
public class AdsUsed
{
[Tooltip("yyyyMMdd(기기 현지 날짜) · 바뀌면 일일 횟수 초기화")]
public string day = "";
public int stamina;
[Tooltip("순찰 광고 2배 수확(일)")]
public int patrol;
public int gacha;
[Tooltip("보옥 → 군량 구매 횟수(일)")]
public int gemStamina;
}
[Serializable]
public class GachaState
{
[Tooltip("구 세이브(배너 하나 시절)의 천장 카운터 — 읽을 때 상시 배너 묶음으로 옮긴다(HeroRules.Sanitize)")]
public int pity;
public int total;
public bool firstTenUsed;
[Tooltip("오늘의 무료 등용(상시 배너 · gacha daily_free) — 쓴 날(EconomyRules.DayKey)과 그날 쓴 수")]
public string freeDay = "";
public int freeUsed;
[Tooltip("천장 묶음(gacha_banners.csv pity_group)별 마지막 ★★★ 이후 등용 횟수")]
public List<CountEntry> pities = new List<CountEntry>();
public int PityOf(string group)
{
return Counts.Get(pities, group);
}
public void SetPity(string group, int n)
{
if (pities == null) pities = new List<CountEntry>();
Counts.Set(pities, group, n);
}
}
/// <summary>
/// 첫 실행 흐름(인트로 → 서장 1 ~ 3막 → 본영 · 등용 · 출정 1-1 · 군영 소개 · PD 2026-11-24) 진행 기록 — 기기 세이브 모드.
/// started = 이 세이브가 첫 실행 흐름에 들어갔는가(서장을 이미 끝낸 예전 세이브 = false 그대로 = 흐름 없음) · line = 끝낸 마지막 대사 줄 번호(표 first_flow_lines n_step).
/// </summary>
[Serializable]
public class FirstFlowState
{
public bool started;
[Tooltip("인트로(그림 3장)를 끝까지 봤거나 건너뜀 = 다시 나오지 않음")]
public bool intro;
[Tooltip("끝낸 마지막 대사 줄(0 = 아직 없음)")]
public int line;
[Tooltip("첫 실행 흐름이 끝남(마지막 대사까지)")]
public bool done;
}
[Serializable]
public class ShopItem
{
public string gearId;
public int price;
public bool sold;
}
[Serializable]
public class ShopState
{
public string day = "";
public List<ShopItem> items = new List<ShopItem>();
public int refreshes;
}
[Serializable]
public class SaveData
{
public int ver = SaveStore.Version;
[Tooltip("기기 세이브의 플레이어 고유 키(PID · GUID · 설정 팝업이 처음 열 때 만든다 · 서버 모드 = 서버 유저 번호를 대신 보여 줌 · 2026-11-25)")]
public string pid = "";
public int gold;
public int gem;
public int stamina;
[Tooltip("군량 회복 기준 시각(UTC · ISO 8601) — 오프라인 회복은 이 시각부터 계산")]
public string staminaAt = "";
public AdsUsed adsUsed = new AdsUsed();
public List<HeroState> heroes = new List<HeroState>();
public List<UnitState> units = new List<UnitState>();
public List<Preset> presets = new List<Preset>();
public int presetIdx;
public List<StageState> stages = new List<StageState>();
[Tooltip("클리어한 최고 챕터(레벨 상한 · 최소 1)")]
public int chapterMax = 1;
public Inventory inv = new Inventory();
public GachaState gacha = new GachaState();
public ShopState shop = new ShopState();
// 내정·보물·연무장(PD #1093 C · §11)
public List<TrainState> training = new List<TrainState>();
public PatrolState patrol = new PatrolState();
public DevState dev = new DevState();
[Tooltip("보물 조건 효과 카운터(cond_key → 누적)")]
public List<CountEntry> counters = new List<CountEntry>();
public ArenaState arena = new ArenaState();
public DailyC dailyC = new DailyC();
[Tooltip("보급전(컨텐츠 모드 ① · 2026-11-17) — 단계별 최고 판정 · 그날 끝낸 곳 · 주간 도장")]
public SupplyState supply = new SupplyState();
[Tooltip("맹장 토벌전(컨텐츠 모드 ③ · 2026-11-18) — 주 · 하루 횟수 · 메인/서브 피해 · 점수 · 누적 단계 · 훈장 상점")]
public RaidState raid = new RaidState();
[Tooltip("연의 전기(컨텐츠 모드 ② · 2026-11-18) — 편별 연의/열전 [승리 · 도전 1 · 도전 2] · 보유하지 않은 주역 조각")]
public ScenarioState scenario = new ScenarioState();
[Tooltip("등급 투기장(컨텐츠 모드 ④ · 2026-11-18) — 점수 · 등급 · 하루 입장 · 상대 3명")]
public LeagueState league = new LeagueState();
[Tooltip("이벤트(PD 2026-11-19) — 출석 · 7일 미션 · 행운 룰렛 진행(기기 세이브 모드만)")]
public EventState ev = new EventState();
[Tooltip("임무(2026-11-20 · 임무 메뉴) — 카운터 누적 · 일일·주간 기간 · 업적 단계")]
public MissionState mission = new MissionState();
[Tooltip("기기 우편함(2026-11-20 · 임무 초기화 때 받지 않은 구간 보상 · 기기 세이브 모드)")]
public MailState mail = new MailState();
[Tooltip("재화 상점 주간 구매 기록(메달 상점 · 임무 주간 경계 · 2026-11-24)")]
public ShopBuys shopBuys = new ShopBuys();
[Tooltip("거래 > 보물 상자 구매 기록(상품 = 상자 × 값의 재화 · 매일 갱신 전까지 1번씩 · week 칸 = 날짜 · PD 2026-11-24)")]
public ShopBuys chestBuys = new ShopBuys();
[Tooltip("받을 때 고르는 보상(탑 층 첫 클리어의 진영 비서 · 불멸 장비 — 보상 낱말 → 남은 수 · 탑 화면에서 고른다 · 2026-11-24)")]
public List<CountEntry> picks = new List<CountEntry>();
[Tooltip("출정 하드 난이도 하루 클리어 수(스테이지마다 hard_mode n_daily_per_stage 회 · 소탕 포함 · 2026-11-24) — 별 · 클리어 기록은 stages 의 「h장-판」 칸")]
public HardDaily hardDaily = new HardDaily();
[Tooltip("떠돌이 상인의 오늘 물품(영웅 조각 · 날마다 확률로 등장 · wander_shop · 2026-11-24)")]
public WanderState wander = new WanderState();
[Tooltip("공방 채굴(갱도 화면 칸 · 깊이 · 곡괭이 · 도구 · PD 2026-11-24)")]
public MineState mine = new MineState();
[Tooltip("공방 제작 대기열(PD 2026-11-24)")]
public CraftState craft = new CraftState();
[Tooltip("첫 실행 흐름 진행(인트로 · 대사 줄 · 끝 · PD 2026-11-24)")]
public FirstFlowState firstFlow = new FirstFlowState();
[Tooltip("보유 꾸미기(2026-11-20 외형 · 계정 공용 · costume_items s_id)")]
public List<string> costumes = new List<string>();
[Tooltip("새로 얻은 꾸미기 = 「외형」 버튼 빨간 점(창을 열면 끔)")]
public bool costumeNew;
public string savedAt = "";
public TrainState Train(UnitType t)
{
var key = UnitTypeInfo.Key(t);
foreach (var s in training)
if (s.type == key) return s;
var n = new TrainState { type = key };
training.Add(n);
return n;
}
public HeroState Hero(string id)
{
foreach (var h in heroes)
if (h.id == id) return h;
return null;
}
public UnitState Unit(string id)
{
foreach (var u in units)
if (u.id == id) return u;
return null;
}
/// <summary>영웅 또는 병사 유닛의 레벨 상태(미보유 = null).</summary>
public LevelState Level(string id)
{
var h = Hero(id);
if (h != null) return h;
return Unit(id);
}
public bool Owns(string id)
{
return Level(id) != null;
}
public StageState Stage(int chapter, int stage, bool create)
{
return Stage(chapter, stage, create, false);
}
/// <summary>스테이지 기록 — hard = 하드 난이도 기록(일반과 따로 · 키 앞에 h).</summary>
public StageState Stage(int chapter, int stage, bool create, bool hard)
{
string key = (hard ? HardPrefix : "") + chapter.ToString(CultureInfo.InvariantCulture) + "-" + stage.ToString(CultureInfo.InvariantCulture);
foreach (var s in stages)
if (s.key == key) return s;
if (!create) return null;
var n = new StageState { key = key };
stages.Add(n);
return n;
}
/// <summary>하드 난이도 스테이지 기록 키의 머리 글자.</summary>
public const string HardPrefix = "h";
public Preset ActivePreset
{
get { return presets.Count == 0 ? null : presets[Mathf.Clamp(presetIdx, 0, presets.Count - 1)]; }
}
}
/// <summary>세이브 읽기·쓰기. 테스트·검증 캡처는 메모리 전용(MemoryOnly)으로 실제 save.json 을 건드리지 않는다.</summary>
public static class SaveStore
{
public const int Version = 1;
public const string FileName = "save.json";
/// <summary>에디터 SessionState 키 — 검증 캡처(DataImporter.CaptureOutGame)가 Play 진입 전에 켠다(도메인 리로드 뒤에도 유지).</summary>
public const string MemoryFlagKey = "TKS_SAVE_MEMORY";
static bool memoryOnly;
static string memory;
/// <summary>세이브 파일 이름 바꾸기(null = save.json) — 서버 모드는 서버 계정의 기기 사본을 다른 파일에 써서 기존 save.json 을 덮지 않는다(Net/ServerLink).</summary>
public static string FileOverride;
/// <summary>Play 진입마다 메모리 전용 해제(도메인 리로드를 끈 설정에서도 테스트의 메모리 모드가 PD 플레이로 새지 않게).</summary>
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStatics()
{
memoryOnly = false;
memory = null;
FileOverride = null;
writeBlocked = false;
}
/// <summary>에디터 시험 메뉴 「첫 실행 흐름 — 시험 세이브로 Play」가 쓰는 파일(내 save.json 은 건드리지 않음 · 빌드에서는 쓰지 않음).</summary>
public const string FirstFlowTestFile = "save_firstflow_test.json";
public static string FilePath
{
get
{
string name = string.IsNullOrEmpty(FileOverride) ? FileName : FileOverride;
#if UNITY_EDITOR
if (string.IsNullOrEmpty(FileOverride) && TestOptions.FirstFlowSave) name = FirstFlowTestFile;
#endif
return Path.Combine(Application.persistentDataPath, name);
}
}
public static bool MemoryOnly
{
get
{
#if UNITY_EDITOR
if (UnityEditor.SessionState.GetBool(MemoryFlagKey, false)) return true;
#endif
return memoryOnly;
}
}
/// <summary>메모리 전용으로 전환(fresh = 비운 상태에서 시작 = 신규 유저).</summary>
public static void UseMemory(bool fresh)
{
memoryOnly = true;
if (fresh) memory = null;
}
/// <summary>계정 삭제 뒤 = 쓰기 막음(씬을 다시 여는 사이에 남은 화면이 Commit 해 지운 세이브가 되살아나지 않게) · 다음 Load 가 푼다.</summary>
static bool writeBlocked;
/// <summary>
/// 기기 세이브 지우기(설정 팝업 「계정 삭제」 · 게스트 = 기기 세이브 모드 · 2026-11-25) — 메모리 전용이면 메모리만 비움 · 지운 뒤 다음 Load 전까지 쓰기 막음.
/// </summary>
public static void DeleteLocal()
{
writeBlocked = true;
if (MemoryOnly)
{
memory = null;
return;
}
try
{
if (File.Exists(FilePath)) File.Delete(FilePath);
}
catch (Exception e)
{
Debug.LogError("[TKS] 세이브 삭제 실패 " + FilePath + ": " + e.Message);
}
}
public static string ReadText()
{
writeBlocked = false;
if (MemoryOnly) return memory;
try
{
return File.Exists(FilePath) ? File.ReadAllText(FilePath) : null;
}
catch (Exception e)
{
Debug.LogError("[TKS] 세이브 읽기 실패 " + FilePath + ": " + e.Message);
return null;
}
}
/// <summary>null = 없음(신규 유저) 또는 해석 실패.</summary>
public static SaveData Load()
{
var text = ReadText();
if (string.IsNullOrEmpty(text)) return null;
try
{
var d = JsonUtility.FromJson<SaveData>(text);
if (d == null) return null;
if (d.ver > Version) Debug.LogWarning("[TKS] 세이브 버전 " + d.ver + " > " + Version + " — 아는 필드만 읽음");
SupplyRules.Migrate(d); // 보급전: 옛 일일 던전 id(forge → bandit · shrine → tactics · existing_tables_patch) 기록 이전
return d;
}
catch (Exception e)
{
Debug.LogError("[TKS] 세이브 해석 실패: " + e.Message);
return null;
}
}
public static void Write(SaveData d, DateTime nowUtc)
{
if (writeBlocked) return; // 계정 삭제 뒤(DeleteLocal) — 다음 Load 까지
d.ver = Version;
d.savedAt = Iso(nowUtc);
var json = JsonUtility.ToJson(d, true);
if (MemoryOnly)
{
memory = json;
return;
}
try
{
var tmp = FilePath + ".tmp";
File.WriteAllText(tmp, json);
if (File.Exists(FilePath)) File.Delete(FilePath);
File.Move(tmp, FilePath);
}
catch (Exception e)
{
Debug.LogError("[TKS] 세이브 쓰기 실패 " + FilePath + ": " + e.Message);
}
}
public static string Iso(DateTime utc)
{
return utc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture);
}
public static DateTime ParseIso(string s, DateTime fallback)
{
DateTime t;
if (!string.IsNullOrEmpty(s) && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out t)) return t.ToUniversalTime();
return fallback;
}
}
}