PlayerStore.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace Olympus
  6. {
  7. [Serializable] public class LedgerEntry { public long time; public string label; public int delta, balance; }
  8. [Serializable] public class RealmProgress { public string id; public int best, firsts; }
  9. [Serializable] public class PlayerData
  10. {
  11. public int version = 3;
  12. public string name = "Rustic Lyra";
  13. public int avatar, coins = 2000;
  14. public bool profileSet, sound = true, music = true, haptics, autoReveal = true, letterPool = true;
  15. public int[] items = {1, 1, 1, 1};
  16. public List<string> found = new List<string>();
  17. public List<RealmProgress> progress = new List<RealmProgress>();
  18. public List<LedgerEntry> ledger = new List<LedgerEntry>();
  19. public string dailyKey = "", weeklyKey = "", lastCheckin = "";
  20. public int dailyScore, weeklyScore, checkinDay = 1, totalCheckins;
  21. public string lastSettledMatch = "";
  22. }
  23. public interface ISaveCodec { string Encode(PlayerData data); PlayerData Decode(string json); }
  24. public sealed class PlayerStore
  25. {
  26. public PlayerData Data { get; private set; }
  27. public string LastError { get; private set; }
  28. readonly string path;
  29. readonly ISaveCodec codec;
  30. readonly Func<DateTime> now;
  31. public PlayerStore(string path, ISaveCodec codec, Func<DateTime> clock = null)
  32. {
  33. this.path = path; this.codec = codec; now = clock ?? (() => DateTime.Now);
  34. Data = Read(path) ?? Read(path + ".bak");
  35. if (Data == null) Reset();
  36. EnsurePeriods();
  37. }
  38. PlayerData Read(string file)
  39. {
  40. try
  41. {
  42. if (!File.Exists(file)) return null;
  43. var d = codec.Decode(File.ReadAllText(file));
  44. if (d == null || d.version < 1 || d.version > 3 || d.coins < 0 || d.items == null || d.items.Length != 4 || d.items.Any(v => v < 0)
  45. || d.progress == null || d.found == null || d.ledger == null || d.checkinDay < 1 || d.checkinDay > 7) return null;
  46. d.avatar = Math.Max(0, Math.Min(9, d.avatar));
  47. // Legacy saves may hide the pool; tile selection now always requires it.
  48. d.letterPool = true;
  49. // Old v2 unfinished-trial fields are ignored; completed progress and economy survive.
  50. d.version = 3;
  51. if (string.IsNullOrWhiteSpace(d.name)) d.name = "Rustic Lyra";
  52. return d;
  53. }
  54. catch (Exception e) { LastError = e.Message; return null; }
  55. }
  56. public bool Save()
  57. {
  58. try
  59. {
  60. Directory.CreateDirectory(Path.GetDirectoryName(path));
  61. string tmp = path + ".tmp";
  62. File.WriteAllText(tmp, codec.Encode(Data));
  63. // Never replace a valid backup with a corrupt primary.
  64. if (File.Exists(path) && Read(path) != null) File.Copy(path, path + ".bak", true);
  65. if (File.Exists(path)) File.Delete(path);
  66. File.Move(tmp, path);
  67. LastError = null; return true;
  68. }
  69. catch (Exception e) { LastError = e.Message; return false; }
  70. }
  71. public void Reset()
  72. {
  73. Data = new PlayerData();
  74. Data.ledger.Add(new LedgerEntry {time = Timestamp(), label = "Starter grant", delta = 2000, balance = 2000});
  75. EnsurePeriods(); Save();
  76. // Reset also replaces the recovery snapshot so erased progress cannot return.
  77. try { if (File.Exists(path)) File.Copy(path, path + ".bak", true); } catch (IOException) { }
  78. }
  79. long Timestamp() => new DateTimeOffset(now()).ToUnixTimeMilliseconds();
  80. public string Today => now().ToString("yyyy-MM-dd");
  81. public bool CanCheckin => Data.lastCheckin != Today;
  82. public void EnsurePeriods()
  83. {
  84. var date = now().Date;
  85. string week = date.AddDays(-(((int)date.DayOfWeek + 6) % 7)).ToString("yyyy-MM-dd");
  86. if (Data.dailyKey != Today) { Data.dailyKey = Today; Data.dailyScore = 0; }
  87. if (Data.weeklyKey != week) { Data.weeklyKey = week; Data.weeklyScore = 0; }
  88. }
  89. public RealmProgress Progress(string id)
  90. {
  91. var p = Data.progress.Find(x => x.id == id);
  92. if (p == null) { p = new RealmProgress {id = id}; Data.progress.Add(p); }
  93. return p;
  94. }
  95. void ChangeCoins(int delta, string label)
  96. {
  97. Data.coins += delta;
  98. Data.ledger.Insert(0, new LedgerEntry {time = Timestamp(), label = label, delta = delta, balance = Data.coins});
  99. if (Data.ledger.Count > 200) Data.ledger.RemoveRange(200, Data.ledger.Count - 200);
  100. }
  101. public bool Enter(Realm realm)
  102. {
  103. if (Data.coins < realm.fee) return false;
  104. ChangeCoins(-realm.fee, "Entry · " + realm.name); Save(); return true;
  105. }
  106. public bool Buy(Item item, GameConfig config)
  107. {
  108. int i = (int)item, price = config.itemPrices[i];
  109. if (Data.coins < price) return false;
  110. ChangeCoins(-price, "Shop · " + Rules.ItemNames[i]); Data.items[i]++; Save(); return true;
  111. }
  112. public bool Consume(Item item)
  113. {
  114. int i = (int)item; if (Data.items[i] <= 0) return false;
  115. Data.items[i]--; Save(); return true;
  116. }
  117. public bool Claim(GameConfig config)
  118. {
  119. if (!CanCheckin) return false;
  120. int d = Data.checkinDay - 1;
  121. int coins = config.checkinCoins[d], item = config.checkinItems[d];
  122. if (coins > 0) ChangeCoins(coins, "Check-in · Day " + (d + 1));
  123. if (item >= 0) Data.items[item]++;
  124. Data.lastCheckin = Today; Data.checkinDay = (d + 1) % 7 + 1; Data.totalCheckins++; Save(); return true;
  125. }
  126. public void Found(string id) { if (!Data.found.Contains(id)) { Data.found.Add(id); Save(); } }
  127. public bool Settle(string matchId, Realm realm, int score, int rank, GameConfig config)
  128. {
  129. if (Data.lastSettledMatch == matchId) return false;
  130. EnsurePeriods(); Data.lastSettledMatch = matchId;
  131. var p = Progress(realm.id); p.best = Math.Max(p.best, score);
  132. if (score > 0 && rank == 1) p.firsts++;
  133. Data.dailyScore += score; Data.weeklyScore += score;
  134. if (score > 0 && rank <= 3) ChangeCoins(config.prizes[rank - 1], "Place " + rank + " · " + realm.name);
  135. Save(); return true;
  136. }
  137. }
  138. }