diff --git a/src/GameLogic/PlayerActions/Craftings/BaseEventTicketCrafting.cs b/src/GameLogic/PlayerActions/Craftings/BaseEventTicketCrafting.cs index d9eb764484..bb4524d076 100644 --- a/src/GameLogic/PlayerActions/Craftings/BaseEventTicketCrafting.cs +++ b/src/GameLogic/PlayerActions/Craftings/BaseEventTicketCrafting.cs @@ -4,6 +4,7 @@ namespace MUnique.OpenMU.GameLogic.PlayerActions.Craftings; +using MUnique.OpenMU.DataModel.Configuration.Items; using MUnique.OpenMU.GameLogic.Crywolf; using MUnique.OpenMU.GameLogic.PlayerActions.Items; using MUnique.OpenMU.GameLogic.Views.NPC; @@ -110,8 +111,8 @@ protected sealed override int GetPrice(byte successRate, IList> CreateOrModifyResultItemsAsync(IList requiredItems, Player player, byte socketIndex, byte successRate) { var item = player.PersistenceContext.CreateNew(); - item.Definition = player.GameContext.Configuration.Items.First(i => i.Name.ValueInNeutralLanguage == this._resultItemName); item.Level = this.GetEventLevel(requiredItems); + item.Definition = this.GetResultItemDefinition(player, item.Level); item.Durability = 1; if (player.TemporaryStorage is { } temporaryStorage) { @@ -121,6 +122,17 @@ protected override async ValueTask> CreateOrModifyResultItemsAsync(IL return new List { item }; } + /// + /// Gets the item definition of the ticket which the crafting creates. + /// + /// The player. + /// The event level, which is the item level of the ticket. + /// The item definition with the name of the result item. + protected virtual ItemDefinition GetResultItemDefinition(Player player, byte eventLevel) + { + return player.GameContext.Configuration.Items.First(i => i.Name.ValueInNeutralLanguage == this._resultItemName); + } + private byte GetEventLevel(IList requiredItems) { var item = requiredItems.First(ri => ri.Items.Any(i => i.Definition?.Name.ValueInNeutralLanguage == this._requiredEventItemName1)); diff --git a/src/GameLogic/PlayerActions/Craftings/IllusionTempleTicketCrafting.cs b/src/GameLogic/PlayerActions/Craftings/IllusionTempleTicketCrafting.cs index 984548b8d8..59d43ac881 100644 --- a/src/GameLogic/PlayerActions/Craftings/IllusionTempleTicketCrafting.cs +++ b/src/GameLogic/PlayerActions/Craftings/IllusionTempleTicketCrafting.cs @@ -4,10 +4,12 @@ namespace MUnique.OpenMU.GameLogic.PlayerActions.Craftings; +using MUnique.OpenMU.DataModel.Configuration.Items; using MUnique.OpenMU.GameLogic.Views.NPC; /// -/// Crafting for Illusion Temple Event Tickets. +/// Crafting for Illusion Temple Event Tickets, the Scroll of Blood, which is combined from an Old Scroll and an +/// Illusion Sorcerer Covenant of the same level. /// public class IllusionTempleTicketCrafting : BaseEventTicketCrafting { @@ -15,13 +17,28 @@ public class IllusionTempleTicketCrafting : BaseEventTicketCrafting /// Initializes a new instance of the class. /// public IllusionTempleTicketCrafting() - : base("Illusion Sorcerer Covenant", "Old Scroll", "Scroll of Blood") + : base("Scroll of Blood", "Old Scroll", "Illusion Sorcerer Covenant") { } /// protected override byte MaximumSuccessRate => 80; + /// + /// + /// The ticket which the temple of the level accepts, so the crafting and the temples stay in step when the + /// server owner selects another ticket item. Only without such a temple, the item named "Scroll of Blood". + /// + protected override ItemDefinition GetResultItemDefinition(Player player, byte eventLevel) + { + return player.GameContext.Configuration.MiniGameDefinitions + .Where(definition => definition.Type == MiniGameType.IllusionTemple && definition.TicketItemLevel == eventLevel) + .OrderBy(definition => definition.GameLevel) + .Select(definition => definition.TicketItem) + .FirstOrDefault(ticket => ticket is not null) + ?? base.GetResultItemDefinition(player, eventLevel); + } + /// protected override int GetPrice(int eventLevel) { diff --git a/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs b/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs index 54a80e1b99..b36eee8dc9 100644 --- a/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs +++ b/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs @@ -34,7 +34,11 @@ public class IllusionTempleDataUpdatePlugIn : UpdatePlugInBase /// /// The plug in description. /// - internal const string PlugInDescription = "This update creates the configuration data for the illusion temple event and assigns the event dialog to the Mirage NPC."; + internal const string PlugInDescription = "This update creates the configuration data for the illusion temple event and assigns the event dialog to the Mirage NPC. " + + "If the items 13/50 and 13/51 have swapped data (Scroll of Blood and Illusion Sorcerer Covenant), it gives them their original data back: " + + "names, sizes, durability, levels and drops, the drop item groups, the temple tickets and the merchant items of 13/51. " + + "If only one of the two has the swapped name, it changes neither. " + + "References to the two items which you added yourself (craftings, quests, item drops, plug-in settings) stay as they are: check them after the update."; /// /// The number of the Mirage NPC, which opens the illusion temple dialog. @@ -93,6 +97,32 @@ public class IllusionTempleDataUpdatePlugIn : UpdatePlugInBase /// private const int DefaultMinimumPlayerCount = 2; + /// + /// The item group of the illusion temple ticket items. + /// + private const byte TicketItemGroup = 13; + + /// + /// The number of the Illusion Sorcerer Covenant, which drops from monsters. + /// + private const short CovenantItemNumber = 50; + + /// + /// The number of the Scroll of Blood, the ticket, which the chaos goblin combines from an Old Scroll and an + /// Illusion Sorcerer Covenant. + /// + private const short ScrollOfBloodItemNumber = 51; + + /// + /// The neutral name of the Illusion Sorcerer Covenant. + /// + private const string CovenantName = "Illusion Sorcerer Covenant"; + + /// + /// The neutral name of the Scroll of Blood. + /// + private const string ScrollOfBloodName = "Scroll of Blood"; + /// /// The map numbers of the six illusion temples, and the arena monster NPC number range (base id and /// how many ids to cycle through) which each of them roams with - temple 6 has none. @@ -188,15 +218,22 @@ private static readonly (short Number, int Level, int Hp, int MinDmg, int MaxDmg public override bool IsMandatory => true; /// - public override int Version => 2; + public override int Version => 3; /// public override DateTime CreatedAt => new(2026, 07, 29, 20, 0, 0, DateTimeKind.Utc); /// - public override DateTime UpdatedAt => new(2026, 11, 5, 0, 0, 0, DateTimeKind.Utc); + public override DateTime UpdatedAt => new(2026, 11, 8, 0, 0, 0, DateTimeKind.Utc); /// + /// + /// Version one swapped the numbers of the Illusion Sorcerer Covenant and the Scroll of Blood, believing the + /// covenant was the ticket. It's the other way around, so version three leaves the original numbers as they + /// are, and gives a database which got the swap the original item data back (see ). + /// The ticket binding repair of version two pointed the temples which reference 13/50 at 13/51, then named the + /// covenant; the restoration still makes that move, as 13/51 becomes the Scroll of Blood. + /// protected override async ValueTask ApplyAsync(IContext context, GameConfiguration gameConfiguration, int? installedVersion) { // Replaying version one's content changes could overwrite owner-customized spawns or safezones. @@ -205,7 +242,7 @@ protected override async ValueTask ApplyAsync(IContext context, GameConfiguratio await this.ApplyAsync(context, gameConfiguration).ConfigureAwait(false); } - this.FixTicketBindings(gameConfiguration); + RestoreTicketItems(gameConfiguration); } /// @@ -213,7 +250,6 @@ protected override async ValueTask ApplyAsync(IContext context, GameConfiguratio protected override async ValueTask ApplyAsync(IContext context, GameConfiguration gameConfiguration) #pragma warning restore CS1998 { - this.FixTicketItemNumbers(gameConfiguration); this.AddRelicItem(context, gameConfiguration); this.AddArenaMonsterDefinitions(context, gameConfiguration); this.AddMapSpawns(context, gameConfiguration); @@ -243,47 +279,102 @@ protected override async ValueTask ApplyAsync(IContext context, GameConfiguratio } /// - /// The illusion temple ticket ("Illusion Sorcerer Covenant") and the "Scroll of Blood" item used to - /// have their numbers swapped (50/51) - looks the ticket up - /// by Group 13, Number 51, so an existing database still using the old numbering needs the two - /// numbers corrected. Only the Number field is touched, so already-owned instances of either item - /// keep referencing the same, unchanged, item definition entity. + /// Gives the items 13/50 and 13/51 their original data back, if the configuration has the data of the + /// two swapped, and points the mini game definitions which reference 13/50 at the ticket 13/51. /// - private void FixTicketItemNumbers(GameConfiguration gameConfiguration) + /// + /// Version one of this update swapped the numbers of the two item definitions, and the data initialization of + /// the same time created them with swapped data. The game client knows the items by their numbers, so the + /// numbers stay and the data is swapped back instead: an owned item which the client shows as the Scroll of + /// Blood stays the ticket, and the item 13/50 drops again. The swapped state is recognized by the names, so + /// nothing changes on a configuration which has the original data. + /// + /// The game configuration. + private static void RestoreTicketItems(GameConfiguration gameConfiguration) { // The names are matched in the neutral language: item names became a LocalizedString, whose // serialized value carries the translations and the resource metadata, so comparing it to a // plain string would never match on a database which has been localized. - var covenant = gameConfiguration.Items.FirstOrDefault(item => item.Group == 13 && item.Name.ValueInNeutralLanguage == "Illusion Sorcerer Covenant"); - var scrollOfBlood = gameConfiguration.Items.FirstOrDefault(item => item.Group == 13 && item.Name.ValueInNeutralLanguage == "Scroll of Blood"); - if (covenant is { Number: 50 } && scrollOfBlood is { Number: 51 }) + // The items are named by their numbers, which is what they are after the restoration. + var ticket = gameConfiguration.Items.FirstOrDefault(item => item.Group == TicketItemGroup && item.Number == ScrollOfBloodItemNumber && item.Name.ValueInNeutralLanguage == CovenantName); + var covenant = gameConfiguration.Items.FirstOrDefault(item => item.Group == TicketItemGroup && item.Number == CovenantItemNumber && item.Name.ValueInNeutralLanguage == ScrollOfBloodName); + if (ticket is null || covenant is null) + { + // Not swapped, or the server owner changed one of the two: the data of one item alone can't be swapped, + // and the description of the update tells the owner to check the items. + return; + } + + RepairTicketBindings(gameConfiguration, ticket, covenant); + RepairMerchantStoreItems(gameConfiguration, ticket, covenant); + SwapData(ticket, covenant); + SwapDropItemGroups(gameConfiguration, ticket, covenant); + } + + /// + /// Points the mini game definitions which reference the item 13/50 at the ticket 13/51. + /// A database which had temple definitions before version one of this update renumbered the items kept + /// them on the item definition which got the number 50, and a server owner who chose a ticket in the + /// swapped state chose 13/50 as the Scroll of Blood. That item definition becomes the Illusion Sorcerer + /// Covenant, so every definition follows the Scroll of Blood to 13/51, also one with an own id or ticket + /// level. A ticket of another item, or of an item definition of another configuration, stays. + /// + private static void RepairTicketBindings(GameConfiguration gameConfiguration, ItemDefinition ticket, ItemDefinition covenant) + { + foreach (var definition in gameConfiguration.MiniGameDefinitions.Where(definition => ReferenceEquals(definition.TicketItem, covenant))) { - covenant.Number = 51; - scrollOfBlood.Number = 50; + definition.TicketItem = ticket; } } /// - /// Repairs the seeded ticket references left pointing at the Scroll of Blood after version one's renumbering. - /// Only owned item instances and the unchanged default temple definition ids and ticket levels are recognized. + /// Points the items of the merchant stores which reference the ticket 13/51 at the item 13/50. + /// No merchant sells the ticket, but a merchant of the original data sells the Illusion Sorcerer Covenant, + /// whose item definition version one of this update renumbered to 51. /// - private void FixTicketBindings(GameConfiguration gameConfiguration) + private static void RepairMerchantStoreItems(GameConfiguration gameConfiguration, ItemDefinition ticket, ItemDefinition covenant) { - var covenant = gameConfiguration.Items.FirstOrDefault(item => item.Group == 13 && item.Number == 51 && item.Name.ValueInNeutralLanguage == "Illusion Sorcerer Covenant"); - var scrollOfBlood = gameConfiguration.Items.FirstOrDefault(item => item.Group == 13 && item.Number == 50 && item.Name.ValueInNeutralLanguage == "Scroll of Blood"); - if (covenant is null || scrollOfBlood is null) + foreach (var item in gameConfiguration.Monsters + .SelectMany(monster => monster.MerchantStore?.Items ?? Enumerable.Empty()) + .Where(item => ReferenceEquals(item.Definition, ticket))) { - return; + item.Definition = covenant; } + } - foreach (var definition in gameConfiguration.MiniGameDefinitions.Where(definition => - definition.Type == MiniGameType.IllusionTemple - && definition.GameLevel is >= 1 and <= 6 - && definition.TicketItemLevel == definition.GameLevel - && definition.GetId() == GuidHelper.CreateGuid((short)MiniGameType.IllusionTemple, definition.GameLevel) - && ReferenceEquals(definition.TicketItem, scrollOfBlood))) + /// + /// Swaps the data which the data initialization sets for each event item, except the number. + /// The other data, like the item rules, the price definition and the game version, is set by the number, + /// so it already fits. + /// + private static void SwapData(ItemDefinition first, ItemDefinition second) + { + (first.Name, second.Name) = (second.Name, first.Name); + (first.Width, second.Width) = (second.Width, first.Width); + (first.Height, second.Height) = (second.Height, first.Height); + (first.Durability, second.Durability) = (second.Durability, first.Durability); + (first.MaximumItemLevel, second.MaximumItemLevel) = (second.MaximumItemLevel, first.MaximumItemLevel); + (first.DropsFromMonsters, second.DropsFromMonsters) = (second.DropsFromMonsters, first.DropsFromMonsters); + (first.DropLevel, second.DropLevel) = (second.DropLevel, first.DropLevel); + (first.MaximumDropLevel, second.MaximumDropLevel) = (second.MaximumDropLevel, first.MaximumDropLevel); + } + + /// + /// Swaps the two item definitions in the drop item groups which contain one of them, which are the groups of + /// the Illusion Sorcerer Covenant, one for each item level. + /// + private static void SwapDropItemGroups(GameConfiguration gameConfiguration, ItemDefinition first, ItemDefinition second) + { + foreach (var group in gameConfiguration.DropItemGroups) { - definition.TicketItem = covenant; + var containsFirst = group.PossibleItems.Contains(first); + if (containsFirst == group.PossibleItems.Contains(second)) + { + continue; + } + + group.PossibleItems.Remove(containsFirst ? first : second); + group.PossibleItems.Add(containsFirst ? second : first); } } diff --git a/src/Persistence/Initialization/VersionSeasonSix/Items/EventTicketItems.cs b/src/Persistence/Initialization/VersionSeasonSix/Items/EventTicketItems.cs index fa06ef924d..2fb95ff424 100644 --- a/src/Persistence/Initialization/VersionSeasonSix/Items/EventTicketItems.cs +++ b/src/Persistence/Initialization/VersionSeasonSix/Items/EventTicketItems.cs @@ -35,10 +35,11 @@ public override void Initialize() // Chaos Castle: this.CreateEventItem(29, 13, 2, 2, LocalizedString.FromResource(() => ItemNames.ArmorOfGuardsman), false); - // Illusion Temple: + // Illusion Temple: the Old Scroll and the Illusion Sorcerer Covenant drop from monsters, and the chaos goblin + // combines them into the Scroll of Blood, which is the ticket. this.CreateEventItem(49, 13, 1, 1, LocalizedString.FromResource(() => ItemNames.OldScroll), false, 6, 66, 72, 78, 84, 90, 96); - this.CreateEventItem(51, 13, 1, 2, LocalizedString.FromResource(() => ItemNames.IllusionSorcererCovenant), false, 6, 70, 76, 82, 88, 94, 100); - this.CreateEventItem(50, 13, 2, 2, LocalizedString.FromResource(() => ItemNames.ScrollOfBlood), false, 6); + this.CreateEventItem(50, 13, 1, 2, LocalizedString.FromResource(() => ItemNames.IllusionSorcererCovenant), false, 6, 70, 76, 82, 88, 94, 100); + this.CreateEventItem(51, 13, 2, 2, LocalizedString.FromResource(() => ItemNames.ScrollOfBlood), false, 6); // Kalima: this.CreateKalimaTicket(); diff --git a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs index f77da5eec5..6f765fe2b8 100644 --- a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs +++ b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs @@ -115,14 +115,16 @@ public async Task UpdateFixesMissingMinimumPlayerCountAsync() } /// - /// Repairs the ticket reference of existing temples both before and after the version-one item renumbering. - /// The legacy initializer selected the Scroll of Blood definition while it still had number 51. + /// Tests that the update leaves the illusion temple items of a configuration with the original numbering as + /// they are, and the temples with the ticket 13/51, the Scroll of Blood, from every installed version. + /// Version one used to swap the numbers of the Illusion Sorcerer Covenant and the Scroll of Blood here. /// - /// Whether version one already corrected the item numbers. + /// The installed version of the update. /// The task. - [TestCase(false)] - [TestCase(true)] - public async Task UpdateRepairsExistingTempleTicketBindingAsync(bool numbersAlreadyCorrected) + [TestCase(0)] + [TestCase(1)] + [TestCase(2)] + public async Task UpdateKeepsOriginalTicketItemsAsync(int installedVersion) { var contextProvider = new InMemoryPersistenceContextProvider(); var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); @@ -130,39 +132,70 @@ public async Task UpdateRepairsExistingTempleTicketBindingAsync(bool numbersAlre using var context = contextProvider.CreateNewContext(); var gameConfiguration = (await context.GetAsync().ConfigureAwait(false)).First(); - var covenant = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 51 }); - var scrollOfBlood = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 50 }); - var covenantId = ((IIdentifiable)covenant).Id; - var scrollId = ((IIdentifiable)scrollOfBlood).Id; - var definitions = GetTempleDefinitions(gameConfiguration); - if (!numbersAlreadyCorrected) + var expected = IllusionTempleTicketItemsTest.CaptureItems(gameConfiguration); + var covenant = IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.CovenantNumber); + var ticket = IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.TicketNumber); + + var update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = installedVersion; + for (var application = 0; application < 2; application++) { - covenant.Number = 50; - scrollOfBlood.Number = 51; + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + IllusionTempleTicketItemsTest.AssertItems(gameConfiguration, expected); + Assert.That(IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.CovenantNumber), Is.SameAs(covenant)); + Assert.That(IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.TicketNumber), Is.SameAs(ticket)); + Assert.That(GetTempleDefinitions(gameConfiguration).Select(definition => definition.TicketItem), Has.All.SameAs(ticket)); } + } - // Keep every existing definition: only its legacy ticket binding is reproduced. - foreach (var definition in definitions) + /// + /// Tests that the update repairs a configuration whose items version one renumbered: the two item definitions + /// get the original data of their numbers back without being renumbered again, so the one at 13/51, which + /// owned tickets reference, becomes the Scroll of Blood. Temple definitions which existed before version one + /// kept the item definition which got the number 50, and get the ticket 13/51. + /// + /// Whether the temple definitions existed before version one. + /// The task. + [TestCase(false)] + [TestCase(true)] + public async Task UpdateRestoresTicketItemsRenumberedByVersionOneAsync(bool templesExistedBefore) + { + var contextProvider = new InMemoryPersistenceContextProvider(); + var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); + await dataInitialization.CreateInitialDataAsync(1, true).ConfigureAwait(false); + + using var context = contextProvider.CreateNewContext(); + var gameConfiguration = (await context.GetAsync().ConfigureAwait(false)).First(); + var expected = IllusionTempleTicketItemsTest.CaptureItems(gameConfiguration); + var definitions = GetTempleDefinitions(gameConfiguration); + IllusionTempleTicketItemsTest.RenumberLikeVersionOne(gameConfiguration); + var ownedTicketDefinition = IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.TicketNumber); + var covenant = IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.CovenantNumber); + if (!templesExistedBefore) { - definition.TicketItem = scrollOfBlood; + foreach (var definition in definitions) + { + definition.TicketItem = ownedTicketDefinition; + } } - var itemsBefore = gameConfiguration.Items.ToArray(); var levelsBefore = definitions.Select(definition => definition.TicketItemLevel).ToArray(); + var itemsBefore = gameConfiguration.Items.ToArray(); var update = new IllusionTempleDataUpdatePlugIn(); var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); - installedUpdate.Version = numbersAlreadyCorrected ? 1 : 0; + installedUpdate.Version = 1; for (var application = 0; application < 2; application++) { await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + IllusionTempleTicketItemsTest.AssertItems(gameConfiguration, expected); Assert.Multiple(() => { - Assert.That(definitions.Select(definition => definition.TicketItem), Has.All.SameAs(covenant)); - Assert.That(covenant.Number, Is.EqualTo(51)); - Assert.That(scrollOfBlood.Number, Is.EqualTo(50)); - Assert.That(((IIdentifiable)covenant).Id, Is.EqualTo(covenantId)); - Assert.That(((IIdentifiable)scrollOfBlood).Id, Is.EqualTo(scrollId)); + Assert.That(IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.TicketNumber), Is.SameAs(ownedTicketDefinition)); + Assert.That(IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.CovenantNumber), Is.SameAs(covenant)); + Assert.That(definitions.Select(definition => definition.TicketItem), Has.All.SameAs(ownedTicketDefinition)); Assert.That(GetTempleDefinitions(gameConfiguration), Has.Count.EqualTo(definitions.Count)); Assert.That(definitions.All(original => gameConfiguration.MiniGameDefinitions.Any(current => ReferenceEquals(current, original))), Is.True); Assert.That(definitions.Select(definition => definition.TicketItemLevel), Is.EqualTo(levelsBefore)); @@ -173,15 +206,17 @@ public async Task UpdateRepairsExistingTempleTicketBindingAsync(bool numbersAlre } /// - /// Owner-selected tickets and detached definitions with the legacy ticket's id are not defaults to repair. + /// A temple definition with an own id or ticket level which references 13/50, the Scroll of Blood of the swapped + /// data, follows it to the ticket 13/51 and keeps its id and ticket level, so it doesn't accept the Illusion + /// Sorcerer Covenant. /// - /// The owner-selected ticket, detached reference, definition id or ticket level to preserve. + /// The customized definition id or ticket level. + /// The installed version of the update. /// The task. - [TestCase("owned-ticket")] - [TestCase("detached-ticket")] - [TestCase("definition-id")] - [TestCase("ticket-level")] - public async Task UpdatePreservesCustomizedTempleTicketBindingAsync(string customization) + [Test] + public async Task UpdateMovesCustomizedTempleToTicketAsync( + [Values("definition-id", "ticket-level")] string customization, + [Values(1, 2)] int installedVersion) { var contextProvider = new InMemoryPersistenceContextProvider(); var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); @@ -189,6 +224,59 @@ public async Task UpdatePreservesCustomizedTempleTicketBindingAsync(string custo using var context = contextProvider.CreateNewContext(); var gameConfiguration = (await context.GetAsync().ConfigureAwait(false)).First(); + IllusionTempleTicketItemsTest.RenumberLikeVersionOne(gameConfiguration); + var swappedScrollOfBlood = IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.CovenantNumber); + var ticket = IllusionTempleTicketItemsTest.GetItem(gameConfiguration, IllusionTempleTicketItemsTest.TicketNumber); + + var definition = GetTempleDefinitions(gameConfiguration).Single(temple => temple.GameLevel == 6); + if (customization == "definition-id") + { + ((IIdentifiable)definition).Id = Guid.NewGuid(); + } + + var definitionId = ((IIdentifiable)definition).Id; + definition.TicketItem = swappedScrollOfBlood; + var selectedLevel = customization == "ticket-level" ? 3 : 6; + definition.TicketItemLevel = selectedLevel; + + var update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = installedVersion; + for (var application = 0; application < 2; application++) + { + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + Assert.Multiple(() => + { + Assert.That(definition.TicketItem, Is.SameAs(ticket)); + Assert.That(ticket.Name.ValueInNeutralLanguage, Is.EqualTo("Scroll of Blood")); + Assert.That(definition.TicketItemLevel, Is.EqualTo(selectedLevel)); + Assert.That(((IIdentifiable)definition).Id, Is.EqualTo(definitionId)); + }); + } + } + + /// + /// A ticket of another item, and a detached item definition with the id of the swapped Scroll of Blood, aren't + /// item definitions of this configuration which the update restores, so the temple keeps them. + /// + /// The owner-selected ticket or detached reference to preserve. + /// The installed version of the update. + /// The task. + [Test] + public async Task UpdatePreservesCustomizedTempleTicketBindingAsync( + [Values("owned-ticket", "detached-ticket")] string customization, + [Values(1, 2)] int installedVersion) + { + var contextProvider = new InMemoryPersistenceContextProvider(); + var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); + await dataInitialization.CreateInitialDataAsync(1, true).ConfigureAwait(false); + + using var context = contextProvider.CreateNewContext(); + var gameConfiguration = (await context.GetAsync().ConfigureAwait(false)).First(); + + // Version one renumbered the Scroll of Blood to 50, which is the state in which the update moves bindings. + IllusionTempleTicketItemsTest.RenumberLikeVersionOne(gameConfiguration); var scrollOfBlood = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 50 }); var selectedTicket = customization == "owned-ticket" ? gameConfiguration.Items.Single(item => item is { Group: 13, Number: 18 }) @@ -205,24 +293,16 @@ public async Task UpdatePreservesCustomizedTempleTicketBindingAsync(string custo } var definition = GetTempleDefinitions(gameConfiguration).Single(temple => temple.GameLevel == 6); - if (customization == "definition-id") - { - ((IIdentifiable)definition).Id = Guid.NewGuid(); - } - - var definitionId = ((IIdentifiable)definition).Id; definition.TicketItem = selectedTicket; - var selectedLevel = customization == "ticket-level" ? 3 : 6; - definition.TicketItemLevel = selectedLevel; var update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = installedVersion; for (var application = 0; application < 2; application++) { await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); Assert.That(definition.TicketItem, Is.SameAs(selectedTicket)); - Assert.That(definition.TicketItemLevel, Is.EqualTo(selectedLevel)); - Assert.That(((IIdentifiable)definition).Id, Is.EqualTo(definitionId)); } } @@ -231,7 +311,7 @@ public async Task UpdatePreservesCustomizedTempleTicketBindingAsync(string custo /// /// The task. [Test] - public async Task VersionTwoPreservesVersionOneContentCustomizationsAsync() + public async Task LaterVersionsPreserveVersionOneContentCustomizationsAsync() { var contextProvider = new InMemoryPersistenceContextProvider(); var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); @@ -266,7 +346,7 @@ public async Task VersionTwoPreservesVersionOneContentCustomizationsAsync() Assert.That(map.MonsterSpawns.Any(current => ReferenceEquals(current, spawn)), Is.True); Assert.That((spawn.Quantity, spawn.X1, spawn.X2, spawn.Y1, spawn.Y2), Is.EqualTo(spawnSettings)); Assert.That(definition.TicketItem, Is.SameAs(ticket)); - Assert.That(installedUpdate.Version, Is.EqualTo(2)); + Assert.That(installedUpdate.Version, Is.EqualTo(update.Version)); } } @@ -297,12 +377,6 @@ private static void RevertToStateBeforeTheEvent(GameConfiguration gameConfigurat gameConfiguration.MiniGameDefinitions.Remove(definition); } - // The ticket and the Scroll of Blood used to have their numbers swapped. - var covenant = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 51 }); - var scrollOfBlood = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 50 }); - covenant.Number = 50; - scrollOfBlood.Number = 51; - gameConfiguration.Items.Remove(gameConfiguration.Items.Single(item => item is { Group: 14, Number: 64 })); foreach (var monster in gameConfiguration.Monsters.Where(monster => monster.Number is >= 386 and <= 399).ToList()) @@ -358,12 +432,17 @@ private static void AssertEventData(GameConfiguration gameConfiguration) private static void AssertItems(GameConfiguration gameConfiguration) { - // The event ticket is looked up as group 13, number 51 by the initializer, and the update - // corrects databases which still carry the two swapped numbers. + // The event ticket is the Scroll of Blood, group 13, number 51, which the chaos goblin combines from an + // Old Scroll and an Illusion Sorcerer Covenant, number 50. The game client knows them by these numbers + // and sizes. var ticket = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 51 }); - Assert.That(ticket.Name.ValueInNeutralLanguage, Is.EqualTo("Illusion Sorcerer Covenant")); - var scrollOfBlood = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 50 }); - Assert.That(scrollOfBlood.Name.ValueInNeutralLanguage, Is.EqualTo("Scroll of Blood")); + Assert.That(ticket.Name.ValueInNeutralLanguage, Is.EqualTo("Scroll of Blood")); + Assert.That((int)ticket.Width, Is.EqualTo(2)); + Assert.That((int)ticket.Height, Is.EqualTo(2)); + var covenant = gameConfiguration.Items.Single(item => item is { Group: 13, Number: 50 }); + Assert.That(covenant.Name.ValueInNeutralLanguage, Is.EqualTo("Illusion Sorcerer Covenant")); + Assert.That((int)covenant.Width, Is.EqualTo(1)); + Assert.That((int)covenant.Height, Is.EqualTo(2)); // The sacred relic, which the game logic looks up by group and number. Assert.That(gameConfiguration.Items.Count(item => item is { Group: 14, Number: 64 }), Is.EqualTo(1), "sacred relic"); diff --git a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleTicketItemsTest.cs b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleTicketItemsTest.cs new file mode 100644 index 0000000000..452c5c0224 --- /dev/null +++ b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleTicketItemsTest.cs @@ -0,0 +1,285 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.Persistence.Initialization.Tests; + +using System.Collections; +using System.Reflection; +using Microsoft.Extensions.Logging.Abstractions; +using MUnique.OpenMU.DataModel.Configuration; +using MUnique.OpenMU.DataModel.Configuration.Items; +using MUnique.OpenMU.Persistence.Initialization.Updates; +using MUnique.OpenMU.Persistence.InMemory; + +/// +/// Tests the illusion temple items 13/50, the Illusion Sorcerer Covenant, and 13/51, the Scroll of Blood which is +/// the ticket, of the season 6 data, and how the illusion temple update gives a configuration with the data of both +/// swapped the original data back. +/// +[TestFixture] +internal class IllusionTempleTicketItemsTest +{ + /// + /// The number of the Illusion Sorcerer Covenant. + /// + internal const short CovenantNumber = 50; + + /// + /// The number of the Scroll of Blood, the ticket of the event. + /// + internal const short TicketNumber = 51; + + private const byte ItemGroup = 13; + + private const short LumenTheBarmaidNumber = 255; + + /// + /// The way in which a configuration got the data of the two items swapped. + /// + public enum SwappedState + { + /// + /// The first version of the illusion temple update renumbered the item definitions, and created the + /// temple definitions with the ticket at its new number 51. + /// + RenumberedByUpdate, + + /// + /// The first version of the illusion temple update renumbered the item definitions, and the temple + /// definitions which existed before kept the item which got the number 50. + /// + RenumberedByUpdateWithExistingTemples, + + /// + /// The configuration was initialized with the swapped data. + /// + Initialized, + } + + /// + /// Tests that a new season 6 database has the original items: the Illusion Sorcerer Covenant (1x2), which + /// drops from monsters and which a merchant sells, and the Scroll of Blood (2x2), which is the ticket of the + /// six temples. The game client knows them by these numbers and sizes. + /// + /// The task. + [Test] + public async Task NewDatabaseHasOriginalItemsAsync() + { + var (context, gameConfiguration) = await CreateSeason6ConfigurationAsync().ConfigureAwait(false); + using var _ = context; + + var covenant = GetItem(gameConfiguration, CovenantNumber); + var ticket = GetItem(gameConfiguration, TicketNumber); + Assert.Multiple(() => + { + Assert.That(covenant.Name.ValueInNeutralLanguage, Is.EqualTo("Illusion Sorcerer Covenant")); + Assert.That(covenant.Width, Is.EqualTo(1)); + Assert.That(covenant.Height, Is.EqualTo(2)); + Assert.That( + GetDropItemGroups(gameConfiguration, covenant).Select(group => group.ItemLevel ?? 0), + Is.EqualTo(new[] { 1, 2, 3, 4, 5, 6 })); + Assert.That( + GetDropItemGroups(gameConfiguration, covenant).Select(group => group.MinimumMonsterLevel ?? 0), + Is.EqualTo(new[] { 70, 76, 82, 88, 94, 100 })); + Assert.That( + gameConfiguration.Monsters.Single(monster => monster.Number == LumenTheBarmaidNumber).MerchantStore!.Items + .Where(item => item.Definition == covenant) + .Select(item => (int)item.Level), + Is.EquivalentTo(new[] { 1, 2, 3, 4, 5 })); + + Assert.That(ticket.Name.ValueInNeutralLanguage, Is.EqualTo("Scroll of Blood")); + Assert.That(ticket.Width, Is.EqualTo(2)); + Assert.That(ticket.Height, Is.EqualTo(2)); + Assert.That(GetDropItemGroups(gameConfiguration, ticket), Is.Empty); + Assert.That( + gameConfiguration.MiniGameDefinitions.Where(definition => definition.TicketItem == ticket).Select(definition => definition.Type), + Is.EqualTo(Enumerable.Repeat(MiniGameType.IllusionTemple, 6))); + }); + } + + /// + /// Tests that the illusion temple update gives a configuration with the swapped data the data of a new + /// database, without renumbering the item definitions: the item definition at 13/51, which owned tickets + /// reference, becomes the Scroll of Blood. It also tests that applying it twice keeps the result. + /// A configuration with the swapped data has version one or two of the update installed. + /// + /// The way in which the configuration got the swapped data. + /// The installed version of the update. + /// The task. + [Test] + public async Task UpdateRestoresSwappedItemsAsync([Values] SwappedState state, [Values(1, 2)] int installedVersion) + { + var (context, gameConfiguration) = await CreateSeason6ConfigurationAsync().ConfigureAwait(false); + using var _ = context; + var expected = CaptureItems(gameConfiguration); + Swap(gameConfiguration, state); + var ownedTicketDefinition = GetItem(gameConfiguration, TicketNumber); + var covenant = GetItem(gameConfiguration, CovenantNumber); + Assert.That(ownedTicketDefinition.Name.ValueInNeutralLanguage, Is.EqualTo("Illusion Sorcerer Covenant"), "The swapped state isn't simulated."); + + var update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = installedVersion; + for (var application = 0; application < 2; application++) + { + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + AssertItems(gameConfiguration, expected); + Assert.That(GetItem(gameConfiguration, TicketNumber), Is.SameAs(ownedTicketDefinition)); + Assert.That(GetItem(gameConfiguration, CovenantNumber), Is.SameAs(covenant)); + Assert.That(installedUpdate.Version, Is.EqualTo(update.Version)); + } + } + + /// + /// Tests that the update changes neither item when only one of the two has the swapped name, because the server + /// owner renamed the other: the data of one item alone can't be swapped. + /// + /// The number of the item which the server owner renamed. + /// The task. + [TestCase(CovenantNumber)] + [TestCase(TicketNumber)] + public async Task UpdateKeepsPartlySwappedItemsAsync(short renamedNumber) + { + var (context, gameConfiguration) = await CreateSeason6ConfigurationAsync().ConfigureAwait(false); + using var _ = context; + Swap(gameConfiguration, SwappedState.RenumberedByUpdate); + GetItem(gameConfiguration, renamedNumber).Name = "Renamed by the owner"; + var expected = CaptureItems(gameConfiguration); + + var update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = 2; + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + AssertItems(gameConfiguration, expected); + } + + /// + /// Captures the data of the two items, and the data which references them: the drop item groups, the mini + /// game definitions which have them as ticket, and the items of the merchant stores. + /// + /// The game configuration. + /// The captured data of each item, by item number. + internal static IReadOnlyDictionary> CaptureItems(GameConfiguration gameConfiguration) + { + return new[] { CovenantNumber, TicketNumber }.ToDictionary(number => number, number => CaptureItem(gameConfiguration, number)); + } + + /// + /// Asserts that the two items have the captured data, property by property. + /// + /// The game configuration. + /// The expected data, captured by . + internal static void AssertItems(GameConfiguration gameConfiguration, IReadOnlyDictionary> expected) + { + Assert.Multiple(() => + { + foreach (var (number, expectedData) in expected) + { + var actualData = CaptureItem(gameConfiguration, number); + foreach (var (name, value) in expectedData) + { + Assert.That(actualData[name], Is.EqualTo(value), $"{ItemGroup}/{number}: {name}"); + } + } + }); + } + + /// + /// Swaps the numbers of the two item definitions, like the first version of the illusion temple update did. + /// + /// The game configuration. + internal static void RenumberLikeVersionOne(GameConfiguration gameConfiguration) + { + var covenant = GetItem(gameConfiguration, CovenantNumber); + var ticket = GetItem(gameConfiguration, TicketNumber); + covenant.Number = TicketNumber; + ticket.Number = CovenantNumber; + } + + /// + /// Gets the item definition with the specified number of the item group 13. + /// + /// The game configuration. + /// The number. + /// The item definition. + internal static ItemDefinition GetItem(GameConfiguration gameConfiguration, short number) + { + return gameConfiguration.Items.Single(item => item.Group == ItemGroup && item.Number == number); + } + + private static void Swap(GameConfiguration gameConfiguration, SwappedState state) + { + if (state == SwappedState.Initialized) + { + // The data initialization created the covenant with the number 51 and the Scroll of Blood with 50. + // The merchant store items and the temple definitions were created by number. + var covenant = GetItem(gameConfiguration, CovenantNumber); + var ticket = GetItem(gameConfiguration, TicketNumber); + var covenantName = covenant.Name; + covenant.Name = ticket.Name; + covenant.Width = 2; + ticket.Name = covenantName; + ticket.Width = 1; + foreach (var group in GetDropItemGroups(gameConfiguration, covenant)) + { + group.PossibleItems.Remove(covenant); + group.PossibleItems.Add(ticket); + } + + return; + } + + RenumberLikeVersionOne(gameConfiguration); + if (state == SwappedState.RenumberedByUpdate) + { + // The temple definitions were created after the renumbering, with the item which got the number 51. + var renumberedCovenant = GetItem(gameConfiguration, TicketNumber); + foreach (var definition in gameConfiguration.MiniGameDefinitions.Where(definition => definition.Type == MiniGameType.IllusionTemple)) + { + definition.TicketItem = renumberedCovenant; + } + } + } + + private static IReadOnlyDictionary CaptureItem(GameConfiguration gameConfiguration, short number) + { + var item = GetItem(gameConfiguration, number); + var data = typeof(ItemDefinition) + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(property => property.GetIndexParameters().Length == 0) + .ToDictionary(property => property.Name, property => AsComparable(property.GetValue(item))); + data["(drop item groups)"] = GetDropItemGroups(gameConfiguration, item); + data["(ticket of mini games)"] = gameConfiguration.MiniGameDefinitions + .Where(definition => ReferenceEquals(definition.TicketItem, item)) + .ToList(); + data["(merchant store items)"] = gameConfiguration.Monsters + .SelectMany(monster => monster.MerchantStore?.Items ?? Enumerable.Empty()) + .Where(storeItem => ReferenceEquals(storeItem.Definition, item)) + .ToList(); + return data; + } + + private static object? AsComparable(object? value) + { + return value is IEnumerable enumerable and not string ? enumerable.Cast().ToList() : value; + } + + private static List GetDropItemGroups(GameConfiguration gameConfiguration, ItemDefinition item) + { + return gameConfiguration.DropItemGroups.Where(group => group.PossibleItems.Any(possibleItem => ReferenceEquals(possibleItem, item))).ToList(); + } + + private static async Task<(IContext Context, GameConfiguration GameConfiguration)> CreateSeason6ConfigurationAsync() + { + var contextProvider = new InMemoryPersistenceContextProvider(); + var dataInitialization = new VersionSeasonSix.DataInitialization(contextProvider, new NullLoggerFactory()); + await dataInitialization.CreateInitialDataAsync(1, true).ConfigureAwait(false); + + var context = contextProvider.CreateNewContext(); + var gameConfiguration = (await context.GetAsync().ConfigureAwait(false)).First(); + return (context, gameConfiguration); + } +} diff --git a/tests/MUnique.OpenMU.Tests/IllusionTempleTicketCraftingTest.cs b/tests/MUnique.OpenMU.Tests/IllusionTempleTicketCraftingTest.cs new file mode 100644 index 0000000000..4ed99705a3 --- /dev/null +++ b/tests/MUnique.OpenMU.Tests/IllusionTempleTicketCraftingTest.cs @@ -0,0 +1,157 @@ +// +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace MUnique.OpenMU.Tests; + +using Microsoft.Extensions.Logging.Abstractions; +using MUnique.OpenMU.DataModel.Configuration; +using MUnique.OpenMU.DataModel.Configuration.Items; +using MUnique.OpenMU.DataModel.Entities; +using MUnique.OpenMU.GameLogic; +using MUnique.OpenMU.GameLogic.PlayerActions.Craftings; +using MUnique.OpenMU.GameLogic.PlayerActions.Items; +using MUnique.OpenMU.GameLogic.Views.NPC; +using MUnique.OpenMU.Persistence.Initialization.VersionSeasonSix; +using MUnique.OpenMU.Persistence.InMemory; +using MUnique.OpenMU.PlugIns; + +/// +/// Tests the chaos goblin combination of the illusion temple ticket with the season 6 configuration: +/// an Old Scroll (13/49) and an Illusion Sorcerer Covenant (13/50) of the same level give the Scroll of Blood +/// (13/51) of this level, which the game client requires to enter the temple. +/// +[TestFixture] +public class IllusionTempleTicketCraftingTest +{ + private const byte EventItemGroup = 13; + + private const short OldScrollNumber = 49; + + private const short CovenantNumber = 50; + + private const short ScrollOfBloodNumber = 51; + + private GameConfiguration _gameConfiguration = null!; + + private IGameContext _gameContext = null!; + + /// + /// Sets up the test environment by initializing the season 6 configuration data. + /// + [OneTimeSetUp] + public async ValueTask SetupAsync() + { + var contextProvider = new InMemoryPersistenceContextProvider(); + await new DataInitialization(contextProvider, new NullLoggerFactory()).CreateInitialDataAsync(0, false).ConfigureAwait(false); + this._gameConfiguration = (await contextProvider.CreateNewConfigurationContext().GetAsync().ConfigureAwait(false)).First(); + + var mapInitializer = new MapInitializer(this._gameConfiguration, new NullLogger(), NullDropGenerator.Instance, null); + var gameContext = new GameContext(this._gameConfiguration, contextProvider, mapInitializer, new NullLoggerFactory(), new PlugInManager(null, new NullLoggerFactory(), null, null), NullDropGenerator.Instance, new ConfigurationChangeMediator()); + mapInitializer.PlugInManager = gameContext.PlugInManager; + mapInitializer.PathFinderPool = gameContext.PathFinderPool; + this._gameContext = gameContext; + } + + /// + /// Tests that an Old Scroll and an Illusion Sorcerer Covenant give the Scroll of Blood of their level. + /// + /// The level of the items, which is the level of the temple. + [TestCase(1)] + [TestCase(6)] + public async ValueTask OldScrollAndCovenantGiveScrollOfBloodAsync(byte level) + { + var player = await PlayerTestHelper.CreatePlayerAsync(this._gameContext).ConfigureAwait(false); + await this.AddToChaosMachineAsync(player, EventItemGroup, OldScrollNumber, level).ConfigureAwait(false); + await this.AddToChaosMachineAsync(player, EventItemGroup, CovenantNumber, level).ConfigureAwait(false); + await this.AddJewelOfChaosAsync(player).ConfigureAwait(false); + var crafting = new TestableIllusionTempleTicketCrafting(); + + Assert.That(crafting.TryGetRequiredItems(player, out var requiredItems, out _), Is.Null); + var result = await crafting.CreateResultItemsAsync(requiredItems, player).ConfigureAwait(false); + + Assert.That(result, Has.Count.EqualTo(1)); + Assert.That(result[0].Definition, Is.SameAs(this.GetItem(EventItemGroup, ScrollOfBloodNumber))); + Assert.That(result[0].Level, Is.EqualTo(level)); + } + + /// + /// Tests that the combination gives the ticket which the temple of the level accepts, also when the server + /// owner selected another ticket item, so the crafting and the temples stay in step. + /// + [Test] + public async ValueTask CombinationGivesTheTicketOfTheTempleAsync() + { + const byte level = 3; + var temple = this._gameConfiguration.MiniGameDefinitions.Single(definition => definition.Type == MiniGameType.IllusionTemple && definition.TicketItemLevel == level); + var originalTicket = temple.TicketItem; + var selectedTicket = this.GetItem(EventItemGroup, OldScrollNumber); + temple.TicketItem = selectedTicket; + try + { + var player = await PlayerTestHelper.CreatePlayerAsync(this._gameContext).ConfigureAwait(false); + await this.AddToChaosMachineAsync(player, EventItemGroup, OldScrollNumber, level).ConfigureAwait(false); + await this.AddToChaosMachineAsync(player, EventItemGroup, CovenantNumber, level).ConfigureAwait(false); + await this.AddJewelOfChaosAsync(player).ConfigureAwait(false); + var crafting = new TestableIllusionTempleTicketCrafting(); + + Assert.That(crafting.TryGetRequiredItems(player, out var requiredItems, out _), Is.Null); + var result = await crafting.CreateResultItemsAsync(requiredItems, player).ConfigureAwait(false); + + Assert.That(result.Single().Definition, Is.SameAs(selectedTicket)); + } + finally + { + temple.TicketItem = originalTicket; + } + } + + /// + /// Tests that the Scroll of Blood is no ingredient: it is the result, so an Old Scroll and a Scroll of Blood + /// are refused. + /// + [Test] + public async ValueTask OldScrollAndScrollOfBloodAreRefusedAsync() + { + var player = await PlayerTestHelper.CreatePlayerAsync(this._gameContext).ConfigureAwait(false); + await this.AddToChaosMachineAsync(player, EventItemGroup, OldScrollNumber, 1).ConfigureAwait(false); + await this.AddToChaosMachineAsync(player, EventItemGroup, ScrollOfBloodNumber, 1).ConfigureAwait(false); + await this.AddJewelOfChaosAsync(player).ConfigureAwait(false); + + Assert.That(new IllusionTempleTicketCrafting().TryGetRequiredItems(player, out _, out _), Is.EqualTo(CraftingResult.IncorrectMixItems)); + } + + private ValueTask AddJewelOfChaosAsync(Player player) + { + var jewelOfChaos = this._gameConfiguration.Items.Single(item => item.Name.ValueInNeutralLanguage == "Jewel of Chaos"); + return this.AddToChaosMachineAsync(player, jewelOfChaos.Group, jewelOfChaos.Number, 0); + } + + private async ValueTask AddToChaosMachineAsync(Player player, byte group, short number, byte level) + { + var item = player.PersistenceContext.CreateNew(); + item.Definition = this.GetItem(group, number); + item.Level = level; + item.Durability = 1; + Assert.That(await player.TemporaryStorage!.AddItemAsync(item).ConfigureAwait(false), Is.True); + } + + private ItemDefinition GetItem(byte group, short number) => this._gameConfiguration.Items.Single(item => item.Group == group && item.Number == number); + + /// + /// Makes the creation of the result accessible, because the combination itself succeeds only by chance. + /// + private sealed class TestableIllusionTempleTicketCrafting : IllusionTempleTicketCrafting + { + /// + /// Creates the result items of the combination. + /// + /// The required items. + /// The player. + /// The result items. + public ValueTask> CreateResultItemsAsync(IList requiredItems, Player player) + { + return this.CreateOrModifyResultItemsAsync(requiredItems, player, 0, 100); + } + } +} diff --git a/tests/MUnique.OpenMU.Tests/StorageTest.cs b/tests/MUnique.OpenMU.Tests/StorageTest.cs index cd62b75a83..24bfcd955b 100644 --- a/tests/MUnique.OpenMU.Tests/StorageTest.cs +++ b/tests/MUnique.OpenMU.Tests/StorageTest.cs @@ -112,6 +112,57 @@ public async ValueTask AddItem1X2FailBottomAsync() Assert.That(storage.FreeSlots.Contains((byte)(12 + (7 * 8))), Is.True); } + /// + /// Tests that loading a storage moves an item which doesn't fit at its slot anymore, e.g. because its item + /// definition became bigger (the Scroll of Blood, 1x2 to 2x2), or the item next to it, to a free place, so both + /// are in the storage without overlapping. + /// + /// The slot of the grown item, relative to the first slot of the grid. + [TestCase(7)] // The rightmost column: the item would hang over the right border. + [TestCase(1)] // Next to an item to its right. + public void LoadingMovesGrownItemToAFreePlace(byte slotInGrid) + { + var grownItem = CreateLoadedItem(2, 2, (byte)(12 + slotInGrid)); + var blockingItem = CreateLoadedItem(1, 1, 12 + 2); + var itemStorage = this.CreateItemStorage(grownItem, blockingItem); + + var storage = new Storage(12 + 64, 12, 0, itemStorage); + + Assert.Multiple(() => + { + Assert.That(storage.Items, Does.Contain(grownItem)); + Assert.That(storage.Items, Does.Contain(blockingItem)); + Assert.That(storage.FreeSlots.Count(), Is.EqualTo(64 - 4 - 1), "The two items overlap."); + }); + } + + /// + /// Tests that loading a storage fails when an item which doesn't fit at its slot finds no free place at all. + /// Only a storage without a function for such an item fails; the inventory and the vault put the item into the + /// waiting items of the character instead (see ). + /// + [Test] + public void LoadingFailsWhenGrownItemFindsNoFreePlace() + { + var items = Enumerable.Range(0, 63).Select(index => CreateLoadedItem(1, 1, (byte)(12 + index))).ToList(); + items.Add(CreateLoadedItem(2, 2, 12 + 63)); + var itemStorage = this.CreateItemStorage(items.ToArray()); + + Assert.That(() => new Storage(12 + 64, 12, 0, itemStorage), Throws.TypeOf().With.Message.Contains("do not fit")); + } + + /// + /// Creates an item as it is loaded from the database, with its collections, at the specified slot. + /// + private static Item CreateLoadedItem(byte width, byte height, byte slot) + { + return new MUnique.OpenMU.Persistence.BasicModel.Item + { + Definition = new ItemDefinition { Name = $"Item {width}x{height}", Durability = 1, Width = width, Height = height }, + ItemSlot = slot, + }; + } + private ItemDefinition GetItemDefintion(byte width, byte heigth) { var itemDefinition = new ItemDefinition @@ -130,10 +181,10 @@ private Item GetItem(byte width, byte heigth) return item; } - private ItemStorage CreateItemStorage() + private ItemStorage CreateItemStorage(params Item[] items) { var storage = new Mock(); - storage.Setup(s => s.Items).Returns(new List()); + storage.Setup(s => s.Items).Returns(items.ToList()); return storage.Object; } } \ No newline at end of file