diff --git a/src/GameLogic/MiniGames/IllusionTempleContext.cs b/src/GameLogic/MiniGames/IllusionTempleContext.cs index c0a24cb4ec..0579fc81e5 100644 --- a/src/GameLogic/MiniGames/IllusionTempleContext.cs +++ b/src/GameLogic/MiniGames/IllusionTempleContext.cs @@ -1,4 +1,4 @@ -// +// // Licensed under the MIT License. See LICENSE file in the project root for full license information. // @@ -9,6 +9,7 @@ namespace MUnique.OpenMU.GameLogic.MiniGames; using MUnique.OpenMU.DataModel.Configuration.Items; using MUnique.OpenMU.GameLogic.Attributes; using MUnique.OpenMU.GameLogic.NPC; +using MUnique.OpenMU.GameLogic.Views; using MUnique.OpenMU.GameLogic.Views.Inventory; using MUnique.OpenMU.Pathfinding; @@ -71,7 +72,7 @@ public sealed class IllusionTempleContext : MiniGameContext /// /// The highest NPC number of the roaming "Illusion Sorc. Spirit" arena monsters, across all temples. /// - private const short ArenaMonsterRangeEnd = 399; + private const short ArenaMonsterRangeEnd = 403; /// /// The skill points a player starts a match with. @@ -356,7 +357,7 @@ public async ValueTask TalkToNpcStoneStatueAsync(Player player) } await this.ForEachPlayerAsync(p => p.InvokeViewPlugInAsync( - vp => vp.ShowHolyItemRelicsAsync(player.Id, player.Name)).AsTask()).ConfigureAwait(false); + vp => vp.ShowHolyItemRelicsAsync(player.GetId(p), player.Name)).AsTask()).ConfigureAwait(false); } catch { @@ -457,11 +458,12 @@ public async ValueTask UseSkillAsync(Player player, ushort skillNumber, ushort t if (this._skillPoints.GetValueOrDefault(player, InitialSkillPoints) < SkillCost(skillNumber)) { await player.InvokeViewPlugInAsync( - p => p.ShowSkillUsageResultAsync(false, skillNumber, player.Id, targetObjectIndex)).ConfigureAwait(false); + p => p.ShowSkillUsageResultAsync(false, skillNumber, player.GetId(player), targetObjectIndex)).ConfigureAwait(false); return; } - var target = player.CurrentMap?.GetObject(targetObjectIndex) as IAttackable; + // The client names itself by the constant player id, not by the id of its player on this map. + var target = player.GetObject(targetObjectIndex) as IAttackable; var success = skillNumber switch { OrderOfProtectionSkillNumber => await this.UseOrderOfProtectionAsync(player).ConfigureAwait(false), @@ -477,7 +479,7 @@ await player.InvokeViewPlugInAsync( } await player.InvokeViewPlugInAsync( - p => p.ShowSkillUsageResultAsync(success, skillNumber, player.Id, target?.Id ?? 0)).ConfigureAwait(false); + p => p.ShowSkillUsageResultAsync(success, skillNumber, player.GetId(player), target?.GetId(player) ?? 0)).ConfigureAwait(false); } /// @@ -575,8 +577,8 @@ protected override async ValueTask OnGameStartAsync(ICollection players) await base.OnGameStartAsync(players).ConfigureAwait(false); // The client keeps its event interface closed and the arena barriers up until it's told that - // the battle started - the barrier areas are hardcoded at client side, so this is the only way - // to open them. The two states are deliberately separated by a short delay, so the players + // the battle started - that's the only way to open them at client side (the server's terrain is + // opened by OpenArenaBarriers at the same time). The two states are deliberately separated by a short delay, so the players // actually get to see the preparation phase before the barriers drop - sending both back to // back made the client skip straight to the battle without any noticeable wait. var templeNumber = (byte)this.Definition.GameLevel; @@ -594,6 +596,8 @@ await this.ForEachPlayerAsync(player => player.InvokeViewPlugInAsync player.InvokeViewPlugInAsync( p => p.ChangeEventStateAsync(templeNumber, IllusionTempleEventStatus.BattleStarted)).AsTask()).ConfigureAwait(false); await this.ShowGoldenMessageAsync(nameof(PlayerMessage.IllusionTempleBattleStartedMessage)).ConfigureAwait(false); @@ -644,7 +648,7 @@ protected override async void OnPlayerDied(object? sender, DeathInformation e) /// /// - /// Killing one of the roaming "Illusion Sorc. Spirit" arena monsters (386 to 399) grants the killer + /// Killing one of the roaming "Illusion Sorc. Spirit" arena monsters (386 to 403) grants the killer /// skill points for the event's special skills. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD100:Avoid async void methods", Justification = "Catching all Exceptions.")] @@ -682,7 +686,9 @@ protected override async void OnMonsterDied(object? sender, DeathInformation e) /// warps and leave the player on two maps with duplicate map-change packets. Leaving the event is /// handled by and by the base class's exit handling, both of which /// respect the map's configured safezone. If fewer than players - /// remain afterwards, the match can't continue and is ended right away. + /// remain afterwards while the match is running, it can't continue and is ended right away. Before the + /// start that's not checked here: a player may leave the waiting room again, and the others can still + /// come in. If too few players are left at the start, the event isn't started. /// protected override async ValueTask OnObjectRemovedFromMapAsync((GameMap Map, ILocateable Object) args) { @@ -702,7 +708,7 @@ protected override async ValueTask OnObjectRemovedFromMapAsync((GameMap Map, ILo await base.OnObjectRemovedFromMapAsync(args).ConfigureAwait(false); - if (args.Object is Player && this.PlayerCount < this.MinimumPlayerCount) + if (args.Object is Player && this.State == MiniGameState.Playing && this.PlayerCount < this.MinimumPlayerCount) { this.FinishEvent(); } @@ -754,7 +760,7 @@ protected async override ValueTask OnPlayerPickedUpItemAsync((Player Picker, ILo // The client needs to be told who the new carrier is - otherwise it keeps showing the // previous one (or nobody) as the hero on its mini map. await this.ForEachPlayerAsync(p => p.InvokeViewPlugInAsync( - vp => vp.ShowHolyItemRelicsAsync(args.Picker.Id, args.Picker.Name)).AsTask()).ConfigureAwait(false); + vp => vp.ShowHolyItemRelicsAsync(args.Picker.GetId(p), args.Picker.Name)).AsTask()).ConfigureAwait(false); } } @@ -1069,7 +1075,7 @@ private void NotifyWhenSkillEffectEnds(MagicEffect magicEffect, ushort skillNumb { magicEffect.EffectTimeOut += _ => this.ForEachPlayerAsync( p => p.InvokeViewPlugInAsync( - view => view.ShowSkillEndedAsync(skillNumber, affectedObject.Id)).AsTask()); + view => view.ShowSkillEndedAsync(skillNumber, affectedObject.GetId(p))).AsTask()); } /// @@ -1094,6 +1100,31 @@ private async ValueTask RemoveRelicFromInventoryAsync(Player player) await player.InvokeViewPlugInAsync(p => p.ItemDropResultAsync(relicItem.ItemSlot, true)).ConfigureAwait(false); } + /// + /// Opens the barriers between the bases of the teams and the arena on the server's terrain. + /// + /// + /// The barriers are the water tiles of the temple map. The client opens its own copy when it's told that + /// the battle started, by clearing every water tile of the map; the server does the same, so that both + /// agree on the configured terrain. Until then the tiles aren't walkable, and every step into the arena + /// is set back. They aren't closed again: the map belongs to this game and is discarded with it. + /// + private void OpenArenaBarriers() + { + var terrain = this.Map.Terrain; + var attributes = terrain.AttributeMap; + for (var x = 0; x < attributes.GetLength(0); x++) + { + for (var y = 0; y < attributes.GetLength(1); y++) + { + if ((attributes[x, y] & (byte)TerrainAttributeType.Water) != 0) + { + terrain.ApplyTerrainAttribute((byte)x, (byte)y, TerrainAttributeType.Water, false); + } + } + } + } + /// /// Moves a player to his team's starting chamber. /// @@ -1159,14 +1190,14 @@ private ValueTask UpdateStateAsync(Player player) var teamMembers = this._teams .Where(entry => entry.Value == ownTeam && entry.Key != player) .Select(entry => ( - PlayerId: entry.Key.Id, + PlayerId: entry.Key.GetId(player), MapNumber: (byte)(entry.Key.CurrentMap?.Definition.Number ?? 0), PositionX: entry.Key.Position.X, PositionY: entry.Key.Position.Y)) .ToList(); (ushort PlayerId, byte PositionX, byte PositionY)? relicCarrier = this._relicCarrier is { } carrier - ? (carrier.Id, carrier.Position.X, carrier.Position.Y) + ? (carrier.GetId(player), carrier.Position.X, carrier.Position.Y) : null; return player.InvokeViewPlugInAsync( diff --git a/src/GameLogic/MiniGames/Kanturu/KanturuContext.cs b/src/GameLogic/MiniGames/Kanturu/KanturuContext.cs index a9ca6c3d43..4dc76c8572 100644 --- a/src/GameLogic/MiniGames/Kanturu/KanturuContext.cs +++ b/src/GameLogic/MiniGames/Kanturu/KanturuContext.cs @@ -203,7 +203,7 @@ public KanturuContext( /// Tower entrants spawn at the tower entry instead of the event start. /// /// The player which enters. - /// The tower entry point, or null to keep the warp target. + /// The tower entry point, or the one of the base class. internal override Point? GetEntrySpawnPosition(Player player) { if (this.TowerMode || this.CurrentKanturuState == KanturuState.Tower) @@ -211,7 +211,7 @@ public KanturuContext( return this.TowerEntryPoint; } - return null; + return base.GetEntrySpawnPosition(player); } /// diff --git a/src/GameLogic/MiniGames/MiniGameContext.cs b/src/GameLogic/MiniGames/MiniGameContext.cs index 9697d81a31..60e7c7b70f 100644 --- a/src/GameLogic/MiniGames/MiniGameContext.cs +++ b/src/GameLogic/MiniGames/MiniGameContext.cs @@ -361,7 +361,25 @@ internal async ValueTask TryRejoinAsync(Player player) /// /// The player which enters. /// The spawn position, or null to keep the warp target. - internal virtual Point? GetEntrySpawnPosition(Player player) => null; + /// + /// The warp picks a random tile of the entrance gate without looking at the terrain, and some gates contain + /// blocked tiles (e.g. the pillars in the entrance of the illusion temples). A player who lands on one would + /// be warped to the safezone, out of the game he just paid for, so he gets a random walkable tile of the + /// entrance gate instead. + /// + internal virtual Point? GetEntrySpawnPosition(Player player) + { + if (player.SelectedCharacter is not { } character + || this.Map.Terrain.WalkMap[character.PositionX, character.PositionY] + || this.Definition.Entrance is not { } entrance) + { + return null; + } + + var walkMap = this.Map.Terrain.WalkMap; + var walkablePoints = entrance.GetPossibleLandingPoints().Where(point => walkMap[point.X, point.Y]).ToList(); + return walkablePoints.Count > 0 ? walkablePoints[Rand.NextInt(0, walkablePoints.Count)] : null; + } /// /// Starts the game loop, unless it was started before. It can't start in the diff --git a/src/GameLogic/PlayerActions/TalkNpcAction.cs b/src/GameLogic/PlayerActions/TalkNpcAction.cs index e4f700d52d..c33ee9a75d 100644 --- a/src/GameLogic/PlayerActions/TalkNpcAction.cs +++ b/src/GameLogic/PlayerActions/TalkNpcAction.cs @@ -68,7 +68,11 @@ public async ValueTask TalkToNpcAsync(Player player, NonPlayerCharacter npc) /// /// The NPC whose dialog is about to be opened. /// A value indicating whether this action advances the player state to . - protected virtual bool AdvancePlayerState(NonPlayerCharacter npc) => true; + /// + /// Not for the illusion temple entrance: its window is closed by the client without a close request (the original + /// client did the same), so the player would stay in the dialog state and couldn't talk to any other npc. + /// + protected virtual bool AdvancePlayerState(NonPlayerCharacter npc) => npc.Definition.NpcWindow != NpcWindow.IllusionTemple; private async ValueTask ShowDialogOfOpenedNpcAsync(Player player) { diff --git a/src/GameServer/RemoteView/MiniGames/Extensions.cs b/src/GameServer/RemoteView/MiniGames/Extensions.cs index b1f2102685..2216594355 100644 --- a/src/GameServer/RemoteView/MiniGames/Extensions.cs +++ b/src/GameServer/RemoteView/MiniGames/Extensions.cs @@ -94,19 +94,21 @@ public static DoppelgangerEnterResult.EnterResult ToDoppelgangerEnterResult(this /// The enter result. /// The converted result. /// - /// The client uses distinct result bytes for admission and ticket failures (3), a full event (4), - /// and a player-killer rejection (7). Preserve these messages instead of collapsing every failure - /// into the not-open result (1). + /// The client shows a text of its own for a character level which doesn't fit the temple of the ticket (3), a full + /// event (4) and a player-killer rejection (7), and none for the other result bytes. The server tells every refusal + /// in words before sending the result, so the other outcomes (a missing ticket, not enough zen, any other failure) get + /// a result byte without a client text (1); with 3 the client added "The admission and scroll levels do not match", + /// which is wrong for them. /// public static byte ToIllusionTempleEnterResult(this EnterResult enterResult) { return enterResult switch { EnterResult.Success => 0, - EnterResult.NotOpen => 1, + EnterResult.CharacterLevelTooHigh or EnterResult.CharacterLevelTooLow => 3, EnterResult.Full => 4, EnterResult.PlayerKillerCantEnter => 7, - _ => 3, + _ => 1, }; } diff --git a/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs b/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs index fdd42d7471..1d1f821bb2 100644 --- a/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs +++ b/src/Persistence/Initialization/Updates/IllusionTempleDataUpdatePlugIn.cs @@ -80,7 +80,7 @@ public class IllusionTempleDataUpdatePlugIn : UpdatePlugInBase /// /// The highest NPC number of the roaming "Illusion Sorc. Spirit" arena monsters, across all temples. /// - private const short ArenaMonsterRangeEnd = 399; + private const short ArenaMonsterRangeEnd = 403; /// /// The default minimum player count for an illusion temple match, if the definition doesn't already @@ -131,7 +131,7 @@ public class IllusionTempleDataUpdatePlugIn : UpdatePlugInBase /// /// 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. + /// how many ids to cycle through) which each of them roams with. /// private static readonly (byte MapNumber, short ArenaMonsterBase, int ArenaMonsterCycleLength)[] Temples = { @@ -139,8 +139,8 @@ private static readonly (byte MapNumber, short ArenaMonsterBase, int ArenaMonste (46, 389, 3), (47, 392, 3), (48, 395, 3), - (49, 398, 2), - (50, 0, 0), + (49, 398, 3), + (50, 401, 3), }; /// @@ -190,8 +190,8 @@ private static readonly (byte X, byte Y)[] ArenaMonsterPositions = }; /// - /// The stats of the 14 "Illusion Sorc. Spirit" arena monster variants (386 to 399), one per temple - /// level (temples 1 to 4 have three variants each, temple 5 has two, temple 6 has none). + /// The stats of the 18 "Illusion Sorc. Spirit" arena monster variants (386 to 403), three per temple + /// level. /// private static readonly (short Number, int Level, int Hp, int MinDmg, int MaxDmg, int Defense, int AttackRate, int DefenseRate, byte AttackRange, short ViewRange, int MoveDelayMs, int AttackDelayMs)[] ArenaMonsterStats = { @@ -209,6 +209,10 @@ private static readonly (short Number, int Level, int Hp, int MinDmg, int MaxDmg (397, 82, 19680, 520, 540, 400, 840, 280, 1, 6, 1600, 2000), (398, 85, 25500, 595, 615, 450, 760, 275, 4, 4, 800, 1600), (399, 85, 25500, 615, 635, 470, 820, 303, 4, 4, 800, 1600), + (400, 87, 26100, 635, 655, 490, 900, 335, 1, 6, 1600, 2000), + (401, 112, 36000, 720, 740, 550, 1015, 405, 4, 4, 800, 1600), + (402, 112, 36000, 740, 760, 570, 1080, 440, 4, 4, 800, 1600), + (403, 114, 36800, 760, 780, 590, 1190, 485, 1, 6, 1600, 2000), }; /// @@ -224,13 +228,13 @@ private static readonly (short Number, int Level, int Hp, int MinDmg, int MaxDmg public override bool IsMandatory => true; /// - public override int Version => 4; + public override int Version => 5; /// public override DateTime CreatedAt => new(2026, 07, 29, 20, 0, 0, DateTimeKind.Utc); /// - public override DateTime UpdatedAt => new(2026, 11, 17, 0, 0, 0, DateTimeKind.Utc); + public override DateTime UpdatedAt => new(2026, 11, 23, 0, 0, 0, DateTimeKind.Utc); /// /// @@ -241,6 +245,9 @@ private static readonly (short Number, int Level, int Hp, int MinDmg, int MaxDmg /// it runs the restoration again on a database which has version three. /// 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. + /// Versions one to four gave temple 5 only two arena monster variants and temple 6 none; version five adds the + /// missing variants (400 to 403) and their spawns (see ), and lets characters of + /// level 400 without the master class enter temple 5 (see ). /// protected override async ValueTask ApplyAsync(IContext context, GameConfiguration gameConfiguration, int? installedVersion) { @@ -251,6 +258,12 @@ protected override async ValueTask ApplyAsync(IContext context, GameConfiguratio } RestoreTicketItems(gameConfiguration); + + if (installedVersion is null or < 5) + { + this.AddMissingArenaMonsters(context, gameConfiguration); + AllowLevel400InTemple5(gameConfiguration); + } } /// @@ -284,6 +297,29 @@ protected override async ValueTask ApplyAsync(IContext context, GameConfiguratio } } + /// + /// Raises the maximum character level of temple 5 from 399 to 400. A character of level 400 without the master + /// class goes to temple 5 (the master classes to temple 6), so with 399 he couldn't enter any temple. + /// + /// Only the values which are still the old default are changed, so an owner's own range stays. + private static void AllowLevel400InTemple5(GameConfiguration gameConfiguration) + { + const int previousMaximumLevel = 399; + const int maximumLevel = 400; + foreach (var temple5 in gameConfiguration.MiniGameDefinitions.Where(d => d is { Type: MiniGameType.IllusionTemple, GameLevel: 5 })) + { + if (temple5.MaximumCharacterLevel == previousMaximumLevel) + { + temple5.MaximumCharacterLevel = maximumLevel; + } + + if (temple5.MaximumSpecialCharacterLevel == previousMaximumLevel) + { + temple5.MaximumSpecialCharacterLevel = maximumLevel; + } + } + } + /// /// 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. @@ -531,7 +567,7 @@ private void AddRelicItem(IContext context, GameConfiguration gameConfiguration) } /// - /// Adds the 14 "Illusion Sorc. Spirit" arena monster definitions (386 to 399), if they don't exist + /// Adds the 18 "Illusion Sorc. Spirit" arena monster definitions (386 to 403), if they don't exist /// yet. /// private void AddArenaMonsterDefinitions(IContext context, GameConfiguration gameConfiguration) @@ -580,6 +616,53 @@ private void AddArenaMonsterDefinitions(IContext context, GameConfiguration game /// them - the game maps aren't recreated by , only its mini /// game definitions are. /// + /// + /// Adds the arena monsters which the versions before five didn't have: the third variant of temple 5 (400) and + /// the three variants of temple 6 (401 to 403), with their spawns. + /// + /// + /// A spawn of temple 5 only gets the new variant when it still has the monster which the old version put there, + /// so a spawn which the server owner changed stays as it is. Temple 6 only gets the spawns which don't exist yet. + /// + private void AddMissingArenaMonsters(IContext context, GameConfiguration gameConfiguration) + { + this.AddArenaMonsterDefinitions(context, gameConfiguration); + + foreach (var temple in Temples.Where(t => t.MapNumber is 49 or 50)) + { + if (gameConfiguration.Maps.FirstOrDefault(m => m.Number == temple.MapNumber) is not { } map) + { + continue; + } + + for (var i = 0; i < ArenaMonsterPositions.Length; i++) + { + var monsterNumber = (short)(temple.ArenaMonsterBase + (i % temple.ArenaMonsterCycleLength)); + if (gameConfiguration.Monsters.FirstOrDefault(monster => monster.Number == monsterNumber) is not { } monsterDefinition) + { + continue; + } + + var spawnNumber = (short)(120 + i); + var id = GuidHelper.CreateGuid(map.Number, spawnNumber); + if (map.MonsterSpawns.FirstOrDefault(spawn => spawn.GetId() == id) is { } existingSpawn) + { + // Temple 5 used to alternate between 398 and 399. + var previousMonsterNumber = (short)(temple.ArenaMonsterBase + (i % 2)); + if (temple.MapNumber == 49 && existingSpawn.MonsterDefinition?.Number == previousMonsterNumber) + { + existingSpawn.MonsterDefinition = monsterDefinition; + } + + continue; + } + + var (x, y) = ArenaMonsterPositions[i]; + this.AddSpawn(context, map, spawnNumber, monsterDefinition, x, y, SpawnTrigger.AutomaticDuringEvent); + } + } + } + private void AddMapSpawns(IContext context, GameConfiguration gameConfiguration) { var stoneStatue = gameConfiguration.Monsters.FirstOrDefault(monster => monster.Number == StoneStatueNumber); diff --git a/src/Persistence/Initialization/VersionSeasonSix/Events/IllusionTempleInitializer.cs b/src/Persistence/Initialization/VersionSeasonSix/Events/IllusionTempleInitializer.cs index e1120e58e9..3be28155ca 100644 --- a/src/Persistence/Initialization/VersionSeasonSix/Events/IllusionTempleInitializer.cs +++ b/src/Persistence/Initialization/VersionSeasonSix/Events/IllusionTempleInitializer.cs @@ -54,11 +54,12 @@ public override void Initialize() illusionTemple4.MinimumSpecialCharacterLevel = 351; illusionTemple4.MaximumSpecialCharacterLevel = 380; + // Up to 400: a character of level 400 without the master class goes to temple 5, as the client expects. var illusionTemple5 = this.CreateIllusionTempleDefinition(5, IllusionTemple5.Number, 7000000); illusionTemple5.MinimumCharacterLevel = 381; - illusionTemple5.MaximumCharacterLevel = 399; + illusionTemple5.MaximumCharacterLevel = 400; illusionTemple5.MinimumSpecialCharacterLevel = 381; - illusionTemple5.MaximumSpecialCharacterLevel = 399; + illusionTemple5.MaximumSpecialCharacterLevel = 400; var illusionTemple6 = this.CreateIllusionTempleDefinition(6, IllusionTemple6.Number, 8000000); illusionTemple6.RequiresMasterClass = true; diff --git a/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple5.cs b/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple5.cs index fcd45a615f..6fdc919f4f 100644 --- a/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple5.cs +++ b/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple5.cs @@ -84,12 +84,12 @@ protected override IEnumerable CreateMonsterSpawns() yield return this.CreateMonsterSpawn(112, this.NpcDictionary[383], 141, 059, Direction.South, SpawnTrigger.AutomaticDuringEvent); // Alliance Item Storage yield return this.CreateMonsterSpawn(113, this.NpcDictionary[384], 194, 113, Direction.South, SpawnTrigger.AutomaticDuringEvent); // Illusion Item Storage - // Roaming "Illusion Sorc. Spirit" monsters (398-399) - killing them grants skill points for the + // Roaming "Illusion Sorc. Spirit" monsters (398-400) - killing them grants skill points for the // event's special skills. for (var i = 0; i < SorcererSpiritPositions.Length; i++) { var (x, y) = SorcererSpiritPositions[i]; - yield return this.CreateMonsterSpawn((short)(120 + i), this.NpcDictionary[(short)(398 + (i % 2))], x, y, Direction.Undefined, SpawnTrigger.AutomaticDuringEvent); + yield return this.CreateMonsterSpawn((short)(120 + i), this.NpcDictionary[(short)(398 + (i % 3))], x, y, Direction.Undefined, SpawnTrigger.AutomaticDuringEvent); } } diff --git a/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple6.cs b/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple6.cs index 804880fcb3..54a2c0d14a 100644 --- a/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple6.cs +++ b/src/Persistence/Initialization/VersionSeasonSix/Maps/IllusionTemple6.cs @@ -18,6 +18,24 @@ internal class IllusionTemple6 : BaseMapInitializer /// internal const byte Number = 50; + /// + /// The positions of the roaming "Illusion Sorc. Spirit" monsters in the arena. + /// + private static readonly (byte X, byte Y)[] SorcererSpiritPositions = + { + (131, 93), (131, 89), (131, 85), + (168, 123), (164, 123), (160, 123), + (169, 48), (169, 52), (169, 56), + (206, 85), (206, 81), (206, 77), + (158, 85), (168, 94), (169, 75), + (179, 85), (157, 66), (162, 66), + (150, 78), (150, 73), (176, 103), + (181, 103), (187, 98), (187, 92), + (197, 57), (141, 113), (193, 61), + (145, 109), (189, 65), (149, 105), + (167, 87), (171, 83), + }; + /// /// Initializes a new instance of the class. /// @@ -66,7 +84,13 @@ protected override IEnumerable CreateMonsterSpawns() yield return this.CreateMonsterSpawn(112, this.NpcDictionary[383], 141, 059, Direction.South, SpawnTrigger.AutomaticDuringEvent); // Alliance Item Storage yield return this.CreateMonsterSpawn(113, this.NpcDictionary[384], 194, 113, Direction.South, SpawnTrigger.AutomaticDuringEvent); // Illusion Item Storage - // Temple 6 has no roaming "Illusion Sorc. Spirit" monsters. + // Roaming "Illusion Sorc. Spirit" monsters (401-403) - killing them grants skill points for the + // event's special skills. + for (var i = 0; i < SorcererSpiritPositions.Length; i++) + { + var (x, y) = SorcererSpiritPositions[i]; + yield return this.CreateMonsterSpawn((short)(120 + i), this.NpcDictionary[(short)(401 + (i % 3))], x, y, Direction.Undefined, SpawnTrigger.AutomaticDuringEvent); + } } /// diff --git a/src/Persistence/Initialization/VersionSeasonSix/NpcInitialization.cs b/src/Persistence/Initialization/VersionSeasonSix/NpcInitialization.cs index c89c9e0815..1452c28ae7 100644 --- a/src/Persistence/Initialization/VersionSeasonSix/NpcInitialization.cs +++ b/src/Persistence/Initialization/VersionSeasonSix/NpcInitialization.cs @@ -1131,9 +1131,10 @@ public override void Initialize() } /// - /// Creates the "Illusion Sorc. Spirit" monsters (386-399) which roam the arena of the six illusion + /// Creates the "Illusion Sorc. Spirit" monsters (386-403) which roam the arena of the six illusion /// temples - killing them grants skill points for the event's special skills. Each temple level uses - /// its own set of three (temple 5: two) increasingly stronger variants. + /// its own set of three increasingly stronger variants, which the client shows as the lightning, ice and + /// poison spirit. /// private void CreateIllusionSorcererSpirits() { @@ -1153,6 +1154,10 @@ private void CreateIllusionSorcererSpirits() (397, 82, 19680, 520, 540, 400, 840, 280, 1, 6, 1600, 2000), (398, 85, 25500, 595, 615, 450, 760, 275, 4, 4, 800, 1600), (399, 85, 25500, 615, 635, 470, 820, 303, 4, 4, 800, 1600), + (400, 87, 26100, 635, 655, 490, 900, 335, 1, 6, 1600, 2000), + (401, 112, 36000, 720, 740, 550, 1015, 405, 4, 4, 800, 1600), + (402, 112, 36000, 740, 760, 570, 1080, 440, 4, 4, 800, 1600), + (403, 114, 36800, 760, 780, 590, 1190, 485, 1, 6, 1600, 2000), }; foreach (var spirit in spirits) diff --git a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs index 0b4d9630d7..ccad8987d1 100644 --- a/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs +++ b/tests/MUnique.OpenMU.Persistence.Initialization.Tests/IllusionTempleDataTest.cs @@ -1,4 +1,4 @@ -// +// // Licensed under the MIT License. See LICENSE file in the project root for full license information. // @@ -35,8 +35,18 @@ internal class IllusionTempleDataTest private static readonly short[] TempleMapNumbers = [45, 46, 47, 48, 49, 50]; /// - /// The temples which roam with arena monsters, and the NPC numbers each of them uses. Temple 6 - /// has none, so it is not listed here. + /// The number of roaming arena monster spawns of each temple. + /// + private const int ArenaMonsterSpawnCount = 32; + + /// + /// The first spawn number of the roaming arena monsters. + /// + private const short FirstArenaMonsterSpawnNumber = 120; + + /// + /// The temples and the NPC numbers of the arena monsters each of them roams with, in the order in which + /// the spawns cycle through them. /// private static readonly (short MapNumber, short[] ArenaMonsters)[] TemplesWithArenaMonsters = [ @@ -44,7 +54,8 @@ private static readonly (short MapNumber, short[] ArenaMonsters)[] TemplesWithAr (46, [389, 390, 391]), (47, [392, 393, 394]), (48, [395, 396, 397]), - (49, [398, 399]), + (49, [398, 399, 400]), + (50, [401, 402, 403]), ]; /// @@ -307,6 +318,74 @@ public async Task UpdatePreservesCustomizedTempleTicketBindingAsync( } } + /// + /// Tests that the update gives a database of version four the arena monsters which it was missing: the third + /// variant of temple 5 and the three variants of temple 6, with their spawns. A temple 5 spawn which the server + /// owner changed stays as it is, and applying the update a second time changes nothing. + /// + /// The task. + [Test] + public async Task UpdateAddsTheMissingArenaMonstersToVersionFourAsync() + { + 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 update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = 4; + RevertToVersionFourArenaMonsters(gameConfiguration); + + // The owner put another monster on the third spawn of temple 5, which version four gave the 398. + var temple5 = gameConfiguration.Maps.Single(map => map.Number == 49); + var customizedSpawn = GetArenaMonsterSpawns(temple5)[2]; + var customMonster = gameConfiguration.Monsters.Single(monster => monster.Number == 397); + customizedSpawn.MonsterDefinition = customMonster; + + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + var spawnCountAfterFirstApplication = gameConfiguration.Maps.Sum(map => map.MonsterSpawns.Count); + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + Assert.That(customizedSpawn.MonsterDefinition, Is.SameAs(customMonster)); + customizedSpawn.MonsterDefinition = gameConfiguration.Monsters.Single(monster => monster.Number == 400); + AssertNpcsAndEffects(gameConfiguration); + AssertMaps(gameConfiguration); + Assert.That(gameConfiguration.Maps.Sum(map => map.MonsterSpawns.Count), Is.EqualTo(spawnCountAfterFirstApplication)); + Assert.That(installedUpdate.Version, Is.EqualTo(update.Version)); + } + + /// + /// Tests that the update raises the maximum level of temple 5 of a database of version four from 399 to 400, and + /// keeps a maximum level which the server owner chose. + /// + /// The maximum level of temple 5 before the update. + /// The expected maximum level after the update. + /// The task. + [TestCase(399, 400)] + [TestCase(390, 390)] + public async Task UpdateLetsLevel400EnterTemple5Async(int maximumLevelBefore, int expectedMaximumLevel) + { + 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 update = new IllusionTempleDataUpdatePlugIn(); + var installedUpdate = (await context.GetAsync().ConfigureAwait(false)).Single(entry => entry.Key == update.Key); + installedUpdate.Version = 4; + var temple5 = GetTempleDefinitions(gameConfiguration).Single(d => d.GameLevel == 5); + temple5.MaximumCharacterLevel = maximumLevelBefore; + temple5.MaximumSpecialCharacterLevel = maximumLevelBefore; + + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + await update.ApplyUpdateAsync(context, gameConfiguration).ConfigureAwait(false); + + Assert.That((temple5.MaximumCharacterLevel, temple5.MaximumSpecialCharacterLevel), Is.EqualTo((expectedMaximumLevel, expectedMaximumLevel))); + } + /// /// Updating an installed version one must not replay its broad content changes over owner customizations. /// @@ -361,6 +440,39 @@ private static async Task CreateSeason6ConfigurationAsync() return (await context.GetAsync().ConfigureAwait(false)).First(); } + private static List GetArenaMonsterSpawns(GameMapDefinition map) + { + return Enumerable.Range(FirstArenaMonsterSpawnNumber, ArenaMonsterSpawnCount) + .Select(number => map.MonsterSpawns.SingleOrDefault(spawn => spawn.GetId() == GuidHelper.CreateGuid(map.Number, (short)number))) + .OfType() + .ToList(); + } + + /// + /// Changes the arena monsters to what version four of the update left: temple 5 alternated between 398 and 399, + /// temple 6 had none, and the definitions 400 to 403 didn't exist. + /// + /// The game configuration to revert. + private static void RevertToVersionFourArenaMonsters(GameConfiguration gameConfiguration) + { + var temple5Spawns = GetArenaMonsterSpawns(gameConfiguration.Maps.Single(map => map.Number == 49)); + for (var i = 0; i < temple5Spawns.Count; i++) + { + temple5Spawns[i].MonsterDefinition = gameConfiguration.Monsters.Single(monster => monster.Number == 398 + (i % 2)); + } + + var temple6 = gameConfiguration.Maps.Single(map => map.Number == 50); + foreach (var spawn in GetArenaMonsterSpawns(temple6)) + { + temple6.MonsterSpawns.Remove(spawn); + } + + foreach (var monster in gameConfiguration.Monsters.Where(monster => monster.Number is >= 400 and <= 403).ToList()) + { + gameConfiguration.Monsters.Remove(monster); + } + } + private static List GetTempleDefinitions(GameConfiguration gameConfiguration) { return gameConfiguration.MiniGameDefinitions.Where(d => d.Type == MiniGameType.IllusionTemple).ToList(); @@ -380,7 +492,7 @@ private static void RevertToStateBeforeTheEvent(GameConfiguration gameConfigurat 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()) + foreach (var monster in gameConfiguration.Monsters.Where(monster => monster.Number is >= 386 and <= 403).ToList()) { gameConfiguration.Monsters.Remove(monster); } @@ -470,6 +582,10 @@ private static void AssertDefinitions(GameConfiguration gameConfiguration) Assert.That(definitions.Where(d => d.GameLevel < 6), Has.All.Matches(d => d.MaximumCharacterLevel > d.MinimumCharacterLevel)); Assert.That(definitions.Single(d => d.GameLevel == 6).RequiresMasterClass, Is.True); + // A character of level 400 without the master class goes to temple 5. + var temple5 = definitions.Single(d => d.GameLevel == 5); + Assert.That((temple5.MaximumCharacterLevel, temple5.MaximumSpecialCharacterLevel), Is.EqualTo((400, 400))); + // Every temple rewards the winning team with experience. Assert.That( definitions, @@ -483,8 +599,8 @@ private static void AssertNpcsAndEffects(GameConfiguration gameConfiguration) Is.EqualTo(NpcWindow.IllusionTemple)); Assert.That( - gameConfiguration.Monsters.Where(monster => monster.Number is >= 386 and <= 399).Select(monster => monster.Number), - Is.EquivalentTo(Enumerable.Range(386, 14).Select(n => (short)n)), + gameConfiguration.Monsters.Where(monster => monster.Number is >= 386 and <= 403).Select(monster => monster.Number), + Is.EquivalentTo(Enumerable.Range(386, 18).Select(n => (short)n)), "the roaming arena monsters of all temples"); // The two special skills which apply a lasting effect need their magic effect definitions; @@ -528,19 +644,16 @@ private static void AssertMaps(GameConfiguration gameConfiguration) foreach (var (mapNumber, arenaMonsters) in TemplesWithArenaMonsters) { var map = temples.Single(m => m.Number == mapNumber); + var spawns = GetArenaMonsterSpawns(map); + Assert.That(spawns, Has.Count.EqualTo(ArenaMonsterSpawnCount), $"map {mapNumber}: arena monster spawns"); Assert.That( - map.MonsterSpawns.Where(spawn => spawn.MonsterDefinition?.Number is >= 386 and <= 399) - .Select(spawn => spawn.MonsterDefinition!.Number) - .Distinct(), - Is.EquivalentTo(arenaMonsters), + spawns.Select(spawn => spawn.MonsterDefinition?.Number), + Is.EqualTo(Enumerable.Range(0, ArenaMonsterSpawnCount).Select(i => (short?)arenaMonsters[i % arenaMonsters.Length])), $"map {mapNumber}: arena monsters"); + Assert.That( + map.MonsterSpawns.Count(spawn => spawn.MonsterDefinition?.Number is >= 386 and <= 403), + Is.EqualTo(ArenaMonsterSpawnCount), + $"map {mapNumber}: no other arena monster spawns"); } - - // The sixth temple is the master class one and roams with no arena monsters. - Assert.That( - temples.Single(map => map.Number == 50).MonsterSpawns - .Any(spawn => spawn.MonsterDefinition?.Number is >= 386 and <= 399), - Is.False, - "temple 6 has no arena monsters"); } } diff --git a/tests/MUnique.OpenMU.Tests/IllusionTempleContextTest.cs b/tests/MUnique.OpenMU.Tests/IllusionTempleContextTest.cs index b96e7dfe0d..82116f2adc 100644 --- a/tests/MUnique.OpenMU.Tests/IllusionTempleContextTest.cs +++ b/tests/MUnique.OpenMU.Tests/IllusionTempleContextTest.cs @@ -1,12 +1,14 @@ -// +// // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace MUnique.OpenMU.Tests; +using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Threading; +using Moq; using MUnique.OpenMU.DataModel.Configuration; using MUnique.OpenMU.DataModel.Configuration.Items; using MUnique.OpenMU.DataModel.Entities; @@ -16,6 +18,7 @@ namespace MUnique.OpenMU.Tests; using MUnique.OpenMU.GameLogic.NPC; using MUnique.OpenMU.GameLogic.PlayerActions; using MUnique.OpenMU.GameLogic.PlayerActions.MiniGames; +using MUnique.OpenMU.GameLogic.Views; using MUnique.OpenMU.GameLogic.Views.NPC; using MUnique.OpenMU.Pathfinding; @@ -155,6 +158,172 @@ public async ValueTask GameStartAssignsEveryPlayerASpawnGateAsync() } + /// + /// The barriers between the bases and the arena are the water tiles of the map. They open on the server + /// when the battle starts, like in the client, while the other blocked tiles stay blocked. + /// + [Test] + public async ValueTask GameStartOpensTheArenaBarriersAsync() + { + var gameContext = CreateGameContext(); + var definition = CreateDefinition(gameContext, minimumPlayerCount: 1); + var terrainData = definition.Entrance!.Map!.TerrainData!; + terrainData[TerrainDataOffset(143, 51)] = (byte)TerrainAttributeType.Water; + terrainData[TerrainDataOffset(196, 118)] = (byte)TerrainAttributeType.Water; + terrainData[TerrainDataOffset(150, 60)] = (byte)TerrainAttributeType.Blocked; + await using var illusionTemple = await CreateContextAsync(gameContext, definition).ConfigureAwait(false); + var players = await EnterPlayersAsync(illusionTemple, gameContext, 1).ConfigureAwait(false); + var walkMap = illusionTemple.Map.Terrain.WalkMap; + var barriersClosedBeforeStart = !walkMap[143, 51] && !walkMap[196, 118]; + + await StartGameAsync(illusionTemple, players).ConfigureAwait(false); + + Assert.That(barriersClosedBeforeStart, Is.True); + Assert.That(walkMap[143, 51], Is.True); + Assert.That(walkMap[196, 118], Is.True); + Assert.That(walkMap[150, 60], Is.False); + } + + /// + /// Killing one of the roaming arena monsters of any temple, from the first one (386) to the ones of + /// temple 6 (401 to 403), grants the killer skill points. + /// + /// The number of the killed arena monster. + [TestCase((short)386)] + [TestCase((short)399)] + [TestCase((short)400)] + [TestCase((short)403)] + public async ValueTask KillingAnArenaMonsterGrantsSkillPointsAsync(short monsterNumber) + { + var gameContext = CreateGameContext(); + var definition = CreateDefinition(gameContext, minimumPlayerCount: 1); + await using var illusionTemple = await CreateContextAsync(gameContext, definition).ConfigureAwait(false); + var players = await EnterPlayersAsync(illusionTemple, gameContext, 1).ConfigureAwait(false); + await StartGameAsync(illusionTemple, players).ConfigureAwait(false); + var killer = players[0]; + var skillPoints = GetSkillPoints(illusionTemple); + var pointsBefore = skillPoints[killer]; + var monster = await CreateMonsterAsync(illusionTemple, gameContext, monsterNumber).ConfigureAwait(false); + + await InvokeProtectedAsync( + illusionTemple, + "OnMonsterDied", + [monster, new DeathInformation(killer.Id, killer.Name, default, 0)]).ConfigureAwait(false); + + await WaitUntilAsync(() => skillPoints[killer] > pointsBefore).ConfigureAwait(false); + Assert.That(skillPoints[killer], Is.EqualTo(pointsBefore + 2)); + } + + /// + /// A player who enters lands on a walkable tile of the entrance gate, even if the gate contains blocked + /// tiles, instead of being warped out of the event to the safezone. + /// + [Test] + public async ValueTask EnteringPlayerLandsOnAWalkableEntranceTileAsync() + { + var gameContext = CreateGameContext(); + var definition = CreateDefinition(gameContext, minimumPlayerCount: 1); + var entrance = definition.Entrance!; + var terrainData = entrance.Map!.TerrainData!; + var walkableTile = (X: (byte)143, Y: (byte)43); + for (var x = entrance.X1; x <= entrance.X2; x++) + { + for (var y = entrance.Y1; y <= entrance.Y2; y++) + { + if ((x, y) != walkableTile) + { + terrainData[TerrainDataOffset(x, y)] = (byte)TerrainAttributeType.Blocked; + } + } + } + + await using var illusionTemple = await CreateContextAsync(gameContext, definition).ConfigureAwait(false); + + var player = (await EnterPlayersAsync(illusionTemple, gameContext, 1).ConfigureAwait(false)).Single(); + + Assert.That(player.CurrentMap, Is.SameAs(illusionTemple.Map)); + Assert.That((player.Position.X, player.Position.Y), Is.EqualTo(walkableTile)); + Assert.That(illusionTemple.State, Is.EqualTo(MiniGameState.Open)); + } + + /// + /// A player who leaves the waiting room before the start doesn't end the event for the others: they can + /// still enter until the entrance closes. + /// + [Test] + public async ValueTask LeavingBeforeTheStartKeepsTheEventOpenAsync() + { + var gameContext = CreateGameContext(); + var definition = CreateDefinition(gameContext, minimumPlayerCount: 2); + await using var illusionTemple = await CreateContextAsync(gameContext, definition).ConfigureAwait(false); + var players = await EnterPlayersAsync(illusionTemple, gameContext, 1).ConfigureAwait(false); + + await illusionTemple.Map.RemoveAsync(players[0]).ConfigureAwait(false); + + Assert.That(GetGameEndedToken(illusionTemple).IsCancellationRequested, Is.False); + Assert.That(illusionTemple.State, Is.EqualTo(MiniGameState.Open)); + var latePlayer = await CreatePlayerAsync(gameContext).ConfigureAwait(false); + Assert.That(await illusionTemple.TryEnterAsync(latePlayer).ConfigureAwait(false), Is.EqualTo(EnterResult.Success)); + } + + /// + /// The client names its own player by the constant player id: a player who casts the Order of Protection on + /// himself gets it, and the result names him by that id as source and target, so his client shows the effect. + /// + [Test] + public async ValueTask OrderOfProtectionOnHimselfIsAnsweredWithTheConstantPlayerIdAsync() + { + const ushort orderOfProtection = 210; + var gameContext = CreateGameContext(); + gameContext.Configuration.MagicEffects.Add(new MUnique.OpenMU.Persistence.BasicModel.MagicEffectDefinition { Number = (short)orderOfProtection }); + var definition = CreateDefinition(gameContext, minimumPlayerCount: 1); + await using var illusionTemple = await CreateContextAsync(gameContext, definition).ConfigureAwait(false); + var players = await EnterPlayersAsync(illusionTemple, gameContext, 1).ConfigureAwait(false); + await StartGameAsync(illusionTemple, players).ConfigureAwait(false); + var player = players[0]; + Assert.That(player.Id, Is.Not.EqualTo(ViewExtensions.ConstantPlayerId), "the map id must differ for this test to mean anything"); + await SetPlayingStateAsync(illusionTemple).ConfigureAwait(false); + + await illusionTemple.UseSkillAsync(player, orderOfProtection, ViewExtensions.ConstantPlayerId).ConfigureAwait(false); + + var view = Mock.Get(player.ViewPlugIns.GetPlugIn()!); + view.Verify(v => v.ShowSkillUsageResultAsync(true, orderOfProtection, ViewExtensions.ConstantPlayerId, ViewExtensions.ConstantPlayerId), Times.Once); + } + + /// + /// The cyclic state names the receiving player by the constant player id when he carries the relic, and his team + /// mates by their ids on the map, which is how his client knows them. + /// + [Test] + public async ValueTask StateNamesTheReceiverByTheConstantPlayerIdAsync() + { + var gameContext = CreateGameContext(); + var definition = CreateDefinition(gameContext, minimumPlayerCount: 2); + await using var illusionTemple = await CreateContextAsync(gameContext, definition).ConfigureAwait(false); + var players = await EnterPlayersAsync(illusionTemple, gameContext, 4).ConfigureAwait(false); + await StartGameAsync(illusionTemple, players).ConfigureAwait(false); + var receiver = players[0]; + var teamMate = players.Skip(1).First(p => GetTeamOf(illusionTemple, p) == GetTeamOf(illusionTemple, receiver)); + Assert.That(receiver.Id, Is.Not.EqualTo(ViewExtensions.ConstantPlayerId), "the map id must differ for this test to mean anything"); + SetRelicCarrier(illusionTemple, receiver); + var view = Mock.Get(receiver.ViewPlugIns.GetPlugIn()!); + view.Invocations.Clear(); + + await InvokePrivateAsync(illusionTemple, "UpdateStateAsync", receiver).ConfigureAwait(false); + + view.Verify( + v => v.UpdateStateAsync( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.Is>(members => + members.Any(m => m.PlayerId == teamMate.Id)), + It.Is<(ushort PlayerId, byte PositionX, byte PositionY)?>(carrier => + carrier.HasValue && carrier.Value.PlayerId == ViewExtensions.ConstantPlayerId)), + Times.Once); + } + /// /// After the game start, every player has a team which plugins can read; a player who /// is not part of the match has none. @@ -460,6 +629,36 @@ public async ValueTask TalkingToTheEntranceNpcShowsTheUserCountsAsync() await gameContext.RemovePlayerAsync(player).ConfigureAwait(false); } + /// + /// The client closes the window of the entrance npc without telling the server, so talking to it must not + /// leave the player in the dialog state: afterwards, the dialog of another npc opens. + /// + [Test] + public async ValueTask TalkingToTheEntranceNpcDoesntBlockOtherNpcsAsync() + { + var gameContext = CreateGameContext(); + var player = await CreatePlayerAsync(gameContext).ConfigureAwait(false); + var map = await gameContext.GetMapAsync(0).ConfigureAwait(false); + var entranceNpc = new NonPlayerCharacter( + new MUnique.OpenMU.Persistence.BasicModel.MonsterSpawnArea { GameMap = map!.Definition }, + new MUnique.OpenMU.Persistence.BasicModel.MonsterDefinition { Number = 385, NpcWindow = NpcWindow.IllusionTemple }, + map); + var otherNpc = new NonPlayerCharacter( + new MUnique.OpenMU.Persistence.BasicModel.MonsterSpawnArea { GameMap = map.Definition }, + new MUnique.OpenMU.Persistence.BasicModel.MonsterDefinition { Number = 238, NpcWindow = NpcWindow.ChaosMachine }, + map); + var talkAction = new TalkNpcAction(); + + await talkAction.TalkToNpcAsync(player, entranceNpc).ConfigureAwait(false); + Assert.That(player.PlayerState.CurrentState, Is.EqualTo(PlayerState.EnteredWorld)); + + await talkAction.TalkToNpcAsync(player, otherNpc).ConfigureAwait(false); + Assert.That(player.OpenedNpc, Is.EqualTo(otherNpc)); + Assert.That(player.PlayerState.CurrentState, Is.EqualTo(PlayerState.NpcDialogOpened)); + + await gameContext.RemovePlayerAsync(player).ConfigureAwait(false); + } + private static bool IsRelicItem(MUnique.OpenMU.DataModel.Entities.Item item) => item.Definition?.Group == 14 && item.Definition?.Number == 64; private static IllusionTempleTeam GetTeamOf(IllusionTempleContext context, Player player) @@ -482,6 +681,17 @@ private static IllusionTempleTeam GetTeamOf(IllusionTempleContext context, Playe return (Player?)field!.GetValue(context); } + /// + /// Sets the private _relicCarrier field of via reflection, to test what + /// the state reports about the carrier without going through the statue and the pick-up. + /// + [SuppressMessage("Security Hotspot", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Test-only code setting a private field of a type from this same solution. The member name is a hardcoded literal - no external input reaches this call - and exposing a public setter purely for tests isn't warranted for an internal implementation detail.")] + private static void SetRelicCarrier(IllusionTempleContext context, Player carrier) + { + var field = typeof(IllusionTempleContext).GetField("_relicCarrier", BindingFlags.NonPublic | BindingFlags.Instance); + field!.SetValue(context, carrier); + } + /// /// Reads the protected GameEndedToken of the via reflection, which tells /// whether the game was finished. Test-only, like . @@ -501,6 +711,49 @@ private static NonPlayerCharacter CreateStatueNpc(IllusionTempleContext context) return npc; } + /// + /// Sets the state which the game loop sets after OnGameStartAsync: the tests call that one directly. + /// + [SuppressMessage("Security Hotspot", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Test-only code reading a private field of a type from this same solution, to set the state which the real-time game loop would set (see the class remarks). The member name is a hardcoded literal - no external input reaches this call.")] + private static async ValueTask SetPlayingStateAsync(MiniGameContext context) + { + var field = typeof(MiniGameContext).GetField("_players", BindingFlags.NonPublic | BindingFlags.Instance); + await ((MiniGamePlayerRegistry)field!.GetValue(context)!).SetStateAsync(MiniGameState.Playing).ConfigureAwait(false); + } + + /// + /// Reads the private _skillPoints field of via reflection. + /// + [SuppressMessage("Security Hotspot", "S3011:Reflection should not be used to increase accessibility of classes, methods, or fields", Justification = "Test-only code reading a private field of a type from this same solution. The member name is a hardcoded literal - no external input reaches this call - and exposing a public accessor purely for tests isn't warranted for an internal implementation detail.")] + private static ConcurrentDictionary GetSkillPoints(IllusionTempleContext context) + { + var field = typeof(IllusionTempleContext).GetField("_skillPoints", BindingFlags.NonPublic | BindingFlags.Instance); + return (ConcurrentDictionary)field!.GetValue(context)!; + } + + private static async ValueTask CreateMonsterAsync(IllusionTempleContext context, IGameContext gameContext, short number) + { + var monsterDefinition = new MUnique.OpenMU.Persistence.BasicModel.MonsterDefinition { Number = number, ObjectKind = NpcObjectKind.Monster }; + monsterDefinition.Attributes.Add(new MUnique.OpenMU.Persistence.BasicModel.MonsterAttribute { AttributeDefinition = Stats.MaximumHealth, Value = 100 }); + var spawnArea = CreateSpawn(context.Map.Definition, 200, monsterDefinition, 150, 80, SpawnTrigger.AutomaticDuringEvent); + var monster = new Monster( + spawnArea, + monsterDefinition, + context.Map, + NullDropGenerator.Instance, + new Mock().Object, + gameContext.PlugInManager, + gameContext.PathFinderPool); + monster.Initialize(); + await context.Map.AddAsync(monster).ConfigureAwait(false); + return monster; + } + + /// + /// Gets the index of a tile in , which starts with a header of 3 bytes. + /// + private static int TerrainDataOffset(byte x, byte y) => 3 + (y * 256) + x; + private static async ValueTask StartGameAsync(IllusionTempleContext context, IReadOnlyCollection players) { await InvokeProtectedAsync(context, "OnGameStartAsync", [(ICollection)players.ToList()]).ConfigureAwait(false); diff --git a/tests/MUnique.OpenMU.Tests/IllusionTempleEnterResultMappingTests.cs b/tests/MUnique.OpenMU.Tests/IllusionTempleEnterResultMappingTests.cs index f6ed1bcdfe..186d0cd432 100644 --- a/tests/MUnique.OpenMU.Tests/IllusionTempleEnterResultMappingTests.cs +++ b/tests/MUnique.OpenMU.Tests/IllusionTempleEnterResultMappingTests.cs @@ -1,4 +1,4 @@ -// +// // Licensed under the MIT License. See LICENSE file in the project root for full license information. // @@ -19,12 +19,12 @@ public class IllusionTempleEnterResultMappingTests /// The admission outcome. /// The result byte understood by the client. [TestCase(EnterResult.Success, (byte)0)] - [TestCase(EnterResult.Failed, (byte)3)] + [TestCase(EnterResult.Failed, (byte)1)] [TestCase(EnterResult.NotOpen, (byte)1)] [TestCase(EnterResult.CharacterLevelTooHigh, (byte)3)] [TestCase(EnterResult.CharacterLevelTooLow, (byte)3)] [TestCase(EnterResult.Full, (byte)4)] - [TestCase(EnterResult.NotEnoughMoney, (byte)3)] + [TestCase(EnterResult.NotEnoughMoney, (byte)1)] [TestCase(EnterResult.PlayerKillerCantEnter, (byte)7)] public void EnterResultUsesClientAdmissionCode(EnterResult result, byte expected) {