SaveService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using UnityEngine;
  8. public static class SaveService
  9. {
  10. const string FileName = "crazy_fruit_master_save.json";
  11. static GameSaveData data;
  12. static bool loaded;
  13. public static event Action Changed;
  14. public static bool SaveAvailable { get; private set; } = true;
  15. public static string SavePath => Path.Combine(Application.persistentDataPath, FileName);
  16. public static GameSaveData Data
  17. {
  18. get
  19. {
  20. EnsureLoaded();
  21. return data;
  22. }
  23. }
  24. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  25. static void ResetStatics()
  26. {
  27. data = null;
  28. loaded = false;
  29. SaveAvailable = true;
  30. Changed = null;
  31. }
  32. public static void EnsureLoaded()
  33. {
  34. if (loaded)
  35. return;
  36. loaded = true;
  37. data = LoadFromDisk();
  38. Normalize(data);
  39. LocaleService.EnsureInitialized();
  40. LocaleService.SyncFromSave(data.settings.localeId, notify: false);
  41. }
  42. static GameSaveData LoadFromDisk()
  43. {
  44. if (!File.Exists(SavePath))
  45. {
  46. var fresh = CreateDefault();
  47. WriteToDisk(fresh);
  48. return fresh;
  49. }
  50. try
  51. {
  52. string json = File.ReadAllText(SavePath, Encoding.UTF8);
  53. var loadedData = JsonUtility.FromJson<GameSaveData>(json);
  54. if (loadedData == null)
  55. throw new InvalidDataException("Save file did not contain a valid object.");
  56. SaveAvailable = true;
  57. return loadedData;
  58. }
  59. catch (Exception exception)
  60. {
  61. Debug.LogWarning($"[SaveService] Could not read save file: {exception.Message}");
  62. SaveAvailable = false;
  63. return CreateDefault();
  64. }
  65. }
  66. static GameSaveData CreateDefault()
  67. {
  68. var fresh = new GameSaveData();
  69. fresh.player.id = GeneratePlayerId();
  70. return fresh;
  71. }
  72. static void Normalize(GameSaveData value)
  73. {
  74. if (value == null)
  75. return;
  76. if (value.items == null) value.items = new SaveItemCounts();
  77. if (value.cleared == null) value.cleared = new SaveModeClears();
  78. if (value.checkin == null) value.checkin = new SaveCheckInState();
  79. if (value.lottery == null) value.lottery = new SaveLotteryState();
  80. if (value.player == null) value.player = new SavePlayerState();
  81. if (value.stats == null) value.stats = new SavePlayerStats();
  82. if (value.settings == null) value.settings = new SaveSettings();
  83. if (value.ads == null) value.ads = new SaveAdState();
  84. if (value.ledger == null) value.ledger = new List<LedgerEntry>();
  85. string today = TodayKey();
  86. if (value.ads.reviveDate != today)
  87. {
  88. value.ads.reviveDate = today;
  89. value.ads.reviveCount = 0;
  90. }
  91. value.coins = Mathf.Max(0, value.coins);
  92. value.tickets = Mathf.Max(0, value.tickets);
  93. value.items.hammer = Mathf.Max(0, value.items.hammer);
  94. value.items.moves = Mathf.Max(0, value.items.moves);
  95. value.items.shuffle = Mathf.Max(0, value.items.shuffle);
  96. value.items.key = Mathf.Max(0, value.items.key);
  97. value.cleared.classic = Mathf.Clamp(value.cleared.classic, 0, GameDefinitions.MaxLevel);
  98. value.cleared.rush = Mathf.Clamp(value.cleared.rush, 0, GameDefinitions.MaxLevel);
  99. value.cleared.sealedLevels = Mathf.Clamp(value.cleared.sealedLevels, 0, GameDefinitions.MaxLevel);
  100. value.checkin.day = Mathf.Clamp(value.checkin.day, 1, GameDefinitions.MaxCheckInDay);
  101. value.checkin.last = value.checkin.last ?? "";
  102. value.lottery.last = value.lottery.last ?? "";
  103. value.stats.clears = Mathf.Max(0, value.stats.clears);
  104. value.stats.served = Mathf.Max(0, value.stats.served);
  105. value.stats.best = Mathf.Max(0, value.stats.best);
  106. value.stats.earned = Mathf.Max(0, value.stats.earned);
  107. value.tut = Mathf.Max(0, value.tut);
  108. value.story = Mathf.Max(0, value.story);
  109. if (string.IsNullOrWhiteSpace(value.player.name))
  110. value.player.name = "LuckyPlayer";
  111. if (!Regex.IsMatch(value.player.id ?? "", "^CFM-[A-Z0-9]{4}$"))
  112. value.player.id = GeneratePlayerId();
  113. if (!GameDefinitions.IsSelectableAvatar(value.player.avatar))
  114. value.player.avatar = 1;
  115. bool validMode = false;
  116. for (int i = 0; i < GameDefinitions.Modes.Length; i++)
  117. {
  118. if (GameDefinitions.Modes[i].key == value.selectedMode)
  119. {
  120. validMode = true;
  121. break;
  122. }
  123. }
  124. if (!validMode)
  125. value.selectedMode = GameDefinitions.ClassicMode;
  126. if (value.ledger.Count > GameDefinitions.LedgerLimit)
  127. value.ledger.RemoveRange(GameDefinitions.LedgerLimit, value.ledger.Count - GameDefinitions.LedgerLimit);
  128. if (string.IsNullOrEmpty(value.settings.localeId) || !LocaleService.IsSupported(value.settings.localeId))
  129. value.settings.localeId = "en";
  130. }
  131. static string GeneratePlayerId()
  132. {
  133. const string alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  134. var random = new System.Random(Guid.NewGuid().GetHashCode());
  135. var builder = new StringBuilder("CFM-");
  136. for (int i = 0; i < 4; i++)
  137. builder.Append(alphabet[random.Next(alphabet.Length)]);
  138. return builder.ToString();
  139. }
  140. public static string TodayKey()
  141. {
  142. return GetDayKey(DateTime.Now);
  143. }
  144. public static string GetDayKey(DateTime now)
  145. {
  146. return now.ToString("yyyy-M-d", CultureInfo.InvariantCulture);
  147. }
  148. public static void SaveNow()
  149. {
  150. EnsureLoaded();
  151. Normalize(data);
  152. WriteToDisk(data);
  153. Changed?.Invoke();
  154. }
  155. public static void Notify()
  156. {
  157. EnsureLoaded();
  158. Changed?.Invoke();
  159. }
  160. static void WriteToDisk(GameSaveData value)
  161. {
  162. try
  163. {
  164. string directory = Path.GetDirectoryName(SavePath);
  165. if (!string.IsNullOrEmpty(directory))
  166. Directory.CreateDirectory(directory);
  167. string json = JsonUtility.ToJson(value, true);
  168. string tempPath = SavePath + ".tmp";
  169. File.WriteAllText(tempPath, json, new UTF8Encoding(false));
  170. if (File.Exists(SavePath))
  171. File.Copy(tempPath, SavePath, true);
  172. else
  173. File.Move(tempPath, SavePath);
  174. if (File.Exists(tempPath))
  175. File.Delete(tempPath);
  176. SaveAvailable = true;
  177. }
  178. catch (Exception exception)
  179. {
  180. SaveAvailable = false;
  181. Debug.LogWarning($"[SaveService] Could not write save file: {exception.Message}");
  182. }
  183. }
  184. public static int PlayerLevel()
  185. {
  186. return Mathf.Max(1, Data.stats.clears / 3 + 1);
  187. }
  188. public static int TotalClears()
  189. {
  190. return Data.cleared.Total();
  191. }
  192. public static int TopAward()
  193. {
  194. return 1200 + TotalClears() * 220;
  195. }
  196. public static bool CanCheckInToday()
  197. {
  198. return Data.checkin.last != TodayKey();
  199. }
  200. public static int CheckInDay()
  201. {
  202. var save = Data;
  203. int day = Mathf.Clamp(save.checkin.day, 1, GameDefinitions.MaxCheckInDay);
  204. if (string.IsNullOrEmpty(save.checkin.last))
  205. return day;
  206. if (!DateTime.TryParseExact(save.checkin.last, "yyyy-M-d", CultureInfo.InvariantCulture,
  207. DateTimeStyles.None, out DateTime lastClaim))
  208. return day;
  209. int elapsedDays = (DateTime.Now.Date - lastClaim.Date).Days;
  210. if (elapsedDays <= 1)
  211. return day;
  212. int advancedDay = day + elapsedDays - 1;
  213. return ((advancedDay - 1) % GameDefinitions.MaxCheckInDay) + 1;
  214. }
  215. public static bool FreeDrawAvailable()
  216. {
  217. return Data.lottery.last != TodayKey();
  218. }
  219. public static bool CanDraw()
  220. {
  221. return FreeDrawAvailable() || Data.tickets > 0;
  222. }
  223. public static void AddCoins(int amount, string note)
  224. {
  225. if (amount <= 0)
  226. return;
  227. var save = Data;
  228. save.coins += amount;
  229. save.stats.earned += amount;
  230. AddLedger(save, amount, note, true);
  231. SaveNow();
  232. }
  233. public static bool TrySpendCoins(int amount, string note)
  234. {
  235. if (amount <= 0)
  236. return true;
  237. var save = Data;
  238. if (save.coins < amount)
  239. return false;
  240. save.coins -= amount;
  241. AddLedger(save, -amount, note, true);
  242. SaveNow();
  243. return true;
  244. }
  245. public static void AddItem(string itemKey, int amount)
  246. {
  247. if (string.IsNullOrEmpty(itemKey) || amount == 0)
  248. return;
  249. Data.items.Add(itemKey, amount);
  250. SaveNow();
  251. }
  252. public static bool TryPurchasePowerUp(string itemKey)
  253. {
  254. var definition = GameDefinitions.GetPowerUp(itemKey);
  255. if (definition == null)
  256. return false;
  257. var save = Data;
  258. if (save.coins < definition.price)
  259. return false;
  260. save.coins -= definition.price;
  261. save.items.Add(itemKey, 1);
  262. AddLedger(save, -definition.price, "ledger.shop|" + itemKey, true);
  263. SaveNow();
  264. return true;
  265. }
  266. public static bool CanAdReviveToday()
  267. {
  268. EnsureLoaded();
  269. return Data.ads.reviveCount < GameDefinitions.MaxAdRevivesPerDay;
  270. }
  271. public static void RecordAdRevive()
  272. {
  273. var save = Data;
  274. string today = TodayKey();
  275. if (save.ads.reviveDate != today)
  276. {
  277. save.ads.reviveDate = today;
  278. save.ads.reviveCount = 0;
  279. }
  280. save.ads.reviveCount += 1;
  281. if (save.ledger == null)
  282. save.ledger = new List<LedgerEntry>();
  283. save.ledger.Insert(0, new LedgerEntry
  284. {
  285. type = "in",
  286. note = "ledger.ad_revive|" + GameDefinitions.AdReviveMoveBonus,
  287. amount = 0,
  288. time = DateTime.Now.ToString("MMM d, hh:mm tt", CultureInfo.InvariantCulture)
  289. });
  290. if (save.ledger.Count > GameDefinitions.LedgerLimit)
  291. save.ledger.RemoveRange(GameDefinitions.LedgerLimit, save.ledger.Count - GameDefinitions.LedgerLimit);
  292. SaveNow();
  293. }
  294. public static bool ClaimCheckIn(out int claimedDay, out CheckInReward reward)
  295. {
  296. claimedDay = 0;
  297. reward = null;
  298. if (!CanCheckInToday())
  299. return false;
  300. var save = Data;
  301. claimedDay = CheckInDay();
  302. reward = GameDefinitions.CheckInRewards[claimedDay - 1];
  303. if (reward.coins)
  304. {
  305. save.coins += reward.amount;
  306. save.stats.earned += reward.amount;
  307. AddLedger(save, reward.amount, "ledger.checkin|" + claimedDay, true);
  308. }
  309. else
  310. {
  311. save.items.Add(reward.itemKey, reward.amount);
  312. }
  313. save.checkin.last = TodayKey();
  314. save.checkin.day = claimedDay >= GameDefinitions.MaxCheckInDay ? 1 : claimedDay + 1;
  315. SaveNow();
  316. return true;
  317. }
  318. public static bool ApplyDrawPrize(int prizeIndex, out DrawPrize prize)
  319. {
  320. prize = null;
  321. if (prizeIndex < 0 || prizeIndex >= GameDefinitions.DrawPrizes.Length)
  322. return false;
  323. if (!CanDraw())
  324. return false;
  325. var save = Data;
  326. prize = GameDefinitions.DrawPrizes[prizeIndex];
  327. if (FreeDrawAvailable())
  328. save.lottery.last = TodayKey();
  329. else
  330. save.tickets = Mathf.Max(0, save.tickets - 1);
  331. if (prize.coins)
  332. {
  333. save.coins += prize.amount;
  334. save.stats.earned += prize.amount;
  335. AddLedger(save, prize.amount, "ledger.lucky_draw", true);
  336. }
  337. else
  338. {
  339. save.items.Add(prize.itemKey, prize.amount);
  340. }
  341. SaveNow();
  342. return true;
  343. }
  344. public static void SetSelectedMode(string modeKey)
  345. {
  346. bool valid = false;
  347. for (int i = 0; i < GameDefinitions.Modes.Length; i++)
  348. {
  349. if (GameDefinitions.Modes[i].key == modeKey)
  350. {
  351. valid = true;
  352. break;
  353. }
  354. }
  355. if (!valid || Data.selectedMode == modeKey)
  356. return;
  357. Data.selectedMode = modeKey;
  358. SaveNow();
  359. }
  360. public static bool SetPlayerName(string rawName, out string sanitized)
  361. {
  362. sanitized = Regex.Replace((rawName ?? "").Trim(), "[^A-Za-z0-9_-]", "");
  363. if (sanitized.Length < 3)
  364. return false;
  365. if (sanitized.Length > 16)
  366. sanitized = sanitized.Substring(0, 16);
  367. Data.player.name = sanitized;
  368. SaveNow();
  369. return true;
  370. }
  371. public static void SetAvatar(int playerAvatar)
  372. {
  373. if (!GameDefinitions.IsSelectableAvatar(playerAvatar))
  374. return;
  375. Data.player.avatar = playerAvatar;
  376. SaveNow();
  377. }
  378. public static void ResetToDefaults()
  379. {
  380. EnsureLoaded();
  381. string localeId = string.IsNullOrEmpty(data.settings.localeId) ? "en" : data.settings.localeId;
  382. data = CreateDefault();
  383. data.settings.localeId = localeId;
  384. loaded = true;
  385. SaveNow();
  386. LocaleService.SyncFromSave(localeId, notify: true);
  387. }
  388. static void AddLedger(GameSaveData save, int amount, string note, bool trim)
  389. {
  390. if (save.ledger == null)
  391. save.ledger = new List<LedgerEntry>();
  392. if (amount != 0)
  393. {
  394. save.ledger.Insert(0, new LedgerEntry
  395. {
  396. type = amount > 0 ? "in" : "out",
  397. note = note,
  398. amount = amount,
  399. time = DateTime.Now.ToString("MMM d, hh:mm tt", CultureInfo.InvariantCulture)
  400. });
  401. }
  402. if (trim && save.ledger.Count > GameDefinitions.LedgerLimit)
  403. save.ledger.RemoveRange(GameDefinitions.LedgerLimit, save.ledger.Count - GameDefinitions.LedgerLimit);
  404. }
  405. }