| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219 |
- using GameAudio = DevilLink2.Presentation.AudioManager;
- using System;
- using System.Globalization;
- using System.Collections.Generic;
- using DevilLink2.Core;
- using DevilLink2.Gameplay;
- using DevilLink2.Interaction;
- using DevilLink2.Presentation;
- using UnityEngine;
- using UnityEngine.UI;
- namespace DevilLink2.UI
- {
- [ExecuteAlways]
- public sealed class GameHUD : MonoBehaviour
- {
- private GameFlowController flow;
- private GameSessionRuntime runtime;
- private BoardView view;
- private BoardInteractionController controller;
- private Action unbindFlow, unbindRuntime;
- private IMonotonicClock visualClock = new StopwatchClock();
- private Board hintBoard;
- private int firstHint, secondHint;
- private double hintUntil;
- private readonly ScoreFeedbackVisuals visuals = new ScoreFeedbackVisuals();
- private readonly HashSet<int> visualizedTiles = new HashSet<int>();
- private long observedScore, lastMatchScore;
- private int observedCombo, observedPairs, pendingPoints;
- public ScoreFeedbackVisuals Visuals => visuals;
- public Text ModeLabel { get; private set; }
- public Text TimerLabel { get; private set; }
- public Text ScoreLabel { get; private set; }
- public Text ComboLabel { get; private set; }
- public Text ComboStateLabel { get; private set; }
- public Text PairsLabel { get; private set; }
- public Text FeedbackLabel { get; private set; }
- public Image TimeFill { get; private set; }
- public Image ComboFill { get; private set; }
- public Button PauseButton { get; private set; }
- public Button[] ItemButtons { get; private set; }
- public PauseScreen Pause { get; private set; }
- public ResultScreen Result { get; private set; }
- public bool IsLowTime { get; private set; }
- public float TimeFraction { get; private set; }
- public Guid BoundSessionId => runtime?.Session.Id ?? Guid.Empty;
- public void Configure(BoardView board, Text mode, Text timer, Text score, Text combo, Text comboState, Text pairs, Text feedback,
- Image timeFill, Image comboFill, Button pauseButton, Button[] items, PauseScreen pause, ResultScreen result)
- {
- view = board; ModeLabel = mode; TimerLabel = timer; ScoreLabel = score; ComboLabel = combo; ComboStateLabel = comboState;
- PairsLabel = pairs; FeedbackLabel = feedback; TimeFill = timeFill; ComboFill = comboFill; PauseButton = pauseButton;
- ItemButtons = items; Pause = pause; Result = result;
- PauseButton.onClick.AddListener(RequestPause); Pause.ResumeButton.onClick.AddListener(Resume);
- Pause.RestartButton.onClick.AddListener(Restart); Pause.LobbyButton.onClick.AddListener(Lobby);
- Result.NextButton.onClick.AddListener(Next); Result.RetryButton.onClick.AddListener(Retry); Result.LobbyButton.onClick.AddListener(Lobby);
- items[0].onClick.AddListener(UseHint); items[1].onClick.AddListener(UseShuffle); items[2].onClick.AddListener(UseTime);
- }
- public void SetVisualClock(IMonotonicClock clock) { ClearHint(); visualClock = clock ?? throw new ArgumentNullException(nameof(clock)); }
- public void Bind(GameFlowController source, BoardInteractionController interaction)
- {
- if (ReferenceEquals(flow, source) && controller == interaction) { Refresh(); return; }
- Unbind(); flow = source ?? throw new ArgumentNullException(nameof(source)); controller = interaction;
- Action<GameSessionRuntime> session = current => { if (ReferenceEquals(flow, source) && ReferenceEquals(source.Runtime, current)) BindRuntime(current); };
- Action<GameFlowState, GameFlowState> state = (a, b) => { if (ReferenceEquals(flow, source)) HandleState(); };
- Action<GameResult> settled = result => { if (ReferenceEquals(flow, source)) ShowResult(result); };
- Action<HintInfo> hint = info => { if (ReferenceEquals(flow, source)) ShowHint(info); };
- source.SessionChanged += session; source.StateChanged += state; source.Settled += settled;
- if (interaction) interaction.HintRequested += hint;
- unbindFlow = () => { source.SessionChanged -= session; source.StateChanged -= state; source.Settled -= settled; if (interaction) interaction.HintRequested -= hint; };
- BindRuntime(source.Runtime); HandleState();
- if (source.Result != null) ShowResult(source.Result);
- }
- private void BindRuntime(GameSessionRuntime current)
- {
- visuals.Clear(); visualizedTiles.Clear(); pendingPoints = 0;
- observedScore = lastMatchScore = current.Score.TotalScore;
- observedCombo = current.Score.ComboCount; observedPairs = current.Session.Board.RemainingTileCount / 2;
- ClearHint(); unbindRuntime?.Invoke(); runtime = current; Result.Clear(); Pause.SetVisible(false); FeedbackLabel.text = "";
- Action<double> time = _ => { if (ReferenceEquals(runtime, current)) Refresh(); };
- Action<int> score = points => {
- if (!ReferenceEquals(runtime, current)) return;
- 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); }
- Refresh();
- };
- Action<int> bonus = _ => { if (ReferenceEquals(runtime, current)) Refresh(); };
- 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); } };
- Action<BoardShuffleResult> shuffled = _ => { if (ReferenceEquals(runtime, current)) { visuals.Clear(); pendingPoints = 0; ClearHint(); } };
- Action<Tile> selected=tile=>{if(ReferenceEquals(runtime,current) && tile!=null && flow.State==GameFlowState.Running)GameAudio.Sound(AudioCue.Tile_Select);};
- Action<Tile,Tile> invalid=(a,b)=>{if(ReferenceEquals(runtime,current) && (flow.State==GameFlowState.Running || flow.State==GameFlowState.Defeat))GameAudio.Sound(AudioCue.Tile_Invalid);};
- current.Interaction.SelectionChanged+=selected;current.Interaction.InvalidMatch+=invalid;
- current.Timer.RemainingTimeChanged += time; current.Score.MatchScored += score; current.Score.ClearBonusAwarded += bonus;
- current.Interaction.Matched += matched; current.Interaction.Reshuffled += shuffled;
- unbindRuntime = () => { current.Interaction.SelectionChanged-=selected;current.Interaction.InvalidMatch-=invalid; current.Timer.RemainingTimeChanged -= time; current.Score.MatchScored -= score; current.Score.ClearBonusAwarded -= bonus;
- current.Interaction.Matched -= matched; current.Interaction.Reshuffled -= shuffled; };
- Refresh();
- }
- private void HandleState()
- {
- if (flow == null) return;
- if(GameAudio.Instance && flow.State==GameFlowState.Running)GameAudio.Instance.SetMusic(MusicTrack.Gameplay);
- if (flow.State == GameFlowState.Paused) { ClearFeedbackVisuals(); Pause.Show(); }
- else Pause.SetVisible(false);
- if (flow.State == GameFlowState.Ready || flow.State == GameFlowState.Abandoned) { ClearFeedbackVisuals(); Result.Clear(); }
- Refresh();
- }
- private void ShowResult(GameResult result)
- {
- 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;
- if (Result.Data?.SessionId == result.SessionId) return;
- GameAudio.Sound(result.Outcome==GameOutcome.Victory?AudioCue.Victory:AudioCue.Defeat,"result:"+result.SessionId);
- if(result.Outcome==GameOutcome.Victory)GameAudio.Sound(AudioCue.Coin_Reward,"coin:"+result.SessionId);
- ClearFeedbackVisuals(); Pause.SetVisible(false); Result.Present(result); Refresh();
- }
- private void LateUpdate() { Refresh(); if (Application.isPlaying) visuals.Advance(Time.unscaledDeltaTime); }
- public void Refresh()
- {
- if (!this || flow == null || runtime == null) return;
- if (hintBoard != null && visualClock.Seconds >= hintUntil) ClearHint();
- var timer = runtime.Timer; var score = runtime.Score; var level = runtime.Session.Definition;
- ModeLabel.text = UIManager.ModeName(level.Mode) + "\nLEVEL " + level.Level + " / 20";
- TimerLabel.text = HudFormatting.Time(timer.HasTimer, timer.RemainingTime);
- IsLowTime = timer.IsLowTime; TimerLabel.color = IsLowTime ? UIBuilder.Hex("FF8EA0") : UIBuilder.LightGold;
- TimeFraction = timer.HasTimer && timer.TimeBarMax > 0 ? Mathf.Clamp01((float)(timer.RemainingTime / timer.TimeBarMax)) : 1;
- SetFraction(TimeFill, TimeFraction); TimeFill.color = IsLowTime ? UIBuilder.Hex("FF4D6A") : Accent(level.Mode);
- int comboCount = score.ComboCount, multiplier = score.CurrentMultiplier;
- int pairs = runtime.Session.Board.RemainingTileCount / 2;
- if (score.TotalScore != observedScore) { observedScore = score.TotalScore; visuals.Emphasize(ScoreLabel); }
- if (pairs != observedPairs) { if (pairs < observedPairs) visuals.Emphasize(PairsLabel, .035f); observedPairs = pairs; }
- if (comboCount != observedCombo)
- {
- if (comboCount > observedCombo) visuals.Emphasize(ComboLabel, .04f + .008f * Mathf.Min(5, multiplier));
- else if (comboCount == 0) visuals.ResetPulse(ComboLabel);
- observedCombo = comboCount;
- }
- ComboLabel.color = score.IsInCombo ? Color.Lerp(UIBuilder.Gold, UIBuilder.LightGold, Mathf.Clamp01(multiplier / 5f)) : UIBuilder.LightGold;
- ScoreLabel.text = "SCORE " + score.TotalScore.ToString("N0", CultureInfo.InvariantCulture);
- ComboLabel.text = "COMBO ×" + Math.Max(1, score.CurrentMultiplier);
- ComboStateLabel.text = score.IsInCombo ? "COMBO ACTIVE" : "READY";
- ComboStateLabel.color = score.IsInCombo ? UIBuilder.Hex("34E0FF") : UIBuilder.Muted;
- SetFraction(ComboFill, (float)(score.ComboRemainingTime / SessionScore.ComboWindowSeconds));
- PairsLabel.text = "PAIRS LEFT " + runtime.Session.Board.RemainingTileCount / 2;
- bool available = flow.State == GameFlowState.Running && !runtime.IsFinished && !runtime.Interaction.IsLocked;
- PauseButton.interactable = flow.State == GameFlowState.Running;
- for (int i = 0; i < ItemButtons.Length; i++)
- {
- int count = flow.Economy.Inventory.GetCount((ItemType)i);
- ItemButtons[i].GetComponentInChildren<Text>(true).text = (i == 0 ? "HINT" : i == 1 ? "SHUFFLE" : "+30 SECONDS") + "\n" + count;
- ItemButtons[i].interactable = available && count > 0 && (i != 2 || timer.HasTimer);
- }
- }
- public static Color Accent(GameMode mode) => mode == GameMode.Classic ? UIBuilder.Gold : mode == GameMode.TimeAttack ? UIBuilder.Hex("FF2E9A") : UIBuilder.Hex("34E0FF");
- private static void SetFraction(Image image, float fraction)
- { var r = image.rectTransform; r.anchorMax = new Vector2(Mathf.Clamp01(fraction), 1); }
- public ItemUseResult TryUse(ItemType type)
- {
- if (flow == null) return new ItemUseResult(ItemUseStatus.GameNotRunning);
- var result = type == ItemType.Hint ? flow.Items.TryUseHint() : type == ItemType.Shuffle ? flow.Items.TryUseShuffle() : flow.Items.TryUseTime();
- FeedbackLabel.text = result.Succeeded ? type == ItemType.Hint ? "CONNECT THE HIGHLIGHTED PAIR" : type == ItemType.Shuffle ? "BOARD SHUFFLED" : "+30 SECONDS" :
- result.Status == ItemUseStatus.InsufficientInventory ? "NO ITEMS AVAILABLE" : result.Status == ItemUseStatus.UnsupportedMode ? "ZEN HAS NO TIMER" :
- result.Status == ItemUseStatus.InteractionLocked ? "WAIT FOR TILES TO SETTLE" : result.Status == ItemUseStatus.NoAvailablePair ? "NO AVAILABLE PAIR" : "ITEM UNAVAILABLE";
- Refresh(); return result;
- }
- private void ShowHint(HintInfo hint)
- {
- if (runtime == null || flow.State != GameFlowState.Running || hint.SessionId != runtime.Session.Id) return;
- ClearHint(); hintBoard = runtime.Session.Board; firstHint = hint.FirstId; secondHint = hint.SecondId;
- hintUntil = visualClock.Seconds + HintInfo.DurationSeconds;
- view.FindTile(firstHint)?.SetHinted(true); view.FindTile(secondHint)?.SetHinted(true);
- }
- private void ClearHint()
- {
- if (hintBoard != null && view && ReferenceEquals(view.Data, hintBoard))
- { view.FindTile(firstHint)?.SetHinted(false); view.FindTile(secondHint)?.SetHinted(false); }
- hintBoard = null;
- }
- private void ShowMatchPoints(PairMatch pair)
- {
- if (pendingPoints <= 0 || flow == null || flow.State != GameFlowState.Running || !view || !view.BoardRoot ||
- !ReferenceEquals(view.Data, runtime.Session.Board) || visualizedTiles.Contains(pair.First.Id) || visualizedTiles.Contains(pair.Second.Id)) return;
- visualizedTiles.Add(pair.First.Id); visualizedTiles.Add(pair.Second.Id);
- int points = pendingPoints; pendingPoints = 0;
- var layout = view.CurrentLayout;
- var board = view.BoardRoot;
- var offset = layout.TilePosition(pair.First.Row, pair.First.Column);
- var local = new Vector3(board.rect.xMin + offset.x + layout.TileSize / 2,
- board.rect.yMax + offset.y - layout.TileSize / 2, 0);
- var parent = view.transform.parent as RectTransform;
- if (parent) visuals.ShowPoints(ScoreLabel, parent, board.TransformPoint(local),
- layout.TileSize * board.lossyScale.x / Mathf.Max(.0001f, parent.lossyScale.x), points);
- }
- private void ClearFeedbackVisuals()
- { visuals.Clear(); pendingPoints = 0; ClearHint(); if (view && view.transform.parent) view.transform.parent.GetComponentInChildren<BoardPathRenderer>(true)?.Clear(); }
- private void RequestPause() { if (flow != null && flow.State == GameFlowState.Running) flow.Pause(); }
- private void Resume() { if (Pause.IsVisible) flow?.Resume(); }
- private void Restart() { if (Pause.IsVisible) flow?.RestartCurrentLevel(); }
- private void Lobby() { if (Pause.IsVisible || Result.IsVisible) flow?.ReturnToLobby(); }
- private void Next() { if (Result.IsVisible && Result.Data?.SessionId == BoundSessionId) flow?.NextLevel(); }
- private void Retry() { if (Result.IsVisible && Result.Data?.SessionId == BoundSessionId) flow?.Retry(); }
- private void UseHint() { TryUse(ItemType.Hint); }
- private void UseShuffle() { TryUse(ItemType.Shuffle); }
- private void UseTime() { TryUse(ItemType.Time); }
- public void Unbind()
- {
- visuals.Clear(); visualizedTiles.Clear(); pendingPoints = 0;
- ClearHint(); unbindRuntime?.Invoke(); unbindRuntime = null; unbindFlow?.Invoke(); unbindFlow = null;
- flow = null; runtime = null; controller = null;
- if (Pause) Pause.SetVisible(false); if (Result) Result.Clear();
- }
- private void OnDisable() { Unbind(); }
- private void OnDestroy()
- {
- Unbind();
- if (!PauseButton) return;
- PauseButton.onClick.RemoveListener(RequestPause); Pause.ResumeButton.onClick.RemoveListener(Resume); Pause.RestartButton.onClick.RemoveListener(Restart); Pause.LobbyButton.onClick.RemoveListener(Lobby);
- Result.NextButton.onClick.RemoveListener(Next); Result.RetryButton.onClick.RemoveListener(Retry); Result.LobbyButton.onClick.RemoveListener(Lobby);
- ItemButtons[0].onClick.RemoveListener(UseHint); ItemButtons[1].onClick.RemoveListener(UseShuffle); ItemButtons[2].onClick.RemoveListener(UseTime);
- }
- }
- }
|