| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 |
- using System;
- using DevilLink2.Core;
- using DevilLink2.Interaction;
- using DevilLink2.Gameplay;
- using UnityEngine;
- using UnityEngine.UI;
- namespace DevilLink2.Presentation
- {
- [DisallowMultipleComponent]
- public sealed class BoardInteractionController : MonoBehaviour
- {
- private BoardView view;
- private BoardPathRenderer paths;
- private Text status;
- private GameFlowController flow;
- private bool ownsRuntime;
- private Action unbindState;
- public BoardInteractionState State { get; private set; }
- public GameSessionRuntime Runtime { get; private set; }
- // The domain runtime consumes the underlying InvalidMatch once; forwarding is observational.
- public event Action<Tile, Tile> InvalidMatch;
- // Legacy visual-completion notification after the 240ms lock. Runtime owns the clear bonus.
- public event Action BoardCleared;
- public event Action<HintInfo> HintRequested;
- public void Initialize(BoardView boardView, int shuffleSeed = 2026)
- { InitializeState(boardView, shuffleSeed, null, null); }
- public void Initialize(BoardView boardView, GameSession session, IMonotonicClock clock = null)
- {
- if (session == null) throw new ArgumentNullException(nameof(session));
- if (!boardView || !ReferenceEquals(boardView.Data, session.Board))
- throw new ArgumentException("BoardView must display the session's exact board.", nameof(boardView));
- InitializeState(boardView, session.RandomSeed, session, clock ?? new StopwatchClock());
- }
- public void Initialize(BoardView boardView, GameFlowController gameFlow)
- {
- if (gameFlow == null) throw new ArgumentNullException(nameof(gameFlow));
- if (!boardView) throw new ArgumentNullException(nameof(boardView));
- Detach(); view = boardView; flow = gameFlow;
- flow.SessionChanged += BindFlowRuntime;
- flow.StateChanged += OnFlowStateChanged;
- flow.Items.HintRequested += OnHintRequested;
- if (flow.State == GameFlowState.Abandoned) { view.Clear(); return; }
- BindFlowRuntime(flow.Runtime);
- }
- private void BindFlowRuntime(GameSessionRuntime runtime)
- {
- if (flow == null || !ReferenceEquals(flow.Runtime, runtime)) return;
- DetachState();
- Runtime = runtime; ownsRuntime = false;
- view.Show(runtime.Session.Board); EnsureOverlay(); paths.Clear(); status.text = "";
- State = runtime.Interaction; BindState();
- if (State.Error != null) OnFailed(State.Error);
- UpdateFlowInput();
- }
- private void OnFlowStateChanged(GameFlowState previous, GameFlowState next)
- {
- if (next == GameFlowState.Abandoned)
- {
- DetachState(); Runtime = null;
- if (paths) paths.Clear(); if (status) status.text = "";
- view.Clear();
- }
- else
- {
- if (next == GameFlowState.Paused) { if (paths) paths.Clear(); if (view) view.FinishVisuals(); }
- UpdateFlowInput();
- }
- }
- private void UpdateFlowInput()
- { if (view) view.SetInteraction(flow.State == GameFlowState.Running ? OnClick : (Action<TileView>)null); }
- private void OnHintRequested(HintInfo hint)
- {
- if (flow != null && flow.State == GameFlowState.Running && Runtime != null && hint.SessionId == Runtime.Session.Id)
- HintRequested?.Invoke(hint);
- }
- private void BindState()
- {
- // Unsubscribing does not cancel an event invocation already in flight.
- // Guard each visual callback by its bound state to isolate old sessions.
- var source = State;
- Action<Tile> selection = tile => { if (ReferenceEquals(State, source)) OnSelection(tile); };
- Action<Tile, Tile> invalid = (a,b) => { if (ReferenceEquals(State, source)) OnInvalid(a,b); };
- Action<PairMatch> matched = pair => { if (ReferenceEquals(State, source)) OnMatched(pair); };
- Action<BoardShuffleResult> shuffled = result => { if (ReferenceEquals(State, source)) OnReshuffled(result); };
- Action cleared = () => { if (ReferenceEquals(State, source)) OnCleared(); };
- Action<string> failed = error => { if (ReferenceEquals(State, source)) OnFailed(error); };
- source.SelectionChanged += selection; source.InvalidMatch += invalid; source.Matched += matched;
- source.Reshuffled += shuffled; source.BoardCleared += cleared; source.Failed += failed;
- unbindState = () => {
- source.SelectionChanged -= selection; source.InvalidMatch -= invalid; source.Matched -= matched;
- source.Reshuffled -= shuffled; source.BoardCleared -= cleared; source.Failed -= failed;
- };
- }
- private void DetachState()
- {
- if (view) { view.SetInteraction(null); view.FinishVisuals(); }
- unbindState?.Invoke(); unbindState = null; State = null;
- }
- private void InitializeState(BoardView boardView, int shuffleSeed, GameSession session, IMonotonicClock clock)
- {
- Detach(); view = boardView;
- if (!view || view.Data == null) throw new InvalidOperationException("Show a Core board before enabling interaction.");
- EnsureOverlay(); paths.Clear(); status.text = "";
- Runtime = session == null ? null : new GameSessionRuntime(session, clock);
- State = Runtime == null ? new BoardInteractionState(view.Data, shuffleSeed) : Runtime.Interaction;
- ownsRuntime = Runtime != null;
- BindState();
- // Runtime initialization may have shuffled the shared board before visual subscriptions.
- if (Runtime != null) view.Refresh();
- view.SetInteraction(OnClick);
- // Runtime already initialized its state before subscribing the visual observers.
- if (State.Error != null) OnFailed(State.Error);
- State.Initialize();
- }
- private void Update()
- { if (flow != null) flow.Update(); else if (Runtime != null) Runtime.Update(); else State?.Advance(Time.unscaledDeltaTime); }
- private void OnClick(TileView tile)
- {
- if (!tile || !view || !ReferenceEquals(view.FindTile(tile.TileId), tile)) return;
- if (flow != null) flow.Click(tile.Data.Row, tile.Data.Column);
- else if (Runtime != null) Runtime.Click(tile.Data.Row, tile.Data.Column);
- else State?.Click(tile.Data.Row, tile.Data.Column);
- }
- private void OnSelection(Tile tile) { view.Highlight(tile == null ? 0 : tile.Id); }
- private void OnInvalid(Tile a, Tile b)
- { view.FindTile(a.Id)?.Shake(); view.FindTile(b.Id)?.Shake(); InvalidMatch?.Invoke(a, b); }
- private void OnMatched(PairMatch match)
- {
- var layout = view.CurrentLayout;
- paths.Show(match.Path, view.BoardRoot, layout);
- view.AnimateRemoval(match.First.Id); view.AnimateRemoval(match.Second.Id);
- }
- private void OnReshuffled(BoardShuffleResult result) { paths.Clear(); view.Refresh(); status.text = "Board reshuffled"; }
- private void OnCleared() { status.text = "Board cleared"; BoardCleared?.Invoke(); }
- private void OnFailed(string error) { status.text = error; Debug.LogError(error, this); }
- private void EnsureOverlay()
- {
- // Sibling of the scroll viewport, so the viewport RectMask2D cannot clip border links.
- var parent = view.transform.parent;
- if (!parent) parent = view.transform;
- var child = parent.Find("InteractionOverlay");
- if (!child) child = new GameObject("InteractionOverlay", typeof(RectTransform)).transform;
- child.SetParent(parent, false); child.SetAsLastSibling();
- var rect = (RectTransform)child; rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one;
- rect.offsetMin = rect.offsetMax = Vector2.zero;
- paths = child.GetComponent<BoardPathRenderer>(); if (!paths) paths = child.gameObject.AddComponent<BoardPathRenderer>();
- var label = child.Find("Status");
- if (!label) label = new GameObject("Status", typeof(RectTransform)).transform;
- label.SetParent(child, false);
- var textRect = (RectTransform)label; textRect.anchorMin = new Vector2(0, 0); textRect.anchorMax = new Vector2(1, 0);
- textRect.pivot = new Vector2(.5f, 0); textRect.sizeDelta = new Vector2(0, 38); textRect.anchoredPosition = Vector2.zero;
- status = label.GetComponent<Text>(); if (!status) status = label.gameObject.AddComponent<Text>();
- status.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf"); status.fontSize = 12;
- status.alignment = TextAnchor.MiddleCenter; status.color = new Color32(255, 211, 77, 255); status.raycastTarget = false;
- }
- private void OnDisable() { if (paths) paths.Clear(); if (view) view.FinishVisuals(); }
- private void OnDestroy() { Detach(); }
- private void Detach()
- {
- if (flow != null)
- { flow.SessionChanged -= BindFlowRuntime; flow.StateChanged -= OnFlowStateChanged; flow.Items.HintRequested -= OnHintRequested; flow = null; }
- DetachState();
- if (ownsRuntime) Runtime?.Dispose();
- Runtime = null; ownsRuntime = false;
- if (paths) paths.Clear();
- }
- }
- }
|