ItemShopLedgerTests.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using DevilLink2.Core;
  6. using NUnit.Framework;
  7. namespace DevilLink2.Gameplay.Tests
  8. {
  9. public sealed class FixedUtc : IUtcClock { public DateTimeOffset UtcNow { get; set; } = new DateTimeOffset(2026,11,3,0,0,0,TimeSpan.Zero); }
  10. public sealed class ItemShopLedgerTests
  11. {
  12. private sealed class ThrowingRandom : Random
  13. { public override int Next(int value) { throw new InvalidOperationException("Injected shuffle failure"); } }
  14. private static PlayerEconomy Economy(long coins=20000,int hint=1,int shuffle=1,int time=1)
  15. => new PlayerEconomy(coins,0,new FixedUtc(),new ItemInventory(hint,shuffle,time));
  16. private static GameFlowController Flow(ManualClock clock,GameMode mode=GameMode.Classic,PlayerEconomy player=null)
  17. => new GameFlowController(mode,new ModeProgress(),player??Economy(),clock);
  18. private static Tile[] Tiles(Board b)
  19. {
  20. var result=new List<Tile>(); for(int r=0;r<b.Rows;r++) for(int c=0;c<b.Columns;c++)
  21. if(!b.IsEmpty(r,c)) result.Add(b.GetTile(r,c)); return result.ToArray();
  22. }
  23. private static int[] Layout(Board b)
  24. {
  25. var ids=new List<int>(); for(int r=0;r<b.Rows;r++)for(int c=0;c<b.Columns;c++)ids.Add(b.GetTile(r,c)?.Id??0); return ids.ToArray();
  26. }
  27. private static ItemUseResult Use(GameFlowController f,ItemType type)
  28. => type==ItemType.Hint?f.Items.TryUseHint():type==ItemType.Shuffle?f.Items.TryUseShuffle():f.Items.TryUseTime();
  29. [Test] public void DefaultInventoryAndEmptyLedgerMatchPrototype()
  30. {
  31. var p=new PlayerEconomy(clock:new FixedUtc());
  32. Assert.That(p.Inventory.GetCount(ItemType.Hint),Is.EqualTo(1)); Assert.That(p.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
  33. Assert.That(p.Inventory.GetCount(ItemType.Time),Is.Zero); Assert.That(p.Ledger.Entries.Count,Is.Zero);
  34. }
  35. [TestCase(-1,1,0)] [TestCase(1,-1,0)] [TestCase(1,1,-1)]
  36. public void NegativeInventoryIsRejected(int h,int s,int t) { Assert.Throws<ArgumentOutOfRangeException>(()=>new ItemInventory(h,s,t)); }
  37. [TestCase(ItemType.Hint,2000)] [TestCase(ItemType.Shuffle,5000)] [TestCase(ItemType.Time,3000)]
  38. public void PurchaseDeductsExactPriceAddsOneAndRecordsOneDebit(ItemType type,int price)
  39. {
  40. var p=Economy(); var shop=new ShopService(p); int before=p.Inventory.GetCount(type); var id=Guid.NewGuid();
  41. Assert.That(ShopService.Price(type),Is.EqualTo(price)); Assert.That(shop.TryBuy(type,id),Is.EqualTo(PurchaseStatus.Success));
  42. Assert.That(p.Coins,Is.EqualTo(20000-price)); Assert.That(p.Inventory.GetCount(type),Is.EqualTo(before+1));
  43. var transaction=p.Ledger.Entries.Single(); Assert.That(transaction.Id,Is.EqualTo(id)); Assert.That(transaction.Delta,Is.EqualTo(-price));
  44. Assert.That(transaction.Category,Is.EqualTo(CoinCategory.ShopPurchase)); Assert.That(transaction.TimestampUtc.Offset,Is.EqualTo(TimeSpan.Zero));
  45. Assert.That(shop.TryBuy(type,id),Is.EqualTo(PurchaseStatus.DuplicateTransaction)); Assert.That(p.Inventory.GetCount(type),Is.EqualTo(before+1));
  46. Assert.That(p.Coins,Is.EqualTo(20000-price)); Assert.That(p.Ledger.Entries.Count,Is.EqualTo(1));
  47. }
  48. [TestCase(ItemType.Hint)] [TestCase(ItemType.Shuffle)] [TestCase(ItemType.Time)]
  49. public void InsufficientFundsNeverChangeInventoryOrLedger(ItemType type)
  50. {
  51. var p=Economy(ShopService.Price(type)-1); int before=p.Inventory.GetCount(type); long coins=p.Coins;
  52. Assert.That(new ShopService(p).TryBuy(type,Guid.NewGuid()),Is.EqualTo(PurchaseStatus.InsufficientCoins));
  53. Assert.That(p.Inventory.GetCount(type),Is.EqualTo(before)); Assert.That(p.Coins,Is.EqualTo(coins)); Assert.That(p.Ledger.Entries.Count,Is.Zero);
  54. }
  55. [Test] public void InvalidPurchaseAndFullInventoryAreAtomicFailures()
  56. {
  57. var p=Economy(hint:int.MaxValue); var shop=new ShopService(p);
  58. Assert.That(shop.TryBuy(ItemType.Hint,Guid.NewGuid()),Is.EqualTo(PurchaseStatus.InventoryFull));
  59. Assert.That(shop.TryBuy((ItemType)8,Guid.NewGuid()),Is.EqualTo(PurchaseStatus.InvalidItem));
  60. Assert.That(shop.TryBuy(ItemType.Time,Guid.Empty),Is.EqualTo(PurchaseStatus.InvalidTransactionId));
  61. Assert.That(p.Coins,Is.EqualTo(20000)); Assert.That(p.Ledger.Entries.Count,Is.Zero);
  62. }
  63. [Test] public void ShoppingDoesNotPauseOrFreezeTheClock()
  64. {
  65. var c=new ManualClock(); using(var f=Flow(c))
  66. { f.Start(); new ShopService(f.Economy).TryBuy(ItemType.Time,Guid.NewGuid()); c.Seconds=1; f.Update(); Assert.That(f.State,Is.EqualTo(GameFlowState.Running)); Assert.That(f.Runtime.Timer.RemainingTime,Is.EqualTo(179)); }
  67. }
  68. [Test] public void HintReturnsRealImmutablePathWithoutChangingBoardOrSelection()
  69. {
  70. var c=new ManualClock(); using(var f=Flow(c))
  71. {
  72. f.Start(); var board=f.Runtime.Session.Board; var selected=board.GetTile(0,0); f.Click(0,0); var ids=Layout(board);
  73. int notifications=0; HintInfo published=null; f.Items.HintRequested += h=> { notifications++; published=h; };
  74. var result=f.Items.TryUseHint(); Assert.That(result.Status,Is.EqualTo(ItemUseStatus.Success));
  75. var a=Tiles(board).Single(t=>t.Id==result.Hint.FirstId); var b=Tiles(board).Single(t=>t.Id==result.Hint.SecondId);
  76. Assert.That(new LinkPathFinder().TryFindPath(board,a.Position,b.Position,out var path),Is.True); Assert.That(result.Hint.Path,Is.EqualTo(path));
  77. Assert.That(result.Hint.SessionId,Is.EqualTo(f.Runtime.Session.Id)); Assert.That(HintInfo.DurationSeconds,Is.EqualTo(1.6));
  78. Assert.That(published,Is.SameAs(result.Hint)); Assert.That(notifications,Is.EqualTo(1)); Assert.That(Layout(board),Is.EqualTo(ids));
  79. Assert.That(f.Runtime.Interaction.Selected,Is.SameAs(selected)); Assert.That(f.Runtime.Timer.IsRunning,Is.True);
  80. Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.Zero); Assert.That(f.Items.TryUseHint().Status,Is.EqualTo(ItemUseStatus.InsufficientInventory));
  81. }
  82. }
  83. [Test] public void NoHintPairDoesNotConsumeInventory()
  84. {
  85. using(var f=Flow(new ManualClock()))
  86. { f.Start(); var b=f.Runtime.Session.Board; foreach(var t in Tiles(b).Skip(1))b.RemoveTile(t); Assert.That(f.Items.TryUseHint().Status,Is.EqualTo(ItemUseStatus.NoAvailablePair)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.EqualTo(1)); }
  87. }
  88. [Test] public void ManualShuffleConservesInstancesIdsSymbolsAndAllEmptyCellsAndClearsSelection()
  89. {
  90. var c=new ManualClock(); using(var f=Flow(c))
  91. {
  92. f.Start(); var b=f.Runtime.Session.Board; new BoardMoveFinder().TryFindMove(b,out var initial);
  93. f.Click(initial.First.Row,initial.First.Column); f.Click(initial.Second.Row,initial.Second.Column); c.Seconds=.25; f.Update();
  94. var before=Tiles(b); var holes=Layout(b).Select((id,i)=>new{id,i}).Where(x=>x.id==0).Select(x=>x.i).ToArray();
  95. var selected=before[0]; f.Click(selected.Row,selected.Column); int refreshed=0; f.Runtime.Interaction.Reshuffled += _=>refreshed++;
  96. Assert.That(f.Items.TryUseShuffle().Succeeded,Is.True); var after=Tiles(b);
  97. Assert.That(after,Is.EquivalentTo(before)); Assert.That(after.Select(t=>t.Id),Is.EquivalentTo(before.Select(t=>t.Id)));
  98. Assert.That(after.Select(t=>t.Symbol),Is.EquivalentTo(before.Select(t=>t.Symbol)));
  99. Assert.That(Layout(b).Select((id,i)=>new{id,i}).Where(x=>x.id==0).Select(x=>x.i),Is.EqualTo(holes));
  100. Assert.That(after.Select(t=>t.Id).Distinct().Count(),Is.EqualTo(after.Length));
  101. Assert.That(new BoardMoveFinder().TryFindMove(b,out var move),Is.True);
  102. Assert.That(new LinkPathFinder().TryFindPath(b,move.First.Position,move.Second.Position,out _),Is.True);
  103. Assert.That(f.Runtime.Interaction.Selected,Is.Null); Assert.That(f.Runtime.Interaction.IsLocked,Is.False);
  104. Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.Zero); Assert.That(refreshed,Is.EqualTo(1));
  105. }
  106. }
  107. [Test] public void ThrowingShuffleRollsBackWithoutConsumingOrClearingSelection()
  108. {
  109. using(var f=Flow(new ManualClock()))
  110. {
  111. f.Start(); f.Click(0,0); var selected=f.Runtime.Interaction.Selected; var before=Layout(f.Runtime.Session.Board);
  112. var result=new ItemUseService(f,new ThrowingRandom()).TryUseShuffle();
  113. Assert.That(result.Status,Is.EqualTo(ItemUseStatus.OperationFailed)); Assert.That(result.Error,Is.Not.Empty);
  114. Assert.That(Layout(f.Runtime.Session.Board),Is.EqualTo(before)); Assert.That(f.Runtime.Interaction.Selected,Is.SameAs(selected));
  115. Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
  116. }
  117. }
  118. [Test] public void NoMatchingSymbolShuffleFailsWithoutConsuming()
  119. {
  120. using(var f=Flow(new ManualClock()))
  121. { f.Start(); var b=f.Runtime.Session.Board; foreach(var t in Tiles(b).Skip(1))b.RemoveTile(t); var before=Layout(b);
  122. Assert.That(f.Items.TryUseShuffle().Status,Is.EqualTo(ItemUseStatus.OperationFailed)); Assert.That(Layout(b),Is.EqualTo(before)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1)); }
  123. }
  124. [TestCase(GameMode.Classic)] [TestCase(GameMode.TimeAttack)]
  125. public void TimeAddsThirtyAndExpandsBarWithoutChangingInitialTime(GameMode mode)
  126. {
  127. using(var f=Flow(new ManualClock(),mode))
  128. { f.Start(); double initial=f.Runtime.Timer.InitialTime; Assert.That(f.Items.TryUseTime().Succeeded,Is.True);
  129. Assert.That(f.Runtime.Timer.RemainingTime,Is.EqualTo(initial+30)); Assert.That(f.Runtime.Timer.TimeBarMax,Is.EqualTo(initial+30));
  130. Assert.That(f.Runtime.Timer.InitialTime,Is.EqualTo(initial)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Time),Is.Zero); }
  131. }
  132. [Test] public void ZenAndEmptyInventoryDoNotConsumeTimeItem()
  133. {
  134. using(var f=Flow(new ManualClock(),GameMode.Zen))
  135. { f.Start(); Assert.That(f.Items.TryUseTime().Status,Is.EqualTo(ItemUseStatus.UnsupportedMode)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Time),Is.EqualTo(1)); }
  136. using(var f=Flow(new ManualClock(),player:Economy(time:0)))
  137. { f.Start(); Assert.That(f.Items.TryUseTime().Status,Is.EqualTo(ItemUseStatus.InsufficientInventory)); }
  138. }
  139. [TestCase(ItemType.Hint)] [TestCase(ItemType.Shuffle)] [TestCase(ItemType.Time)]
  140. public void ReadyPausedAndAnimationLockRejectAllItems(ItemType item)
  141. {
  142. var c=new ManualClock(); using(var f=Flow(c))
  143. {
  144. Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); f.Start(); f.Pause();
  145. Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); f.Resume();
  146. new BoardMoveFinder().TryFindMove(f.Runtime.Session.Board,out var pair); f.Click(pair.First.Row,pair.First.Column); f.Click(pair.Second.Row,pair.Second.Column);
  147. Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.InteractionLocked)); Assert.That(f.Economy.Inventory.GetCount(item),Is.EqualTo(1));
  148. }
  149. }
  150. [TestCase(ItemType.Hint)] [TestCase(ItemType.Shuffle)] [TestCase(ItemType.Time)]
  151. public void TerminalStatesRejectItemsWithoutConsuming(ItemType item)
  152. {
  153. var c=new ManualClock(); using(var f=Flow(c))
  154. { f.Start(); c.Seconds=180; Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); Assert.That(f.State,Is.EqualTo(GameFlowState.Defeat));
  155. Assert.That(f.Economy.Inventory.GetCount(item),Is.EqualTo(1)); f.ReturnToLobby(); Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); }
  156. }
  157. [Test] public void VictoryRejectsItemsAndRestartRetainsConsumedInventory()
  158. {
  159. var c=new ManualClock(); using(var f=Flow(c))
  160. {
  161. f.Start(); f.Items.TryUseHint(); f.Pause(); f.RestartCurrentLevel(); Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.Zero);
  162. while(f.State==GameFlowState.Running)
  163. { c.Seconds+=.25; f.Update(); new BoardMoveFinder().TryFindMove(f.Runtime.Session.Board,out var pair); f.Click(pair.First.Row,pair.First.Column); f.Click(pair.Second.Row,pair.Second.Column); }
  164. foreach(ItemType type in Enum.GetValues(typeof(ItemType)))Assert.That(Use(f,type).Status,Is.EqualTo(ItemUseStatus.GameNotRunning));
  165. Assert.That(f.Economy.Ledger.Entries.Single().Category,Is.EqualTo(CoinCategory.LevelVictory));
  166. Assert.That(f.Economy.Ledger.Entries.Single().Delta,Is.EqualTo(1000));
  167. }
  168. }
  169. [Test] public void ReentrantHintNotificationCannotConsumeSecondItem()
  170. {
  171. using(var f=Flow(new ManualClock(),player:Economy(hint:2)))
  172. { f.Start(); f.Items.HintRequested += _=>Assert.That(f.Items.TryUseHint().Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); f.Items.TryUseHint(); Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.EqualTo(1)); }
  173. }
  174. private sealed class IdentityRandom : Random { public override int Next(int value)=>value-1; }
  175. private sealed class PartialFailureRandom : Random
  176. {
  177. private int calls;
  178. public override int Next(int value)
  179. { if(++calls>15)throw new InvalidOperationException("Failure after a deadlocked permutation"); int i=value-1; return i>=8?15-i:i; }
  180. }
  181. private static void DeadlockFixture(GameFlowController flow)
  182. {
  183. var board=flow.Runtime.Session.Board; var original=Tiles(board);
  184. var symbols=original.Select(t=>t.Symbol).Distinct().Take(4).ToArray();
  185. var groups=symbols.Select(symbol=>new Queue<Tile>(original.Where(t=>t.Symbol==symbol))).ToArray();
  186. var chosen=new Tile[board.Rows*board.Columns]; var used=new HashSet<Tile>();
  187. for(int r=0;r<4;r++)for(int c=0;c<4;c++)
  188. { var tile=groups[(r+c)%4].Dequeue(); chosen[r*board.Columns+c]=tile; used.Add(tile); }
  189. var rest=new Queue<Tile>(original.Where(t=>!used.Contains(t)));
  190. for(int i=0;i<chosen.Length;i++)if(chosen[i]==null)chosen[i]=rest.Dequeue();
  191. // Fixture-only placement through the existing Core permutation operation.
  192. typeof(Board).GetMethod("Rearrange",BindingFlags.NonPublic|BindingFlags.Instance).Invoke(board,new object[]{chosen});
  193. foreach(var tile in Tiles(board))if(tile.Row>=4 || tile.Column>=4)board.RemoveTile(tile);
  194. Assert.That(new BoardMoveFinder().TryFindMove(board,out _),Is.False);
  195. }
  196. [Test] public void ManualShuffleUsesFortyAttemptsAndExistingDeterministicFallback()
  197. {
  198. using(var f=Flow(new ManualClock(),GameMode.TimeAttack))
  199. {
  200. f.Start(); DeadlockFixture(f); BoardShuffleResult observed=null; f.Runtime.Interaction.Reshuffled += r=>observed=r;
  201. Assert.That(new ItemUseService(f,new IdentityRandom()).TryUseShuffle().Succeeded,Is.True);
  202. Assert.That(observed.RandomAttempts,Is.EqualTo(40)); Assert.That(observed.UsedFallback,Is.True);
  203. Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.Zero);
  204. Assert.That(new LinkPathFinder().TryFindPath(f.Runtime.Session.Board,observed.Move.First.Position,observed.Move.Second.Position,out _),Is.True);
  205. }
  206. }
  207. [Test] public void AutomaticDeadlockShuffleDoesNotConsumeAnyInventory()
  208. {
  209. using(var f=Flow(new ManualClock(),GameMode.TimeAttack))
  210. {
  211. f.Start(); DeadlockFixture(f); int events=0; f.Runtime.Interaction.Reshuffled += _=>events++;
  212. typeof(DevilLink2.Interaction.BoardInteractionState).GetMethod("CheckMoves",BindingFlags.NonPublic|BindingFlags.Instance).Invoke(f.Runtime.Interaction,null);
  213. Assert.That(events,Is.EqualTo(1)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
  214. Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.EqualTo(1));
  215. Assert.That(new BoardMoveFinder().TryFindMove(f.Runtime.Session.Board,out _),Is.True);
  216. }
  217. }
  218. [Test] public void ManualFailureAfterChangedPermutationRestoresOriginalLayoutAndSelection()
  219. {
  220. using(var f=Flow(new ManualClock(),GameMode.TimeAttack))
  221. {
  222. f.Start(); DeadlockFixture(f); f.Click(0,0); var selected=f.Runtime.Interaction.Selected; var ids=Layout(f.Runtime.Session.Board);
  223. Assert.That(new ItemUseService(f,new PartialFailureRandom()).TryUseShuffle().Status,Is.EqualTo(ItemUseStatus.OperationFailed));
  224. Assert.That(Layout(f.Runtime.Session.Board),Is.EqualTo(ids)); Assert.That(f.Runtime.Interaction.Selected,Is.SameAs(selected));
  225. Assert.That(selected.Position,Is.EqualTo(new GridPosition(0,0))); Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
  226. }
  227. }
  228. [Test] public void LedgerCapsSortsAndSummarizesOnlyRetainedRecords()
  229. {
  230. var utc=new FixedUtc(); var p=new PlayerEconomy(clock:utc); var first=Guid.NewGuid();
  231. Assert.That(p.TryCredit(first,10,"first"),Is.True);
  232. for(int i=1;i<=205;i++) { utc.UtcNow=utc.UtcNow.AddSeconds(1); p.TryCredit(Guid.NewGuid(),10,"reward"); }
  233. Assert.That(p.Ledger.Entries.Count,Is.EqualTo(200)); Assert.That(p.Ledger.Income,Is.EqualTo(2000m)); Assert.That(p.Ledger.Expenses,Is.Zero);
  234. Assert.That(p.Ledger.Entries.Select(t=>t.TimestampUtc),Is.Ordered.Descending);
  235. Assert.That(p.Ledger.Entries.Any(t=>t.Id==first),Is.False); long before=p.Coins;
  236. Assert.That(p.TryCredit(first,10,"duplicate"),Is.False); Assert.That(p.Coins,Is.EqualTo(before));
  237. }
  238. [Test] public void LedgerHandlesUtcClockReversalAndSeparateIncomeExpenseTotals()
  239. {
  240. var utc=new FixedUtc(); var p=new PlayerEconomy(10000,clock:utc); var later=utc.UtcNow;
  241. p.TryCredit(Guid.NewGuid(),100,"reward"); utc.UtcNow=utc.UtcNow.AddHours(-1); new ShopService(p).TryBuy(ItemType.Hint,Guid.NewGuid());
  242. Assert.That(p.Ledger.Entries[0].TimestampUtc,Is.EqualTo(later)); Assert.That(p.Ledger.Income,Is.EqualTo(100m)); Assert.That(p.Ledger.Expenses,Is.EqualTo(2000m));
  243. Assert.That(p.Ledger.Entries.Select(t=>t.Id).Distinct().Count(),Is.EqualTo(2));
  244. }
  245. }
  246. }