feat(CS-P3): PROPER siege - position-based Crown Switch hold (stand on them) + gates & statues destructibles + auto throne capture; remove non-working talk handlers
Some checks failed
.NET Core / build (push) Has been cancelled

This commit is contained in:
Acentech Dev
2026-07-15 02:28:14 +03:00
parent c50af5e5c2
commit db8bdd394f
5 changed files with 171 additions and 245 deletions

View File

@@ -5,16 +5,23 @@
namespace MUnique.OpenMU.GameLogic.CastleSiege; namespace MUnique.OpenMU.GameLogic.CastleSiege;
/// <summary> /// <summary>
/// In-memory Castle Siege phase state machine (P1 skeleton: no battle/persistence). /// In-memory Castle Siege phase state machine and battle contention (P3).
/// Time is injected via method parameters so it can be tested deterministically. /// Time is injected via method parameters so it can be tested deterministically.
/// Battle rule: attackers must destroy all castle defenses (gates + guardian statues) and then hold BOTH
/// Crown Switches at the same time — the switches are held by standing on them (evaluated per tick by the
/// plugin), and once both are held by one guild with the defenses down, that guild captures the throne.
/// The throne holder when the siege ends becomes the castle owner.
/// </summary> /// </summary>
public class CastleSiegeContext public class CastleSiegeContext
{ {
/// <summary>The Crown Switch NPC numbers on Valley of Loren; both must be held to take the throne.</summary>
public static readonly short[] SwitchNumbers = { 217, 218 };
private readonly List<string> _registeredGuilds = new(); private readonly List<string> _registeredGuilds = new();
private readonly Dictionary<short, string> _switchHolders = new(); private readonly Dictionary<short, string?> _switchHolders = new() { { 217, null }, { 218, null } };
private DateTime _phaseStartedUtc; private DateTime _phaseStartedUtc;
private string? _occupier; private string? _occupier;
private int _statuesRemaining; private int _defensesRemaining;
/// <summary>Initializes a new instance of the <see cref="CastleSiegeContext"/> class.</summary> /// <summary>Initializes a new instance of the <see cref="CastleSiegeContext"/> class.</summary>
/// <param name="configuration">The cycle timing configuration.</param> /// <param name="configuration">The cycle timing configuration.</param>
@@ -36,12 +43,15 @@ public class CastleSiegeContext
/// <summary>Gets the current owner guild name, or null if unowned.</summary> /// <summary>Gets the current owner guild name, or null if unowned.</summary>
public string? OwnerGuildName { get; private set; } public string? OwnerGuildName { get; private set; }
/// <summary>Gets the guild names registered for the current cycle.</summary>
public IReadOnlyList<string> RegisteredGuilds => this._registeredGuilds;
/// <summary>Gets the guild currently holding the throne during the siege (P3), or null.</summary> /// <summary>Gets the guild currently holding the throne during the siege (P3), or null.</summary>
public string? OccupierGuildName => this._occupier; public string? OccupierGuildName => this._occupier;
/// <summary>Gets the number of castle defenses (gates + statues) still standing; the throne needs 0.</summary>
public int DefensesRemaining => this._defensesRemaining;
/// <summary>Gets the guild names registered for the current cycle.</summary>
public IReadOnlyList<string> RegisteredGuilds => this._registeredGuilds;
/// <summary>Advances the state machine based on the current time.</summary> /// <summary>Advances the state machine based on the current time.</summary>
/// <param name="now">The current UTC time.</param> /// <param name="now">The current UTC time.</param>
public ValueTask TickAsync(DateTime now) public ValueTask TickAsync(DateTime now)
@@ -77,13 +87,13 @@ public class CastleSiegeContext
break; break;
case CastleSiegePhase.Settlement: case CastleSiegePhase.Settlement:
// Winner = guild holding the throne at siege end (P3). If none captured, owner unchanged. // Winner = guild holding the throne at siege end. If none captured, owner unchanged.
if (this._occupier is { } occupier) if (this._occupier is { } occupier)
{ {
this.SetOwner(occupier); this.SetOwner(occupier);
} }
this._occupier = null; this.ClearBattleState();
return this.TransitionAsync(CastleSiegePhase.Ownership, now); return this.TransitionAsync(CastleSiegePhase.Ownership, now);
default: default:
break; break;
@@ -97,9 +107,7 @@ public class CastleSiegeContext
public ValueTask ForceStartRegistrationAsync(DateTime now) public ValueTask ForceStartRegistrationAsync(DateTime now)
{ {
this._registeredGuilds.Clear(); this._registeredGuilds.Clear();
this._switchHolders.Clear(); this.ClearBattleState();
this._statuesRemaining = 0;
this._occupier = null;
return this.TransitionAsync(CastleSiegePhase.Registration, now); return this.TransitionAsync(CastleSiegePhase.Registration, now);
} }
@@ -109,14 +117,12 @@ public class CastleSiegeContext
public ValueTask ForcePhaseAsync(CastleSiegePhase phase, DateTime now) public ValueTask ForcePhaseAsync(CastleSiegePhase phase, DateTime now)
=> this.TransitionAsync(phase, now); => this.TransitionAsync(phase, now);
/// <summary>Admin: resets to the ownership (resting) phase and clears registrations.</summary> /// <summary>Admin: resets to the ownership (resting) phase and clears registrations/battle state.</summary>
/// <param name="now">The current UTC time.</param> /// <param name="now">The current UTC time.</param>
public ValueTask ResetAsync(DateTime now) public ValueTask ResetAsync(DateTime now)
{ {
this._registeredGuilds.Clear(); this._registeredGuilds.Clear();
this._switchHolders.Clear(); this.ClearBattleState();
this._statuesRemaining = 0;
this._occupier = null;
return this.TransitionAsync(CastleSiegePhase.Ownership, now); return this.TransitionAsync(CastleSiegePhase.Ownership, now);
} }
@@ -135,69 +141,70 @@ public class CastleSiegeContext
/// <param name="guildName">The owner guild name, or null to clear.</param> /// <param name="guildName">The owner guild name, or null to clear.</param>
public void SetOwner(string? guildName) => this.OwnerGuildName = guildName; public void SetOwner(string? guildName) => this.OwnerGuildName = guildName;
/// <summary>Gets the number of guardian statues still standing (must be 0 before the throne can be taken).</summary> /// <summary>Sets how many castle defenses (gates + guardian statues) exist this siege (when spawned).</summary>
public int StatuesRemaining => this._statuesRemaining; /// <param name="count">The defense count.</param>
public void SetDefenseCount(int count) => this._defensesRemaining = count > 0 ? count : 0;
/// <summary>Sets how many guardian statues defend the castle this siege (called when they are spawned).</summary> /// <summary>Notifies that a castle defense (gate/statue) was destroyed. Lowers the remaining count (min 0).</summary>
/// <param name="count">The statue count.</param> public void NotifyDefenseDestroyed()
public void SetStatueCount(int count) => this._statuesRemaining = count > 0 ? count : 0;
/// <summary>Notifies that a guardian statue was destroyed. Lowers the remaining count (min 0).</summary>
public void NotifyStatueDestroyed()
{ {
if (this._statuesRemaining > 0) if (this._defensesRemaining > 0)
{ {
this._statuesRemaining--; this._defensesRemaining--;
} }
} }
/// <summary> /// <summary>
/// P3: a registered guild member activates one of the two Crown Switches (217/218) during the siege. /// Sets which guild is currently standing on (holding) a Crown Switch. Called every tick by the plugin
/// The throne can only be taken by a guild holding BOTH switches. No-op outside the siege phase. /// based on player positions. Pass <c>null</c> when no registered member stands on it. No-op outside the siege.
/// </summary> /// </summary>
/// <param name="switchNumber">The Crown Switch NPC number (217 or 218).</param> /// <param name="switchNumber">The Crown Switch NPC number (217 or 218).</param>
/// <param name="guildName">The activating guild's name.</param> /// <param name="guildName">The holding guild's name, or null.</param>
public void HoldSwitch(short switchNumber, string guildName) public void SetSwitchHolder(short switchNumber, string? guildName)
{ {
if (this.Phase == CastleSiegePhase.Siege) if (this.Phase == CastleSiegePhase.Siege && this._switchHolders.ContainsKey(switchNumber))
{ {
this._switchHolders[switchNumber] = guildName; this._switchHolders[switchNumber] = guildName;
} }
} }
/// <summary> /// <summary>
/// P3: attempts to capture the throne for a guild. Succeeds only during the siege when all guardian /// Evaluates the throne capture: if the siege is running, all defenses are destroyed, the throne is not
/// statues are destroyed and the guild holds both Crown Switches. /// yet taken, and one guild holds BOTH Crown Switches at once, that guild captures the throne.
/// </summary> /// </summary>
/// <param name="guildName">The capturing guild's name.</param> /// <returns>The guild that just captured the throne (for announcing), or <c>null</c> if nothing changed.</returns>
/// <returns>A tuple of success and a human-readable reason/result message.</returns> public string? EvaluateCapture()
public (bool Success, string Reason) TryCaptureThrone(string guildName)
{ {
if (this.Phase != CastleSiegePhase.Siege) if (this.Phase != CastleSiegePhase.Siege || this._occupier is not null || this._defensesRemaining > 0)
{ {
return (false, "The siege is not running."); return null;
} }
if (this._statuesRemaining > 0) var holder217 = this._switchHolders[217];
var holder218 = this._switchHolders[218];
if (holder217 is not null && holder217 == holder218)
{ {
return (false, $"Destroy the guardian statues first ({this._statuesRemaining} remaining)."); this._occupier = holder217;
return holder217;
} }
var holdsBoth = this._switchHolders.TryGetValue(217, out var s217) && s217 == guildName return null;
&& this._switchHolders.TryGetValue(218, out var s218) && s218 == guildName;
if (!holdsBoth)
{
return (false, "Your guild must hold both Crown Switches (217 and 218) at once.");
}
this._occupier = guildName;
return (true, "throne captured");
} }
/// <summary>Returns a human-readable status summary for admin display.</summary> /// <summary>Returns a human-readable status summary for admin display.</summary>
public string GetStatusText() public string GetStatusText()
=> $"CS phase={this.Phase}, owner={this.OwnerGuildName ?? "(none)"}, " => $"CS phase={this.Phase}, owner={this.OwnerGuildName ?? "(none)"}, "
+ $"registered={this._registeredGuilds.Count} [{string.Join(", ", this._registeredGuilds)}]"; + $"registered={this._registeredGuilds.Count} [{string.Join(", ", this._registeredGuilds)}], "
+ $"defenses={this._defensesRemaining}, throne={this._occupier ?? "(none)"}, "
+ $"switch217={this._switchHolders[217] ?? "-"}, switch218={this._switchHolders[218] ?? "-"}";
private void ClearBattleState()
{
this._switchHolders[217] = null;
this._switchHolders[218] = null;
this._defensesRemaining = 0;
this._occupier = null;
}
private ValueTask TransitionAsync(CastleSiegePhase phase, DateTime now) private ValueTask TransitionAsync(CastleSiegePhase phase, DateTime now)
{ {

View File

@@ -1,77 +0,0 @@
// <copyright file="CastleSiegeCrownTalkPlugIn.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameLogic.CastleSiege;
using System.Linq;
using System.Runtime.InteropServices;
using MUnique.OpenMU.GameLogic.NPC;
using MUnique.OpenMU.GameLogic.PlugIns;
using MUnique.OpenMU.GameLogic.PlugIns.PeriodicTasks;
using MUnique.OpenMU.GameLogic.Views;
using MUnique.OpenMU.Interfaces;
using MUnique.OpenMU.PlugIns;
/// <summary>
/// Handles talking to the Castle Siege throne NPCs — Crown (216) and Sinior (223) — on Valley of Loren.
/// A registered guild takes the throne only when it has destroyed all guardian statues AND holds both
/// Crown Switches (217/218). The guild on the throne when the siege ends becomes the castle owner.
/// </summary>
[Guid("CA5710A0-7A1B-4C2D-8E3F-000000000216")]
[PlugIn]
[Display(Name = "Castle Siege Crown/Throne", Description = "Captures the throne (Crown 216 / Sinior 223) once statues are down and both switches held.")]
public class CastleSiegeCrownTalkPlugIn : IPlayerTalkToNpcPlugIn
{
private static readonly short[] ThroneNpcNumbers = { 216, 223 };
/// <inheritdoc />
public async ValueTask PlayerTalksToNpcAsync(Player player, NonPlayerCharacter npc, NpcTalkEventArgs eventArgs)
{
if (!ThroneNpcNumbers.Contains(npc.Definition.Number))
{
return;
}
eventArgs.HasBeenHandled = true;
var context = CastleSiegeEventPlugIn.TryGetContext(player.GameContext);
if (context is null)
{
await ShowAsync(player, "Castle Siege is not active on this server.").ConfigureAwait(false);
return;
}
if (player.GuildStatus is not { } guildStatus)
{
await ShowAsync(player, "Only members of a registered guild can take the throne.").ConfigureAwait(false);
return;
}
var guildName = guildStatus.GuildId.ToString();
if (player.GameContext is IGameServerContext serverContext)
{
var guild = await serverContext.GuildServer.GetGuildAsync(guildStatus.GuildId).ConfigureAwait(false);
if (guild?.Name is { Length: > 0 } name)
{
guildName = name;
}
}
if (!context.RegisteredGuilds.Contains(guildName))
{
await ShowAsync(player, "Your guild is not registered for this Castle Siege.").ConfigureAwait(false);
return;
}
var (success, reason) = context.TryCaptureThrone(guildName);
await ShowAsync(
player,
success
? $"Your guild '{guildName}' has CAPTURED THE THRONE! Hold it until the siege ends to win the castle!"
: reason).ConfigureAwait(false);
}
private static ValueTask ShowAsync(Player player, string text)
=> player.InvokeViewPlugInAsync<IShowMessagePlugIn>(p => p.ShowMessageAsync(text, MessageType.BlueNormal));
}

View File

@@ -1,79 +0,0 @@
// <copyright file="CastleSiegeThroneTalkPlugIn.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameLogic.CastleSiege;
using System.Linq;
using System.Runtime.InteropServices;
using MUnique.OpenMU.GameLogic.NPC;
using MUnique.OpenMU.GameLogic.PlugIns;
using MUnique.OpenMU.GameLogic.PlugIns.PeriodicTasks;
using MUnique.OpenMU.GameLogic.Views;
using MUnique.OpenMU.Interfaces;
using MUnique.OpenMU.PlugIns;
/// <summary>
/// Handles talking to the Castle Siege 'Crown Switch' NPCs (217, 218) on Valley of Loren: while the
/// siege phase is running, a registered guild member using a switch captures the throne for their guild.
/// The guild holding the throne when the siege ends becomes the castle owner (see <see cref="CastleSiegeContext"/>).
/// </summary>
[Guid("CA5710A0-7A1B-4C2D-8E3F-000000000217")]
[PlugIn]
[Display(Name = "Castle Siege Crown Switch", Description = "Captures the throne for a registered guild during the siege (Crown Switch NPCs 217/218).")]
public class CastleSiegeThroneTalkPlugIn : IPlayerTalkToNpcPlugIn
{
private static readonly short[] CrownSwitchNumbers = { 217, 218 };
/// <inheritdoc />
public async ValueTask PlayerTalksToNpcAsync(Player player, NonPlayerCharacter npc, NpcTalkEventArgs eventArgs)
{
if (!CrownSwitchNumbers.Contains(npc.Definition.Number))
{
return;
}
eventArgs.HasBeenHandled = true;
var context = CastleSiegeEventPlugIn.TryGetContext(player.GameContext);
if (context is null)
{
await ShowAsync(player, "Castle Siege is not active on this server.").ConfigureAwait(false);
return;
}
if (context.Phase != CastleSiegePhase.Siege)
{
await ShowAsync(player, "The siege is not running right now.").ConfigureAwait(false);
return;
}
if (player.GuildStatus is not { } guildStatus)
{
await ShowAsync(player, "Only members of a registered guild can capture the throne.").ConfigureAwait(false);
return;
}
var guildName = guildStatus.GuildId.ToString();
if (player.GameContext is IGameServerContext serverContext)
{
var guild = await serverContext.GuildServer.GetGuildAsync(guildStatus.GuildId).ConfigureAwait(false);
if (guild?.Name is { Length: > 0 } name)
{
guildName = name;
}
}
if (!context.RegisteredGuilds.Contains(guildName))
{
await ShowAsync(player, "Your guild is not registered for this Castle Siege.").ConfigureAwait(false);
return;
}
context.HoldSwitch(npc.Definition.Number, guildName);
await ShowAsync(player, $"Your guild '{guildName}' is holding this Crown Switch. Hold BOTH switches (217 and 218) and destroy the guardian statues, then take the throne!").ConfigureAwait(false);
}
private static ValueTask ShowAsync(Player player, string text)
=> player.InvokeViewPlugInAsync<IShowMessagePlugIn>(p => p.ShowMessageAsync(text, MessageType.BlueNormal));
}

View File

@@ -11,6 +11,7 @@ using MUnique.OpenMU.GameLogic.CastleSiege;
using MUnique.OpenMU.GameLogic.NPC; using MUnique.OpenMU.GameLogic.NPC;
using MUnique.OpenMU.GameLogic.Views; using MUnique.OpenMU.GameLogic.Views;
using MUnique.OpenMU.Interfaces; using MUnique.OpenMU.Interfaces;
using MUnique.OpenMU.Pathfinding;
using MUnique.OpenMU.PlugIns; using MUnique.OpenMU.PlugIns;
/// <summary> /// <summary>
@@ -24,8 +25,25 @@ using MUnique.OpenMU.PlugIns;
public sealed class CastleSiegeEventPlugIn : IPeriodicTaskPlugIn, ISupportCustomConfiguration<CastleSiegeConfiguration>, ISupportDefaultCustomConfiguration public sealed class CastleSiegeEventPlugIn : IPeriodicTaskPlugIn, ISupportCustomConfiguration<CastleSiegeConfiguration>, ISupportDefaultCustomConfiguration
{ {
private const ushort ValleyOfLorenMapNumber = 30; private const ushort ValleyOfLorenMapNumber = 30;
private const short GuardianStatueNumber = 132; // reuse the "Statue of Saint" destructible definition private const short CastleGateNumber = 131; // reuse BloodCastle "Castle Gate" destructible definition
private static readonly (byte X, byte Y)[] StatuePositions = { (170, 206), (182, 206) }; private const short GuardianStatueNumber = 132; // reuse BloodCastle "Statue of Saint" destructible definition
private const int SwitchHoldRange = 3;
// Castle defenses spawned at siege start — destructibles the attackers must break: (number, x, y).
private static readonly (short Number, byte X, byte Y)[] DefenseSpawns =
{
(CastleGateNumber, 160, 180),
(CastleGateNumber, 190, 180),
(GuardianStatueNumber, 170, 206),
(GuardianStatueNumber, 182, 206),
};
// Crown Switch positions on Valley of Loren (from the map init) — held by standing on them: (number, x, y).
private static readonly (short SwitchNumber, byte X, byte Y)[] SwitchPositions =
{
(217, 167, 194),
(218, 184, 195),
};
private static readonly ConcurrentDictionary<IGameContext, CastleSiegeContext> Contexts = new(); private static readonly ConcurrentDictionary<IGameContext, CastleSiegeContext> Contexts = new();
@@ -57,6 +75,12 @@ public sealed class CastleSiegeEventPlugIn : IPeriodicTaskPlugIn, ISupportCustom
}); });
await context.TickAsync(DateTime.UtcNow).ConfigureAwait(false); await context.TickAsync(DateTime.UtcNow).ConfigureAwait(false);
// During the siege, evaluate the Crown Switches (held by standing on them) and the throne capture every tick.
if (context.Phase == CastleSiegePhase.Siege)
{
await ProcessSiegeTickAsync(gameContext, context).ConfigureAwait(false);
}
} }
/// <inheritdoc /> /// <inheritdoc />
@@ -79,8 +103,8 @@ public sealed class CastleSiegeEventPlugIn : IPeriodicTaskPlugIn, ISupportCustom
await AnnounceAsync(gameContext, "Castle Siege registration is now open! Guild masters, register at the Guardsman in the Valley of Loren.").ConfigureAwait(false); await AnnounceAsync(gameContext, "Castle Siege registration is now open! Guild masters, register at the Guardsman in the Valley of Loren.").ConfigureAwait(false);
break; break;
case CastleSiegePhase.Siege: case CastleSiegePhase.Siege:
await AnnounceAsync(gameContext, "The Castle Siege has begun! Destroy the guardian statues, hold both Crown Switches, then take the throne!").ConfigureAwait(false); await AnnounceAsync(gameContext, "The Castle Siege has begun! Break the castle gates and guardian statues, then hold BOTH Crown Switches to take the throne!").ConfigureAwait(false);
await SpawnGuardianStatuesAsync(gameContext, context).ConfigureAwait(false); await SpawnCastleDefensesAsync(gameContext, context).ConfigureAwait(false);
await WarpRegisteredMembersToSiegeAsync(gameContext, context).ConfigureAwait(false); await WarpRegisteredMembersToSiegeAsync(gameContext, context).ConfigureAwait(false);
break; break;
case CastleSiegePhase.Ownership when context.OwnerGuildName is { } owner: case CastleSiegePhase.Ownership when context.OwnerGuildName is { } owner:
@@ -101,36 +125,41 @@ public sealed class CastleSiegeEventPlugIn : IPeriodicTaskPlugIn, ISupportCustom
=> gameContext.ForEachPlayerAsync(player => => gameContext.ForEachPlayerAsync(player =>
player.InvokeViewPlugInAsync<IShowMessagePlugIn>(p => p.ShowMessageAsync(message, MessageType.GoldenCenter)).AsTask()); player.InvokeViewPlugInAsync<IShowMessagePlugIn>(p => p.ShowMessageAsync(message, MessageType.GoldenCenter)).AsTask());
private static async Task SpawnGuardianStatuesAsync(IGameContext gameContext, CastleSiegeContext context) private static async Task SpawnCastleDefensesAsync(IGameContext gameContext, CastleSiegeContext context)
{ {
try try
{ {
if (gameContext is not GameContext concrete) if (gameContext is not GameContext concrete)
{ {
context.SetStatueCount(0); context.SetDefenseCount(0);
return; return;
} }
var map = await gameContext.GetMapAsync(ValleyOfLorenMapNumber).ConfigureAwait(false); var map = await gameContext.GetMapAsync(ValleyOfLorenMapNumber).ConfigureAwait(false);
var statueDef = gameContext.Configuration.Monsters.FirstOrDefault(m => m.Number == GuardianStatueNumber); if (map is null)
if (map is null || statueDef is null)
{ {
context.SetStatueCount(0); context.SetDefenseCount(0);
return; return;
} }
var spawned = 0; var spawned = 0;
for (var i = 0; i < StatuePositions.Length; i++) for (var i = 0; i < DefenseSpawns.Length; i++)
{ {
var pos = StatuePositions[i]; var spawn = DefenseSpawns[i];
var definition = gameContext.Configuration.Monsters.FirstOrDefault(m => m.Number == spawn.Number);
if (definition is null)
{
continue;
}
var spawnArea = new MonsterSpawnArea var spawnArea = new MonsterSpawnArea
{ {
MonsterDefinition = statueDef, MonsterDefinition = definition,
Quantity = 1, Quantity = 1,
X1 = pos.X, X1 = spawn.X,
X2 = pos.X, X2 = spawn.X,
Y1 = pos.Y, Y1 = spawn.Y,
Y2 = pos.Y, Y2 = spawn.Y,
Direction = Direction.South, Direction = Direction.South,
SpawnTrigger = SpawnTrigger.OnceAtEventStart, SpawnTrigger = SpawnTrigger.OnceAtEventStart,
}; };
@@ -138,18 +167,59 @@ public sealed class CastleSiegeEventPlugIn : IPeriodicTaskPlugIn, ISupportCustom
var npc = await concrete.MapInitializer.InitializeSpawnAsync(1000 + i, map, spawnArea).ConfigureAwait(false); var npc = await concrete.MapInitializer.InitializeSpawnAsync(1000 + i, map, spawnArea).ConfigureAwait(false);
if (npc is AttackableNpcBase attackable) if (npc is AttackableNpcBase attackable)
{ {
attackable.Died += (_, _) => context.NotifyStatueDestroyed(); attackable.Died += (_, _) => context.NotifyDefenseDestroyed();
spawned++; spawned++;
} }
} }
context.SetStatueCount(spawned); context.SetDefenseCount(spawned);
} }
catch (Exception ex) catch (Exception ex)
{ {
gameContext.LoggerFactory.CreateLogger<CastleSiegeEventPlugIn>() gameContext.LoggerFactory.CreateLogger<CastleSiegeEventPlugIn>()
.LogError(ex, "Castle Siege: error while spawning guardian statues."); .LogError(ex, "Castle Siege: error while spawning castle defenses.");
context.SetStatueCount(0); context.SetDefenseCount(0);
}
}
private static async Task ProcessSiegeTickAsync(IGameContext gameContext, CastleSiegeContext context)
{
try
{
var map = await gameContext.GetMapAsync(ValleyOfLorenMapNumber).ConfigureAwait(false);
if (map is null)
{
return;
}
// Each Crown Switch is held by whichever registered guild currently has a member standing on it.
foreach (var (switchNumber, x, y) in SwitchPositions)
{
string? holder = null;
var nearby = map.GetAttackablesInRange(new Point(x, y), SwitchHoldRange).OfType<Player>();
foreach (var player in nearby)
{
var guildName = await GetGuildNameAsync(player).ConfigureAwait(false);
if (guildName is not null && context.RegisteredGuilds.Contains(guildName))
{
holder = guildName;
break;
}
}
context.SetSwitchHolder(switchNumber, holder);
}
var captured = context.EvaluateCapture();
if (captured is not null)
{
await AnnounceAsync(gameContext, $"Guild '{captured}' has CAPTURED THE THRONE! They win the castle if they hold it until the siege ends.").ConfigureAwait(false);
}
}
catch (Exception ex)
{
gameContext.LoggerFactory.CreateLogger<CastleSiegeEventPlugIn>()
.LogError(ex, "Castle Siege: error during siege tick processing.");
} }
} }

