| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using DevilLink2.Core;
- using NUnit.Framework;
- namespace DevilLink2.Gameplay.Tests
- {
- public sealed class FixedUtc : IUtcClock { public DateTimeOffset UtcNow { get; set; } = new DateTimeOffset(2026,11,3,0,0,0,TimeSpan.Zero); }
- public sealed class ItemShopLedgerTests
- {
- private sealed class ThrowingRandom : Random
- { public override int Next(int value) { throw new InvalidOperationException("Injected shuffle failure"); } }
- private static PlayerEconomy Economy(long coins=20000,int hint=1,int shuffle=1,int time=1)
- => new PlayerEconomy(coins,0,new FixedUtc(),new ItemInventory(hint,shuffle,time));
- private static GameFlowController Flow(ManualClock clock,GameMode mode=GameMode.Classic,PlayerEconomy player=null)
- => new GameFlowController(mode,new ModeProgress(),player??Economy(),clock);
- private static Tile[] Tiles(Board b)
- {
- var result=new List<Tile>(); for(int r=0;r<b.Rows;r++) for(int c=0;c<b.Columns;c++)
- if(!b.IsEmpty(r,c)) result.Add(b.GetTile(r,c)); return result.ToArray();
- }
- private static int[] Layout(Board b)
- {
- 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();
- }
- private static ItemUseResult Use(GameFlowController f,ItemType type)
- => type==ItemType.Hint?f.Items.TryUseHint():type==ItemType.Shuffle?f.Items.TryUseShuffle():f.Items.TryUseTime();
- [Test] public void DefaultInventoryAndEmptyLedgerMatchPrototype()
- {
- var p=new PlayerEconomy(clock:new FixedUtc());
- Assert.That(p.Inventory.GetCount(ItemType.Hint),Is.EqualTo(1)); Assert.That(p.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
- Assert.That(p.Inventory.GetCount(ItemType.Time),Is.Zero); Assert.That(p.Ledger.Entries.Count,Is.Zero);
- }
- [TestCase(-1,1,0)] [TestCase(1,-1,0)] [TestCase(1,1,-1)]
- public void NegativeInventoryIsRejected(int h,int s,int t) { Assert.Throws<ArgumentOutOfRangeException>(()=>new ItemInventory(h,s,t)); }
- [TestCase(ItemType.Hint,2000)] [TestCase(ItemType.Shuffle,5000)] [TestCase(ItemType.Time,3000)]
- public void PurchaseDeductsExactPriceAddsOneAndRecordsOneDebit(ItemType type,int price)
- {
- var p=Economy(); var shop=new ShopService(p); int before=p.Inventory.GetCount(type); var id=Guid.NewGuid();
- Assert.That(ShopService.Price(type),Is.EqualTo(price)); Assert.That(shop.TryBuy(type,id),Is.EqualTo(PurchaseStatus.Success));
- Assert.That(p.Coins,Is.EqualTo(20000-price)); Assert.That(p.Inventory.GetCount(type),Is.EqualTo(before+1));
- var transaction=p.Ledger.Entries.Single(); Assert.That(transaction.Id,Is.EqualTo(id)); Assert.That(transaction.Delta,Is.EqualTo(-price));
- Assert.That(transaction.Category,Is.EqualTo(CoinCategory.ShopPurchase)); Assert.That(transaction.TimestampUtc.Offset,Is.EqualTo(TimeSpan.Zero));
- Assert.That(shop.TryBuy(type,id),Is.EqualTo(PurchaseStatus.DuplicateTransaction)); Assert.That(p.Inventory.GetCount(type),Is.EqualTo(before+1));
- Assert.That(p.Coins,Is.EqualTo(20000-price)); Assert.That(p.Ledger.Entries.Count,Is.EqualTo(1));
- }
- [TestCase(ItemType.Hint)] [TestCase(ItemType.Shuffle)] [TestCase(ItemType.Time)]
- public void InsufficientFundsNeverChangeInventoryOrLedger(ItemType type)
- {
- var p=Economy(ShopService.Price(type)-1); int before=p.Inventory.GetCount(type); long coins=p.Coins;
- Assert.That(new ShopService(p).TryBuy(type,Guid.NewGuid()),Is.EqualTo(PurchaseStatus.InsufficientCoins));
- Assert.That(p.Inventory.GetCount(type),Is.EqualTo(before)); Assert.That(p.Coins,Is.EqualTo(coins)); Assert.That(p.Ledger.Entries.Count,Is.Zero);
- }
- [Test] public void InvalidPurchaseAndFullInventoryAreAtomicFailures()
- {
- var p=Economy(hint:int.MaxValue); var shop=new ShopService(p);
- Assert.That(shop.TryBuy(ItemType.Hint,Guid.NewGuid()),Is.EqualTo(PurchaseStatus.InventoryFull));
- Assert.That(shop.TryBuy((ItemType)8,Guid.NewGuid()),Is.EqualTo(PurchaseStatus.InvalidItem));
- Assert.That(shop.TryBuy(ItemType.Time,Guid.Empty),Is.EqualTo(PurchaseStatus.InvalidTransactionId));
- Assert.That(p.Coins,Is.EqualTo(20000)); Assert.That(p.Ledger.Entries.Count,Is.Zero);
- }
- [Test] public void ShoppingDoesNotPauseOrFreezeTheClock()
- {
- var c=new ManualClock(); using(var f=Flow(c))
- { 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)); }
- }
- [Test] public void HintReturnsRealImmutablePathWithoutChangingBoardOrSelection()
- {
- var c=new ManualClock(); using(var f=Flow(c))
- {
- f.Start(); var board=f.Runtime.Session.Board; var selected=board.GetTile(0,0); f.Click(0,0); var ids=Layout(board);
- int notifications=0; HintInfo published=null; f.Items.HintRequested += h=> { notifications++; published=h; };
- var result=f.Items.TryUseHint(); Assert.That(result.Status,Is.EqualTo(ItemUseStatus.Success));
- var a=Tiles(board).Single(t=>t.Id==result.Hint.FirstId); var b=Tiles(board).Single(t=>t.Id==result.Hint.SecondId);
- Assert.That(new LinkPathFinder().TryFindPath(board,a.Position,b.Position,out var path),Is.True); Assert.That(result.Hint.Path,Is.EqualTo(path));
- Assert.That(result.Hint.SessionId,Is.EqualTo(f.Runtime.Session.Id)); Assert.That(HintInfo.DurationSeconds,Is.EqualTo(1.6));
- Assert.That(published,Is.SameAs(result.Hint)); Assert.That(notifications,Is.EqualTo(1)); Assert.That(Layout(board),Is.EqualTo(ids));
- Assert.That(f.Runtime.Interaction.Selected,Is.SameAs(selected)); Assert.That(f.Runtime.Timer.IsRunning,Is.True);
- Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.Zero); Assert.That(f.Items.TryUseHint().Status,Is.EqualTo(ItemUseStatus.InsufficientInventory));
- }
- }
- [Test] public void NoHintPairDoesNotConsumeInventory()
- {
- using(var f=Flow(new ManualClock()))
- { 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)); }
- }
- [Test] public void ManualShuffleConservesInstancesIdsSymbolsAndAllEmptyCellsAndClearsSelection()
- {
- var c=new ManualClock(); using(var f=Flow(c))
- {
- f.Start(); var b=f.Runtime.Session.Board; new BoardMoveFinder().TryFindMove(b,out var initial);
- f.Click(initial.First.Row,initial.First.Column); f.Click(initial.Second.Row,initial.Second.Column); c.Seconds=.25; f.Update();
- var before=Tiles(b); var holes=Layout(b).Select((id,i)=>new{id,i}).Where(x=>x.id==0).Select(x=>x.i).ToArray();
- var selected=before[0]; f.Click(selected.Row,selected.Column); int refreshed=0; f.Runtime.Interaction.Reshuffled += _=>refreshed++;
- Assert.That(f.Items.TryUseShuffle().Succeeded,Is.True); var after=Tiles(b);
- Assert.That(after,Is.EquivalentTo(before)); Assert.That(after.Select(t=>t.Id),Is.EquivalentTo(before.Select(t=>t.Id)));
- Assert.That(after.Select(t=>t.Symbol),Is.EquivalentTo(before.Select(t=>t.Symbol)));
- Assert.That(Layout(b).Select((id,i)=>new{id,i}).Where(x=>x.id==0).Select(x=>x.i),Is.EqualTo(holes));
- Assert.That(after.Select(t=>t.Id).Distinct().Count(),Is.EqualTo(after.Length));
- Assert.That(new BoardMoveFinder().TryFindMove(b,out var move),Is.True);
- Assert.That(new LinkPathFinder().TryFindPath(b,move.First.Position,move.Second.Position,out _),Is.True);
- Assert.That(f.Runtime.Interaction.Selected,Is.Null); Assert.That(f.Runtime.Interaction.IsLocked,Is.False);
- Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.Zero); Assert.That(refreshed,Is.EqualTo(1));
- }
- }
- [Test] public void ThrowingShuffleRollsBackWithoutConsumingOrClearingSelection()
- {
- using(var f=Flow(new ManualClock()))
- {
- f.Start(); f.Click(0,0); var selected=f.Runtime.Interaction.Selected; var before=Layout(f.Runtime.Session.Board);
- var result=new ItemUseService(f,new ThrowingRandom()).TryUseShuffle();
- Assert.That(result.Status,Is.EqualTo(ItemUseStatus.OperationFailed)); Assert.That(result.Error,Is.Not.Empty);
- Assert.That(Layout(f.Runtime.Session.Board),Is.EqualTo(before)); Assert.That(f.Runtime.Interaction.Selected,Is.SameAs(selected));
- Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
- }
- }
- [Test] public void NoMatchingSymbolShuffleFailsWithoutConsuming()
- {
- using(var f=Flow(new ManualClock()))
- { f.Start(); var b=f.Runtime.Session.Board; foreach(var t in Tiles(b).Skip(1))b.RemoveTile(t); var before=Layout(b);
- 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)); }
- }
- [TestCase(GameMode.Classic)] [TestCase(GameMode.TimeAttack)]
- public void TimeAddsThirtyAndExpandsBarWithoutChangingInitialTime(GameMode mode)
- {
- using(var f=Flow(new ManualClock(),mode))
- { f.Start(); double initial=f.Runtime.Timer.InitialTime; Assert.That(f.Items.TryUseTime().Succeeded,Is.True);
- Assert.That(f.Runtime.Timer.RemainingTime,Is.EqualTo(initial+30)); Assert.That(f.Runtime.Timer.TimeBarMax,Is.EqualTo(initial+30));
- Assert.That(f.Runtime.Timer.InitialTime,Is.EqualTo(initial)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Time),Is.Zero); }
- }
- [Test] public void ZenAndEmptyInventoryDoNotConsumeTimeItem()
- {
- using(var f=Flow(new ManualClock(),GameMode.Zen))
- { f.Start(); Assert.That(f.Items.TryUseTime().Status,Is.EqualTo(ItemUseStatus.UnsupportedMode)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Time),Is.EqualTo(1)); }
- using(var f=Flow(new ManualClock(),player:Economy(time:0)))
- { f.Start(); Assert.That(f.Items.TryUseTime().Status,Is.EqualTo(ItemUseStatus.InsufficientInventory)); }
- }
- [TestCase(ItemType.Hint)] [TestCase(ItemType.Shuffle)] [TestCase(ItemType.Time)]
- public void ReadyPausedAndAnimationLockRejectAllItems(ItemType item)
- {
- var c=new ManualClock(); using(var f=Flow(c))
- {
- Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); f.Start(); f.Pause();
- Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); f.Resume();
- 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);
- Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.InteractionLocked)); Assert.That(f.Economy.Inventory.GetCount(item),Is.EqualTo(1));
- }
- }
- [TestCase(ItemType.Hint)] [TestCase(ItemType.Shuffle)] [TestCase(ItemType.Time)]
- public void TerminalStatesRejectItemsWithoutConsuming(ItemType item)
- {
- var c=new ManualClock(); using(var f=Flow(c))
- { f.Start(); c.Seconds=180; Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); Assert.That(f.State,Is.EqualTo(GameFlowState.Defeat));
- Assert.That(f.Economy.Inventory.GetCount(item),Is.EqualTo(1)); f.ReturnToLobby(); Assert.That(Use(f,item).Status,Is.EqualTo(ItemUseStatus.GameNotRunning)); }
- }
- [Test] public void VictoryRejectsItemsAndRestartRetainsConsumedInventory()
- {
- var c=new ManualClock(); using(var f=Flow(c))
- {
- f.Start(); f.Items.TryUseHint(); f.Pause(); f.RestartCurrentLevel(); Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.Zero);
- while(f.State==GameFlowState.Running)
- { 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); }
- foreach(ItemType type in Enum.GetValues(typeof(ItemType)))Assert.That(Use(f,type).Status,Is.EqualTo(ItemUseStatus.GameNotRunning));
- Assert.That(f.Economy.Ledger.Entries.Single().Category,Is.EqualTo(CoinCategory.LevelVictory));
- Assert.That(f.Economy.Ledger.Entries.Single().Delta,Is.EqualTo(1000));
- }
- }
- [Test] public void ReentrantHintNotificationCannotConsumeSecondItem()
- {
- using(var f=Flow(new ManualClock(),player:Economy(hint:2)))
- { 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)); }
- }
- private sealed class IdentityRandom : Random { public override int Next(int value)=>value-1; }
- private sealed class PartialFailureRandom : Random
- {
- private int calls;
- public override int Next(int value)
- { if(++calls>15)throw new InvalidOperationException("Failure after a deadlocked permutation"); int i=value-1; return i>=8?15-i:i; }
- }
- private static void DeadlockFixture(GameFlowController flow)
- {
- var board=flow.Runtime.Session.Board; var original=Tiles(board);
- var symbols=original.Select(t=>t.Symbol).Distinct().Take(4).ToArray();
- var groups=symbols.Select(symbol=>new Queue<Tile>(original.Where(t=>t.Symbol==symbol))).ToArray();
- var chosen=new Tile[board.Rows*board.Columns]; var used=new HashSet<Tile>();
- for(int r=0;r<4;r++)for(int c=0;c<4;c++)
- { var tile=groups[(r+c)%4].Dequeue(); chosen[r*board.Columns+c]=tile; used.Add(tile); }
- var rest=new Queue<Tile>(original.Where(t=>!used.Contains(t)));
- for(int i=0;i<chosen.Length;i++)if(chosen[i]==null)chosen[i]=rest.Dequeue();
- // Fixture-only placement through the existing Core permutation operation.
- typeof(Board).GetMethod("Rearrange",BindingFlags.NonPublic|BindingFlags.Instance).Invoke(board,new object[]{chosen});
- foreach(var tile in Tiles(board))if(tile.Row>=4 || tile.Column>=4)board.RemoveTile(tile);
- Assert.That(new BoardMoveFinder().TryFindMove(board,out _),Is.False);
- }
- [Test] public void ManualShuffleUsesFortyAttemptsAndExistingDeterministicFallback()
- {
- using(var f=Flow(new ManualClock(),GameMode.TimeAttack))
- {
- f.Start(); DeadlockFixture(f); BoardShuffleResult observed=null; f.Runtime.Interaction.Reshuffled += r=>observed=r;
- Assert.That(new ItemUseService(f,new IdentityRandom()).TryUseShuffle().Succeeded,Is.True);
- Assert.That(observed.RandomAttempts,Is.EqualTo(40)); Assert.That(observed.UsedFallback,Is.True);
- Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.Zero);
- Assert.That(new LinkPathFinder().TryFindPath(f.Runtime.Session.Board,observed.Move.First.Position,observed.Move.Second.Position,out _),Is.True);
- }
- }
- [Test] public void AutomaticDeadlockShuffleDoesNotConsumeAnyInventory()
- {
- using(var f=Flow(new ManualClock(),GameMode.TimeAttack))
- {
- f.Start(); DeadlockFixture(f); int events=0; f.Runtime.Interaction.Reshuffled += _=>events++;
- typeof(DevilLink2.Interaction.BoardInteractionState).GetMethod("CheckMoves",BindingFlags.NonPublic|BindingFlags.Instance).Invoke(f.Runtime.Interaction,null);
- Assert.That(events,Is.EqualTo(1)); Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
- Assert.That(f.Economy.Inventory.GetCount(ItemType.Hint),Is.EqualTo(1));
- Assert.That(new BoardMoveFinder().TryFindMove(f.Runtime.Session.Board,out _),Is.True);
- }
- }
- [Test] public void ManualFailureAfterChangedPermutationRestoresOriginalLayoutAndSelection()
- {
- using(var f=Flow(new ManualClock(),GameMode.TimeAttack))
- {
- f.Start(); DeadlockFixture(f); f.Click(0,0); var selected=f.Runtime.Interaction.Selected; var ids=Layout(f.Runtime.Session.Board);
- Assert.That(new ItemUseService(f,new PartialFailureRandom()).TryUseShuffle().Status,Is.EqualTo(ItemUseStatus.OperationFailed));
- Assert.That(Layout(f.Runtime.Session.Board),Is.EqualTo(ids)); Assert.That(f.Runtime.Interaction.Selected,Is.SameAs(selected));
- Assert.That(selected.Position,Is.EqualTo(new GridPosition(0,0))); Assert.That(f.Economy.Inventory.GetCount(ItemType.Shuffle),Is.EqualTo(1));
- }
- }
- [Test] public void LedgerCapsSortsAndSummarizesOnlyRetainedRecords()
- {
- var utc=new FixedUtc(); var p=new PlayerEconomy(clock:utc); var first=Guid.NewGuid();
- Assert.That(p.TryCredit(first,10,"first"),Is.True);
- for(int i=1;i<=205;i++) { utc.UtcNow=utc.UtcNow.AddSeconds(1); p.TryCredit(Guid.NewGuid(),10,"reward"); }
- Assert.That(p.Ledger.Entries.Count,Is.EqualTo(200)); Assert.That(p.Ledger.Income,Is.EqualTo(2000m)); Assert.That(p.Ledger.Expenses,Is.Zero);
- Assert.That(p.Ledger.Entries.Select(t=>t.TimestampUtc),Is.Ordered.Descending);
- Assert.That(p.Ledger.Entries.Any(t=>t.Id==first),Is.False); long before=p.Coins;
- Assert.That(p.TryCredit(first,10,"duplicate"),Is.False); Assert.That(p.Coins,Is.EqualTo(before));
- }
- [Test] public void LedgerHandlesUtcClockReversalAndSeparateIncomeExpenseTotals()
- {
- var utc=new FixedUtc(); var p=new PlayerEconomy(10000,clock:utc); var later=utc.UtcNow;
- p.TryCredit(Guid.NewGuid(),100,"reward"); utc.UtcNow=utc.UtcNow.AddHours(-1); new ShopService(p).TryBuy(ItemType.Hint,Guid.NewGuid());
- 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));
- Assert.That(p.Ledger.Entries.Select(t=>t.Id).Distinct().Count(),Is.EqualTo(2));
- }
- }
- }
|