444 lines
14 KiB
C#
444 lines
14 KiB
C#
using System.Collections.Concurrent;
|
|
using DataServer.Data.Entities;
|
|
using DataServer.Data.Enums;
|
|
|
|
namespace Server.Game.Dungeon;
|
|
|
|
/// <summary>
|
|
/// Runtime simulation for an active dungeon instance
|
|
/// </summary>
|
|
public 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();
|
|
|
|
// ID generator for loot chests
|
|
private int _nextLootChestId = 1;
|
|
public int GetNextLootChestId() => _nextLootChestId++;
|
|
|
|
// Combat tracking
|
|
private readonly List<DamageEvent> _pendingDamageEvents = new();
|
|
private readonly List<DeathEvent> _pendingDeathEvents = new();
|
|
|
|
private int _nextDroppedItemId = 1;
|
|
private readonly Dictionary<int, DungeonMobDefinition> _mobDefinitions;
|
|
|
|
public DungeonSimulation(DungeonLayout layout, int tier, Dictionary<int, DungeonMobDefinition> mobDefinitions, int bracketMin = 1)
|
|
{
|
|
Layout = layout;
|
|
Tier = tier;
|
|
BracketMin = bracketMin;
|
|
_mobDefinitions = mobDefinitions;
|
|
|
|
SpawnMobs();
|
|
InitializeChests();
|
|
SpawnExitPortal();
|
|
}
|
|
|
|
private void SpawnExitPortal()
|
|
{
|
|
// Spawn exit portal near the entrance room (but offset so players don't spawn on it)
|
|
if (Layout.Rooms.Count == 0) return;
|
|
|
|
var entranceRoom = Layout.Rooms[0];
|
|
|
|
// Find a valid floor tile near the entrance that's not at the exact center
|
|
// Try positions around the room center
|
|
var offsets = new[] { (2, 0), (-2, 0), (0, 2), (0, -2), (2, 2), (-2, -2) };
|
|
|
|
foreach (var (dx, dy) in offsets)
|
|
{
|
|
int portalTileX = entranceRoom.CenterX + dx;
|
|
int portalTileY = entranceRoom.CenterY + dy;
|
|
|
|
// Check if this is a valid floor tile
|
|
if (portalTileX >= 0 && portalTileX < Layout.Width &&
|
|
portalTileY >= 0 && portalTileY < Layout.Height &&
|
|
Layout.Tiles[portalTileX, portalTileY] == 1) // 1 = floor
|
|
{
|
|
var portal = new PortalInstance
|
|
{
|
|
Id = 1,
|
|
X = portalTileX * 32 + 16, // Center of tile in world coords
|
|
Y = portalTileY * 32 + 16,
|
|
Type = PortalType.Exit,
|
|
IsActive = true
|
|
};
|
|
|
|
Portals[portal.Id] = portal;
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Fallback: spawn at room center if no offset worked
|
|
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)
|
|
{
|
|
var mobDef = SelectMobDefinition(mobSpawn.MobType, rng);
|
|
if (mobDef == null) continue;
|
|
|
|
// Use bracket-aware stat scaling
|
|
var stats = mobDef.GetStatsForBracket(BracketMin);
|
|
|
|
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,
|
|
SpriteConfigJson = mobDef.SpriteConfigJson,
|
|
TintColor = mobDef.TintColor,
|
|
Scale = mobDef.Scale,
|
|
Type = mobDef.Type
|
|
};
|
|
}
|
|
}
|
|
|
|
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();
|
|
|
|
// Update all mobs (AI)
|
|
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
|
|
{
|
|
UpdateMob(mob);
|
|
}
|
|
|
|
// Update players (movement, regeneration)
|
|
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),
|
|
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)
|
|
{
|
|
mob.State = MobState.Returning;
|
|
mob.TargetId = null;
|
|
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f);
|
|
return;
|
|
}
|
|
|
|
if (closestDist <= mob.Stats.AggroRange)
|
|
{
|
|
mob.TargetId = target.CharacterId;
|
|
|
|
float distFromSpawn = Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY);
|
|
if (distFromSpawn > mob.Stats.LeashRange)
|
|
{
|
|
mob.State = MobState.Returning;
|
|
mob.TargetId = null;
|
|
MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed);
|
|
mob.Health = Math.Min(mob.MaxHealth, mob.Health + (int)(mob.MaxHealth * 0.02f));
|
|
return;
|
|
}
|
|
|
|
if (closestDist <= mob.Stats.AttackRange)
|
|
{
|
|
mob.State = MobState.Attacking;
|
|
|
|
float attackInterval = 1f / mob.Stats.AttackSpeed;
|
|
if (CurrentTick - mob.LastAttackTick >= (long)(attackInterval * TicksPerSecond))
|
|
{
|
|
MobAttackPlayer(mob, target);
|
|
mob.LastAttackTick = CurrentTick;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
mob.State = MobState.Chasing;
|
|
MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
mob.State = MobState.Idle;
|
|
mob.TargetId = null;
|
|
}
|
|
}
|
|
|
|
private void MobAttackPlayer(MobInstance mob, PlayerInstance player)
|
|
{
|
|
int damage = mob.Stats.PhysicalDamage + mob.Stats.MagicDamage;
|
|
player.Health -= damage;
|
|
player.IsInCombat = true;
|
|
player.LastCombatTick = CurrentTick;
|
|
|
|
_pendingDamageEvents.Add(new DamageEvent
|
|
{
|
|
SourceType = EntityType.Mob,
|
|
SourceId = mob.Id,
|
|
TargetType = EntityType.Player,
|
|
TargetId = (int)player.CharacterId,
|
|
Damage = damage
|
|
});
|
|
|
|
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,
|
|
KillerName = mob.Name
|
|
});
|
|
}
|
|
}
|
|
|
|
private void UpdatePlayer(PlayerInstance player)
|
|
{
|
|
// Process movement input
|
|
if (player.InputX != 0 || player.InputY != 0)
|
|
{
|
|
float speed = player.MoveSpeed * 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);
|
|
}
|
|
}
|
|
|
|
// Process attack
|
|
if (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 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
|
|
|
|
// Calculate damage
|
|
int damage = (int)(10 * (1 + player.Strength * 0.05f));
|
|
|
|
mob.Health -= damage;
|
|
player.IsInCombat = true;
|
|
player.LastCombatTick = CurrentTick;
|
|
|
|
_pendingDamageEvents.Add(new DamageEvent
|
|
{
|
|
SourceType = EntityType.Player,
|
|
SourceId = (int)player.CharacterId,
|
|
TargetType = EntityType.Mob,
|
|
TargetId = mob.Id,
|
|
Damage = damage
|
|
});
|
|
|
|
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);
|
|
|
|
if (tileX < 0 || tileX >= Layout.Width || tileY < 0 || tileY >= Layout.Height)
|
|
return false;
|
|
|
|
return Layout.Tiles[tileX, tileY] == 1;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
public enum DungeonPhase
|
|
{
|
|
Active,
|
|
Cleared,
|
|
Abandoned
|
|
}
|