GameHUD.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. Result.NextButton.onClick.AddListener(Next); Result.RetryButton.onClick.AddListener(Retry); Result.LobbyButton.onClick.AddListener(Lobby);
  55. items[0].onClick.AddListener(UseHint); items[1].onClick.AddListener(UseShuffle); items[2].onClick.AddListener(UseTime);
  56. }
  57. public void SetVisualClock(IMonotonicClock clock) { ClearHint(); visualClock = clock ?? throw new ArgumentNullException(nameof(clock)); }
  58. public void Bind(GameFlowController source, BoardInteractionController interaction)
  59. {
  60. if (ReferenceEquals(flow, source) && controller == interaction) { Refresh(); return; }
  61. Unbind(); flow = source ?? throw new ArgumentNullException(nameof(source)); controller = interaction;
  62. Action<GameSessionRuntime> session = current => { if (ReferenceEquals(flow, source) && ReferenceEquals(source.Runtime, current)) BindRuntime(current); };
  63. Action<GameFlowState, GameFlowState> state = (a, b) => { if (ReferenceEquals(flow, source)) HandleState(); };
  64. Action<GameResult> settled = result => { if (ReferenceEquals(flow, source)) ShowResult(result); };
  65. Action<HintInfo> hint = info => { if (ReferenceEquals(flow, source)) ShowHint(info); };
  66. source.SessionChanged += session; source.StateChanged += state; source.Settled += settled;
  67. if (interaction) interaction.HintRequested += hint;
  68. unbindFlow = () => { source.SessionChanged -= session; source.StateChanged -= state; source.Settled -= settled; if (interaction) interaction.HintRequested -= hint; };
  69. BindRuntime(source.Runtime); HandleState();
  70. if (source.Result != null) ShowResult(source.Result);
  71. }
  72. private void BindRuntime(GameSessionRuntime current)
  73. {
  74. visuals.Clear(); visualizedTiles.Clear(); pendingPoints = 0;
  75. observedScore = lastMatchScore = current.Score.TotalScore;
  76. observedCombo = current.Score.ComboCount; observedPairs = current.Session.Board.RemainingTileCount / 2;
  77. ClearHint(); unbindRuntime?.Invoke(); runtime = current; Result.Clear(); Pause.SetVisible(false); FeedbackLabel.text = "";
  78. Action<double> time = _ => { if (ReferenceEquals(runtime, current)) Refresh(); };
  79. Action<int> score = points => {
  80. if (!ReferenceEquals(runtime, current)) return;
  81. 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); }
  82. Refresh();
  83. };
  84. Action<int> bonus = _ => { if (ReferenceEquals(runtime, current)) Refresh(); };
  85. 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); } };
  86. Action<BoardShuffleResult> shuffled = _ => { if (ReferenceEquals(runtime, current)) { visuals.Clear(); pendingPoints = 0; ClearHint(); } };
  87. Action<Tile> selected=tile=>{if(ReferenceEquals(runtime,current) && tile!=null && flow.State==GameFlowState.Running)GameAudio.Sound(AudioCue.Tile_Select);};
  88. Action<Tile,Tile> invalid=(a,b)=>{if(ReferenceEquals(runtime,current) && (flow.State==GameFlowState.Running || flow.State==GameFlowState.Defeat))GameAudio.Sound(AudioCue.Tile_Invalid);};
  89. current.Interaction.SelectionChanged+=selected;current.Interaction.InvalidMatch+=invalid;
  90. current.Timer.RemainingTimeChanged += time; current.Score.MatchScored += score; current.Score.ClearBonusAwarded += bonus;
  91. current.Interaction.Matched += matched; current.Interaction.Reshuffled += shuffled;
  92. unbindRuntime = () => { current.Interaction.SelectionChanged-=selected;current.Interaction.InvalidMatch-=invalid; current.Timer.RemainingTimeChanged -= time; current.Score.MatchScored -= score; current.Score.ClearBonusAwarded -= bonus;
  93. current.Interaction.Matched -= matched; current.Interaction.Reshuffled -= shuffled; };
  94. Refresh();
  95. }
  96. private void HandleState()
  97. {
  98. if (flow == null) return;
  99. if(GameAudio.Instance && flow.State==GameFlowState.Running)GameAudio.Instance.SetMusic(MusicTrack.Gameplay);
  100. if (flow.State == GameFlowState.Paused) { ClearFeedbackVisuals(); Pause.Show(); }
  101. else Pause.SetVisible(false);
  102. if (flow.State == GameFlowState.Ready || flow.State == GameFlowState.Abandoned) { ClearFeedbackVisuals(); Result.Clear(); }
  103. Refresh();
  104. }
  105. private void ShowResult(GameResult result)
  106. {
  107. 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;
  108. if (Result.Data?.SessionId == result.SessionId) return;
  109. GameAudio.Sound(result.Outcome==GameOutcome.Victory?AudioCue.Victory:AudioCue.Defeat,"result:"+result.SessionId);
  110. if(result.Outcome==GameOutcome.Victory)GameAudio.Sound(AudioCue.Coin_Reward,"coin:"+result.SessionId);
  111. ClearFeedbackVisuals(); Pause.SetVisible(false); Result.Present(result); Refresh();
  112. }
  113. private void LateUpdate() { Refresh(); if (Application.isPlaying) visuals.Advance(Time.unscaledDeltaTime); }
  114. public void Refresh()
  115. {
  116. if (!this || flow == null || runtime == null) return;
  117. if (hintBoard != null && visualClock.Seconds >= hintUntil) ClearHint();
  118. var timer = runtime.Timer; var score = runtime.Score; var level = runtime.Session.Definition;
  119. ModeLabel.text = UIManager.ModeName(level.Mode) + "\nLEVEL " + level.Level + " / 20";
  120. TimerLabel.text = HudFormatting.Time(timer.HasTimer, timer.RemainingTime);
  121. IsLowTime = timer.IsLowTime; TimerLabel.color = IsLowTime ? UIBuilder.Hex("FF8EA0") : UIBuilder.LightGold;
  122. TimeFraction = timer.HasTimer && timer.TimeBarMax > 0 ? Mathf.Clamp01((float)(timer.RemainingTime / timer.TimeBarMax)) : 1;
  123. SetFraction(TimeFill, TimeFraction); TimeFill.color = IsLowTime ? UIBuilder.Hex("FF4D6A") : Accent(level.Mode);
  124. int comboCount = score.ComboCount, multiplier = score.CurrentMultiplier;
  125. int pairs = runtime.Session.Board.RemainingTileCount / 2;
  126. if (score.TotalScore != observedScore) { observedScore = score.TotalScore; visuals.Emphasize(ScoreLabel); }
  127. if (pairs != observedPairs) { if (pairs < observedPairs) visuals.Emphasize(PairsLabel, .035f); observedPairs = pairs; }
  128. if (comboCount != observedCombo)
  129. {
  130. if (comboCount > observedCombo) visuals.Emphasize(ComboLabel, .04f + .008f * Mathf.Min(5, multiplier));
  131. else if (comboCount == 0) visuals.ResetPulse(ComboLabel);
  132. observedCombo = comboCount;
  133. }
  134. ComboLabel.color = score.IsInCombo ? Color.Lerp(UIBuilder.Gold, UIBuilder.LightGold, Mathf.Clamp01(multiplier / 5f)) : UIBuilder.LightGold;
  135. ScoreLabel.text = "SCORE " + score.TotalScore.ToString("N0", CultureInfo.InvariantCulture);
  136. ComboLabel.text = "COMBO ×" + Math.Max(1, score.CurrentMultiplier);
  137. ComboStateLabel.text = score.IsInCombo ? "COMBO ACTIVE" : "READY";
  138. ComboStateLabel.color = score.IsInCombo ? UIBuilder.Hex("34E0FF") : UIBuilder.Muted;
  139. SetFraction(ComboFill, (float)(score.ComboRemainingTime / SessionScore.ComboWindowSeconds));
  140. PairsLabel.text = "PAIRS LEFT " + runtime.Session.Board.RemainingTileCount / 2;
  141. bool available = flow.State == GameFlowState.Running && !runtime.IsFinished && !runtime.Interaction.IsLocked;
  142. PauseButton.interactable = flow.State == GameFlowState.Running;
  143. for (int i = 0; i < ItemButtons.Length; i++)
  144. {
  145. int count = flow.Economy.Inventory.GetCount((ItemType)i);
  146. ItemButtons[i].GetComponentInChildren<Text>(true).text = (i == 0 ? "HINT" : i == 1 ? "SHUFFLE" : "+30 SECONDS") + "\n" + count;
  147. ItemButtons[i].interactable = available && count > 0 && (i != 2 || timer.HasTimer);
  148. }
  149. }
  150. public static Color Accent(GameMode mode) => mode == GameMode.Classic ? UIBuilder.Gold : mode == GameMode.TimeAttack ? UIBuilder.Hex("FF2E9A") : UIBuilder.Hex("34E0FF");
  151. private static void SetFraction(Image image, float fraction)
  152. { var r = image.rectTransform; r.anchorMax = new Vector2(Mathf.Clamp01(fraction), 1); }
  153. public ItemUseResult TryUse(ItemType type)
  154. {
  155. if (flow == null) return new ItemUseResult(ItemUseStatus.GameNotRunning);
  156. var result = type == ItemType.Hint ? flow.Items.TryUseHint() : type == ItemType.Shuffle ? flow.Items.TryUseShuffle() : flow.Items.TryUseTime();
  157. FeedbackLabel.text = result.Succeeded ? type == ItemType.Hint ? "CONNECT THE HIGHLIGHTED PAIR" : type == ItemType.Shuffle ? "BOARD SHUFFLED" : "+30 SECONDS" :
  158. result.Status == ItemUseStatus.InsufficientInventory ? "NO ITEMS AVAILABLE" : result.Status == ItemUseStatus.UnsupportedMode ? "ZEN HAS NO TIMER" :
  159. result.Status == ItemUseStatus.InteractionLocked ? "WAIT FOR TILES TO SETTLE" : result.Status == ItemUseStatus.NoAvailablePair ? "NO AVAILABLE PAIR" : "ITEM UNAVAILABLE";
  160. Refresh(); return result;
  161. }
  162. private void ShowHint(HintInfo hint)
  163. {
  164. if (runtime == null || flow.State != GameFlowState.Running || hint.SessionId != runtime.Session.Id) return;
  165. ClearHint(); hintBoard = runtime.Session.Board; firstHint = hint.FirstId; secondHint = hint.SecondId;
  166. hintUntil = visualClock.Seconds + HintInfo.DurationSeconds;
  167. view.FindTile(firstHint)?.SetHinted(true); view.FindTile(secondHint)?.SetHinted(true);
  168. }
  169. private void ClearHint()
  170. {
  171. if (hintBoard != null && view && ReferenceEquals(view.Data, hintBoard))
  172. { view.FindTile(firstHint)?.SetHinted(false); view.FindTile(secondHint)?.SetHinted(false); }
  173. hintBoard = null;
  174. }
  175. private void ShowMatchPoints(PairMatch pair)
  176. {
  177. if (pendingPoints <= 0 || flow == null || flow.State != GameFlowState.Running || !view || !view.BoardRoot ||
  178. !ReferenceEquals(view.Data, runtime.Session.Board) || visualizedTiles.Contains(pair.First.Id) || visualizedTiles.Contains(pair.Second.Id)) return;
  179. visualizedTiles.Add(pair.First.Id); visualizedTiles.Add(pair.Second.Id);
  180. int points = pendingPoints; pendingPoints = 0;
  181. var layout = view.CurrentLayout;
  182. var board = view.BoardRoot;
  183. var offset = layout.TilePosition(pair.First.Row, pair.First.Column);
  184. var local = new Vector3(board.rect.xMin + offset.x + layout.TileSize / 2,
  185. board.rect.yMax + offset.y - layout.TileSize / 2, 0);
  186. var parent = view.transform.parent as RectTransform;
  187. if (parent) visuals.ShowPoints(ScoreLabel, parent, board.TransformPoint(local),
  188. layout.TileSize * board.lossyScale.x / Mathf.Max(.0001f, parent.lossyScale.x), points);
  189. }
  190. private void ClearFeedbackVisuals()
  191. { visuals.Clear(); pendingPoints = 0; ClearHint(); if (view && view.transform.parent) view.transform.parent.GetComponentInChildren<BoardPathRenderer>(true)?.Clear(); }
  192. private void RequestPause() { if (flow != null && flow.State == GameFlowState.Running) flow.Pause(); }
  193. private void Resume() { if (Pause.IsVisible) flow?.Resume(); }
  194. private void Restart() { if (Pause.IsVisible) flow?.RestartCurrentLevel(); }
  195. private void Lobby() { if (Pause.IsVisible || Result.IsVisible) flow?.ReturnToLobby(); }
  196. private void Next() { if (Result.IsVisible && Result.Data?.SessionId == BoundSessionId) flow?.NextLevel(); }
  197. private void Retry() { if (Result.IsVisible && Result.Data?.SessionId == BoundSessionId) flow?.Retry(); }
  198. private void UseHint() { TryUse(ItemType.Hint); }
  199. private void UseShuffle() { TryUse(ItemType.Shuffle); }
  200. private void UseTime() { TryUse(ItemType.Time); }
  201. public void Unbind()
  202. {
  203. visuals.Clear(); visualizedTiles.Clear(); pendingPoints = 0;
  204. ClearHint(); unbindRuntime?.Invoke(); unbindRuntime = null; unbindFlow?.Invoke(); unbindFlow = null;
  205. flow = null; runtime = null; controller = null;
  206. if (Pause) Pause.SetVisible(false); if (Result) Result.Clear();
  207. }
  208. private void OnDisable() { Unbind(); }
  209. private void OnDestroy()
  210. {
  211. Unbind();
  212. if (!PauseButton) return;
  213. PauseButton.onClick.RemoveListener(RequestPause); Pause.ResumeButton.onClick.RemoveListener(Resume); Pause.RestartButton.onClick.RemoveListener(Restart); Pause.LobbyButton.onClick.RemoveListener(Lobby);
  214. Result.NextButton.onClick.RemoveListener(Next); Result.RetryButton.onClick.RemoveListener(Retry); Result.LobbyButton.onClick.RemoveListener(Lobby);
  215. ItemButtons[0].onClick.RemoveListener(UseHint); ItemButtons[1].onClick.RemoveListener(UseShuffle); ItemButtons[2].onClick.RemoveListener(UseTime);
  216. }
  217. }
  218. }