BoardInteractionController.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. using System;
  2. using DevilLink2.Core;
  3. using DevilLink2.Interaction;
  4. using DevilLink2.Gameplay;
  5. using UnityEngine;
  6. using UnityEngine.UI;
  7. namespace DevilLink2.Presentation
  8. {
  9. [DisallowMultipleComponent]
  10. public sealed class BoardInteractionController : MonoBehaviour
  11. {
  12. private BoardView view;
  13. private BoardPathRenderer paths;
  14. private Text status;
  15. private GameFlowController flow;
  16. private bool ownsRuntime;
  17. private Action unbindState;
  18. public BoardInteractionState State { get; private set; }
  19. public GameSessionRuntime Runtime { get; private set; }
  20. // The domain runtime consumes the underlying InvalidMatch once; forwarding is observational.
  21. public event Action<Tile, Tile> InvalidMatch;
  22. // Legacy visual-completion notification after the 240ms lock. Runtime owns the clear bonus.
  23. public event Action BoardCleared;
  24. public event Action<HintInfo> HintRequested;
  25. public void Initialize(BoardView boardView, int shuffleSeed = 2026)
  26. { InitializeState(boardView, shuffleSeed, null, null); }
  27. public void Initialize(BoardView boardView, GameSession session, IMonotonicClock clock = null)
  28. {
  29. if (session == null) throw new ArgumentNullException(nameof(session));
  30. if (!boardView || !ReferenceEquals(boardView.Data, session.Board))
  31. throw new ArgumentException("BoardView must display the session's exact board.", nameof(boardView));
  32. InitializeState(boardView, session.RandomSeed, session, clock ?? new StopwatchClock());
  33. }
  34. public void Initialize(BoardView boardView, GameFlowController gameFlow)
  35. {
  36. if (gameFlow == null) throw new ArgumentNullException(nameof(gameFlow));
  37. if (!boardView) throw new ArgumentNullException(nameof(boardView));
  38. Detach(); view = boardView; flow = gameFlow;
  39. flow.SessionChanged += BindFlowRuntime;
  40. flow.StateChanged += OnFlowStateChanged;
  41. flow.Items.HintRequested += OnHintRequested;
  42. if (flow.State == GameFlowState.Abandoned) { view.Clear(); return; }
  43. BindFlowRuntime(flow.Runtime);
  44. }
  45. private void BindFlowRuntime(GameSessionRuntime runtime)
  46. {
  47. if (flow == null || !ReferenceEquals(flow.Runtime, runtime)) return;
  48. DetachState();
  49. Runtime = runtime; ownsRuntime = false;
  50. view.Show(runtime.Session.Board); EnsureOverlay(); paths.Clear(); status.text = "";
  51. State = runtime.Interaction; BindState();
  52. if (State.Error != null) OnFailed(State.Error);
  53. UpdateFlowInput();
  54. }
  55. private void OnFlowStateChanged(GameFlowState previous, GameFlowState next)
  56. {
  57. if (next == GameFlowState.Abandoned)
  58. {
  59. DetachState(); Runtime = null;
  60. if (paths) paths.Clear(); if (status) status.text = "";
  61. view.Clear();
  62. }
  63. else
  64. {
  65. if (next == GameFlowState.Paused) { if (paths) paths.Clear(); if (view) view.FinishVisuals(); }
  66. UpdateFlowInput();
  67. }
  68. }
  69. private void UpdateFlowInput()
  70. { if (view) view.SetInteraction(flow.State == GameFlowState.Running ? OnClick : (Action<TileView>)null); }
  71. private void OnHintRequested(HintInfo hint)
  72. {
  73. if (flow != null && flow.State == GameFlowState.Running && Runtime != null && hint.SessionId == Runtime.Session.Id)
  74. HintRequested?.Invoke(hint);
  75. }
  76. private void BindState()
  77. {
  78. // Unsubscribing does not cancel an event invocation already in flight.
  79. // Guard each visual callback by its bound state to isolate old sessions.
  80. var source = State;
  81. Action<Tile> selection = tile => { if (ReferenceEquals(State, source)) OnSelection(tile); };
  82. Action<Tile, Tile> invalid = (a,b) => { if (ReferenceEquals(State, source)) OnInvalid(a,b); };
  83. Action<PairMatch> matched = pair => { if (ReferenceEquals(State, source)) OnMatched(pair); };
  84. Action<BoardShuffleResult> shuffled = result => { if (ReferenceEquals(State, source)) OnReshuffled(result); };
  85. Action cleared = () => { if (ReferenceEquals(State, source)) OnCleared(); };
  86. Action<string> failed = error => { if (ReferenceEquals(State, source)) OnFailed(error); };
  87. source.SelectionChanged += selection; source.InvalidMatch += invalid; source.Matched += matched;
  88. source.Reshuffled += shuffled; source.BoardCleared += cleared; source.Failed += failed;
  89. unbindState = () => {
  90. source.SelectionChanged -= selection; source.InvalidMatch -= invalid; source.Matched -= matched;
  91. source.Reshuffled -= shuffled; source.BoardCleared -= cleared; source.Failed -= failed;
  92. };
  93. }
  94. private void DetachState()
  95. {
  96. if (view) { view.SetInteraction(null); view.FinishVisuals(); }
  97. unbindState?.Invoke(); unbindState = null; State = null;
  98. }
  99. private void InitializeState(BoardView boardView, int shuffleSeed, GameSession session, IMonotonicClock clock)
  100. {
  101. Detach(); view = boardView;
  102. if (!view || view.Data == null) throw new InvalidOperationException("Show a Core board before enabling interaction.");
  103. EnsureOverlay(); paths.Clear(); status.text = "";
  104. Runtime = session == null ? null : new GameSessionRuntime(session, clock);
  105. State = Runtime == null ? new BoardInteractionState(view.Data, shuffleSeed) : Runtime.Interaction;
  106. ownsRuntime = Runtime != null;
  107. BindState();
  108. // Runtime initialization may have shuffled the shared board before visual subscriptions.
  109. if (Runtime != null) view.Refresh();
  110. view.SetInteraction(OnClick);
  111. // Runtime already initialized its state before subscribing the visual observers.
  112. if (State.Error != null) OnFailed(State.Error);
  113. State.Initialize();
  114. }
  115. private void Update()
  116. { if (flow != null) flow.Update(); else if (Runtime != null) Runtime.Update(); else State?.Advance(Time.unscaledDeltaTime); }
  117. private void OnClick(TileView tile)
  118. {
  119. if (!tile || !view || !ReferenceEquals(view.FindTile(tile.TileId), tile)) return;
  120. if (flow != null) flow.Click(tile.Data.Row, tile.Data.Column);
  121. else if (Runtime != null) Runtime.Click(tile.Data.Row, tile.Data.Column);
  122. else State?.Click(tile.Data.Row, tile.Data.Column);
  123. }
  124. private void OnSelection(Tile tile) { view.Highlight(tile == null ? 0 : tile.Id); }
  125. private void OnInvalid(Tile a, Tile b)
  126. { view.FindTile(a.Id)?.Shake(); view.FindTile(b.Id)?.Shake(); InvalidMatch?.Invoke(a, b); }
  127. private void OnMatched(PairMatch match)
  128. {
  129. var layout = view.CurrentLayout;
  130. paths.Show(match.Path, view.BoardRoot, layout);
  131. view.AnimateRemoval(match.First.Id); view.AnimateRemoval(match.Second.Id);
  132. }
  133. private void OnReshuffled(BoardShuffleResult result) { paths.Clear(); view.Refresh(); status.text = "Board reshuffled"; }
  134. private void OnCleared() { status.text = "Board cleared"; BoardCleared?.Invoke(); }
  135. private void OnFailed(string error) { status.text = error; Debug.LogError(error, this); }
  136. private void EnsureOverlay()
  137. {
  138. // Sibling of the scroll viewport, so the viewport RectMask2D cannot clip border links.
  139. var parent = view.transform.parent;
  140. if (!parent) parent = view.transform;
  141. var child = parent.Find("InteractionOverlay");
  142. if (!child) child = new GameObject("InteractionOverlay", typeof(RectTransform)).transform;
  143. child.SetParent(parent, false); child.SetAsLastSibling();
  144. var rect = (RectTransform)child; rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one;
  145. rect.offsetMin = rect.offsetMax = Vector2.zero;
  146. paths = child.GetComponent<BoardPathRenderer>(); if (!paths) paths = child.gameObject.AddComponent<BoardPathRenderer>();
  147. var label = child.Find("Status");
  148. if (!label) label = new GameObject("Status", typeof(RectTransform)).transform;
  149. label.SetParent(child, false);
  150. var textRect = (RectTransform)label; textRect.anchorMin = new Vector2(0, 0); textRect.anchorMax = new Vector2(1, 0);
  151. textRect.pivot = new Vector2(.5f, 0); textRect.sizeDelta = new Vector2(0, 38); textRect.anchoredPosition = Vector2.zero;
  152. status = label.GetComponent<Text>(); if (!status) status = label.gameObject.AddComponent<Text>();
  153. status.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf"); status.fontSize = 12;
  154. status.alignment = TextAnchor.MiddleCenter; status.color = new Color32(255, 211, 77, 255); status.raycastTarget = false;
  155. }
  156. private void OnDisable() { if (paths) paths.Clear(); if (view) view.FinishVisuals(); }
  157. private void OnDestroy() { Detach(); }
  158. private void Detach()
  159. {
  160. if (flow != null)
  161. { flow.SessionChanged -= BindFlowRuntime; flow.StateChanged -= OnFlowStateChanged; flow.Items.HintRequested -= OnHintRequested; flow = null; }
  162. DetachState();
  163. if (ownsRuntime) Runtime?.Dispose();
  164. Runtime = null; ownsRuntime = false;
  165. if (paths) paths.Clear();
  166. }
  167. }
  168. }