GameHUD.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using GameAudio = DevilLink2.Presentation.AudioManager;
  2. using System;
  3. using System.Globalization;
  4. using System.Collections.Generic;
  5. using DevilLink2.Core;
  6. using DevilLink2.Gameplay;
  7. using DevilLink2.Interaction;
  8. using DevilLink2.Presentation;
  9. using UnityEngine;
  10. using UnityEngine.UI;
  11. namespace DevilLink2.UI
  12. {
  13. [ExecuteAlways]
  14. public sealed class GameHUD : MonoBehaviour
  15. {
  16. private GameFlowController flow;
  17. private GameSessionRuntime runtime;
  18. private BoardView view;
  19. private BoardInteractionController controller;
  20. private Action unbindFlow, unbindRuntime;
  21. private IMonotonicClock visualClock = new StopwatchClock();
  22. private Board hintBoard;
  23. private int firstHint, secondHint;
  24. private double hintUntil;
  25. private readonly ScoreFeedbackVisuals visuals = new ScoreFeedbackVisuals();
  26. private readonly HashSet<int> visualizedTiles = new HashSet<int>();
  27. private long observedScore, lastMatchScore;
  28. private int observedCombo, observedPairs, pendingPoints;
  29. public ScoreFeedbackVisuals Visuals => visuals;
  30. public Text ModeLabel { get; private set; }
  31. public Text TimerLabel { get; private set; }
  32. public Text ScoreLabel { get; private set; }
  33. public Text ComboLabel { get; private set; }
  34. public Text ComboStateLabel { get; private set; }
  35. public Text PairsLabel { get; private set; }
  36. public Text FeedbackLabel { get; private set; }
  37. public Image TimeFill { get; private set; }
  38. public Image ComboFill { get; private set; }
  39. public Button PauseButton { get; private set; }
  40. public Button[] ItemButtons { get; private set; }
  41. public PauseScreen Pause { get; private set; }
  42. public ResultScreen Result { get; private set; }
  43. public bool IsLowTime { get; private set; }
  44. public float TimeFraction { get; private set; }
  45. public Guid BoundSessionId => runtime?.Session.Id ?? Guid.Empty;
  46. public void Configure(BoardView board, Text mode, Text timer, Text score, Text combo, Text comboState, Text pairs, Text feedback,
  47. Image timeFill, Image comboFill, Button pauseButton, Button[] items, PauseScreen pause, ResultScreen result)
  48. {
  49. view = board; ModeLabel = mode; TimerLabel = timer; ScoreLabel = score; ComboLabel = combo; ComboStateLabel = comboState;
  50. PairsLabel = pairs; FeedbackLabel = feedback; TimeFill = timeFill; ComboFill = comboFill; PauseButton = pauseButton;
  51. ItemButtons = items; Pause = pause; Result = result;
  52. PauseButton.onClick.AddListener(RequestPause); Pause.ResumeButton.onClick.AddListener(Resume);
  53. Pause.RestartButton.onClick.AddListener(Restart); Pause.LobbyButton.onClick.AddListener(Lobby);
  54. adReviveButton=UIBuilder.Button("WatchAdRevive",Result.NextButton.transform.parent,"WATCH AD TO REVIVE · +30s",16,226,364,44,UIBuilder.Hex("382044"),UIBuilder.Hex("21122F"),12);
  55. adReviveButton.transition=Selectable.Transition.None;adReviveButton.GetComponentInChildren<Text>().color=UIBuilder.LightGold;
  56. adReviveButton.onClick.AddListener(WatchReviveAd);adReviveButton.gameObject.SetActive(false);
  57. Result.NextButton.onClick.AddListener(Next); Result.RetryButton.onClick.AddListener(Retry); Result.LobbyButton.onClick.AddListener(Lobby);
  58. items[0].onClick.AddListener(UseHint); items[1].onClick.AddListener(UseShuffle); items[2].onClick.AddListener(UseTime);
  59. }
  60. public void SetVisualClock(IMonotonicClock clock) { ClearHint(); visualClock = clock ?? throw new ArgumentNullException(nameof(clock)); }
  61. public void Bind(GameFlowController source, BoardInteractionController interaction)
  62. {
  63. if (ReferenceEquals(flow, source) && controller == interaction) { Refresh(); return; }
  64. Unbind(); flow = source ?? throw new ArgumentNullException(nameof(source)); controller = interaction;
  65. Action<GameSessionRuntime> session = current => { if (ReferenceEquals(flow, source) && ReferenceEquals(source.Runtime, current)) BindRuntime(current); };
  66. Action<GameFlowState, GameFlowState> state = (a, b) => { if (ReferenceEquals(flow, source)) HandleState(); };
  67. Action<GameResult> settled = result => { if (ReferenceEquals(flow, source)) ShowResult(result); };
  68. Action<HintInfo> hint = info => { if (ReferenceEquals(flow, source)) ShowHint(info); };
  69. source.SessionChanged += session; source.StateChanged += state; source.Settled += settled;
  70. if (interaction) interaction.HintRequested += hint;
  71. unbindFlow = () => { source.SessionChanged -= session; source.StateChanged -= state; source.Settled -= settled; if (interaction) interaction.HintRequested -= hint; };
  72. BindRuntime(source.Runtime); HandleState();
  73. if (source.Result != null) ShowResult(source.Result);
  74. }
  75. private void BindRuntime(GameSessionRuntime current)
  76. {
  77. visuals.Clear(); visualizedTiles.Clear(); pendingPoints = 0;
  78. observedScore = lastMatchScore = current.Score.TotalScore;
  79. observedCombo = current.Score.ComboCount; observedPairs = current.Session.Board.RemainingTileCount / 2;
  80. ClearHint(); unbindRuntime?.Invoke(); runtime = current; Result.Clear(); Pause.SetVisible(false); FeedbackLabel.text = "";
  81. Action<double> time = _ => { if (ReferenceEquals(runtime, current)) Refresh(); };
  82. Action<int> score = points => {
  83. if (!ReferenceEquals(runtime, current)) return;
  84. if (current.Score.TotalScore > lastMatchScore) { lastMatchScore = current.Score.TotalScore; pendingPoints = points; if(current.Score.ComboCount>1 && flow.State==GameFlowState.Running)GameAudio.Sound(AudioCue.Combo_Up,"combo:"+current.Session.Id+":"+current.Score.TotalScore); }
  85. Refresh();
  86. };
  87. Action<int> bonus = _ => { if (ReferenceEquals(runtime, current)) Refresh(); };
  88. Action<PairMatch> matched = pair => { if (ReferenceEquals(runtime, current)) { if(flow.State==GameFlowState.Running || flow.State==GameFlowState.Victory)GameAudio.Sound(AudioCue.Tile_Match,"match:"+current.Session.Id+":"+Math.Min(pair.First.Id,pair.Second.Id)); ClearHint(); ShowMatchPoints(pair); } };
  89. Action<BoardShuffleResult> shuffled = _ => { if (ReferenceEquals(runtime, current)) { visuals.Clear(); pendingPoints = 0; ClearHint(); } };
  90. Action<Tile> selected=tile=>{if(ReferenceEquals(runtime,current) && tile!=null && flow.State==GameFlowState.Running)GameAudio.Sound(AudioCue.Tile_Select);};
  91. Action<Tile,Tile> invalid=(a,b)=>{if(ReferenceEquals(runtime,current) && (flow.State==GameFlowState.Running || flow.State==GameFlowState.Defeat))GameAudio.Sound(AudioCue.Tile_Invalid);};
  92. current.Interaction.SelectionChanged+=selected;current.Interaction.InvalidMatch+=invalid;
  93. current.Timer.RemainingTimeChanged += time; current.Score.MatchScored += score; current.Score.ClearBonusAwarded += bonus;
  94. current.Interaction.Matched += matched; current.Interaction.Reshuffled += shuffled;
  95. unbindRuntime = () => { current.Interaction.SelectionChanged-=selected;current.Interaction.InvalidMatch-=invalid; current.Timer.RemainingTimeChanged -= time; current.Score.MatchScored -= score; current.Score.ClearBonusAwarded -= bonus;
  96. current.Interaction.Matched -= matched; current.Interaction.Reshuffled -= shuffled; };
  97. Refresh();
  98. }
  99. private Button adReviveButton;
  100. private static Type Ads => Type.GetType("DevilLink2.Ads.AdManager, DevilLink2.AdMob");
  101. private void WatchReviveAd()
  102. {
  103. var source=flow;if(source==null || !source.CanAdRevive)return;var sessionId=source.Runtime.Session.Id;
  104. Action<Guid> earned=id=>{if(this && ReferenceEquals(flow,source))source.TryAdRevive(sessionId);};
  105. Action<string> finished=message=>{if(this && ReferenceEquals(flow,source) && message!=null)FeedbackLabel.text=message;};
  106. bool started=Ads!=null && (bool)Ads.GetMethod("TryShow").Invoke(null,new object[]{"Revive",earned,finished});
  107. if(!started)FeedbackLabel.text=Ads==null?"ADS UNAVAILABLE":(string)Ads.GetMethod("Status").Invoke(null,null);
  108. }
  109. private void HandleState()
  110. {
  111. if (flow == null) return;
  112. if(GameAudio.Instance && flow.State==GameFlowState.Running)GameAudio.Instance.SetMusic(MusicTrack.Gameplay);
  113. if (flow.State == GameFlowState.Paused) { ClearFeedbackVisuals(); Pause.Show(); }
  114. else Pause.SetVisible(false);
  115. if (flow.State == GameFlowState.Ready || flow.State == GameFlowState.Abandoned || flow.State == GameFlowState.Running && Result.Data != null) { ClearFeedbackVisuals(); Result.Clear(); }
  116. Refresh();
  117. }
  118. private void ShowResult(GameResult result)
  119. {
  120. if (flow == null || runtime == null || result == null || (flow.State!=GameFlowState.Victory && flow.State!=GameFlowState.Defeat) || result.SessionId != runtime.Session.Id || !ReferenceEquals(flow.Result, result)) return;
  121. if (Result.Data?.SessionId == result.SessionId) return;
  122. GameAudio.Sound(result.Outcome==GameOutcome.Victory?AudioCue.Victory:AudioCue.Defeat,"result:"+result.SessionId);
  123. if(result.Outcome==GameOutcome.Victory)GameAudio.Sound(AudioCue.Coin_Reward,"coin:"+result.SessionId);
  124. ClearFeedbackVisuals(); Pause.SetVisible(false); Result.Present(result); Refresh();
  125. }
  126. private void LateUpdate() { Refresh(); if (Application.isPlaying) visuals.Advance(Time.unscaledDeltaTime); }
  127. public void Refresh()
  128. {
  129. if (!this || flow == null || runtime == null) return;
  130. if(adReviveButton){
  131. adReviveButton.gameObject.SetActive(Ads!=null && flow.CanAdRevive);
  132. // PopupLayout owns the measured footer slot, including hidden Next/Revive states.
  133. adReviveButton.GetComponentInChildren<Text>().text=Ads!=null && (bool)Ads.GetMethod("Ready").Invoke(null,null)?"WATCH AD TO REVIVE · +30s":Ads==null?"ADS UNAVAILABLE":(string)Ads.GetMethod("Status").Invoke(null,null);
  134. }
  135. if (hintBoard != null && visualClock.Seconds >= hintUntil) ClearHint();
  136. var timer = runtime.Timer; var score = runtime.Score; var level = runtime.Session.Definition;
  137. ModeLabel.text = UIManager.ModeName(level.Mode) + "\nLEVEL " + level.Level + " / 20";
  138. TimerLabel.text = HudFormatting.Time(timer.HasTimer, timer.RemainingTime);
  139. IsLowTime = timer.IsLowTime; TimerLabel.color = IsLowTime ? UIBuilder.Hex("FF8EA0") : UIBuilder.LightGold;
  140. TimeFraction = timer.HasTimer && timer.TimeBarMax > 0 ? Mathf.Clamp01((float)(timer.RemainingTime / timer.TimeBarMax)) : 1;
  141. SetFraction(TimeFill, TimeFraction); TimeFill.color = IsLowTime ? UIBuilder.Hex("FF4D6A") : Accent(level.Mode);
  142. int comboCount = score.ComboCount, multiplier = score.CurrentMultiplier;
  143. int pairs = runtime.Session.Board.RemainingTileCount / 2;
  144. if (score.TotalScore != observedScore) { observedScore = score.TotalScore; visuals.Emphasize(ScoreLabel); }
  145. if (pairs != observedPairs) { if (pairs < observedPairs) visuals.Emphasize(PairsLabel, .035f); observedPairs = pairs; }
  146. if (comboCount != observedCombo)
  147. {
  148. if (comboCount > observedCombo) visuals.Emphasize(ComboLabel, .04f + .008f * Mathf.Min(5, multiplier));
  149. else if (comboCount == 0) visuals.ResetPulse(ComboLabel);
  150. observedCombo = comboCount;
  151. }
  152. ComboLabel.color = score.IsInCombo ? Color.Lerp(UIBuilder.Gold, UIBuilder.LightGold, Mathf.Clamp01(multiplier / 5f)) : UIBuilder.LightGold;
  153. ScoreLabel.text = "SCORE " + score.TotalScore.ToString("N0", CultureInfo.InvariantCulture);
  154. ComboLabel.text = "COMBO ×" + Math.Max(1, score.CurrentMultiplier);
  155. ComboStateLabel.text = score.IsInCombo ? "COMBO ACTIVE" : "READY";
  156. ComboStateLabel.color = score.IsInCombo ? UIBuilder.Hex("34E0FF") : UIBuilder.Muted;
  157. SetFraction(ComboFill, (float)(score.ComboRemainingTime / SessionScore.ComboWindowSeconds));
  158. PairsLabel.text = "PAIRS LEFT " + runtime.Session.Board.RemainingTileCount / 2;
  159. bool available = flow.State == GameFlowState.Running && !runtime.IsFinished && !runtime.Interaction.IsLocked;
  160. PauseButton.interactable = flow.State == GameFlowState.Running;
  161. for (int i = 0; i < ItemButtons.Length; i++)
  162. {
  163. int count = flow.Economy.Inventory.GetCount((ItemType)i);
  164. ItemButtons[i].GetComponentInChildren<Text>(true).text = (i == 0 ? "HINT" : i == 1 ? "SHUFFLE" : "+30 SECONDS") + "\n" + count;
  165. ItemButtons[i].interactable = available && count > 0 && (i != 2 || timer.HasTimer);
  166. }
  167. }
  168. public static Color Accent(GameMode mode) => mode == GameMode.Classic ? UIBuilder.Gold : mode == GameMode.TimeAttack ? UIBuilder.Hex("FF2E9A") : UIBuilder.Hex("34E0FF");
  169. private static void SetFraction(Image image, float fraction)
  170. { var r = image.rectTransform; r.anchorMax = new Vector2(Mathf.Clamp01(fraction), 1); }
  171. public ItemUseResult TryUse(ItemType type)
  172. {
  173. if (flow == null) return new ItemUseResult(ItemUseStatus.GameNotRunning);
  174. var result = type == ItemType.Hint ? flow.Items.TryUseHint() : type == ItemType.Shuffle ? flow.Items.TryUseShuffle() : flow.Items.TryUseTime();
  175. FeedbackLabel.text = result.Succeeded ? type == ItemType.Hint ? "CONNECT THE HIGHLIGHTED PAIR" : type == ItemType.Shuffle ? "BOARD SHUFFLED" : "+30 SECONDS" :
  176. result.Status == ItemUseStatus.InsufficientInventory ? "NO ITEMS AVAILABLE" : result.Status == ItemUseStatus.UnsupportedMode ? "ZEN HAS NO TIMER" :
  177. result.Status == ItemUseStatus.InteractionLocked ? "WAIT FOR TILES TO SETTLE" : result.Status == ItemUseStatus.NoAvailablePair ? "NO AVAILABLE PAIR" : "ITEM UNAVAILABLE";
  178. Refresh(); return result;
  179. }
  180. private void ShowHint(HintInfo hint)
  181. {
  182. if (runtime == null || flow.State != GameFlowState.Running || hint.SessionId != runtime.Session.Id) return;
  183. ClearHint(); hintBoard = runtime.Session.Board; firstHint = hint.FirstId; secondHint = hint.SecondId;
  184. hintUntil = visualClock.Seconds + HintInfo.DurationSeconds;
  185. view.FindTile(firstHint)?.SetHinted(true); view.FindTile(secondHint)?.SetHinted(true);
  186. }
  187. private void ClearHint()
  188. {
  189. if (hintBoard != null && view && ReferenceEquals(view.Data, hintBoard))
  190. { view.FindTile(firstHint)?.SetHinted(false); view.FindTile(secondHint)?.SetHinted(false); }
  191. hintBoard = null;
  192. }
  193. private void ShowMatchPoints(PairMatch pair)
  194. {
  195. if (pendingPoints <= 0 || flow == null || flow.State != GameFlowState.Running || !view || !view.BoardRoot ||
  196. !ReferenceEquals(view.Data, runtime.Session.Board) || visualizedTiles.Contains(pair.First.Id) || visualizedTiles.Contains(pair.Second.Id)) return;
  197. visualizedTiles.Add(pair.First.Id); visualizedTiles.Add(pair.Second.Id);
  198. int points = pendingPoints; pendingPoints = 0;
  199. var layout = view.CurrentLayout;
  200. var board = view.BoardRoot;
  201. var offset = layout.TilePosition(pair.First.Row, pair.First.Column);
  202. var local = new Vector3(board.rect.xMin + offset.x + layout.TileSize / 2,
  203. board.rect.yMax + offset.y - layout.TileSize / 2, 0);
  204. var parent = view.transform.parent as RectTransform;
  205. if (parent) visuals.ShowPoints(ScoreLabel, parent, board.TransformPoint(local),
  206. layout.TileSize * board.lossyScale.x / Mathf.Max(.0001f, parent.lossyScale.x), points);
  207. }
  208. private void ClearFeedbackVisuals()
  209. { visuals.Clear(); pendingPoints = 0; ClearHint(); if (view && view.transform.parent) view.transform.parent.GetComponentInChildren<BoardPathRenderer>(true)?.Clear(); }
  210. private void RequestPause() { if (flow != null && flow.State == GameFlowState.Running) flow.Pause(); }
  211. private void Resume() { if (Pause.IsVisible) flow?.Resume(); }
  212. private void Restart() { if (Pause.IsVisible) flow?.RestartCurrentLevel(); }
  213. private void Lobby() { if (Pause.IsVisible || Result.IsVisible) flow?.ReturnToLobby(); }
  214. private void Next() { if (Result.IsVisible && Result.Data?.SessionId == BoundSessionId) flow?.NextLevel(); }
  215. private void Retry() { if (Result.IsVisible && Result.Data?.SessionId == BoundSessionId) flow?.Retry(); }
  216. private void UseHint() { TryUse(ItemType.Hint); }
  217. private void UseShuffle() { TryUse(ItemType.Shuffle); }
  218. private void UseTime() { TryUse(ItemType.Time); }
  219. public void Unbind()
  220. {
  221. visuals.Clear(); visualizedTiles.Clear(); pendingPoints = 0;
  222. ClearHint(); unbindRuntime?.Invoke(); unbindRuntime = null; unbindFlow?.Invoke(); unbindFlow = null;
  223. flow = null; runtime = null; controller = null;
  224. if (Pause) Pause.SetVisible(false); if (Result) Result.Clear();
  225. }
  226. private void OnDisable() { Unbind(); }
  227. private void OnDestroy()
  228. {
  229. Unbind();
  230. if (!PauseButton) return;
  231. PauseButton.onClick.RemoveListener(RequestPause); Pause.ResumeButton.onClick.RemoveListener(Resume); Pause.RestartButton.onClick.RemoveListener(Restart); Pause.LobbyButton.onClick.RemoveListener(Lobby);
  232. Result.NextButton.onClick.RemoveListener(Next); Result.RetryButton.onClick.RemoveListener(Retry); Result.LobbyButton.onClick.RemoveListener(Lobby);
  233. ItemButtons[0].onClick.RemoveListener(UseHint); ItemButtons[1].onClick.RemoveListener(UseShuffle); ItemButtons[2].onClick.RemoveListener(UseTime);
  234. }
  235. }
  236. }