GameFlowTests.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Linq;
  5. using NUnit.Framework;
  6. using TMPro;
  7. using UnityEngine;
  8. using UnityEngine.EventSystems;
  9. using UnityEngine.TestTools;
  10. using UnityEngine.UI;
  11. using Object=UnityEngine.Object;
  12. namespace HexaCrazy.Tests
  13. {
  14. public class GameFlowTests
  15. {
  16. HexGameApp app;string directory;
  17. [UnitySetUp] public IEnumerator Setup()
  18. {
  19. directory=Path.Combine(Path.GetTempPath(),"HexaCrazyPlayTests",Guid.NewGuid().ToString("N"));
  20. app=new GameObject("TestGameApp").AddComponent<HexGameApp>();app.UseReviewProfile(Path.Combine(directory,"save.json"));app.Profile.Data.reduceMotion=true;
  21. if(Object.FindAnyObjectByType<AudioListener>()==null)app.gameObject.AddComponent<AudioListener>();
  22. app.GetComponent<HexAudio>().Music=false;app.GetComponent<HexAudio>().Sound=false;
  23. yield return new WaitForSecondsRealtime(.95f);
  24. }
  25. [UnityTearDown] public IEnumerator Cleanup(){Object.Destroy(app.gameObject);yield return null;if(Directory.Exists(directory))Directory.Delete(directory,true);}
  26. Button Button(string name)=>app.Root.GetComponentsInChildren<Button>().First(b=>b.name==name);
  27. [UnityTest] public IEnumerator WheelTurnsUnderFixedPointerAndStopsOnAwardedPrize()
  28. {
  29. app.Profile.Data.reduceMotion = false;
  30. app.Profile.Data.tickets = 1;
  31. app.ShowLobby();
  32. app.OpenPanel("draw");
  33. Button("Spin").onClick.Invoke();
  34. var spin = Button("Spin");
  35. var frame = spin.transform.parent;
  36. var wheel = frame.Find("WheelAperture/PrizeWheel");
  37. var rim = frame.Find("WheelRim");
  38. var rimStart = rim.rotation;
  39. var pointer = frame.Find("PrizeIndicator");
  40. var start = wheel.localRotation;
  41. var pointerStart = pointer.rotation;
  42. var hubStart = spin.transform.rotation;
  43. Assert.False(spin.interactable);
  44. spin.onClick.Invoke();
  45. Assert.AreEqual(1, app.Profile.Data.tickets, "Repeated input during a free spin must not spend a ticket.");
  46. yield return new WaitForSecondsRealtime(.35f);
  47. Assert.Greater(Quaternion.Angle(start, wheel.localRotation), 1f);
  48. Assert.Less(Quaternion.Angle(rimStart, rim.rotation), .01f);
  49. var aperture = wheel.GetComponentInParent<Mask>();
  50. Assert.NotNull(aperture, "The spinning artwork must be clipped inside the stationary rim.");
  51. Assert.False(rim.IsChildOf(aperture.transform));
  52. Assert.Less(Quaternion.Angle(pointerStart, pointer.rotation), .01f);
  53. Assert.Less(Quaternion.Angle(hubStart, spin.transform.rotation), .01f);
  54. Assert.AreEqual(1f, spin.image.canvasRenderer.GetColor().a, .001f);
  55. float deadline = Time.realtimeSinceStartup + 5;
  56. yield return new WaitUntil(() => Button("Spin").interactable || Time.realtimeSinceStartup >= deadline);
  57. Assert.True(Button("Spin").interactable);
  58. wheel = Button("Spin").transform.parent.Find("WheelAperture/PrizeWheel");
  59. var winner = Enumerable.Range(0, wheel.childCount).Select(i => wheel.GetChild(i))
  60. .OrderByDescending(wedge => wedge.position.y).First();
  61. Assert.AreEqual(wheel.position.x, winner.position.x, .1f, "The winning sector should be centered at twelve o'clock.");
  62. var award = app.Root.GetComponentsInChildren<TextMeshProUGUI>().First(t => t.name == "ToastText");
  63. Assert.AreEqual("WON " + winner.GetComponentInChildren<TextMeshProUGUI>().text, award.text);
  64. app.Profile.Data.reduceMotion = true;
  65. Button("Spin").onClick.Invoke();
  66. yield return new WaitForSecondsRealtime(.2f);
  67. spin = Button("Spin");
  68. Assert.Zero(app.Profile.Data.tickets);
  69. Assert.False(spin.interactable);
  70. Assert.AreEqual(1f, spin.image.canvasRenderer.GetColor().a, .001f);
  71. }
  72. [UnityTest] public IEnumerator RewardedButtonsHandleUnavailableSkippedAndRepeatedCallbacks()
  73. {
  74. var ad=app.gameObject.AddComponent<TestRewardedAds>();app.Ads=ad;
  75. app.ShowLobby();app.OpenPanel("checkin");Button("Footer_CLAIM DAY 1").onClick.Invoke();
  76. Button("AdCheckin").onClick.Invoke();ad.Close();
  77. Assert.AreEqual(1700,app.Profile.Data.coins);
  78. Button("AdCheckin").onClick.Invoke();ad.Earn();ad.Earn();ad.Close();
  79. Assert.AreEqual(1900,app.Profile.Data.coins);Assert.False(app.Profile.CanClaimCheckinBonus);
  80. app.ClosePanel();app.OpenPanel("draw");const string button="Footer_WATCH AD · +1 TICKET";
  81. ad.Available=false;Button(button).onClick.Invoke();Assert.False(ad.IsShowing);
  82. Assert.False(Button(button).interactable);
  83. Assert.AreEqual(1,ad.Retries);
  84. ad.SetStatus(HexaCrazy.Ads.RewardedAdStatus.NetworkError);yield return null;
  85. Assert.True(Button(button).interactable);
  86. StringAssert.Contains("NETWORK ERROR",Button(button).GetComponentInChildren<TextMeshProUGUI>().text);
  87. Button(button).onClick.Invoke();Assert.AreEqual(2,ad.Retries);Assert.AreEqual(0,app.Profile.Data.tickets);
  88. ad.SetStatus(HexaCrazy.Ads.RewardedAdStatus.NoFill);yield return null;
  89. StringAssert.Contains("NO AD AVAILABLE",Button(button).GetComponentInChildren<TextMeshProUGUI>().text);
  90. ad.SetStatus(HexaCrazy.Ads.RewardedAdStatus.Ready);yield return null;
  91. StringAssert.Contains("WATCH AD",Button(button).GetComponentInChildren<TextMeshProUGUI>().text);
  92. ad.Available=true;Button(button).onClick.Invoke();
  93. var oldEarn=ad.Earn;var oldClose=ad.Close;
  94. Button(button).onClick.Invoke();Assert.AreSame(oldEarn,ad.Earn);
  95. ad.Close();oldEarn();Assert.AreEqual(0,app.Profile.Data.tickets);
  96. for(int i=1;i<=2;i++)
  97. {
  98. Button(button).onClick.Invoke();oldClose();Assert.True(ad.IsShowing);
  99. ad.Earn();ad.Earn();ad.Close();
  100. Assert.AreEqual(i,new LocalProfile(app.Profile.Path).Data.tickets);
  101. }
  102. Assert.True(app.Profile.FreeDraw);
  103. Button("Spin").onClick.Invoke();Assert.AreEqual(2,app.Profile.Data.tickets);
  104. yield return null;
  105. }
  106. [UnityTest] public IEnumerator TimeoutDuringMoveCanReviveOnCloseAndWinOnce()
  107. {
  108. var ad=app.gameObject.AddComponent<TestRewardedAds>();app.Ads=ad;
  109. app.Profile.Data.reduceMotion=false;app.Profile.Data.tutorial=1;
  110. app.StartLevel(1,1,true);var round=app.Game;
  111. round.Hand[0]=new HandGroup(0,1);round.Hand[1]=round.Hand[2]=null;
  112. Assert.True(app.PlaceAt(0,0));round.Time=0;
  113. yield return new WaitUntil(()=>round.Over);
  114. Assert.AreEqual(2,round.Score);Assert.True(round.Hand.All(h=>h!=null));
  115. Button("AdRevive").onClick.Invoke();ad.Close();Assert.True(round.Over);Assert.False(round.ReviveUsed);
  116. Button("AdRevive").onClick.Invoke();ad.Earn();Assert.True(round.Over);ad.Close();
  117. Assert.False(round.Over);Assert.AreSame(round,app.Game);Assert.AreEqual(30,round.Time);
  118. Assert.True(round.ReviveUsed);Assert.IsNull(app.Modal);Assert.False(app.Busy);
  119. app.Profile.Data.reduceMotion=true;round.Score=round.Spec.target-2;
  120. round.Hand[0]=new HandGroup(1,1);Assert.True(app.PlaceAt(0,1));
  121. Assert.AreEqual(1,app.Profile.Data.totalWins);Assert.True(round.Over);
  122. ad.Close();Assert.AreEqual(1,app.Profile.Data.totalWins);
  123. Assert.False(app.Modal.GetComponentsInChildren<Button>().Any(b=>b.name=="AdRevive"));
  124. }
  125. [UnityTest] public IEnumerator FullBoardOffersOnlyOneRevivePerRound()
  126. {
  127. var ad=app.gameObject.AddComponent<TestRewardedAds>();app.Ads=ad;
  128. app.StartLevel(0,1,true);
  129. foreach(var c in app.Game.Cells)c.tiles.Add(0);
  130. app.UseItem(1);Assert.True(app.Game.Over);
  131. Button("AdRevive").onClick.Invoke();ad.Earn();ad.Close();
  132. Assert.AreEqual(3,app.Game.Cells.Count(c=>c.tiles.Count==0));
  133. foreach(var c in app.Game.Cells.Where(c=>c.tiles.Count==0))c.tiles.Add(0);
  134. app.Profile.Data.items[1]++;app.UseItem(1);Assert.True(app.Game.Over);
  135. Assert.False(app.Modal.GetComponentsInChildren<Button>().Any(b=>b.name=="AdRevive"));
  136. Assert.NotNull(Button("Footer_RETRY"));yield return null;
  137. }
  138. Vector2 Position(RectTransform rect)=>RectTransformUtility.WorldToScreenPoint(null,rect.position);
  139. [UnityTest] public IEnumerator StartLobbyModesAndPanelsWork()
  140. {
  141. Assert.AreEqual("Start",app.ScreenName);Button("GameStart").onClick.Invoke();Assert.AreEqual("Lobby",app.ScreenName);
  142. Button("CoinBalance").onClick.Invoke();
  143. Assert.AreEqual("Modal_shop", app.Modal.name);
  144. app.ClosePanel();
  145. Button("NextMode").onClick.Invoke();Button("Play").onClick.Invoke();Assert.AreEqual(1,app.Game.Spec.mode);
  146. Button("Pause").onClick.Invoke();Assert.True(app.Paused);Button("Resume").onClick.Invoke();Assert.False(app.Paused);
  147. app.LeaveGame();foreach(string panel in new[]{"shop","checkin","draw","help","profile","settings"}){app.OpenPanel(panel);yield return null;Assert.NotNull(app.Modal);app.ClosePanel();Assert.IsNull(app.Modal);}
  148. }
  149. [UnityTest] public IEnumerator RealDragHandlersSurviveBeginDragAndFinishTutorial()
  150. {
  151. app.StartLevel(0,1);yield return null;
  152. var source=app.Root.GetComponentsInChildren<HandDrag>().First(h=>h.slot==0);
  153. int center=app.Game.Cells.FindIndex(c=>c.q==0&&c.r==0);int target=app.Game.Neighbors(center)[0];
  154. var e=new PointerEventData(EventSystem.current){position=Position((RectTransform)source.transform)};
  155. ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.beginDragHandler);yield return null;
  156. Assert.True(source!=null,"BeginDrag must not destroy its own receiver");
  157. e.position=Position((RectTransform)Button("Cell_"+target).transform);
  158. ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.dragHandler);ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.endDragHandler);yield return null;
  159. Assert.AreEqual(62,app.Game.Score);Assert.AreEqual(1,app.Profile.Data.tutorial);Assert.False(app.Busy);
  160. Canvas.ForceUpdateCanvases();var fill=app.Root.GetComponentInChildren<HexProgress>();Assert.Greater(fill.Value,0);Assert.Greater(fill.canvasRenderer.GetMesh().vertexCount,0,"Score progress must have a visible mesh");
  161. }
  162. [UnityTest] public IEnumerator DownwardDragReleasedOverHandSlotLeavesAllThreeSlotsUsable()
  163. {
  164. app.Profile.Data.tutorial = 1;
  165. app.StartLevel(0, 6);
  166. yield return null;
  167. var effects = app.Root.Find("Effects");
  168. var hand = app.Game.Hand.ToArray();
  169. foreach (int slot in new[] { 2, 0, 1 })
  170. {
  171. var source = app.Root.GetComponentsInChildren<HandDrag>().Single(h => h.slot == slot);
  172. var rect = (RectTransform)source.transform;
  173. var e = new PointerEventData(EventSystem.current) { position = Position(rect), eligibleForClick = true };
  174. ExecuteEvents.Execute(source.gameObject, e, ExecuteEvents.pointerDownHandler);
  175. e.position = RectTransformUtility.WorldToScreenPoint(null, rect.TransformPoint(Vector2.down * rect.rect.height * .4f));
  176. ExecuteEvents.Execute(source.gameObject, e, ExecuteEvents.beginDragHandler);
  177. e.dragging = true;
  178. ExecuteEvents.Execute(source.gameObject, e, ExecuteEvents.dragHandler);
  179. Assert.AreEqual(1, effects.childCount, "Each slot must be able to start a fresh drag");
  180. // uGUI sends a same-target click before endDrag if the gesture is still eligible.
  181. if (e.eligibleForClick)
  182. ExecuteEvents.Execute(source.gameObject, e, ExecuteEvents.pointerClickHandler);
  183. ExecuteEvents.Execute(source.gameObject, e, ExecuteEvents.endDragHandler);
  184. yield return null;
  185. Assert.AreEqual(0, effects.childCount, "Releasing below the tile must remove the preview");
  186. Assert.AreEqual(-1, app.SelectedSlot);
  187. CollectionAssert.AreEqual(hand, app.Game.Hand);
  188. source = app.Root.GetComponentsInChildren<HandDrag>().Single(h => h.slot == slot);
  189. var tap = new PointerEventData(EventSystem.current) { position = Position((RectTransform)source.transform) };
  190. ExecuteEvents.Execute(source.gameObject, tap, ExecuteEvents.pointerDownHandler);
  191. ExecuteEvents.Execute(source.gameObject, tap, ExecuteEvents.pointerClickHandler);
  192. Assert.AreEqual(slot, app.SelectedSlot);
  193. }
  194. }
  195. [UnityTest] public IEnumerator InvalidDropPreservesHandAndShopRefreshesInventory()
  196. {
  197. app.StartLevel(0,1,true);yield return null;var group=app.Game.Hand[0];app.BeginHandDrag(0,Vector2.zero);app.EndHandDrag(new Vector2(-100,-100));Assert.AreSame(group,app.Game.Hand[0]);
  198. app.Game.Cells[0].tiles.Add(0);yield return null;
  199. var source=app.Root.GetComponentsInChildren<HandDrag>().First(h=>h.slot==0);
  200. var e=new PointerEventData(EventSystem.current){position=Position((RectTransform)source.transform)};
  201. ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.beginDragHandler);
  202. e.position=Position((RectTransform)Button("Cell_0").transform);ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.endDragHandler);
  203. yield return null;Assert.AreSame(group,app.Game.Hand[0]);
  204. ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.pointerDownHandler);ExecuteEvents.Execute(source.gameObject,e,ExecuteEvents.pointerClickHandler);
  205. Assert.AreEqual(-1,app.SelectedSlot,"The next tap after an occupied-cell drop must not be swallowed");
  206. app.OpenPanel("shop");Button("BuyItem_0").onClick.Invoke();app.ClosePanel();yield return null;
  207. Assert.AreEqual(700,app.Profile.Data.coins);Assert.AreEqual("2",Button("UseItem_0").GetComponentsInChildren<TextMeshProUGUI>().First(t=>t.name=="Count").text);
  208. }
  209. [UnityTest] public IEnumerator TimerPausesAndTimeoutDoesNotPayRewards()
  210. {
  211. app.StartLevel(1,1,true);app.OpenPanel("pause");float before=app.Game.Time;yield return new WaitForSecondsRealtime(.2f);Assert.AreEqual(before,app.Game.Time,.01f);
  212. app.ClosePanel();app.Game.Time=.05f;yield return new WaitForSecondsRealtime(.15f);Assert.True(app.Game.Over);Assert.AreEqual(1500,app.Profile.Data.coins);Assert.AreEqual("Modal_result",app.Modal.name);
  213. }
  214. [UnityTest] public IEnumerator WinPaysOnceAndNextLevelAdvances()
  215. {
  216. app.StartLevel(0,1,true);app.Game.Score=app.Game.Spec.target-2;app.Game.Hand[0]=new HandGroup(0,1);
  217. Assert.True(app.PlaceAt(0,0));yield return null;Assert.True(app.Game.Over);Assert.AreEqual(1,app.Profile.Data.totalWins);Assert.AreEqual(1660,app.Profile.Data.coins);Assert.AreEqual(1,app.Profile.Data.tickets);
  218. Assert.False(app.PlaceAt(1,1));Assert.AreEqual(1660,app.Profile.Data.coins);Button("Footer_NEXT LEVEL").onClick.Invoke();Assert.AreEqual(2,app.Game.Spec.level);
  219. }
  220. [UnityTest] public IEnumerator AllLevelViewsStayInsideDesignCanvasAndTextRenders()
  221. {
  222. for(int mode=0;mode<3;mode++)foreach(int level in new[]{1,7,20})
  223. {
  224. app.StartLevel(mode,level,true);yield return null;Canvas.ForceUpdateCanvases();
  225. foreach(var b in app.Root.GetComponentsInChildren<Button>().Where(b=>b.name.StartsWith("Cell_")))
  226. {var rt=(RectTransform)b.transform;Assert.Greater(rt.anchoredPosition.x-rt.rect.width/2,0);Assert.Less(rt.anchoredPosition.x+rt.rect.width/2,750);Assert.Greater(-rt.anchoredPosition.y-rt.rect.height/2,250);Assert.Less(-rt.anchoredPosition.y+rt.rect.height/2,935);}
  227. foreach(var text in app.Root.GetComponentsInChildren<TextMeshProUGUI>().Where(t=>!string.IsNullOrEmpty(t.text)))
  228. {text.ForceMeshUpdate();Assert.Greater(text.textInfo.characterCount,0,"Empty text mesh: "+text.name+" / "+text.text);}
  229. }
  230. }
  231. [UnityTest] public IEnumerator CarouselAnimatesExistingCardsAndCanRetargetWithoutRebuilding()
  232. {
  233. app.Profile.Data.reduceMotion=false;app.ShowLobby();yield return null;
  234. var center=(RectTransform)Button("ModeCard0").transform;var next=(RectTransform)Button("ModeCard1").transform;int instance=center.GetInstanceID();
  235. var carousel=app.Root.GetComponentInChildren<HexLobbyCarousel>();float start=next.anchoredPosition.x;
  236. Button("NextMode").onClick.Invoke();Assert.True(carousel.IsAnimating);Assert.AreEqual(1,app.SelectedMode);
  237. yield return new WaitForSecondsRealtime(.08f);
  238. Assert.Less(next.anchoredPosition.x,start);Assert.Greater(next.anchoredPosition.x,375);Assert.AreEqual(instance,Button("ModeCard0").transform.GetInstanceID());
  239. Button("NextMode").onClick.Invoke();Button("NextMode").onClick.Invoke();Assert.AreEqual(0,app.SelectedMode);
  240. yield return new WaitForSecondsRealtime(.47f);
  241. Assert.False(carousel.IsAnimating);Assert.AreEqual(375,center.anchoredPosition.x,.01f);Assert.AreEqual(1,center.localScale.x,.001f);
  242. Assert.AreEqual(HexLobbyCarousel.SideScale,next.localScale.x,.001f);Assert.AreEqual(.5f,next.GetComponent<CanvasGroup>().alpha,.001f);
  243. Button("ModeCard0").onClick.Invoke();Assert.AreEqual("Game",app.ScreenName);Assert.AreEqual(0,app.Game.Spec.mode);
  244. }
  245. [UnityTest] public IEnumerator CarouselSwipeDotsAndPlayUseTheSelectedMode()
  246. {
  247. app.Profile.Data.cleared[1]=6;app.Profile.Data.cleared[2]=20;app.ShowLobby();yield return null;
  248. var carousel=app.Root.GetComponentInChildren<HexLobbyCarousel>();
  249. var e=new PointerEventData(EventSystem.current){position=Position((RectTransform)carousel.transform)};var start=e.position;
  250. ExecuteEvents.Execute(carousel.gameObject,e,ExecuteEvents.beginDragHandler);e.position=start+new Vector2(-150,0);ExecuteEvents.Execute(carousel.gameObject,e,ExecuteEvents.endDragHandler);
  251. Assert.AreEqual(1,app.SelectedMode);Button("Play").onClick.Invoke();Assert.AreEqual(1,app.Game.Spec.mode);Assert.AreEqual(7,app.Game.Spec.level);
  252. app.LeaveGame();Button("ModeDot2").onClick.Invoke();Assert.AreEqual("REPLAY",Button("Play").GetComponentInChildren<TextMeshProUGUI>().text);
  253. Button("Play").onClick.Invoke();Assert.AreEqual(2,app.Game.Spec.mode);Assert.AreEqual(20,app.Game.Spec.level);
  254. }
  255. [UnityTest] public IEnumerator SpriteMeshesKeepTheirNativeAspectAcrossScreensAndPanels()
  256. {
  257. app.ShowLobby();yield return null;CheckImageMeshes();
  258. app.StartLevel(2,1,true);yield return null;CheckImageMeshes();
  259. foreach(var panel in new[]{"shop","draw","profile","settings"}){app.OpenPanel(panel);yield return null;CheckImageMeshes();app.ClosePanel();}
  260. }
  261. void CheckImageMeshes()
  262. {
  263. Canvas.ForceUpdateCanvases();
  264. foreach(var im in app.Root.GetComponentsInChildren<Image>().Where(i=>i.sprite!=null))
  265. {
  266. if(HexUI.Resizable(im.sprite.name)){Assert.AreEqual(Image.Type.Sliced,im.type,im.name);Assert.Greater(im.sprite.border.sqrMagnitude,0);continue;}
  267. Assert.True(im.preserveAspect,im.name+" must retain native aspect");var mesh=im.canvasRenderer.GetMesh();if(mesh==null||mesh.vertexCount==0)continue;
  268. var v=mesh.vertices;float w=v.Max(p=>p.x)-v.Min(p=>p.x),h=v.Max(p=>p.y)-v.Min(p=>p.y);
  269. // Unity trims transparent sprite padding. Compare geometry to sampled texels,
  270. // not the full source rectangle, so the test measures actual deformation.
  271. var uv=mesh.uv;float pixelsWide=(uv.Max(p=>p.x)-uv.Min(p=>p.x))*im.mainTexture.width,pixelsHigh=(uv.Max(p=>p.y)-uv.Min(p=>p.y))*im.mainTexture.height;
  272. Assert.AreEqual(pixelsWide/pixelsHigh,w/h,.025f,"Stretched mesh: "+im.name);
  273. }
  274. }
  275. }
  276. }