| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489 |
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Text;
- using System.Text.RegularExpressions;
- using UnityEngine;
- public static class SaveService
- {
- const string FileName = "crazy_fruit_master_save.json";
- static GameSaveData data;
- static bool loaded;
- public static event Action Changed;
- public static bool SaveAvailable { get; private set; } = true;
- public static string SavePath => Path.Combine(Application.persistentDataPath, FileName);
- public static GameSaveData Data
- {
- get
- {
- EnsureLoaded();
- return data;
- }
- }
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
- static void ResetStatics()
- {
- data = null;
- loaded = false;
- SaveAvailable = true;
- Changed = null;
- }
- public static void EnsureLoaded()
- {
- if (loaded)
- return;
- loaded = true;
- data = LoadFromDisk();
- Normalize(data);
- LocaleService.EnsureInitialized();
- LocaleService.SyncFromSave(data.settings.localeId, notify: false);
- }
- static GameSaveData LoadFromDisk()
- {
- if (!File.Exists(SavePath))
- {
- var fresh = CreateDefault();
- WriteToDisk(fresh);
- return fresh;
- }
- try
- {
- string json = File.ReadAllText(SavePath, Encoding.UTF8);
- var loadedData = JsonUtility.FromJson<GameSaveData>(json);
- if (loadedData == null)
- throw new InvalidDataException("Save file did not contain a valid object.");
- SaveAvailable = true;
- return loadedData;
- }
- catch (Exception exception)
- {
- Debug.LogWarning($"[SaveService] Could not read save file: {exception.Message}");
- SaveAvailable = false;
- return CreateDefault();
- }
- }
- static GameSaveData CreateDefault()
- {
- var fresh = new GameSaveData();
- fresh.player.id = GeneratePlayerId();
- return fresh;
- }
- static void Normalize(GameSaveData value)
- {
- if (value == null)
- return;
- if (value.items == null) value.items = new SaveItemCounts();
- if (value.cleared == null) value.cleared = new SaveModeClears();
- if (value.checkin == null) value.checkin = new SaveCheckInState();
- if (value.lottery == null) value.lottery = new SaveLotteryState();
- if (value.player == null) value.player = new SavePlayerState();
- if (value.stats == null) value.stats = new SavePlayerStats();
- if (value.settings == null) value.settings = new SaveSettings();
- if (value.ads == null) value.ads = new SaveAdState();
- if (value.ledger == null) value.ledger = new List<LedgerEntry>();
- string today = TodayKey();
- if (value.ads.reviveDate != today)
- {
- value.ads.reviveDate = today;
- value.ads.reviveCount = 0;
- }
- value.coins = Mathf.Max(0, value.coins);
- value.tickets = Mathf.Max(0, value.tickets);
- value.items.hammer = Mathf.Max(0, value.items.hammer);
- value.items.moves = Mathf.Max(0, value.items.moves);
- value.items.shuffle = Mathf.Max(0, value.items.shuffle);
- value.items.key = Mathf.Max(0, value.items.key);
- value.cleared.classic = Mathf.Clamp(value.cleared.classic, 0, GameDefinitions.MaxLevel);
- value.cleared.rush = Mathf.Clamp(value.cleared.rush, 0, GameDefinitions.MaxLevel);
- value.cleared.sealedLevels = Mathf.Clamp(value.cleared.sealedLevels, 0, GameDefinitions.MaxLevel);
- value.checkin.day = Mathf.Clamp(value.checkin.day, 1, GameDefinitions.MaxCheckInDay);
- value.checkin.last = value.checkin.last ?? "";
- value.lottery.last = value.lottery.last ?? "";
- value.stats.clears = Mathf.Max(0, value.stats.clears);
- value.stats.served = Mathf.Max(0, value.stats.served);
- value.stats.best = Mathf.Max(0, value.stats.best);
- value.stats.earned = Mathf.Max(0, value.stats.earned);
- value.tut = Mathf.Max(0, value.tut);
- value.story = Mathf.Max(0, value.story);
- if (string.IsNullOrWhiteSpace(value.player.name))
- value.player.name = "LuckyPlayer";
- if (!Regex.IsMatch(value.player.id ?? "", "^CFM-[A-Z0-9]{4}$"))
- value.player.id = GeneratePlayerId();
- if (!GameDefinitions.IsSelectableAvatar(value.player.avatar))
- value.player.avatar = 1;
- bool validMode = false;
- for (int i = 0; i < GameDefinitions.Modes.Length; i++)
- {
- if (GameDefinitions.Modes[i].key == value.selectedMode)
- {
- validMode = true;
- break;
- }
- }
- if (!validMode)
- value.selectedMode = GameDefinitions.ClassicMode;
- if (value.ledger.Count > GameDefinitions.LedgerLimit)
- value.ledger.RemoveRange(GameDefinitions.LedgerLimit, value.ledger.Count - GameDefinitions.LedgerLimit);
- if (string.IsNullOrEmpty(value.settings.localeId) || !LocaleService.IsSupported(value.settings.localeId))
- value.settings.localeId = "en";
- }
- static string GeneratePlayerId()
- {
- const string alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
- var random = new System.Random(Guid.NewGuid().GetHashCode());
- var builder = new StringBuilder("CFM-");
- for (int i = 0; i < 4; i++)
- builder.Append(alphabet[random.Next(alphabet.Length)]);
- return builder.ToString();
- }
- public static string TodayKey()
- {
- return GetDayKey(DateTime.Now);
- }
- public static string GetDayKey(DateTime now)
- {
- return now.ToString("yyyy-M-d", CultureInfo.InvariantCulture);
- }
- public static void SaveNow()
- {
- EnsureLoaded();
- Normalize(data);
- WriteToDisk(data);
- Changed?.Invoke();
- }
- public static void Notify()
- {
- EnsureLoaded();
- Changed?.Invoke();
- }
- static void WriteToDisk(GameSaveData value)
- {
- try
- {
- string directory = Path.GetDirectoryName(SavePath);
- if (!string.IsNullOrEmpty(directory))
- Directory.CreateDirectory(directory);
- string json = JsonUtility.ToJson(value, true);
- string tempPath = SavePath + ".tmp";
- File.WriteAllText(tempPath, json, new UTF8Encoding(false));
- if (File.Exists(SavePath))
- File.Copy(tempPath, SavePath, true);
- else
- File.Move(tempPath, SavePath);
- if (File.Exists(tempPath))
- File.Delete(tempPath);
- SaveAvailable = true;
- }
- catch (Exception exception)
- {
- SaveAvailable = false;
- Debug.LogWarning($"[SaveService] Could not write save file: {exception.Message}");
- }
- }
- public static int PlayerLevel()
- {
- return Mathf.Max(1, Data.stats.clears / 3 + 1);
- }
- public static int TotalClears()
- {
- return Data.cleared.Total();
- }
- public static int TopAward()
- {
- return 1200 + TotalClears() * 220;
- }
- public static bool CanCheckInToday()
- {
- return Data.checkin.last != TodayKey();
- }
- public static int CheckInDay()
- {
- var save = Data;
- int day = Mathf.Clamp(save.checkin.day, 1, GameDefinitions.MaxCheckInDay);
- if (string.IsNullOrEmpty(save.checkin.last))
- return day;
- if (!DateTime.TryParseExact(save.checkin.last, "yyyy-M-d", CultureInfo.InvariantCulture,
- DateTimeStyles.None, out DateTime lastClaim))
- return day;
- int elapsedDays = (DateTime.Now.Date - lastClaim.Date).Days;
- if (elapsedDays <= 1)
- return day;
- int advancedDay = day + elapsedDays - 1;
- return ((advancedDay - 1) % GameDefinitions.MaxCheckInDay) + 1;
- }
- public static bool FreeDrawAvailable()
- {
- return Data.lottery.last != TodayKey();
- }
- public static bool CanDraw()
- {
- return FreeDrawAvailable() || Data.tickets > 0;
- }
- public static void AddCoins(int amount, string note)
- {
- if (amount <= 0)
- return;
- var save = Data;
- save.coins += amount;
- save.stats.earned += amount;
- AddLedger(save, amount, note, true);
- SaveNow();
- }
- public static bool TrySpendCoins(int amount, string note)
- {
- if (amount <= 0)
- return true;
- var save = Data;
- if (save.coins < amount)
- return false;
- save.coins -= amount;
- AddLedger(save, -amount, note, true);
- SaveNow();
- return true;
- }
- public static void AddItem(string itemKey, int amount)
- {
- if (string.IsNullOrEmpty(itemKey) || amount == 0)
- return;
- Data.items.Add(itemKey, amount);
- SaveNow();
- }
- public static bool TryPurchasePowerUp(string itemKey)
- {
- var definition = GameDefinitions.GetPowerUp(itemKey);
- if (definition == null)
- return false;
- var save = Data;
- if (save.coins < definition.price)
- return false;
- save.coins -= definition.price;
- save.items.Add(itemKey, 1);
- AddLedger(save, -definition.price, "ledger.shop|" + itemKey, true);
- SaveNow();
- return true;
- }
- public static bool CanAdReviveToday()
- {
- EnsureLoaded();
- return Data.ads.reviveCount < GameDefinitions.MaxAdRevivesPerDay;
- }
- public static void RecordAdRevive()
- {
- var save = Data;
- string today = TodayKey();
- if (save.ads.reviveDate != today)
- {
- save.ads.reviveDate = today;
- save.ads.reviveCount = 0;
- }
- save.ads.reviveCount += 1;
- if (save.ledger == null)
- save.ledger = new List<LedgerEntry>();
- save.ledger.Insert(0, new LedgerEntry
- {
- type = "in",
- note = "ledger.ad_revive|" + GameDefinitions.AdReviveMoveBonus,
- amount = 0,
- time = DateTime.Now.ToString("MMM d, hh:mm tt", CultureInfo.InvariantCulture)
- });
- if (save.ledger.Count > GameDefinitions.LedgerLimit)
- save.ledger.RemoveRange(GameDefinitions.LedgerLimit, save.ledger.Count - GameDefinitions.LedgerLimit);
- SaveNow();
- }
- public static bool ClaimCheckIn(out int claimedDay, out CheckInReward reward)
- {
- claimedDay = 0;
- reward = null;
- if (!CanCheckInToday())
- return false;
- var save = Data;
- claimedDay = CheckInDay();
- reward = GameDefinitions.CheckInRewards[claimedDay - 1];
- if (reward.coins)
- {
- save.coins += reward.amount;
- save.stats.earned += reward.amount;
- AddLedger(save, reward.amount, "ledger.checkin|" + claimedDay, true);
- }
- else
- {
- save.items.Add(reward.itemKey, reward.amount);
- }
- save.checkin.last = TodayKey();
- save.checkin.day = claimedDay >= GameDefinitions.MaxCheckInDay ? 1 : claimedDay + 1;
- SaveNow();
- return true;
- }
- public static bool ApplyDrawPrize(int prizeIndex, out DrawPrize prize)
- {
- prize = null;
- if (prizeIndex < 0 || prizeIndex >= GameDefinitions.DrawPrizes.Length)
- return false;
- if (!CanDraw())
- return false;
- var save = Data;
- prize = GameDefinitions.DrawPrizes[prizeIndex];
- if (FreeDrawAvailable())
- save.lottery.last = TodayKey();
- else
- save.tickets = Mathf.Max(0, save.tickets - 1);
- if (prize.coins)
- {
- save.coins += prize.amount;
- save.stats.earned += prize.amount;
- AddLedger(save, prize.amount, "ledger.lucky_draw", true);
- }
- else
- {
- save.items.Add(prize.itemKey, prize.amount);
- }
- SaveNow();
- return true;
- }
- public static void SetSelectedMode(string modeKey)
- {
- bool valid = false;
- for (int i = 0; i < GameDefinitions.Modes.Length; i++)
- {
- if (GameDefinitions.Modes[i].key == modeKey)
- {
- valid = true;
- break;
- }
- }
- if (!valid || Data.selectedMode == modeKey)
- return;
- Data.selectedMode = modeKey;
- SaveNow();
- }
- public static bool SetPlayerName(string rawName, out string sanitized)
- {
- sanitized = Regex.Replace((rawName ?? "").Trim(), "[^A-Za-z0-9_-]", "");
- if (sanitized.Length < 3)
- return false;
- if (sanitized.Length > 16)
- sanitized = sanitized.Substring(0, 16);
- Data.player.name = sanitized;
- SaveNow();
- return true;
- }
- public static void SetAvatar(int playerAvatar)
- {
- if (!GameDefinitions.IsSelectableAvatar(playerAvatar))
- return;
- Data.player.avatar = playerAvatar;
- SaveNow();
- }
- public static void ResetToDefaults()
- {
- EnsureLoaded();
- string localeId = string.IsNullOrEmpty(data.settings.localeId) ? "en" : data.settings.localeId;
- data = CreateDefault();
- data.settings.localeId = localeId;
- loaded = true;
- SaveNow();
- LocaleService.SyncFromSave(localeId, notify: true);
- }
- static void AddLedger(GameSaveData save, int amount, string note, bool trim)
- {
- if (save.ledger == null)
- save.ledger = new List<LedgerEntry>();
- if (amount != 0)
- {
- save.ledger.Insert(0, new LedgerEntry
- {
- type = amount > 0 ? "in" : "out",
- note = note,
- amount = amount,
- time = DateTime.Now.ToString("MMM d, hh:mm tt", CultureInfo.InvariantCulture)
- });
- }
- if (trim && save.ledger.Count > GameDefinitions.LedgerLimit)
- save.ledger.RemoveRange(GameDefinitions.LedgerLimit, save.ledger.Count - GameDefinitions.LedgerLimit);
- }
- }
|