Files
systemrevivalserver/Game/Dungeon/DungeonSimulation.cs
T
2025-12-06 11:20:32 -05:00

835 lines
26 KiB
C#

using System.Collections.Concurrent;
using DungeonCrawler.Data.Entities;
namespace DungeonCrawler.Game.Dungeon;
/// <summary>
/// Runtime simulation for an active dungeon instance
/// </summary>
public class DungeonSimulation
{
public Guid Id { get; }
public int Tier { get; }
public int Seed { get; }
public DungeonLayout Layout { 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();
// Combat tracking
private readonly List<DamageEvent> _pendingDamageEvents = new();
private readonly List<DeathEvent> _pendingDeathEvents = new();
private readonly List<LootEvent> _pendingLootEvents = new();
private int _nextDroppedItemId = 1;
private readonly object _lock = new();
// Mob definitions cache
private readonly Dictionary<int, MobDefinition> _mobDefinitions;
public DungeonSimulation(Guid id, int tier, int seed, Dictionary<int, MobDefinition> mobDefinitions)
{
Id = id;
Tier = tier;
Seed = seed;
_mobDefinitions = mobDefinitions;
// Generate dungeon layout
var generator = new DungeonGenerator(seed, tier);
Layout = generator.Generate();
// Spawn mobs from layout
SpawnMobs();
// Initialize chests
foreach (var chestSpawn in Layout.ChestSpawns)
{
Chests[chestSpawn.Id] = new ChestInstance
{
Id = chestSpawn.Id,
X = chestSpawn.X * 32 + 16, // Center of tile
Y = chestSpawn.Y * 32 + 16,
Type = chestSpawn.ChestType,
IsOpened = false
};
}
}
private void SpawnMobs()
{
foreach (var mobSpawn in Layout.MobSpawns)
{
// Pick appropriate mob definition based on spawn type and tier
var mobDef = SelectMobDefinition(mobSpawn.MobType);
if (mobDef == null) continue;
var stats = mobDef.GetStatsForTier(Tier);
Mobs[mobSpawn.Id] = 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,
Stats = stats,
State = MobState.Idle,
SpriteSheet = mobDef.SpriteSheet,
SpriteWidth = mobDef.SpriteWidth,
SpriteHeight = mobDef.SpriteHeight,
TintColor = mobDef.TintColor,
Type = mobDef.Type
};
}
}
private MobDefinition? SelectMobDefinition(MobSpawnType spawnType)
{
var candidates = _mobDefinitions.Values
.Where(m => m.IsEnabled && m.MinTier <= Tier && m.MaxTier >= Tier)
.ToList();
if (candidates.Count == 0) return null;
// Filter by spawn type
candidates = spawnType switch
{
MobSpawnType.Boss => candidates.Where(m => m.Type == MobType.Boss).ToList(),
MobSpawnType.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)
{
// Fallback to any mob for this tier
candidates = _mobDefinitions.Values
.Where(m => m.IsEnabled && m.MinTier <= Tier)
.ToList();
}
if (candidates.Count == 0) return null;
// Random selection (could add weights later)
var rng = new Random(Seed + Layout.MobSpawns.Count);
return candidates[rng.Next(candidates.Count)];
}
/// <summary>
/// Add a player to the dungeon
/// </summary>
public PlayerInstance AddPlayer(ulong characterId, string name, CharacterCombatStats stats, float x, float y)
{
var player = new PlayerInstance
{
CharacterId = characterId,
Name = name,
X = x,
Y = y,
Health = stats.MaxHealth,
MaxHealth = stats.MaxHealth,
Mana = stats.MaxMana,
MaxMana = stats.MaxMana,
Stamina = stats.MaxStamina,
MaxStamina = stats.MaxStamina,
Stats = stats,
IsAlive = true
};
Players[characterId] = player;
return player;
}
/// <summary>
/// Process one simulation tick
/// </summary>
public TickResult Tick()
{
if (Phase != DungeonPhase.Active)
return new TickResult();
CurrentTick++;
_pendingDamageEvents.Clear();
_pendingDeathEvents.Clear();
_pendingLootEvents.Clear();
// Update all mobs (AI)
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
{
UpdateMob(mob);
}
// Update players (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;
// Spawn exit
SpawnExit();
}
return new TickResult
{
DamageEvents = new List<DamageEvent>(_pendingDamageEvents),
DeathEvents = new List<DeathEvent>(_pendingDeathEvents),
LootEvents = new List<LootEvent>(_pendingLootEvents),
Phase = Phase
};
}
private void UpdateMob(MobInstance mob)
{
// Find closest player
PlayerInstance? target = null;
float closestDist = float.MaxValue;
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
float dist = Distance(mob.X, mob.Y, player.X, player.Y);
if (dist < closestDist)
{
closestDist = dist;
target = player;
}
}
if (target == null)
{
// No players - return to spawn
mob.State = MobState.Returning;
mob.TargetId = null;
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f);
return;
}
// Check if in aggro range
if (closestDist <= mob.Stats.AggroRange)
{
mob.TargetId = target.CharacterId;
// Check leash range
float distFromSpawn = Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY);
if (distFromSpawn > mob.Stats.LeashRange)
{
// Too far from spawn, return
mob.State = MobState.Returning;
mob.TargetId = null;
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed);
// Heal while returning
mob.Health = Math.Min(mob.MaxHealth, mob.Health + (int)(mob.MaxHealth * 0.02f));
return;
}
// In attack range?
if (closestDist <= mob.Stats.AttackRange)
{
mob.State = MobState.Attacking;
// Check attack cooldown
float attackInterval = 1f / mob.Stats.AttackSpeed;
if (CurrentTick - mob.LastAttackTick >= (long)(attackInterval * TicksPerSecond))
{
// Attack!
MobAttackPlayer(mob, target);
mob.LastAttackTick = CurrentTick;
}
}
else
{
// Chase
mob.State = MobState.Chasing;
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed);
}
}
else
{
// Out of aggro range
if (mob.State == MobState.Chasing || mob.State == MobState.Attacking)
{
// Lost target, return
mob.State = MobState.Returning;
mob.TargetId = null;
}
else
{
mob.State = MobState.Idle;
}
// Return to spawn if not at spawn
if (Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY) > 5)
{
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f);
}
}
}
private void MobAttackPlayer(MobInstance mob, PlayerInstance player)
{
// Calculate damage
int damage = mob.Stats.PhysicalDamage;
// Apply player armor reduction
if (player.Stats.Armor > 0)
{
float reduction = player.Stats.Armor / (float)(player.Stats.Armor + 100);
damage = (int)(damage * (1f - reduction));
}
damage = Math.Max(1, damage); // Minimum 1 damage
// Apply damage
player.Health -= damage;
player.LastCombatTick = CurrentTick;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Mob,
SourceId = mob.Id,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
Damage = damage,
DamageType = DamageType.Physical
});
// Check death
if (player.Health <= 0)
{
player.Health = 0;
player.IsAlive = false;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Player,
EntityId = (int)player.CharacterId,
KillerType = EntityType.Mob,
KillerId = mob.Id,
EntityName = player.Name,
KillerName = mob.Name
});
// Drop player's inventory (mob holds it)
mob.HeldLoot.AddRange(player.Inventory);
player.Inventory.Clear();
}
}
private void UpdatePlayer(PlayerInstance player)
{
// Check if out of combat (for escape teleport)
float secondsSinceCombat = (CurrentTick - player.LastCombatTick) / (float)TicksPerSecond;
player.IsInCombat = secondsSinceCombat < 5f; // 5 seconds to leave combat
// Regeneration (only out of combat or reduced in combat)
float regenMultiplier = player.IsInCombat ? 0.2f : 1f;
float regenRate = player.Stats.RegenRate * regenMultiplier * TickDelta;
player.Health = Math.Min(player.MaxHealth, player.Health + regenRate * 2);
player.Mana = Math.Min(player.MaxMana, player.Mana + regenRate);
player.Stamina = Math.Min(player.MaxStamina, player.Stamina + regenRate * 3);
}
/// <summary>
/// Player attacks - called from input handler
/// </summary>
public void PlayerAttack(ulong characterId, float aimAngle)
{
if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive)
return;
// Check attack cooldown
float attackInterval = 1f / player.Stats.AttackSpeed;
if (CurrentTick - player.LastAttackTick < (long)(attackInterval * TicksPerSecond))
return;
player.LastAttackTick = CurrentTick;
player.LastCombatTick = CurrentTick;
// Get attack range and damage from equipped weapon (or use base)
float attackRange = player.WeaponRange > 0 ? player.WeaponRange : 50f;
int baseDamage = player.WeaponDamage > 0 ? player.WeaponDamage : 5 + player.Stats.Strength;
// Apply damage multiplier
int damage = (int)(baseDamage * player.Stats.PhysicalDamageMultiplier);
// Find mobs in attack arc
float attackArc = 0.5f; // radians (~30 degrees)
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
{
float dist = Distance(player.X, player.Y, mob.X, mob.Y);
if (dist > attackRange) continue;
// Check angle
float angleToMob = MathF.Atan2(mob.Y - player.Y, mob.X - player.X);
float angleDiff = NormalizeAngle(angleToMob - aimAngle);
if (MathF.Abs(angleDiff) > attackArc) continue;
// Hit!
int actualDamage = mob.Stats.CalculateDamage(damage, DamageType.Physical);
mob.Health -= actualDamage;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)characterId,
TargetType = EntityType.Mob,
TargetId = mob.Id,
Damage = actualDamage,
DamageType = DamageType.Physical
});
// Check death
if (mob.Health <= 0)
{
MobDeath(mob, player);
}
// Only hit one mob per swing (for melee)
// TODO: Make this configurable for cleave weapons
break;
}
}
/// <summary>
/// Player attacks another player (PvP)
/// </summary>
public void PlayerAttackPlayer(ulong attackerId, ulong targetId, float aimAngle)
{
if (!Players.TryGetValue(attackerId, out var attacker) || !attacker.IsAlive)
return;
if (!Players.TryGetValue(targetId, out var target) || !target.IsAlive)
return;
// Check attack cooldown
float attackInterval = 1f / attacker.Stats.AttackSpeed;
if (CurrentTick - attacker.LastAttackTick < (long)(attackInterval * TicksPerSecond))
return;
attacker.LastAttackTick = CurrentTick;
attacker.LastCombatTick = CurrentTick;
target.LastCombatTick = CurrentTick;
float attackRange = attacker.WeaponRange > 0 ? attacker.WeaponRange : 50f;
float dist = Distance(attacker.X, attacker.Y, target.X, target.Y);
if (dist > attackRange) return;
int baseDamage = attacker.WeaponDamage > 0 ? attacker.WeaponDamage : 5 + attacker.Stats.Strength;
int damage = (int)(baseDamage * attacker.Stats.PhysicalDamageMultiplier);
// Apply target armor
if (target.Stats.Armor > 0)
{
float reduction = target.Stats.Armor / (float)(target.Stats.Armor + 100);
damage = (int)(damage * (1f - reduction));
}
damage = Math.Max(1, damage);
target.Health -= damage;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
SourceId = (int)attackerId,
TargetType = EntityType.Player,
TargetId = (int)targetId,
Damage = damage,
DamageType = DamageType.Physical,
IsPvP = true
});
if (target.Health <= 0)
{
target.Health = 0;
target.IsAlive = false;
attacker.PlayersKilled++;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Player,
EntityId = (int)targetId,
KillerType = EntityType.Player,
KillerId = (int)attackerId,
EntityName = target.Name,
KillerName = attacker.Name,
IsPvP = true
});
// Transfer inventory to killer
attacker.Inventory.AddRange(target.Inventory);
target.Inventory.Clear();
}
}
private void MobDeath(MobInstance mob, PlayerInstance killer)
{
mob.Health = 0;
mob.IsAlive = false;
mob.State = MobState.Dead;
_pendingDeathEvents.Add(new DeathEvent
{
EntityType = EntityType.Mob,
EntityId = mob.Id,
KillerType = EntityType.Player,
KillerId = (int)killer.CharacterId,
EntityName = mob.Name,
KillerName = killer.Name,
XpReward = mob.Stats.XpReward
});
// Award XP
int xp = (int)(mob.Stats.XpReward * killer.Stats.XpBonus);
killer.XpGained += xp;
// Drop loot (including any player loot the mob was holding)
DropMobLoot(mob);
}
private void DropMobLoot(MobInstance mob)
{
// Drop any held player loot
foreach (var item in mob.HeldLoot)
{
CreateDroppedItem(mob.X, mob.Y, item);
}
mob.HeldLoot.Clear();
// TODO: Roll loot table for mob drops
// For now, just create some placeholder loot
if (mob.Type == MobType.Boss)
{
// Guaranteed drop from boss
_pendingLootEvents.Add(new LootEvent
{
X = mob.X,
Y = mob.Y,
MobId = mob.Id,
MobName = mob.Name,
IsBoss = true
});
}
}
private void CreateDroppedItem(float x, float y, ItemDrop item)
{
int id = _nextDroppedItemId++;
DroppedItems[id] = new DroppedItem
{
Id = id,
ItemDefinitionId = item.ItemDefinitionId,
Quantity = item.Quantity,
X = x + (new Random().NextSingle() - 0.5f) * 30,
Y = y + (new Random().NextSingle() - 0.5f) * 30,
DroppedAtTick = CurrentTick
};
}
private void SpawnExit()
{
// Spawn exit at boss room or last room
var lastRoom = Layout.Rooms.LastOrDefault();
if (lastRoom != null)
{
Layout.ExitPosition = new Point(lastRoom.CenterX, lastRoom.CenterY);
}
}
/// <summary>
/// Player picks up an item
/// </summary>
public bool TryPickupItem(ulong characterId, int droppedItemId)
{
if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive)
return false;
if (!DroppedItems.TryRemove(droppedItemId, out var item))
return false;
// Check distance
if (Distance(player.X, player.Y, item.X, item.Y) > 60)
{
// Too far, put item back
DroppedItems[droppedItemId] = item;
return false;
}
// Add to inventory
player.Inventory.Add(new ItemDrop
{
ItemDefinitionId = item.ItemDefinitionId,
Quantity = item.Quantity
});
return true;
}
/// <summary>
/// Player opens a chest
/// </summary>
public bool TryOpenChest(ulong characterId, int chestId)
{
if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive)
return false;
if (!Chests.TryGetValue(chestId, out var chest) || chest.IsOpened)
return false;
// Check distance
if (Distance(player.X, player.Y, chest.X, chest.Y) > 60)
return false;
chest.IsOpened = true;
// TODO: Roll loot table
_pendingLootEvents.Add(new LootEvent
{
X = chest.X,
Y = chest.Y,
ChestId = chestId,
ChestType = chest.Type
});
return true;
}
// Movement helpers
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;
// Check collision with walls
if (CanMoveTo(newX, mob.Y)) mob.X = newX;
if (CanMoveTo(mob.X, newY)) mob.Y = newY;
// Update facing direction
mob.Rotation = MathF.Atan2(dy, dx);
}
public bool CanMoveTo(float x, float y)
{
int tileX = (int)(x / 32);
int tileY = (int)(y / 32);
if (tileX < 0 || tileX >= Layout.Width || tileY < 0 || tileY >= Layout.Height)
return false;
return Layout.Tiles[tileX, tileY] == 1;
}
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);
}
private static float NormalizeAngle(float angle)
{
while (angle > MathF.PI) angle -= MathF.PI * 2;
while (angle < -MathF.PI) angle += MathF.PI * 2;
return angle;
}
}
// Runtime instances
public class PlayerInstance
{
public ulong CharacterId { get; set; }
public string Name { get; set; } = "";
public float X { get; set; }
public float Y { get; set; }
public float Rotation { get; set; }
public float Health { get; set; }
public float MaxHealth { get; set; }
public float Mana { get; set; }
public float MaxMana { get; set; }
public float Stamina { get; set; }
public float MaxStamina { get; set; }
public bool IsAlive { get; set; } = true;
public bool IsInCombat { get; set; }
public CharacterCombatStats Stats { get; set; } = new();
// Equipped weapon stats
public int WeaponDamage { get; set; }
public float WeaponRange { get; set; }
public DamageType WeaponDamageType { get; set; } = DamageType.Physical;
// Inventory (items being carried)
public List<ItemDrop> Inventory { get; set; } = new();
// Session stats
public int XpGained { get; set; }
public int MobsKilled { get; set; }
public int PlayersKilled { get; set; }
// Tick tracking
public long LastAttackTick { get; set; }
public long LastCombatTick { get; set; }
// Input state
public float InputDx { get; set; }
public float InputDy { get; set; }
public float AimAngle { get; set; }
}
public class MobInstance
{
public int Id { get; set; }
public int DefinitionId { get; set; }
public string Name { get; set; } = "";
public float X { get; set; }
public float Y { get; set; }
public float Rotation { get; set; }
public float SpawnX { get; set; }
public float SpawnY { get; set; }
public int Health { get; set; }
public int MaxHealth { get; set; }
public bool IsAlive { get; set; } = true;
public MobCombatStats Stats { get; set; } = new();
public MobState State { get; set; } = MobState.Idle;
public MobType Type { get; set; }
public ulong? TargetId { get; set; }
public long LastAttackTick { get; set; }
// Visual
public string SpriteSheet { get; set; } = "";
public int SpriteWidth { get; set; } = 32;
public int SpriteHeight { get; set; } = 32;
public string TintColor { get; set; } = "#ffffff";
// Loot being held (from killed players)
public List<ItemDrop> HeldLoot { get; set; } = new();
}
public enum MobState
{
Idle,
Chasing,
Attacking,
Returning,
Fleeing,
Dead
}
public class ChestInstance
{
public int Id { get; set; }
public float X { get; set; }
public float Y { get; set; }
public ChestType Type { get; set; }
public bool IsOpened { get; set; }
}
public class DroppedItem
{
public int Id { get; set; }
public int ItemDefinitionId { get; set; }
public int Quantity { get; set; }
public float X { get; set; }
public float Y { get; set; }
public long DroppedAtTick { get; set; }
}
public class ItemDrop
{
public int ItemDefinitionId { get; set; }
public int Quantity { get; set; }
}
// Events
public class TickResult
{
public List<DamageEvent> DamageEvents { get; set; } = new();
public List<DeathEvent> DeathEvents { get; set; } = new();
public List<LootEvent> LootEvents { get; set; } = new();
public DungeonPhase Phase { get; set; }
}
public class DamageEvent
{
public EntityType SourceType { get; set; }
public int SourceId { get; set; }
public EntityType TargetType { get; set; }
public int TargetId { get; set; }
public int Damage { get; set; }
public DamageType DamageType { get; set; }
public bool IsPvP { get; set; }
}
public class DeathEvent
{
public EntityType EntityType { get; set; }
public int EntityId { get; set; }
public EntityType KillerType { get; set; }
public int KillerId { get; set; }
public string EntityName { get; set; } = "";
public string KillerName { get; set; } = "";
public int XpReward { get; set; }
public bool IsPvP { get; set; }
}
public class LootEvent
{
public float X { get; set; }
public float Y { get; set; }
public int? MobId { get; set; }
public string? MobName { get; set; }
public int? ChestId { get; set; }
public ChestType? ChestType { get; set; }
public bool IsBoss { get; set; }
}
public enum EntityType
{
Player,
Mob,
Chest
}
public enum DungeonPhase
{
Active,
Cleared,
Abandoned
}