GameModel.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using UnityEngine;
  6. namespace DiamondArrow
  7. {
  8. [Serializable] public struct Cell { public int x, y; public Cell(int x, int y) { this.x=x; this.y=y; } }
  9. [Serializable] public sealed class ArrowData { public Cell[] cells; }
  10. [Serializable] public sealed class LevelData { public int number, size, seconds; public ArrowData[] arrows; }
  11. [Serializable] public sealed class LevelBook
  12. {
  13. public LevelData[] levels;
  14. public static readonly string[] Chapters = { "Neon Alley", "Chrome Vault", "Cherry Circuit", "Jackpot Row", "Midnight Hall", "Diamond Crown" };
  15. [NonSerialized] LevelData generated;
  16. public string Chapter(int number) => number > levels.Length ? "Endless Vault" : Chapters[Mathf.Clamp((number - 1) / 5, 0, Chapters.Length - 1)];
  17. public LevelData GetLevel(int number)
  18. {
  19. if (number < 1) throw new ArgumentOutOfRangeException(nameof(number));
  20. if (number <= levels.Length) return levels[number - 1];
  21. if (generated == null || generated.number != number)
  22. generated = EndlessLevels.Generate(number, levels[levels.Length - 1]);
  23. return generated;
  24. }
  25. public static LevelBook Parse(string json) => JsonUtility.FromJson<LevelBook>(json.TrimStart('\uFEFF'));
  26. public List<string> Validate()
  27. {
  28. var errors = new List<string>();
  29. if (levels == null || levels.Length == 0) { errors.Add("No configured levels"); return errors; }
  30. for (int n=0;n<levels.Length;n++)
  31. {
  32. var l=levels[n]; var occupied=new HashSet<int>();
  33. if(l.number!=n+1 || l.size<5 || l.size>11 || l.seconds<=0 || l.arrows.Length==0) errors.Add("Invalid level header "+(n+1));
  34. foreach(var a in l.arrows)
  35. {
  36. if(a.cells.Length<2) { errors.Add("Short arrow "+l.number); continue; }
  37. for(int i=0;i<a.cells.Length;i++)
  38. {
  39. var c=a.cells[i];
  40. if(c.x<0 || c.y<0 || c.x>=l.size || c.y>=l.size || !occupied.Add(c.y*l.size+c.x)) errors.Add("Overlapping/outside cell "+l.number);
  41. if(i>0 && Math.Abs(c.x-a.cells[i-1].x)+Math.Abs(c.y-a.cells[i-1].y)!=1) errors.Add("Disconnected arrow "+l.number);
  42. }
  43. }
  44. var game=new GameSession(l);
  45. while(game.Status==RunStatus.Playing)
  46. {
  47. var free=game.FreeArrows();
  48. if(free.Count==0) { errors.Add("Unsolvable level "+l.number); break; }
  49. game.Tap(free[0]);
  50. }
  51. }
  52. return errors;
  53. }
  54. }
  55. public enum RunStatus { Playing, Cleared, FailedHearts, FailedTime }
  56. public enum TapResult { Ignored, Blocked, Removed, Smashed }
  57. public sealed class GameSession
  58. {
  59. public readonly LevelData Level;
  60. public readonly bool[] Alive;
  61. public int Hearts=3, Mistakes, Remaining;
  62. public float TimeLeft, Elapsed;
  63. public bool HammerArmed, RewardClaimed;
  64. public RunStatus Status=RunStatus.Playing;
  65. public GameSession(LevelData level) { Level=level; Alive=Enumerable.Repeat(true,level.arrows.Length).ToArray(); Remaining=Alive.Length; TimeLeft=level.seconds; }
  66. public int Blocker(int index)
  67. {
  68. var a=Level.arrows[index].cells; var h=a[a.Length-1]; var p=a[a.Length-2]; int dx=h.x-p.x,dy=h.y-p.y;
  69. for(int x=h.x+dx,y=h.y+dy;x>=0&&y>=0&&x<Level.size&&y<Level.size;x+=dx,y+=dy)
  70. for(int j=0;j<Alive.Length;j++) if(j!=index&&Alive[j])
  71. foreach(var c in Level.arrows[j].cells) if(c.x==x&&c.y==y) return j;
  72. return -1;
  73. }
  74. public List<int> FreeArrows() { var r=new List<int>(); for(int i=0;i<Alive.Length;i++) if(Alive[i]&&Blocker(i)<0) r.Add(i); return r; }
  75. public TapResult Tap(int index)
  76. {
  77. if(Status!=RunStatus.Playing||index<0||index>=Alive.Length||!Alive[index]) return TapResult.Ignored;
  78. bool smash=HammerArmed;
  79. if(!smash && Blocker(index)>=0) { Mistakes++; Hearts--; if(Hearts<=0) Status=RunStatus.FailedHearts; return TapResult.Blocked; }
  80. HammerArmed=false; Alive[index]=false; Remaining--; if(Remaining==0) Status=RunStatus.Cleared;
  81. return smash?TapResult.Smashed:TapResult.Removed;
  82. }
  83. public void Tick(float seconds) { if(Status!=RunStatus.Playing) return; seconds=Mathf.Max(0,seconds); Elapsed+=Mathf.Min(seconds,TimeLeft); TimeLeft=Mathf.Max(0,TimeLeft-seconds); if(TimeLeft<=0) Status=RunStatus.FailedTime; }
  84. public bool RefillHeart() { if(Status!=RunStatus.Playing||Hearts>=5) return false; Hearts++; return true; }
  85. public bool ReviveUsed { get; private set; }
  86. public bool CanRevive => !ReviveUsed && (Status == RunStatus.FailedTime || Status == RunStatus.FailedHearts);
  87. public bool Revive()
  88. {
  89. if (!CanRevive) return false;
  90. if (Status == RunStatus.FailedTime) TimeLeft = 30;
  91. Hearts++;
  92. ReviveUsed = true;
  93. Status = RunStatus.Playing;
  94. return true;
  95. }
  96. public int Stars => Mistakes==0?3:Mistakes==1?2:1;
  97. }
  98. [Serializable] public sealed class PlayerSave
  99. {
  100. public int version=1;
  101. public string name="Lucky Vega";
  102. public int avatar, gems=150, keys, earned, spotlight=1, hammer=1, heart=1;
  103. public int[] stars=new int[30];
  104. public float[] best=new float[30];
  105. public int checkinDay=1, checkinTotal;
  106. public string checkinDate="", chestDate="";
  107. public bool seen, tutorial, sfx=true, music=true, haptics;
  108. public long lastRewardedChestUnixMs;
  109. public bool hasGuestIdentity;
  110. public bool InitializeGuest(System.Random random)
  111. {
  112. if (hasGuestIdentity) return false;
  113. string[] names = { "Lucky Vega", "Nova Spark", "Ruby Ace", "Neon Iris", "Crystal Kai",
  114. "Aqua Juno", "Violet Ray", "Diamond Nyx", "Jade Sky", "Amber Star" };
  115. name = names[random.Next(names.Length)];
  116. avatar = AvatarCatalog.LegacyCount + random.Next(AvatarCatalog.NewCount);
  117. hasGuestIdentity = true;
  118. return true;
  119. }
  120. public int TotalStars => stars.Sum();
  121. public int Cleared => stars.Count(x=>x>0);
  122. public int NextLevel
  123. {
  124. get
  125. {
  126. int next = Array.IndexOf(stars, 0);
  127. return next < 0 ? stars.Length + 1 : next + 1;
  128. }
  129. }
  130. public bool Unlocked(int number) => number > 0 && number <= NextLevel;
  131. internal void EnsureLevelCapacity(int count)
  132. {
  133. if (stars == null || stars.Length < count) Array.Resize(ref stars, count);
  134. if (best == null || best.Length < count) Array.Resize(ref best, count);
  135. }
  136. public void Normalize()
  137. {
  138. int count = Math.Max(30, Math.Max(stars?.Length ?? 0, best?.Length ?? 0));
  139. EnsureLevelCapacity(count);
  140. for (int i = 0; i < count; i++)
  141. {
  142. stars[i] = Mathf.Clamp(stars[i], 0, 3);
  143. if (float.IsNaN(best[i]) || float.IsInfinity(best[i]) || best[i] < 0) best[i] = 0;
  144. }
  145. gems=Mathf.Max(0,gems); keys=Mathf.Max(0,keys); spotlight=Mathf.Max(0,spotlight); hammer=Mathf.Max(0,hammer); heart=Mathf.Max(0,heart);
  146. checkinDay=Mathf.Clamp(checkinDay,1,7); avatar=Mathf.Clamp(avatar,0,AvatarCatalog.Count-1);
  147. if(string.IsNullOrWhiteSpace(name)) name="Lucky Vega"; if(name.Length>18) name=name.Substring(0,18);
  148. }
  149. }
  150. public struct ClearReward { public int stars, basic, first, time; public bool newBest; public int Total=>basic+first+time; }
  151. public static class Economy
  152. {
  153. public static ClearReward Clear(GameSession run, PlayerSave save)
  154. {
  155. if(run.Status!=RunStatus.Cleared||run.RewardClaimed) return default;
  156. save.EnsureLevelCapacity(run.Level.number);
  157. run.RewardClaimed=true; int i=run.Level.number-1; bool first=save.stars[i]==0;
  158. var r=new ClearReward {stars=run.Stars,basic=6+run.Stars*3+Math.Min(10,run.Level.number/3),first=first?5:0,time=Mathf.Min(15,Mathf.FloorToInt(run.TimeLeft/8))};
  159. float used=Mathf.Max(.1f,Mathf.Round(run.Elapsed*10)/10); r.newBest=save.best[i]<=0||used<save.best[i];
  160. if(r.newBest) save.best[i]=used; save.stars[i]=Math.Max(save.stars[i],r.stars); save.gems+=r.Total; save.earned+=r.Total; return r;
  161. }
  162. public static readonly string[] Products={"Spotlight","Heart refill","Hammer","Power bundle"};
  163. public static readonly int[] Prices={90,120,160,320};
  164. public static bool Buy(PlayerSave s,int product)
  165. {
  166. if(product<0||product>=Prices.Length||s.gems<Prices[product]) return false;
  167. s.gems-=Prices[product];
  168. switch(product) { case 0:s.spotlight++;break; case 1:s.heart++;break; case 2:s.hammer++;break; case 3:s.spotlight++;s.heart++;s.hammer++;break; }
  169. return true;
  170. }
  171. public static readonly string[] CheckinLabels={"30 diamonds","40 diamonds","60 diamonds","1 Spotlight","80 diamonds","100 diamonds","120 diamonds + Hammer"};
  172. public static bool CheckIn(PlayerSave s,string today)
  173. {
  174. if(s.checkinDate==today) return false; int gems=0;
  175. switch(s.checkinDay) { case 1:gems=30;break;case 2:gems=40;break;case 3:gems=60;break;case 4:s.spotlight++;break;case 5:gems=80;break;case 6:gems=100;break;case 7:gems=120;s.hammer++;break; }
  176. s.gems+=gems;s.earned+=gems;s.checkinDate=today;s.checkinTotal++;s.checkinDay=s.checkinDay%7+1;return true;
  177. }
  178. public static int ChestWaitSeconds(PlayerSave save, DateTimeOffset now)
  179. {
  180. if (save.lastRewardedChestUnixMs <= 0) return 0;
  181. double elapsed = (now.ToUnixTimeMilliseconds() - save.lastRewardedChestUnixMs) / 1000d;
  182. return (int)Math.Ceiling(Math.Max(0, Math.Min(300, 300 - elapsed)));
  183. }
  184. public static bool IsFreeChest(PlayerSave save, DateTimeOffset now) =>
  185. save.chestDate != now.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
  186. public static string OpenChest(PlayerSave s, DateTimeOffset now, bool earnedAd, double roll)
  187. {
  188. if (ChestWaitSeconds(s, now) > 0 || (!earnedAd && !IsFreeChest(s, now))) return null;
  189. // A paid opening spanning midnight leaves the new day's free claim available.
  190. if (earnedAd) s.lastRewardedChestUnixMs = now.ToUnixTimeMilliseconds();
  191. else s.chestDate = now.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
  192. double[] limits={.26,.46,.58,.70,.78,.86,.96,1}; int[] gems={20,40,70,100,150,70,0,300};
  193. int index=0; while(index<7&&roll>=limits[index]) index++;
  194. s.gems+=gems[index];s.earned+=gems[index];
  195. if(index==6) { s.spotlight++;s.hammer++;return "SPOTLIGHT + HAMMER"; }
  196. return (index==7?"JACKPOT! ":"")+gems[index]+" DIAMONDS";
  197. }
  198. }
  199. public sealed class SaveStore
  200. {
  201. public readonly string Path;
  202. public string Warning { get; private set; }
  203. public SaveStore(string folder) { Path=System.IO.Path.Combine(folder,"diamond_arrow_v1.json"); }
  204. public PlayerSave Load()
  205. {
  206. foreach(var path in new[]{Path,Path+".bak"})
  207. {
  208. if(!File.Exists(path)) continue;
  209. try { var s=JsonUtility.FromJson<PlayerSave>(File.ReadAllText(path));if(s==null)throw new IOException("Empty save");s.Normalize();if(path!=Path)Warning="Recovered your backup save.";return s; }
  210. catch(Exception e) { Warning="Save could not be read: "+e.Message; }
  211. }
  212. return new PlayerSave();
  213. }
  214. public bool Save(PlayerSave s)
  215. {
  216. try { Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path));File.WriteAllText(Path+".tmp",JsonUtility.ToJson(s,true)); if(File.Exists(Path))File.Copy(Path,Path+".bak",true);File.Copy(Path+".tmp",Path,true);File.Delete(Path+".tmp");return true; }
  217. catch(Exception e) { Warning="Progress could not be saved: "+e.Message;Debug.LogWarning(Warning);return false; }
  218. }
  219. public void Reset() { foreach(var p in new[]{Path,Path+".bak",Path+".tmp"})if(File.Exists(p))File.Delete(p); }
  220. }
  221. }