using System; using System.IO; using System.Linq; using System.Reflection; using DevilLink2.Core; using DevilLink2.Gameplay; using DevilLink2.Persistence; using DevilLink2.Presentation; using DevilLink2.UI; using NUnit.Framework; using UnityEditor; using UnityEngine; using UnityEngine.UI; using Object=UnityEngine.Object; namespace DevilLink2.Tests { public sealed partial class GameHUDTests { private sealed class Clock : IMonotonicClock { public double Seconds {get;set;} } private sealed class Utc : IUtcClock { public DateTimeOffset UtcNow=>new DateTimeOffset(2026,11,3,12,0,0,TimeSpan.Zero); } private GameObject root; private RectTransform frame; private BoardView view; private BoardInteractionController interaction; private BoardDemoBootstrap bootstrap; private SavedPlayer player; private UIManager ui; private GameHUD hud; private GameFlowController flow; private Clock clock; private string directory; [SetUp] public void Setup() { directory=Path.Combine(Path.GetTempPath(),"DevilLink2.HUDTests",Guid.NewGuid().ToString("N")); var saves=new LocalSaveService(new FileSaveStorage(directory)); saves.Save(new SaveData{TimeCount=3}); player=new SavedPlayer(saves,new Utc()); root=new GameObject("HUDTestCanvas",typeof(RectTransform),typeof(Canvas)); root.GetComponent().renderMode=RenderMode.ScreenSpaceOverlay; frame=UIBuilder.Rect("Frame",root.transform,0,0,430,932); var viewport=UIBuilder.Rect("BoardViewport",frame,6,60,418,860); var content=UIBuilder.Rect("Content",viewport,0,0,418,860); var board=UIBuilder.Rect("Board",content,0,0,418,385); var prefab=AssetDatabase.LoadAssetAtPath("Assets/DevilLink2/Prefabs/Gameplay/TileView.prefab"); view=viewport.gameObject.AddComponent(); view.Configure(prefab.GetComponent(),viewport,content,board); bootstrap=root.AddComponent(); bootstrap.Configure(view); interaction=root.AddComponent(); ui=UIBuilder.Build(frame,bootstrap,view); ui.Initialize(player,bootstrap); hud=ui.Hud; clock=new Clock(); } [TearDown] public void Cleanup() { Object.DestroyImmediate(root); player.Dispose(); string expected=Path.GetFullPath(Path.Combine(Path.GetTempPath(),"DevilLink2.HUDTests"))+Path.DirectorySeparatorChar; string target=Path.GetFullPath(directory); if(!target.StartsWith(expected,StringComparison.OrdinalIgnoreCase)||!Guid.TryParseExact(Path.GetFileName(target),"N",out _))throw new InvalidOperationException("Unsafe cleanup path"); if(Directory.Exists(target))Directory.Delete(target,true); } private void Bind(GameMode mode=GameMode.Classic,int level=1) { if(level>1)player.Progress.RecordClear(mode,level-1); flow=player.CreateFlow(mode,clock); ui.Gameplay.SetVisible(true); view.Show(flow.Runtime.Session.Board); interaction.Initialize(view,flow); hud.SetVisualClock(clock); hud.Bind(flow,interaction); flow.Start(); hud.Refresh(); } private void Match() { clock.Seconds+=.25; flow.Update(); Assert.That(new BoardMoveFinder().TryFindMove(flow.Runtime.Session.Board,out var pair),Is.True); flow.Click(pair.First.Row,pair.First.Column); flow.Click(pair.Second.Row,pair.Second.Column); hud.Refresh(); } private void Win() { while(flow.State==GameFlowState.Running)Match(); Assert.That(flow.State,Is.EqualTo(GameFlowState.Victory)); } private static T Signal(object source,string name) where T:class => source.GetType().GetField(name,BindingFlags.NonPublic|BindingFlags.Instance).GetValue(source) as T; [TestCase(GameMode.Classic,"03:00",true)] [TestCase(GameMode.TimeAttack,"02:00",true)] [TestCase(GameMode.Zen,"∞",false)] public void HudUsesRealModeTimeScoreAndInventory(GameMode mode,string timer,bool timeEnabled) { Bind(mode); Assert.That(hud.TimerLabel.text,Is.EqualTo(timer)); Assert.That(hud.ModeLabel.text,Does.Contain(UIManager.ModeName(mode))); Assert.That(hud.ScoreLabel.text,Is.EqualTo("SCORE 0")); Assert.That(hud.ComboLabel.text,Does.Contain("×1")); Assert.That(hud.ItemButtons[0].GetComponentInChildren().text,Does.Contain("1")); Assert.That(hud.ItemButtons[2].GetComponentInChildren().text,Does.Contain("3")); Assert.That(hud.ItemButtons[2].interactable,Is.EqualTo(timeEnabled)); Assert.That(hud.TimeFraction,Is.EqualTo(1)); } [Test] public void ScoresAndComboWindowRefreshWithoutUiScoringLogic() { Bind(); Match(); Assert.That(hud.ScoreLabel.text,Does.Contain("100")); Assert.That(hud.ItemButtons.All(b=>!b.interactable),Is.True); Match(); Assert.That(hud.ScoreLabel.text,Does.Contain("300")); Assert.That(hud.ComboLabel.text,Does.Contain("×2")); clock.Seconds+=4.01; flow.Update(); hud.Refresh(); Assert.That(hud.ComboStateLabel.text,Is.EqualTo("READY")); Assert.That(hud.ComboLabel.text,Does.Contain("×1")); } [Test] public void WarningTimeBarAndSuccessfulTimeItemFollowTimer() { Bind(); hud.ItemButtons[2].onClick.Invoke(); Assert.That(hud.TimerLabel.text,Is.EqualTo("03:30")); Assert.That(flow.Runtime.Timer.TimeBarMax,Is.EqualTo(210)); clock.Seconds=200; flow.Update(); hud.Refresh(); Assert.That(hud.IsLowTime,Is.True); Assert.That(hud.TimeFraction,Is.EqualTo(10f/210).Within(.0001)); hud.ItemButtons[2].onClick.Invoke(); Assert.That(hud.IsLowTime,Is.False); Assert.That(hud.TimerLabel.text,Is.EqualTo("00:40")); Assert.That(flow.Economy.Inventory.GetCount(ItemType.Time),Is.EqualTo(1)); } [Test] public void HintExpiresAfterOnePointSixSecondsWithoutChangingSelectionOrBoard() { Bind(); new BoardMoveFinder().TryFindMove(view.Data,out var pair); flow.Click(pair.First.Row,pair.First.Column); var selected=flow.Runtime.Interaction.Selected; int before=view.Data.RemainingTileCount; Assert.That(hud.TryUse(ItemType.Hint).Succeeded,Is.True); Assert.That(view.FindTile(pair.First.Id).IsHinted,Is.True); Assert.That(view.FindTile(pair.Second.Id).IsHinted,Is.True); clock.Seconds=1.59; hud.Refresh(); Assert.That(view.FindTile(pair.First.Id).IsHinted,Is.True); clock.Seconds=1.6; hud.Refresh(); Assert.That(view.FindTile(pair.First.Id).IsHinted,Is.False); Assert.That(view.FindTile(pair.Second.Id).IsHinted,Is.False); Assert.That(flow.Runtime.Interaction.Selected,Is.SameAs(selected)); Assert.That(view.Data.RemainingTileCount,Is.EqualTo(before)); Assert.That(hud.ItemButtons[0].interactable,Is.False); } [Test] public void ShuffleUsesServiceClearsHintAndRetainsCount() { Bind(); hud.TryUse(ItemType.Hint); int before=view.Data.RemainingTileCount; Assert.That(hud.TryUse(ItemType.Shuffle).Succeeded,Is.True); Assert.That(view.VisibleTileCount,Is.EqualTo(before)); Assert.That(view.BoardRoot.GetComponentsInChildren().Any(t=>t.IsHinted),Is.False); Assert.That(flow.Runtime.Interaction.Selected,Is.Null); Assert.That(hud.ItemButtons[1].interactable,Is.False); } [Test] public void PauseResumePreserveBoardAndScoreWhileComboExpires() { Bind(); Match(); var board=view.Data; var score=flow.Runtime.Score.TotalScore; hud.PauseButton.onClick.Invoke(); Assert.That(hud.Pause.IsVisible,Is.True); double remaining=flow.Runtime.Timer.RemainingTime; clock.Seconds+=10; flow.Update(); hud.Refresh(); Assert.That(flow.Runtime.Timer.RemainingTime,Is.EqualTo(remaining)); Assert.That(hud.ComboStateLabel.text,Is.EqualTo("READY")); Assert.That(hud.ItemButtons.All(b=>!b.interactable),Is.True); Assert.That(flow.Click(0,0),Is.EqualTo(DevilLink2.Interaction.TileClickResult.Ignored)); hud.Pause.ResumeButton.onClick.Invoke(); Assert.That(flow.State,Is.EqualTo(GameFlowState.Running)); Assert.That(hud.Pause.IsVisible,Is.False); Assert.That(view.Data,Is.SameAs(board)); Assert.That(flow.Runtime.Score.TotalScore,Is.EqualTo(score)); } [Test] public void RestartRebindsNewSessionAndOldEventsCannotMutateHud() { Bind(); Match(); var old=flow.Runtime; var oldTime=Signal>(old.Timer,"RemainingTimeChanged"); var oldScore=Signal>(old.Score,"MatchScored"); var sessionSignal=Signal>(flow,"SessionChanged"); hud.PauseButton.onClick.Invoke(); hud.Pause.RestartButton.onClick.Invoke(); var current=flow.Runtime; Assert.That(current.Session.Id,Is.Not.EqualTo(old.Session.Id)); Assert.That(hud.BoundSessionId,Is.EqualTo(current.Session.Id)); Assert.That(hud.Result.IsVisible||hud.Pause.IsVisible,Is.False); oldTime(0); oldScore(999); sessionSignal(old); hud.Refresh(); Assert.That(hud.BoundSessionId,Is.EqualTo(current.Session.Id)); Assert.That(hud.ScoreLabel.text,Is.EqualTo("SCORE 0")); Assert.That(hud.TimerLabel.text,Is.EqualTo("03:00")); Assert.That(view.Data,Is.SameAs(current.Session.Board)); } [Test] public void VictoryReadsOneImmutableResultAndNextDoesNotDuplicateReward() { Bind(); Win(); var result=flow.Result; long coins=flow.Economy.Coins; int shown=hud.Result.PresentationCount; Assert.That(hud.Result.Data,Is.SameAs(result)); Assert.That(hud.Result.IsVisible,Is.True); Assert.That(hud.Result.ScoreLabel.text,Does.Contain(result.FinalScore.ToString("N0",System.Globalization.CultureInfo.InvariantCulture))); Assert.That(hud.Result.RewardsLabel.text,Does.Contain("1,000")); Assert.That(hud.ItemButtons.All(b=>!b.interactable),Is.True); var settle=Signal>(flow,"Settled"); settle(result); settle(result); Assert.That(hud.Result.PresentationCount,Is.EqualTo(shown)); Assert.That(flow.Economy.Coins,Is.EqualTo(coins)); hud.Result.NextButton.onClick.Invoke(); var id=flow.Runtime.Session.Id; hud.Result.NextButton.onClick.Invoke(); Assert.That(flow.Runtime.Session.Definition.Level,Is.EqualTo(2)); Assert.That(flow.Runtime.Session.Id,Is.EqualTo(id)); Assert.That(flow.Economy.Coins,Is.EqualTo(coins)); Assert.That(hud.Result.IsVisible,Is.False); settle(result); Assert.That(hud.Result.IsVisible,Is.False); Assert.That(hud.ScoreLabel.text,Is.EqualTo("SCORE 0")); } [Test] public void DefeatHidesRewardsAndNextAndRetryKeepsCurrentLevel() { Bind(GameMode.TimeAttack,4); Match(); clock.Seconds=500; flow.Update(); hud.Refresh(); Assert.That(hud.Result.IsVisible,Is.True); Assert.That(hud.Result.Data.Outcome,Is.EqualTo(GameOutcome.Defeat)); Assert.That(hud.Result.NextButton.gameObject.activeSelf,Is.False); Assert.That(hud.Result.RewardsLabel.gameObject.activeSelf,Is.False); Assert.That(hud.Result.RewardsLabel.text,Is.Empty); Assert.That(flow.Economy.Coins,Is.EqualTo(2000)); hud.Result.RetryButton.onClick.Invoke(); Assert.That(flow.Runtime.Session.Definition.Level,Is.EqualTo(4)); Assert.That(hud.TimerLabel.text,Is.EqualTo("01:48")); Assert.That(flow.Runtime.Score.TotalScore,Is.Zero); } [Test] public void LevelTwentyReplaysAndEachVictoryReceivesOnlyItsConfiguredReward() { Bind(GameMode.Classic,20); Win(); Assert.That(hud.Result.NextButton.GetComponentInChildren(true).text,Is.EqualTo("REPLAY LEVEL 20")); Assert.That(flow.Economy.Coins,Is.EqualTo(7000)); hud.Result.NextButton.onClick.Invoke(); Assert.That(flow.Runtime.Session.Definition.Level,Is.EqualTo(20)); Win(); Assert.That(flow.Economy.Coins,Is.EqualTo(12000)); Assert.That(flow.Economy.SpinTickets,Is.EqualTo(2)); } [Test] public void UnbindRemovesRuntimeObserversAndRebindingDoesNotMultiplyThem() { Bind(); var timer=flow.Runtime.Timer; int count=Signal>(timer,"RemainingTimeChanged").GetInvocationList().Length; hud.Bind(flow,interaction); Assert.That(Signal>(timer,"RemainingTimeChanged").GetInvocationList().Length,Is.EqualTo(count)); hud.Unbind(); Assert.That(Signal>(timer,"RemainingTimeChanged"),Is.Null); Assert.That(hud.BoundSessionId,Is.EqualTo(Guid.Empty)); hud.Bind(flow,interaction); Assert.That(Signal>(timer,"RemainingTimeChanged").GetInvocationList().Length,Is.EqualTo(count)); } [Test] public void ModalDimensionsAndReturnToLobbyDoNotCreditRewards() { Bind(); Assert.That(hud.Pause.transform.Find("Card").GetComponent().sizeDelta.x,Is.EqualTo(330)); Assert.That(hud.Result.transform.Find("Card").GetComponent().sizeDelta.x,Is.EqualTo(400)); hud.PauseButton.onClick.Invoke(); hud.Pause.LobbyButton.onClick.Invoke(); Assert.That(flow.State,Is.EqualTo(GameFlowState.Abandoned)); Assert.That(flow.Result,Is.Null); Assert.That(flow.Economy.Coins,Is.EqualTo(2000)); Assert.That(flow.Economy.SpinTickets,Is.Zero); } [Test] public void PopupReadsActualPointsAndDuplicateEventsAreIgnored() { Bind(); DevilLink2.Interaction.PairMatch accepted=null; flow.Runtime.Interaction.Matched+=pair=>accepted=pair; Match(); Assert.That(hud.Visuals.LastPopupPoints,Is.EqualTo(100)); int count=hud.Visuals.PopupCount, pulses=hud.Visuals.PulseRequests; Signal>(flow.Runtime.Score,"MatchScored")(999); Signal>(flow.Runtime.Interaction,"Matched")(accepted); hud.Refresh(); Assert.That(hud.Visuals.PopupCount,Is.EqualTo(count)); Assert.That(hud.Visuals.PulseRequests,Is.EqualTo(pulses)); Match(); Assert.That(hud.Visuals.LastPopupPoints,Is.EqualTo(200)); Assert.That(flow.Runtime.Score.TotalScore,Is.EqualTo(300)); } [Test] public void PopupLimitExpiryAndClickThroughAreSafe() { Bind(); Match(); for(int i=0;i<8;i++)hud.Visuals.ShowPoints(hud.ScoreLabel,frame,Vector3.zero,42,hud.Visuals.LastPopupPoints); Assert.That(hud.Visuals.PopupCount,Is.EqualTo(ScoreFeedbackVisuals.MaxPopups)); Assert.That(frame.GetComponentsInChildren().Where(t=>t.name=="MatchScorePopup").All(t=>!t.raycastTarget),Is.True); long score=flow.Runtime.Score.TotalScore; hud.Visuals.Advance(ScoreFeedbackVisuals.PopupSeconds); Assert.That(hud.Visuals.PopupCount,Is.Zero); Assert.That(flow.Runtime.Score.TotalScore,Is.EqualTo(score)); Assert.That(frame.GetComponentsInChildren(true).Any(t=>t.name=="MatchScorePopup"),Is.False); } [Test] public void HudEmphasizesChangesOnlyAndComboExpiryRestoresScale() { Bind(); int pulses=hud.Visuals.PulseRequests; Match(); Assert.That(hud.Visuals.PulseRequests-pulses,Is.EqualTo(3)); pulses=hud.Visuals.PulseRequests; hud.Refresh(); hud.Refresh(); Assert.That(hud.Visuals.PulseRequests,Is.EqualTo(pulses)); clock.Seconds+=5; flow.Update(); hud.Refresh(); Assert.That(hud.ComboStateLabel.text,Is.EqualTo("READY")); Assert.That(hud.ComboLabel.transform.localScale,Is.EqualTo(Vector3.one)); Assert.That(hud.Visuals.PulseRequests,Is.EqualTo(pulses)); } [Test] public void PauseResumeAndLobbyCleanFloatingFeedback() { Bind(); Match(); var board=view.Data; long score=flow.Runtime.Score.TotalScore; hud.PauseButton.onClick.Invoke(); Assert.That(hud.Visuals.PopupCount,Is.Zero); hud.Pause.ResumeButton.onClick.Invoke(); Assert.That(hud.Visuals.PopupCount,Is.Zero); Assert.That(view.Data,Is.SameAs(board)); Assert.That(flow.Runtime.Score.TotalScore,Is.EqualTo(score)); hud.PauseButton.onClick.Invoke(); hud.Pause.LobbyButton.onClick.Invoke(); Assert.That(hud.Visuals.PopupCount,Is.Zero); } [Test] public void QueuedOldSessionCallbacksCannotCreateFeedback() { Bind(); DevilLink2.Interaction.PairMatch accepted=null; flow.Runtime.Interaction.Matched+=pair=>accepted=pair; Match(); var score=Signal>(flow.Runtime.Score,"MatchScored"); var matched=Signal>(flow.Runtime.Interaction,"Matched"); hud.PauseButton.onClick.Invoke(); hud.Pause.RestartButton.onClick.Invoke(); score(999); matched(accepted); hud.Refresh(); Assert.That(hud.Visuals.PopupCount,Is.Zero); Assert.That(hud.ScoreLabel.text,Is.EqualTo("SCORE 0")); } [Test] public void VictoryRewardEmphasisOccursOnceAndRetryCleansIt() { Bind(); Win(); var result=flow.Result; long balance=flow.Economy.Coins; Assert.That(hud.Result.RewardEmphasisCount,Is.EqualTo(1)); Signal>(flow,"Settled")(result); Assert.That(hud.Result.RewardEmphasisCount,Is.EqualTo(1)); Assert.That(flow.Economy.Coins,Is.EqualTo(balance)); hud.Result.RetryButton.onClick.Invoke(); Assert.That(hud.Visuals.PopupCount,Is.Zero); Assert.That(hud.Result.ScoreLabel.transform.localScale,Is.EqualTo(Vector3.one)); } [Test] public void DefeatDoesNotPlayVictoryRewardFeedback() { Bind(); clock.Seconds=1000; flow.Update(); Assert.That(hud.Result.Data.Outcome,Is.EqualTo(GameOutcome.Defeat)); Assert.That(hud.Result.RewardEmphasisCount,Is.Zero); Assert.That(hud.Result.RewardsLabel.text,Is.Empty); } [Test] public void MissingResourcesAndUnbindSafelyClearFeedback() { using(var visuals=new ScoreFeedbackVisuals()) { visuals.ShowPoints(null,frame,Vector3.zero,42,100); visuals.Emphasize(null); Assert.That(visuals.PopupCount,Is.Zero); } Bind(); Match(); hud.Unbind(); Assert.That(hud.Visuals.PopupCount,Is.Zero); } [Test] public void PauseAndResumeTransitionsDoNotChangeSessionOrAdvancePausedTime() { Bind();Match();var id=flow.Runtime.Session.Id;double remaining=flow.Runtime.Timer.RemainingTime; hud.PauseButton.onClick.Invoke();Assert.That(UITransition.IsVisible(hud.Pause.gameObject),Is.True); clock.Seconds+=10;flow.Update();Assert.That(flow.Runtime.Timer.RemainingTime,Is.EqualTo(remaining)); hud.Pause.ResumeButton.onClick.Invoke();hud.Pause.ResumeButton.onClick.Invoke(); Assert.That(flow.Runtime.Session.Id,Is.EqualTo(id));Assert.That(flow.State,Is.EqualTo(GameFlowState.Running)); Assert.That(UITransition.IsVisible(hud.Pause.gameObject),Is.False); } [Test] public void RestartAndOldSettlementDoNotReopenTransitionedResult() { Bind();Win();var old=flow.Result;var settle=Signal>(flow,"Settled"); hud.Result.RetryButton.onClick.Invoke();settle(old);Assert.That(hud.Result.IsVisible,Is.False); Assert.That(hud.Result.GetComponent().IsShown,Is.False); Assert.That(hud.BoundSessionId,Is.Not.EqualTo(old.SessionId)); } } }