View File

@@ -67,25 +67,30 @@ public class CastleSiegeContextTest
Assert.That(ctx.RegisteredGuilds, Does.Contain("Attackers")); Assert.That(ctx.RegisteredGuilds, Does.Contain("Attackers"));
} }
/// <summary>Tests the full siege objective chain: destroy statues, hold both switches, then capture the throne.</summary> /// <summary>Tests the full siege objective chain: destroy defenses, then hold both switches to capture the throne.</summary>
[Test] [Test]
public async Task FullSiegeObjectiveChainToOwnershipAsync() public async Task FullSiegeObjectiveChainToOwnershipAsync()
{ {
var ctx = new CastleSiegeContext(Config()); var ctx = new CastleSiegeContext(Config());
await ctx.ForceStartRegistrationAsync(T0); await ctx.ForceStartRegistrationAsync(T0);
await ctx.ForcePhaseAsync(CastleSiegePhase.Siege, T0); await ctx.ForcePhaseAsync(CastleSiegePhase.Siege, T0);
ctx.SetStatueCount(2); ctx.SetDefenseCount(2);
// Throne blocked until statues destroyed + both switches held. // Both switches held but defenses still up -> no capture.
Assert.That(ctx.TryCaptureThrone("Attackers").Success, Is.False); ctx.SetSwitchHolder(217, "Attackers");
ctx.SetSwitchHolder(218, "Attackers");
Assert.That(ctx.EvaluateCapture(), Is.Null);
ctx.NotifyStatueDestroyed(); ctx.NotifyDefenseDestroyed();
ctx.NotifyStatueDestroyed(); ctx.NotifyDefenseDestroyed();
ctx.HoldSwitch(217, "Attackers");
Assert.That(ctx.TryCaptureThrone("Attackers").Success, Is.False); // only one switch held
ctx.HoldSwitch(218, "Attackers"); // Only one switch held -> still no capture.
Assert.That(ctx.TryCaptureThrone("Attackers").Success, Is.True); // both switches + statues down ctx.SetSwitchHolder(218, null);
Assert.That(ctx.EvaluateCapture(), Is.Null);
// Both switches held by the same guild + defenses down -> capture.
ctx.SetSwitchHolder(218, "Attackers");
Assert.That(ctx.EvaluateCapture(), Is.EqualTo("Attackers"));
Assert.That(ctx.OccupierGuildName, Is.EqualTo("Attackers")); Assert.That(ctx.OccupierGuildName, Is.EqualTo("Attackers"));
await ctx.TickAsync(T0.AddMinutes(20)); // Siege -> Settlement await ctx.TickAsync(T0.AddMinutes(20)); // Siege -> Settlement
@@ -93,27 +98,27 @@ public class CastleSiegeContextTest
Assert.That(ctx.OwnerGuildName, Is.EqualTo("Attackers")); Assert.That(ctx.OwnerGuildName, Is.EqualTo("Attackers"));
} }
/// <summary>Tests that a rival guild holding only one switch cannot steal the throne.</summary> /// <summary>Tests that two different guilds each holding one switch cannot capture the throne.</summary>
[Test] [Test]
public async Task ThroneRequiresBothSwitchesBySameGuildAsync() public async Task ThroneRequiresBothSwitchesBySameGuildAsync()
{ {
var ctx = new CastleSiegeContext(Config()); var ctx = new CastleSiegeContext(Config());
await ctx.ForceStartRegistrationAsync(T0); await ctx.ForceStartRegistrationAsync(T0);
await ctx.ForcePhaseAsync(CastleSiegePhase.Siege, T0); await ctx.ForcePhaseAsync(CastleSiegePhase.Siege, T0);
ctx.SetStatueCount(0); ctx.SetDefenseCount(0);
ctx.HoldSwitch(217, "A"); ctx.SetSwitchHolder(217, "A");
ctx.HoldSwitch(218, "B"); ctx.SetSwitchHolder(218, "B");
Assert.That(ctx.TryCaptureThrone("A").Success, Is.False); Assert.That(ctx.EvaluateCapture(), Is.Null);
Assert.That(ctx.TryCaptureThrone("B").Success, Is.False);
} }
/// <summary>Tests that objective actions outside the siege phase are no-ops.</summary> /// <summary>Tests that switch holding outside the siege phase is a no-op.</summary>
[Test] [Test]
public void ObjectiveActionsOutsideSiegeAreNoOp() public void SwitchHoldOutsideSiegeIsNoOp()
{ {
var ctx = new CastleSiegeContext(Config()); var ctx = new CastleSiegeContext(Config());
ctx.HoldSwitch(217, "A"); ctx.SetSwitchHolder(217, "A");
Assert.That(ctx.TryCaptureThrone("A").Success, Is.False); ctx.SetSwitchHolder(218, "A");
Assert.That(ctx.EvaluateCapture(), Is.Null);
Assert.That(ctx.OccupierGuildName, Is.Null); Assert.That(ctx.OccupierGuildName, Is.Null);
} }