Files
systemrevivalserver/Game/Dungeon/DungeonSimulation.cs
T

1057 lines
39 KiB
C#

using System.Collections.Concurrent;
using DataServer.Data.Entities;
using DataServer.Data.Enums;
namespace GameServer.Dungeon;
/// <summary>
/// Runtime simulation for an active dungeon instance
/// </summary>
public partial class DungeonSimulation
{
public DungeonLayout Layout { get; }
public int Tier { get; }
public int BracketMin { get; }
// Tick rate
public const int TicksPerSecond = 20;
public const float TickDelta = 1f / TicksPerSecond;
public long CurrentTick { get; private set; }
public DungeonPhase Phase { get; private set; } = DungeonPhase.Active;
// Entities
public ConcurrentDictionary<ulong, PlayerInstance> Players { get; } = new();
public ConcurrentDictionary<int, MobInstance> Mobs { get; } = new();
public ConcurrentDictionary<int, ChestInstance> Chests { get; } = new();
public ConcurrentDictionary<int, DroppedItem> DroppedItems { get; } = new();
public ConcurrentDictionary<int, PortalInstance> Portals { get; } = new();
public ConcurrentDictionary<int, LootChestInstance> LootChests { get; } = new();
public ConcurrentDictionary<int, ProjectileInstance> Projectiles { get; } = new();
public ConcurrentDictionary<int, HazardZone> HazardZones { get; } = new();
// ID generators
private int _nextLootChestId = 1;
private int _nextProjectileId = 1;
private int _nextHazardId = 1;
public int GetNextLootChestId() => _nextLootChestId++;
public int GetNextProjectileId() => _nextProjectileId++;
public int GetNextHazardId() => _nextHazardId++;
// Combat tracking
private readonly List<DamageEvent> _pendingDamageEvents = new();
private readonly List<DeathEvent> _pendingDeathEvents = new();
private readonly List<AbilityEvent> _pendingAbilityEvents = new();
private int _nextDroppedItemId = 1;
private readonly Dictionary<int, DungeonMobDefinition> _mobDefinitions;
private readonly Dictionary<int, MobAbilityDefinition>? _abilityDefinitions;
private readonly Dictionary<int, string?>? _spriteConfigs;
public DungeonSimulation(
DungeonLayout layout,
int tier,
Dictionary<int, DungeonMobDefinition> mobDefinitions,
int bracketMin = 1,
Dictionary<int, MobAbilityDefinition>? abilityDefinitions = null,
Dictionary<int, string?>? spriteConfigs = null)
{
Layout = layout;
Tier = tier;
BracketMin = bracketMin;
_mobDefinitions = mobDefinitions;
_abilityDefinitions = abilityDefinitions;
_spriteConfigs = spriteConfigs;
SpawnMobs();
InitializeChests();
SpawnExitPortal();
}
private void SpawnExitPortal()
{
// Spawn exit portal in corner of entrance room (away from center and hallways)
if (Layout.Rooms.Count == 0) return;
var entranceRoom = Layout.Rooms[0];
// Room uses X, Y as top-left corner
int roomLeft = entranceRoom.X + 1;
int roomRight = entranceRoom.X + entranceRoom.Width - 2;
int roomTop = entranceRoom.Y + 1;
int roomBottom = entranceRoom.Y + entranceRoom.Height - 2;
// Try corners first (away from center where players spawn)
var cornerPositions = new[]
{
(roomLeft + 1, roomTop + 1), // Top-left
(roomRight - 1, roomTop + 1), // Top-right
(roomLeft + 1, roomBottom - 1), // Bottom-left
(roomRight - 1, roomBottom - 1), // Bottom-right
};
foreach (var (tileX, tileY) in cornerPositions)
{
// Check if this is a valid floor tile
if (Layout.IsWalkable(tileX, tileY))
{
// Check surrounding tiles to avoid placing near hallways
bool nearHallway = false;
for (int dx = -1; dx <= 1 && !nearHallway; dx++)
{
for (int dy = -1; dy <= 1 && !nearHallway; dy++)
{
int checkX = tileX + dx;
int checkY = tileY + dy;
// Check if this position is outside the room bounds (potential hallway)
bool outsideRoom = checkX < entranceRoom.X ||
checkX >= entranceRoom.X + entranceRoom.Width ||
checkY < entranceRoom.Y ||
checkY >= entranceRoom.Y + entranceRoom.Height;
if (outsideRoom && Layout.IsWalkable(checkX, checkY)) // Floor outside room = hallway
{
nearHallway = true;
}
}
}
if (!nearHallway)
{
var portal = new PortalInstance
{
Id = 1,
X = tileX * 32 + 16, // Center of tile in world coords
Y = tileY * 32 + 16,
Type = PortalType.Exit,
IsActive = true
};
Portals[portal.Id] = portal;
return;
}
}
}
// Fallback: try any position in the room away from center
var offsets = new[] { (-3, -3), (3, -3), (-3, 3), (3, 3), (-3, 0), (3, 0), (0, -3), (0, 3) };
foreach (var (dx, dy) in offsets)
{
int portalTileX = entranceRoom.CenterX + dx;
int portalTileY = entranceRoom.CenterY + dy;
if (Layout.IsWalkable(portalTileX, portalTileY))
{
var portal = new PortalInstance
{
Id = 1,
X = portalTileX * 32 + 16,
Y = portalTileY * 32 + 16,
Type = PortalType.Exit,
IsActive = true
};
Portals[portal.Id] = portal;
return;
}
}
// Last fallback: spawn at room center
var fallbackPortal = new PortalInstance
{
Id = 1,
X = entranceRoom.CenterX * 32 + 16,
Y = entranceRoom.CenterY * 32 + 16,
Type = PortalType.Exit,
IsActive = true
};
Portals[fallbackPortal.Id] = fallbackPortal;
}
private void SpawnMobs()
{
var rng = new Random(Layout.Seed);
foreach (var mobSpawn in Layout.MobSpawns)
{
// Use specific mob if MobDefinitionId is set, otherwise select randomly
DungeonMobDefinition? mobDef = null;
if (mobSpawn.MobDefinitionId.HasValue)
{
_mobDefinitions.TryGetValue(mobSpawn.MobDefinitionId.Value, out mobDef);
}
// Fall back to random selection if no specific mob or mob not found
if (mobDef == null)
{
mobDef = SelectMobDefinition(mobSpawn.MobType, rng);
}
if (mobDef == null) continue;
// Use bracket-aware stat scaling
var stats = mobDef.GetStatsForBracket(BracketMin);
// Get sprite config - prefer new format from _spriteConfigs, fallback to legacy SpriteConfigJson
string? spriteConfig = null;
if (_spriteConfigs != null && _spriteConfigs.TryGetValue(mobDef.Id, out var newConfig) && !string.IsNullOrEmpty(newConfig))
{
spriteConfig = newConfig;
}
else
{
spriteConfig = mobDef.SpriteConfigJson;
}
var mob = new MobInstance
{
Id = mobSpawn.Id,
DefinitionId = mobDef.Id,
Name = mobDef.Name,
X = mobSpawn.X * 32 + 16,
Y = mobSpawn.Y * 32 + 16,
SpawnX = mobSpawn.X * 32 + 16,
SpawnY = mobSpawn.Y * 32 + 16,
Health = stats.MaxHealth,
MaxHealth = stats.MaxHealth,
Mana = mobDef.BaseMana,
MaxMana = mobDef.BaseMana,
Stats = stats,
State = MobState.Idle,
StateTime = (float)(rng.NextDouble() * 3f), // Randomize so mobs don't all start moving at once
SpriteConfigJson = spriteConfig,
TintColor = mobDef.TintColor,
Scale = mobDef.Scale,
Type = mobDef.Type,
Behavior = mobDef.Behavior,
PreferredRange = mobDef.PreferredRange,
FleeThreshold = mobDef.FleeThreshold,
Phases = mobDef.Phases,
CurrentAnimation = "idle_down",
FacingDirection = "down"
};
// Load abilities for this mob
if (_abilityDefinitions != null && mobDef.AbilityAssignments != null)
{
foreach (var assignment in mobDef.AbilityAssignments.Where(a => a.IsEnabled))
{
if (_abilityDefinitions.TryGetValue(assignment.AbilityDefinitionId, out var abilityDef))
{
mob.Abilities.Add(new MobAbilityState
{
AbilityId = abilityDef.Id,
Definition = abilityDef,
CooldownRemaining = 0,
Priority = assignment.PriorityOverride ?? abilityDef.Priority,
Phase = assignment.Phase,
MinHpPercent = assignment.MinHpPercent,
MaxHpPercent = assignment.MaxHpPercent
});
}
}
}
// If no abilities loaded, give a basic attack
if (mob.Abilities.Count == 0)
{
mob.Abilities.Add(new MobAbilityState
{
AbilityId = 0,
Definition = new MobAbilityDefinition
{
Id = 0,
Name = "Basic Attack",
Key = "basic_attack",
AbilityType = MobAbilityType.MeleeAttack,
BaseDamage = stats.PhysicalDamage,
Range = stats.AttackRange,
Cooldown = 1f / stats.AttackSpeed,
AnimationKey = "attack",
DamageTypeKey = stats.DamageTypeKey
},
CooldownRemaining = 0,
Priority = 1
});
}
Mobs[mobSpawn.Id] = mob;
}
}
private void InitializeChests()
{
foreach (var chestSpawn in Layout.ChestSpawns)
{
Chests[chestSpawn.Id] = new ChestInstance
{
Id = chestSpawn.Id,
X = chestSpawn.X * 32 + 16,
Y = chestSpawn.Y * 32 + 16,
Type = chestSpawn.ChestType,
IsOpened = false
};
}
}
private DungeonMobDefinition? SelectMobDefinition(DungeonMobSpawnType spawnType, Random rng)
{
var candidates = _mobDefinitions.Values
.Where(m => m.IsEnabled && m.MinTier <= Tier && m.MaxTier >= Tier)
.ToList();
if (candidates.Count == 0) return null;
candidates = spawnType switch
{
DungeonMobSpawnType.Boss => candidates.Where(m => m.Type == MobType.Boss).ToList(),
DungeonMobSpawnType.Elite => candidates.Where(m => m.Type == MobType.Elite || m.Type == MobType.Miniboss).ToList(),
_ => candidates.Where(m => m.Type == MobType.Normal || m.Type == MobType.Swarm).ToList()
};
if (candidates.Count == 0)
{
candidates = _mobDefinitions.Values.Where(m => m.IsEnabled && m.MinTier <= Tier).ToList();
}
return candidates.Count == 0 ? null : candidates[rng.Next(candidates.Count)];
}
/// <summary>
/// Process one simulation tick
/// </summary>
public TickResult Tick(long tick)
{
CurrentTick = tick;
if (Phase != DungeonPhase.Active)
return new TickResult { Phase = Phase };
_pendingDamageEvents.Clear();
_pendingDeathEvents.Clear();
_pendingAbilityEvents.Clear();
// Update all mobs (AI)
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
{
MobAI.UpdateMob(mob, this, TickDelta);
// Process mob attacks if in attacking state
if (mob.State == MobState.Attacking && mob.TargetId.HasValue)
{
float attackInterval = 1f / mob.Stats.AttackSpeed;
if (CurrentTick - mob.LastAttackTick >= (long)(attackInterval * TicksPerSecond))
{
if (Players.TryGetValue(mob.TargetId.Value, out var target) && target.IsAlive)
{
ProcessMobAbility(mob, target);
}
mob.LastAttackTick = CurrentTick;
}
}
}
// Update projectiles
UpdateProjectiles();
// Update hazard zones
UpdateHazardZones();
// Update players (movement, regeneration, status effects)
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
UpdatePlayer(player);
}
// Check dungeon completion
if (Mobs.Values.All(m => !m.IsAlive))
{
Phase = DungeonPhase.Cleared;
SpawnExit();
}
return new TickResult
{
DamageEvents = new List<DamageEvent>(_pendingDamageEvents),
DeathEvents = new List<DeathEvent>(_pendingDeathEvents),
AbilityEvents = new List<AbilityEvent>(_pendingAbilityEvents),
Phase = Phase
};
}
/// <summary>
/// Process a mob's ability/attack against a target
/// </summary>
private void ProcessMobAbility(MobInstance mob, PlayerInstance target)
{
// Find the best available ability
var ability = mob.Abilities
.Where(a => a.IsAvailable(mob.HpPercent))
.Where(a => a.Phase == 0 || a.Phase == mob.CurrentPhase)
.OrderByDescending(a => a.Priority)
.FirstOrDefault();
if (ability == null) return;
float distance = Distance(mob.X, mob.Y, target.X, target.Y);
if (ability.Definition.Range > 0 && distance > ability.Definition.Range) return;
// Put ability on cooldown
ability.CooldownRemaining = ability.Definition.Cooldown;
// Emit ability event for client animation
_pendingAbilityEvents.Add(new AbilityEvent
{
SourceType = EntityType.Mob,
SourceId = mob.Id,
AbilityKey = ability.Definition.Key,
AnimationKey = ability.Definition.AnimationKey,
TargetX = target.X,
TargetY = target.Y,
TargetId = (int)target.CharacterId
});
// Process ability based on type
switch (ability.Definition.AbilityType)
{
case MobAbilityType.MeleeAttack:
case MobAbilityType.Cleave:
ProcessMeleeAbility(mob, ability.Definition, target);
break;
case MobAbilityType.ProjectileSingle:
case MobAbilityType.ProjectileAoe:
SpawnProjectile(mob, ability.Definition, target);
break;
case MobAbilityType.GroundAoe:
case MobAbilityType.ConeAttack:
ProcessAoeAbility(mob, ability.Definition, target.X, target.Y);
break;
case MobAbilityType.Poison:
case MobAbilityType.Bleed:
case MobAbilityType.Burn:
ApplyDotToPlayer(mob, ability.Definition, target);
break;
case MobAbilityType.Stun:
case MobAbilityType.Slow:
case MobAbilityType.Root:
case MobAbilityType.Fear:
ApplyStatusToPlayer(ability.Definition, target);
break;
case MobAbilityType.Knockback:
ApplyKnockback(mob, ability.Definition, target);
break;
case MobAbilityType.Pull:
ApplyPull(mob, ability.Definition, target);
break;
case MobAbilityType.HazardZone:
SpawnHazardZone(mob, ability.Definition, target.X, target.Y);
break;
}
}
private void ProcessMeleeAbility(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
int damage = ability.BaseDamage;
string damageTypeKey = ability.DamageTypeKey ?? "physical";
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, damageTypeKey, damage, target.Resistances);
ApplyDamageToPlayer(mob, target, result.FinalDamage, damageTypeKey, result.WasResisted, result.WasWeakness);
// Cleave hits other nearby players
if (ability.AbilityType == MobAbilityType.Cleave && ability.AoeRadius > 0)
{
foreach (var other in Players.Values.Where(p => p.IsAlive && p.CharacterId != target.CharacterId))
{
if (Distance(mob.X, mob.Y, other.X, other.Y) <= ability.AoeRadius)
{
var otherResult = CombatCalculator.CalculateMobToPlayerDamage(
mob, other, damageTypeKey, damage, other.Resistances);
ApplyDamageToPlayer(mob, other, otherResult.FinalDamage, damageTypeKey, otherResult.WasResisted, otherResult.WasWeakness);
}
}
}
}
private void SpawnProjectile(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
var projectile = new ProjectileInstance
{
Id = GetNextProjectileId(),
SourceMobId = mob.Id,
AbilityId = ability.Id,
X = mob.X,
Y = mob.Y,
TargetX = target.X,
TargetY = target.Y,
Speed = ability.ProjectileSpeed,
Damage = ability.BaseDamage,
DamageTypeKey = ability.DamageTypeKey,
AoeRadius = ability.AoeRadius,
SpriteKey = ability.ProjectileSprite ?? "projectile_default"
};
// Calculate direction
float dx = target.X - mob.X;
float dy = target.Y - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
projectile.VelocityX = (dx / dist) * ability.ProjectileSpeed;
projectile.VelocityY = (dy / dist) * ability.ProjectileSpeed;
}
Projectiles[projectile.Id] = projectile;
}
private void UpdateProjectiles()
{
var toRemove = new List<int>();
foreach (var projectile in Projectiles.Values)
{
// Move projectile
projectile.X += projectile.VelocityX * TickDelta;
projectile.Y += projectile.VelocityY * TickDelta;
projectile.DistanceTraveled += MathF.Sqrt(
projectile.VelocityX * projectile.VelocityX +
projectile.VelocityY * projectile.VelocityY) * TickDelta;
// Check max range
if (projectile.DistanceTraveled > 500)
{
toRemove.Add(projectile.Id);
continue;
}
// Check collision with players
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(projectile.X, projectile.Y, player.X, player.Y) < 20)
{
// Hit!
if (projectile.AoeRadius > 0)
{
// AOE explosion
ProcessAoeAbilityAtLocation(projectile, projectile.X, projectile.Y);
}
else
{
// Single target
if (Mobs.TryGetValue(projectile.SourceMobId, out var sourceMob))
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, projectile.DamageTypeKey, projectile.Damage, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, projectile.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
toRemove.Add(projectile.Id);
break;
}
}
// Check wall collision
if (!CanMoveTo(projectile.X, projectile.Y))
{
if (projectile.AoeRadius > 0)
{
ProcessAoeAbilityAtLocation(projectile, projectile.X, projectile.Y);
}
toRemove.Add(projectile.Id);
}
}
foreach (var id in toRemove)
{
Projectiles.TryRemove(id, out _);
}
}
private void ProcessAoeAbility(MobInstance mob, MobAbilityDefinition ability, float targetX, float targetY)
{
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(targetX, targetY, player.X, player.Y) <= ability.AoeRadius)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, player, ability.DamageTypeKey, ability.BaseDamage, player.Resistances);
ApplyDamageToPlayer(mob, player, result.FinalDamage, ability.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
}
private void ProcessAoeAbilityAtLocation(ProjectileInstance projectile, float x, float y)
{
if (!Mobs.TryGetValue(projectile.SourceMobId, out var sourceMob)) return;
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(x, y, player.X, player.Y) <= projectile.AoeRadius)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, projectile.DamageTypeKey, projectile.Damage, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, projectile.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
}
}
private void ApplyDotToPlayer(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
// First apply initial hit if any
if (ability.BaseDamage > 0)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, ability.DamageTypeKey, ability.BaseDamage, target.Resistances);
ApplyDamageToPlayer(mob, target, result.FinalDamage, ability.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
// Apply DOT status effect
string effectType = ability.AbilityType switch
{
MobAbilityType.Poison => "poison",
MobAbilityType.Bleed => "bleed",
MobAbilityType.Burn => "burn",
_ => "dot"
};
target.StatusEffects.Add(new PlayerStatusEffect
{
EffectType = effectType,
Duration = ability.EffectDuration,
TickInterval = ability.DotTickInterval,
NextTickIn = ability.DotTickInterval,
DamagePerTick = ability.DotDamagePerTick,
SourceMobId = mob.Id
});
}
private void ApplyStatusToPlayer(MobAbilityDefinition ability, PlayerInstance target)
{
string effectType = ability.AbilityType switch
{
MobAbilityType.Stun => "stun",
MobAbilityType.Slow => "slow",
MobAbilityType.Root => "root",
MobAbilityType.Fear => "fear",
MobAbilityType.Silence => "silence",
_ => "debuff"
};
target.StatusEffects.Add(new PlayerStatusEffect
{
EffectType = effectType,
Duration = ability.EffectDuration,
Modifier = ability.SpeedModifier
});
}
private void ApplyKnockback(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
// Apply damage first
if (ability.BaseDamage > 0)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
mob, target, ability.DamageTypeKey, ability.BaseDamage, target.Resistances);
ApplyDamageToPlayer(mob, target, result.FinalDamage, ability.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
// Calculate knockback direction (away from mob)
float dx = target.X - mob.X;
float dy = target.Y - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
float newX = target.X + (dx / dist) * ability.DisplacementDistance;
float newY = target.Y + (dy / dist) * ability.DisplacementDistance;
if (CanMoveTo(newX, target.Y)) target.X = newX;
if (CanMoveTo(target.X, newY)) target.Y = newY;
}
}
private void ApplyPull(MobInstance mob, MobAbilityDefinition ability, PlayerInstance target)
{
// Calculate pull direction (toward mob)
float dx = mob.X - target.X;
float dy = mob.Y - target.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
float pullDist = Math.Min(ability.DisplacementDistance, dist - 30); // Don't pull on top of mob
if (pullDist > 0)
{
float newX = target.X + (dx / dist) * pullDist;
float newY = target.Y + (dy / dist) * pullDist;
if (CanMoveTo(newX, target.Y)) target.X = newX;
if (CanMoveTo(target.X, newY)) target.Y = newY;
}
}
}
private void SpawnHazardZone(MobInstance mob, MobAbilityDefinition ability, float x, float y)
{
var hazard = new HazardZone
{
Id = GetNextHazardId(),
SourceMobId = mob.Id,
X = x,
Y = y,
Radius = ability.AoeRadius,
DamagePerTick = ability.DotDamagePerTick,
TickInterval = ability.DotTickInterval,
Duration = ability.EffectDuration,
NextTickIn = ability.DotTickInterval,
DamageTypeKey = ability.DamageTypeKey,
VisualKey = ability.VisualEffectKey ?? "hazard_default"
};
HazardZones[hazard.Id] = hazard;
}
private void UpdateHazardZones()
{
var toRemove = new List<int>();
foreach (var hazard in HazardZones.Values)
{
hazard.Duration -= TickDelta;
hazard.NextTickIn -= TickDelta;
if (hazard.Duration <= 0)
{
toRemove.Add(hazard.Id);
continue;
}
if (hazard.NextTickIn <= 0)
{
hazard.NextTickIn = hazard.TickInterval;
// Damage players in zone
MobInstance? sourceMob = null;
Mobs.TryGetValue(hazard.SourceMobId, out sourceMob);
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
if (Distance(hazard.X, hazard.Y, player.X, player.Y) <= hazard.Radius)
{
if (sourceMob != null)
{
var result = CombatCalculator.CalculateMobToPlayerDamage(
sourceMob, player, hazard.DamageTypeKey, hazard.DamagePerTick, player.Resistances);
ApplyDamageToPlayer(sourceMob, player, result.FinalDamage, hazard.DamageTypeKey, result.WasResisted, result.WasWeakness);
}
else
{
ApplyDamageToPlayer(null, player, hazard.DamagePerTick, hazard.DamageTypeKey, false, false);
}
}
}
}
}
foreach (var id in toRemove)
{
HazardZones.TryRemove(id, out _);
}
}
private void ApplyDamageToPlayer(MobInstance? mob, PlayerInstance player, int damage, string damageTypeKey, bool wasResisted, bool wasWeakness)
{
player.Health -= damage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Mob,
SourceId = mob?.Id ?? 0,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
Damage = damage,
DamageTypeKey = damageTypeKey,
WasResisted = wasResisted,
WasWeakness = wasWeakness
});
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Player,
EntityId = (int)player.CharacterId,
EntityName = player.CharacterName,
KillerType = EntityType.Mob,
KillerId = mob?.Id ?? 0,
KillerName = mob?.Name ?? "Hazard"
});
}
}
private void UpdatePlayer(PlayerInstance player)
{
// Update status effects first
UpdatePlayerStatusEffects(player);
// If stunned, can't do anything
if (player.IsStunned) return;
// Process movement input (unless rooted or feared)
if (!player.IsRooted && !player.IsFeared)
{
if (player.InputX != 0 || player.InputY != 0)
{
float speedMod = player.GetSpeedModifier();
float speed = player.MoveSpeed * speedMod * TickDelta;
float newX = player.X + player.InputX * speed;
float newY = player.Y + player.InputY * speed;
if (CanMoveTo(newX, player.Y)) player.X = newX;
if (CanMoveTo(player.X, newY)) player.Y = newY;
if (player.InputX != 0 || player.InputY != 0)
{
player.Rotation = MathF.Atan2(player.InputY, player.InputX);
}
}
}
// If feared, run away from nearest mob
if (player.IsFeared)
{
var nearestMob = Mobs.Values
.Where(m => m.IsAlive)
.OrderBy(m => Distance(player.X, player.Y, m.X, m.Y))
.FirstOrDefault();
if (nearestMob != null)
{
float dx = player.X - nearestMob.X;
float dy = player.Y - nearestMob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist > 0)
{
float speed = player.MoveSpeed * 1.2f * TickDelta; // Run faster when feared
float newX = player.X + (dx / dist) * speed;
float newY = player.Y + (dy / dist) * speed;
if (CanMoveTo(newX, player.Y)) player.X = newX;
if (CanMoveTo(player.X, newY)) player.Y = newY;
}
}
}
// Process attack (unless stunned or silenced for abilities)
if (!player.IsStunned && player.WantsToAttack && player.AttackTargetId.HasValue)
{
TryPlayerAttack(player, player.AttackTargetId.Value);
player.WantsToAttack = false;
}
// Regeneration (out of combat)
if (CurrentTick - player.LastCombatTick > TicksPerSecond * 5)
{
player.IsInCombat = false;
player.Health = Math.Min(player.MaxHealth, player.Health + 0.5f);
player.Mana = Math.Min(player.MaxMana, player.Mana + 0.3f);
player.Stamina = Math.Min(player.MaxStamina, player.Stamina + 1f);
}
}
private void UpdatePlayerStatusEffects(PlayerInstance player)
{
var expired = new List<PlayerStatusEffect>();
foreach (var effect in player.StatusEffects)
{
effect.Duration -= TickDelta;
// Handle DOT
if (effect.DamagePerTick > 0)
{
effect.NextTickIn -= TickDelta;
if (effect.NextTickIn <= 0)
{
player.Health -= effect.DamagePerTick;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
effect.NextTickIn = effect.TickInterval;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Mob,
SourceId = effect.SourceMobId,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
Damage = effect.DamagePerTick,
DamageTypeKey = effect.EffectType
});
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
string killerName = "DOT";
if (Mobs.TryGetValue(effect.SourceMobId, out var mob))
killerName = mob.Name;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Player,
EntityId = (int)player.CharacterId,
EntityName = player.CharacterName,
KillerType = EntityType.Mob,
KillerId = effect.SourceMobId,
KillerName = killerName
});
}
}
}
if (effect.Duration <= 0)
expired.Add(effect);
}
foreach (var e in expired)
player.StatusEffects.Remove(e);
}
private void TryPlayerAttack(PlayerInstance player, ulong targetId)
{
if (!Mobs.TryGetValue((int)targetId, out var mob) || !mob.IsAlive)
return;
float dist = Distance(player.X, player.Y, mob.X, mob.Y);
if (dist > 60) return; // Out of range
// Use player's weapon damage type (set when loading equipped weapon)
string damageTypeKey = player.WeaponDamageTypeKey ?? "physical";
int baseDamage = 10 + (int)(player.Strength * 0.5f);
// Calculate damage with mob resistances
var result = CombatCalculator.CalculatePlayerToMobDamage(
player, mob, damageTypeKey, baseDamage);
if (result.WasImmune)
{
// Mob is immune, still add event for client feedback
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)player.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = 0,
DamageTypeKey = damageTypeKey,
WasImmune = true
});
return;
}
mob.Health -= result.FinalDamage;
player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)player.CharacterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = result.FinalDamage,
DamageTypeKey = damageTypeKey,
WasResisted = result.WasResisted,
WasWeakness = result.WasWeakness
});
if (mob.Health > 0)
{
mob.State = MobState.Damaged;
}
if (mob.Health <= 0)
{
mob.Health = 0;
mob.IsAlive = false;
mob.State = MobState.Dead;
player.XpGained += mob.Stats.XpReward;
player.MobsKilled++;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Mob,
EntityId = mob.Id,
EntityName = mob.Name,
KillerType = EntityType.Player,
KillerId = (int)player.CharacterId,
KillerName = player.CharacterName,
XpReward = mob.Stats.XpReward
});
}
}
private void SpawnExit()
{
// Spawn exit at boss room location
if (Layout.Rooms.Count > 0)
{
var bossRoom = Layout.Rooms.LastOrDefault(r => r.Type == DungeonRoomType.Boss)
?? Layout.Rooms[^1];
Layout.ExitPosition = new DungeonPoint(bossRoom.CenterX, bossRoom.CenterY);
}
}
public bool CanMoveTo(float x, float y)
{
int tileX = (int)(x / 32);
int tileY = (int)(y / 32);
return Layout.IsWalkable(tileX, tileY);
}
private void MoveToward(MobInstance mob, float targetX, float targetY, float speed)
{
float dx = targetX - mob.X;
float dy = targetY - mob.Y;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist < 1) return;
float moveAmount = speed * TickDelta;
if (moveAmount > dist) moveAmount = dist;
float newX = mob.X + (dx / dist) * moveAmount;
float newY = mob.Y + (dy / dist) * moveAmount;
if (CanMoveTo(newX, mob.Y)) mob.X = newX;
if (CanMoveTo(mob.X, newY)) mob.Y = newY;
mob.Rotation = MathF.Atan2(dy, dx);
}
private static float Distance(float x1, float y1, float x2, float y2)
{
float dx = x2 - x1;
float dy = y2 - y1;
return MathF.Sqrt(dx * dx + dy * dy);
}
}