diff --git a/Game/Dungeon/ChestInstance.cs b/Game/Dungeon/ChestInstance.cs
new file mode 100644
index 0000000..0314f84
--- /dev/null
+++ b/Game/Dungeon/ChestInstance.cs
@@ -0,0 +1,20 @@
+namespace Server.Game.Dungeon;
+
+public class ChestInstance
+{
+ public int Id { get; set; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public DungeonChestType 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; }
+}
diff --git a/Game/Dungeon/DungeonChestSpawn.cs b/Game/Dungeon/DungeonChestSpawn.cs
new file mode 100644
index 0000000..d483e62
--- /dev/null
+++ b/Game/Dungeon/DungeonChestSpawn.cs
@@ -0,0 +1,18 @@
+namespace Server.Game.Dungeon;
+
+public class DungeonChestSpawn
+{
+ public int Id { get; set; }
+ public int X { get; set; }
+ public int Y { get; set; }
+ public DungeonChestType ChestType { get; set; }
+ public int RoomIndex { get; set; }
+ public bool IsOpened { get; set; } = false;
+}
+
+public enum DungeonChestType
+{
+ Normal,
+ Rare,
+ Boss
+}
diff --git a/Game/Dungeon/DungeonGameHandler.cs b/Game/Dungeon/DungeonGameHandler.cs
deleted file mode 100644
index 3c9f9bd..0000000
--- a/Game/Dungeon/DungeonGameHandler.cs
+++ /dev/null
@@ -1,729 +0,0 @@
-using System.Collections.Concurrent;
-using System.Net.WebSockets;
-using System.Text;
-using System.Text.Json;
-using DungeonCrawler.Data.Entities;
-using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
-using Server.Data;
-
-namespace DungeonCrawler.Game.Dungeon;
-
-///
-/// Manages WebSocket connections, dungeon instances, and game state
-///
-public class DungeonGameHandler
-{
- private readonly IServiceScopeFactory _scopeFactory;
- private readonly ILogger _log;
- private readonly JsonSerializerOptions _jsonOptions;
-
- // Active connections
- private readonly ConcurrentDictionary _connections = new();
-
- // Active dungeon instances
- private readonly ConcurrentDictionary _dungeons = new();
-
- // Mob definitions cache
- private Dictionary _mobDefinitions = new();
-
- // Tick timer
- private Timer? _tickTimer;
-
- public DungeonGameHandler(IServiceScopeFactory scopeFactory, ILogger log)
- {
- _scopeFactory = scopeFactory;
- _log = log;
- _jsonOptions = new JsonSerializerOptions
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
- WriteIndented = false
- };
- }
-
- public async Task StartAsync()
- {
- // Load mob definitions
- await LoadMobDefinitionsAsync();
-
- // Start tick loop (20 ticks per second)
- _tickTimer = new Timer(TickAll, null, 0, 50);
-
- _log.LogInformation("DungeonGameHandler started with {MobCount} mob definitions", _mobDefinitions.Count);
- }
-
- private async Task LoadMobDefinitionsAsync()
- {
- using var scope = _scopeFactory.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
-
- var mobs = await db.Set()
- .Where(m => m.IsEnabled)
- .ToListAsync();
-
- if (mobs.Count == 0)
- {
- // Seed default mobs
- var defaults = DefaultMobs.GetDefaultMobs();
- db.Set().AddRange(defaults);
- await db.SaveChangesAsync();
- mobs = defaults;
- _log.LogInformation("Seeded {Count} default mob definitions", defaults.Count);
- }
-
- _mobDefinitions = mobs.ToDictionary(m => m.Id);
- }
-
- public async Task HandleConnectionAsync(WebSocket ws, ulong accountId, Character character)
- {
- var connection = new PlayerConnection
- {
- AccountId = accountId,
- CharacterId = character.Id,
- CharacterName = character.Name,
- WebSocket = ws,
- Character = character
- };
-
- _connections[character.Id] = connection;
-
- _log.LogInformation("Player {Name} connected (CharId: {CharId})", character.Name, character.Id);
-
- // Send initial state (hub)
- await SendAsync(connection, OpCodes.HUB_STATE, GetHubState(character));
-
- try
- {
- var buffer = new byte[4096];
- while (ws.State == WebSocketState.Open)
- {
- var result = await ws.ReceiveAsync(buffer, CancellationToken.None);
-
- if (result.MessageType == WebSocketMessageType.Close)
- break;
-
- if (result.MessageType == WebSocketMessageType.Binary ||
- result.MessageType == WebSocketMessageType.Text)
- {
- await HandleMessageAsync(connection, buffer, result.Count);
- }
- }
- }
- catch (WebSocketException ex)
- {
- _log.LogWarning("WebSocket error for {Name}: {Error}", character.Name, ex.Message);
- }
- finally
- {
- await HandleDisconnectAsync(connection);
- }
- }
-
- private async Task HandleDisconnectAsync(PlayerConnection connection)
- {
- _connections.TryRemove(connection.CharacterId, out _);
-
- // Remove from dungeon if in one
- if (connection.CurrentDungeonId.HasValue)
- {
- if (_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon))
- {
- dungeon.Simulation.Players.TryRemove(connection.CharacterId, out var player);
-
- // Save character state
- if (player != null)
- {
- await SaveCharacterStateAsync(connection.Character, player, false);
- }
- }
- }
-
- _log.LogInformation("Player {Name} disconnected", connection.CharacterName);
- }
-
- private async Task HandleMessageAsync(PlayerConnection connection, byte[] buffer, int length)
- {
- try
- {
- // Parse message (expecting JSON with OpCode and Payload)
- var json = Encoding.UTF8.GetString(buffer, 0, length);
- var msg = JsonSerializer.Deserialize(json, _jsonOptions);
-
- if (msg == null) return;
-
- switch (msg.OpCode)
- {
- case OpCodes.STAT_ALLOCATE:
- await HandleStatAllocate(connection, msg.Payload);
- break;
-
- case OpCodes.DUNGEON_ENTER:
- await HandleDungeonEnter(connection, msg.Payload);
- break;
-
- case OpCodes.DUNGEON_LEAVE:
- await HandleDungeonLeave(connection);
- break;
-
- case OpCodes.INPUT_MOVE:
- HandleInputMove(connection, msg.Payload);
- break;
-
- case OpCodes.INPUT_ATTACK:
- HandleInputAttack(connection, msg.Payload);
- break;
-
- case OpCodes.INPUT_PICKUP:
- HandleInputPickup(connection, msg.Payload);
- break;
-
- case OpCodes.INPUT_CHEST:
- HandleInputChest(connection, msg.Payload);
- break;
-
- case OpCodes.ESCAPE_START:
- HandleEscapeStart(connection);
- break;
-
- case OpCodes.ESCAPE_CANCEL:
- HandleEscapeCancel(connection);
- break;
- }
- }
- catch (Exception ex)
- {
- _log.LogError(ex, "Error handling message from {Name}", connection.CharacterName);
- }
- }
-
- private async Task HandleStatAllocate(PlayerConnection connection, JsonElement payload)
- {
- var stat = payload.GetProperty("stat").GetString();
- if (string.IsNullOrEmpty(stat)) return;
-
- var character = connection.Character;
- if (character.UnspentStatPoints <= 0) return;
-
- switch (stat.ToLower())
- {
- case "strength": character.Strength++; break;
- case "intelligence": character.Intelligence++; break;
- case "wisdom": character.Wisdom++; break;
- case "endurance": character.Endurance++; break;
- case "dexterity": character.Dexterity++; break;
- default: return;
- }
-
- character.UnspentStatPoints--;
-
- // Save to database
- using var scope = _scopeFactory.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
- db.Attach(character);
- db.Entry(character).Property(c => c.Strength).IsModified = true;
- db.Entry(character).Property(c => c.Intelligence).IsModified = true;
- db.Entry(character).Property(c => c.Wisdom).IsModified = true;
- db.Entry(character).Property(c => c.Endurance).IsModified = true;
- db.Entry(character).Property(c => c.Dexterity).IsModified = true;
- db.Entry(character).Property(c => c.UnspentStatPoints).IsModified = true;
- await db.SaveChangesAsync();
-
- await SendAsync(connection, OpCodes.HUB_STATE, GetHubState(character));
- }
-
- private async Task HandleDungeonEnter(PlayerConnection connection, JsonElement payload)
- {
- int tier = payload.TryGetProperty("tier", out var t) ? t.GetInt32() : 1;
- tier = Math.Clamp(tier, 1, 10);
-
- // Find or create dungeon
- DungeonInstance? dungeon = null;
-
- // Look for existing incomplete dungeon at this tier
- foreach (var d in _dungeons.Values)
- {
- if (d.Tier == tier && d.Simulation.Phase == DungeonPhase.Active)
- {
- dungeon = d;
- break;
- }
- }
-
- if (dungeon == null)
- {
- // Create new dungeon
- var id = Guid.NewGuid();
- var seed = Random.Shared.Next();
- var simulation = new DungeonSimulation(id, tier, seed, _mobDefinitions);
-
- dungeon = new DungeonInstance
- {
- Id = id,
- Tier = tier,
- Seed = seed,
- Simulation = simulation
- };
-
- _dungeons[id] = dungeon;
- _log.LogInformation("Created new Tier {Tier} dungeon: {Id}", tier, id);
- }
-
- // Add player to dungeon
- var character = connection.Character;
- var stats = CharacterStats.GetCombatStats(character);
-
- // Spawn at entrance
- var spawnX = dungeon.Simulation.Layout.SpawnPoint.X * 32 + 16;
- var spawnY = dungeon.Simulation.Layout.SpawnPoint.Y * 32 + 16;
-
- var player = dungeon.Simulation.AddPlayer(
- character.Id,
- character.Name,
- stats,
- spawnX,
- spawnY
- );
-
- connection.CurrentDungeonId = dungeon.Id;
- connection.State = PlayerState.InDungeon;
-
- // Send dungeon layout and initial state
- await SendAsync(connection, OpCodes.DUNGEON_ENTER_RESULT, new
- {
- ok = true,
- dungeonId = dungeon.Id,
- tier = tier,
- layout = new
- {
- width = dungeon.Simulation.Layout.Width,
- height = dungeon.Simulation.Layout.Height,
- tiles = dungeon.Simulation.Layout.SerializeTiles(),
- spawn = new { x = spawnX, y = spawnY }
- }
- });
-
- // Send initial game state
- await SendDungeonStateAsync(connection, dungeon);
- }
-
- private async Task HandleDungeonLeave(PlayerConnection connection)
- {
- if (!connection.CurrentDungeonId.HasValue) return;
-
- if (_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon))
- {
- if (dungeon.Simulation.Players.TryRemove(connection.CharacterId, out var player))
- {
- // Save character with XP and any surviving inventory
- await SaveCharacterStateAsync(connection.Character, player, true);
- }
- }
-
- connection.CurrentDungeonId = null;
- connection.State = PlayerState.InHub;
-
- await SendAsync(connection, OpCodes.HUB_STATE, GetHubState(connection.Character));
- }
-
- private void HandleInputMove(PlayerConnection connection, JsonElement payload)
- {
- if (!connection.CurrentDungeonId.HasValue) return;
- if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return;
- if (!dungeon.Simulation.Players.TryGetValue(connection.CharacterId, out var player)) return;
- if (!player.IsAlive) return;
-
- float dx = payload.TryGetProperty("dx", out var dxProp) ? dxProp.GetSingle() : 0;
- float dy = payload.TryGetProperty("dy", out var dyProp) ? dyProp.GetSingle() : 0;
- float aimAngle = payload.TryGetProperty("aimAngle", out var aProp) ? aProp.GetSingle() : 0;
-
- player.InputDx = Math.Clamp(dx, -1f, 1f);
- player.InputDy = Math.Clamp(dy, -1f, 1f);
- player.AimAngle = aimAngle;
- }
-
- private void HandleInputAttack(PlayerConnection connection, JsonElement payload)
- {
- if (!connection.CurrentDungeonId.HasValue) return;
- if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return;
-
- float aimAngle = payload.TryGetProperty("aimAngle", out var aProp) ? aProp.GetSingle() : 0;
-
- dungeon.Simulation.PlayerAttack(connection.CharacterId, aimAngle);
- }
-
- private void HandleInputPickup(PlayerConnection connection, JsonElement payload)
- {
- if (!connection.CurrentDungeonId.HasValue) return;
- if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return;
-
- int itemId = payload.TryGetProperty("itemId", out var idProp) ? idProp.GetInt32() : 0;
- dungeon.Simulation.TryPickupItem(connection.CharacterId, itemId);
- }
-
- private void HandleInputChest(PlayerConnection connection, JsonElement payload)
- {
- if (!connection.CurrentDungeonId.HasValue) return;
- if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return;
-
- int chestId = payload.TryGetProperty("chestId", out var idProp) ? idProp.GetInt32() : 0;
- dungeon.Simulation.TryOpenChest(connection.CharacterId, chestId);
- }
-
- private void HandleEscapeStart(PlayerConnection connection)
- {
- if (!connection.CurrentDungeonId.HasValue) return;
- if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return;
- if (!dungeon.Simulation.Players.TryGetValue(connection.CharacterId, out var player)) return;
-
- // Can only escape if out of combat
- if (!player.IsInCombat)
- {
- connection.IsEscaping = true;
- connection.EscapeStartTick = dungeon.Simulation.CurrentTick;
- }
- }
-
- private void HandleEscapeCancel(PlayerConnection connection)
- {
- connection.IsEscaping = false;
- connection.EscapeStartTick = 0;
- }
-
- // Tick loop
- private void TickAll(object? state)
- {
- foreach (var dungeon in _dungeons.Values)
- {
- try
- {
- TickDungeon(dungeon);
- }
- catch (Exception ex)
- {
- _log.LogError(ex, "Error ticking dungeon {Id}", dungeon.Id);
- }
- }
-
- // Cleanup empty dungeons
- var emptyDungeons = _dungeons.Values
- .Where(d => d.Simulation.Players.IsEmpty &&
- (DateTime.UtcNow - d.CreatedAt).TotalMinutes > 5)
- .Select(d => d.Id)
- .ToList();
-
- foreach (var id in emptyDungeons)
- {
- _dungeons.TryRemove(id, out _);
- _log.LogInformation("Removed empty dungeon {Id}", id);
- }
- }
-
- private void TickDungeon(DungeonInstance dungeon)
- {
- var sim = dungeon.Simulation;
-
- // Process player movement
- foreach (var player in sim.Players.Values.Where(p => p.IsAlive))
- {
- if (player.InputDx != 0 || player.InputDy != 0)
- {
- float speed = player.Stats.MoveSpeed * DungeonSimulation.TickDelta;
-
- // Normalize input
- float len = MathF.Sqrt(player.InputDx * player.InputDx + player.InputDy * player.InputDy);
- if (len > 0)
- {
- float dx = (player.InputDx / len) * speed;
- float dy = (player.InputDy / len) * speed;
-
- if (sim.CanMoveTo(player.X + dx, player.Y)) player.X += dx;
- if (sim.CanMoveTo(player.X, player.Y + dy)) player.Y += dy;
- }
- }
-
- player.Rotation = player.AimAngle;
- }
-
- // Run simulation tick
- var tickResult = sim.Tick();
-
- // Check escape teleports
- foreach (var conn in _connections.Values.Where(c => c.CurrentDungeonId == dungeon.Id && c.IsEscaping))
- {
- if (sim.Players.TryGetValue(conn.CharacterId, out var player))
- {
- if (player.IsInCombat)
- {
- conn.IsEscaping = false;
- conn.EscapeStartTick = 0;
- _ = SendAsync(conn, OpCodes.ESCAPE_INTERRUPTED, new { reason = "combat" });
- }
- else
- {
- // Check if escape complete (2 minutes = 2400 ticks at 20 TPS)
- long escapeTicks = sim.CurrentTick - conn.EscapeStartTick;
- if (escapeTicks >= 2400)
- {
- // Successful escape!
- conn.IsEscaping = false;
- _ = HandleDungeonLeave(conn);
- }
- }
- }
- }
-
- // Broadcast state to all players in dungeon
- foreach (var conn in _connections.Values.Where(c => c.CurrentDungeonId == dungeon.Id))
- {
- _ = SendDungeonStateAsync(conn, dungeon, tickResult);
- }
- }
-
- private async Task SendDungeonStateAsync(PlayerConnection connection, DungeonInstance dungeon, TickResult? tickResult = null)
- {
- var sim = dungeon.Simulation;
-
- var state = new
- {
- tick = sim.CurrentTick,
- phase = sim.Phase.ToString().ToLower(),
-
- players = sim.Players.Values.Select(p => new
- {
- id = p.CharacterId,
- name = p.Name,
- x = p.X,
- y = p.Y,
- rotation = p.Rotation,
- health = (int)p.Health,
- maxHealth = (int)p.MaxHealth,
- mana = (int)p.Mana,
- maxMana = (int)p.MaxMana,
- stamina = (int)p.Stamina,
- maxStamina = (int)p.MaxStamina,
- isAlive = p.IsAlive,
- isInCombat = p.IsInCombat
- }),
-
- mobs = sim.Mobs.Values.Where(m => m.IsAlive).Select(m => new
- {
- id = m.Id,
- name = m.Name,
- x = m.X,
- y = m.Y,
- rotation = m.Rotation,
- health = m.Health,
- maxHealth = m.MaxHealth,
- state = m.State.ToString().ToLower(),
- spriteSheet = m.SpriteSheet,
- spriteWidth = m.SpriteWidth,
- spriteHeight = m.SpriteHeight,
- tintColor = m.TintColor
- }),
-
- chests = sim.Chests.Values.Select(c => new
- {
- id = c.Id,
- x = c.X,
- y = c.Y,
- opened = c.IsOpened
- }),
-
- droppedItems = sim.DroppedItems.Values.Select(i => new
- {
- id = i.Id,
- itemId = i.ItemDefinitionId,
- quantity = i.Quantity,
- x = i.X,
- y = i.Y
- }),
-
- events = tickResult == null ? null : new
- {
- damage = tickResult.DamageEvents.Select(e => new
- {
- sourceType = e.SourceType.ToString().ToLower(),
- sourceId = e.SourceId,
- targetType = e.TargetType.ToString().ToLower(),
- targetId = e.TargetId,
- damage = e.Damage
- }),
- deaths = tickResult.DeathEvents.Select(e => new
- {
- entityType = e.EntityType.ToString().ToLower(),
- entityId = e.EntityId,
- entityName = e.EntityName,
- killerType = e.KillerType.ToString().ToLower(),
- killerId = e.KillerId,
- killerName = e.KillerName,
- xp = e.XpReward
- })
- },
-
- exitPosition = sim.Layout.ExitPosition != null ? new
- {
- x = sim.Layout.ExitPosition.Value.X * 32 + 16,
- y = sim.Layout.ExitPosition.Value.Y * 32 + 16
- } : null
- };
-
- await SendAsync(connection, OpCodes.DUNGEON_STATE, state);
- }
-
- private object GetHubState(Character character)
- {
- return new
- {
- character = new
- {
- id = character.Id,
- name = character.Name,
- level = character.Level,
- xp = character.Experience,
- xpNext = LevelSystem.GetXpForLevel(character.Level + 1),
- unspentPoints = character.UnspentStatPoints,
- strength = character.Strength,
- intelligence = character.Intelligence,
- wisdom = character.Wisdom,
- endurance = character.Endurance,
- dexterity = character.Dexterity,
- maxHealth = CharacterStats.GetMaxHealth(character),
- maxMana = CharacterStats.GetMaxMana(character),
- maxStamina = CharacterStats.GetMaxStamina(character)
- }
- };
- }
-
- private async Task SaveCharacterStateAsync(Character character, PlayerInstance player, bool extracted)
- {
- using var scope = _scopeFactory.CreateScope();
- var db = scope.ServiceProvider.GetRequiredService();
-
- // Add XP earned
- character.Experience += player.XpGained;
- character.TotalKills += player.MobsKilled;
- character.PlayersKilled += player.PlayersKilled;
-
- if (extracted)
- {
- character.DungeonsCompleted++;
- // Save current health/mana (they extracted alive)
- character.CurrentHealth = (int)player.Health;
- character.CurrentMana = (int)player.Mana;
- }
- else
- {
- character.TotalDeaths++;
- // Reset to full on death
- character.CurrentHealth = CharacterStats.GetMaxHealth(character);
- character.CurrentMana = CharacterStats.GetMaxMana(character);
- }
-
- // Check for level up
- while (character.Experience >= LevelSystem.GetTotalXpForLevel(character.Level + 1))
- {
- character.Level++;
- character.UnspentStatPoints += 5;
- }
-
- character.LastPlayedAt = DateTime.UtcNow;
-
- db.Attach(character);
- db.Entry(character).State = EntityState.Modified;
- await db.SaveChangesAsync();
-
- _log.LogInformation("Saved character {Name}: Level {Level}, XP {Xp}",
- character.Name, character.Level, character.Experience);
- }
-
- private async Task SendAsync(PlayerConnection connection, int opCode, object payload)
- {
- if (connection.WebSocket.State != WebSocketState.Open) return;
-
- try
- {
- var msg = new { opCode, payload };
- var json = JsonSerializer.Serialize(msg, _jsonOptions);
- var bytes = Encoding.UTF8.GetBytes(json);
-
- await connection.WebSocket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);
- }
- catch (Exception ex)
- {
- _log.LogWarning("Failed to send to {Name}: {Error}", connection.CharacterName, ex.Message);
- }
- }
-}
-
-// Connection tracking
-
-public class PlayerConnection
-{
- public ulong AccountId { get; set; }
- public ulong CharacterId { get; set; }
- public string CharacterName { get; set; } = "";
- public WebSocket WebSocket { get; set; } = null!;
- public Character Character { get; set; } = null!;
-
- public PlayerState State { get; set; } = PlayerState.InHub;
- public Guid? CurrentDungeonId { get; set; }
-
- public bool IsEscaping { get; set; }
- public long EscapeStartTick { get; set; }
-}
-
-public enum PlayerState
-{
- InHub,
- InDungeon
-}
-
-public class DungeonInstance
-{
- public Guid Id { get; set; }
- public int Tier { get; set; }
- public int Seed { get; set; }
- public DungeonSimulation Simulation { get; set; } = null!;
- public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
-}
-
-// Messages
-
-public class ClientMessage
-{
- public int OpCode { get; set; }
- public JsonElement Payload { get; set; }
-}
-
-// OpCodes
-public static class OpCodes
-{
- // Hub
- public const int HUB_STATE = 200;
- public const int STAT_ALLOCATE = 201;
-
- // Dungeon
- public const int DUNGEON_ENTER = 300;
- public const int DUNGEON_ENTER_RESULT = 301;
- public const int DUNGEON_STATE = 302;
- public const int DUNGEON_LEAVE = 303;
-
- // Input
- public const int INPUT_MOVE = 400;
- public const int INPUT_ATTACK = 401;
- public const int INPUT_PICKUP = 402;
- public const int INPUT_CHEST = 403;
-
- // Escape
- public const int ESCAPE_START = 450;
- public const int ESCAPE_CANCEL = 451;
- public const int ESCAPE_INTERRUPTED = 452;
- public const int ESCAPE_SUCCESS = 453;
-
- // Events
- public const int EVENT_DAMAGE = 500;
- public const int EVENT_DEATH = 501;
- public const int EVENT_LEVELUP = 502;
- public const int EVENT_LOOT = 503;
-}
diff --git a/Game/Dungeon/DungeonGenerator.cs b/Game/Dungeon/DungeonGenerator.cs
index dea6570..7fb66bc 100644
--- a/Game/Dungeon/DungeonGenerator.cs
+++ b/Game/Dungeon/DungeonGenerator.cs
@@ -1,16 +1,24 @@
-using System.Text.Json;
-
-namespace DungeonCrawler.Game.Dungeon;
+namespace Server.Game.Dungeon;
///
/// Procedural dungeon generator using BSP (Binary Space Partition) + room placement
///
-public class DungeonGenerator
+public static class DungeonGenerator
+{
+ ///
+ /// Generate a dungeon layout for the given seed and tier
+ ///
+ public static DungeonLayout Generate(int seed, int tier)
+ {
+ var generator = new DungeonGeneratorInstance(seed, tier);
+ return generator.Generate();
+ }
+}
+
+internal class DungeonGeneratorInstance
{
private readonly Random _rng;
private readonly int _seed;
-
- // Generation parameters
private readonly int _tier;
private readonly int _tileSize = 32;
@@ -22,7 +30,7 @@ public class DungeonGenerator
private int MapWidth => 50 + (_tier * 10); // In tiles
private int MapHeight => 50 + (_tier * 10);
- public DungeonGenerator(int seed, int tier)
+ public DungeonGeneratorInstance(int seed, int tier)
{
_seed = seed;
_tier = Math.Max(1, tier);
@@ -45,7 +53,7 @@ public class DungeonGenerator
// Generate rooms
int roomCount = _rng.Next(MinRooms, MaxRooms + 1);
- var rooms = new List();
+ var rooms = new List();
int attempts = 0;
int maxAttempts = roomCount * 20;
@@ -58,7 +66,7 @@ public class DungeonGenerator
int x = _rng.Next(2, MapWidth - w - 2);
int y = _rng.Next(2, MapHeight - h - 2);
- var newRoom = new Room(x, y, w, h);
+ var newRoom = new DungeonRoom(x, y, w, h);
// Check for overlap with existing rooms (with padding)
bool overlaps = rooms.Any(r => newRoom.Intersects(r, padding: 2));
@@ -94,8 +102,8 @@ public class DungeonGenerator
AssignRoomTypes(rooms, layout);
// Place spawn point (first room)
- layout.SpawnPoint = new Point(rooms[0].CenterX, rooms[0].CenterY);
- rooms[0].Type = RoomType.Entrance;
+ layout.SpawnPoint = new DungeonPoint(rooms[0].CenterX, rooms[0].CenterY);
+ rooms[0].Type = DungeonRoomType.Entrance;
// Generate mob spawns
GenerateMobSpawns(rooms, layout);
@@ -109,7 +117,7 @@ public class DungeonGenerator
return layout;
}
- private void CarveRoom(int[,] tiles, Room room)
+ private void CarveRoom(int[,] tiles, DungeonRoom room)
{
for (int x = room.X; x < room.X + room.Width; x++)
{
@@ -120,7 +128,7 @@ public class DungeonGenerator
}
}
- private void ConnectRooms(int[,] tiles, Room a, Room b)
+ private void ConnectRooms(int[,] tiles, DungeonRoom a, DungeonRoom b)
{
int x = a.CenterX;
int y = a.CenterY;
@@ -174,7 +182,7 @@ public class DungeonGenerator
}
}
- private void AssignRoomTypes(List rooms, DungeonLayout layout)
+ private void AssignRoomTypes(List rooms, DungeonLayout layout)
{
if (rooms.Count == 0) return;
@@ -182,7 +190,7 @@ public class DungeonGenerator
// Last room is boss room
if (rooms.Count > 1)
{
- rooms[^1].Type = RoomType.Boss;
+ rooms[^1].Type = DungeonRoomType.Boss;
}
// Assign some treasure rooms (10-20% of rooms)
@@ -192,28 +200,22 @@ public class DungeonGenerator
for (int i = 0; i < treasureCount && availableRooms.Count > 0; i++)
{
int idx = _rng.Next(availableRooms.Count);
- availableRooms[idx].Type = RoomType.Treasure;
+ availableRooms[idx].Type = DungeonRoomType.Treasure;
availableRooms.RemoveAt(idx);
}
-
- // Rest are combat rooms
- foreach (var room in rooms.Where(r => r.Type == RoomType.Combat))
- {
- // Already default
- }
}
- private void GenerateMobSpawns(List rooms, DungeonLayout layout)
+ private void GenerateMobSpawns(List rooms, DungeonLayout layout)
{
foreach (var room in rooms)
{
- if (room.Type == RoomType.Entrance) continue;
+ if (room.Type == DungeonRoomType.Entrance) continue;
int mobCount = room.Type switch
{
- RoomType.Boss => 1, // Just the boss
- RoomType.Treasure => _rng.Next(1, 3), // Light guard
- RoomType.Combat => _rng.Next(2, 5 + _tier),
+ DungeonRoomType.Boss => 1, // Just the boss
+ DungeonRoomType.Treasure => _rng.Next(1, 3), // Light guard
+ DungeonRoomType.Combat => _rng.Next(2, 5 + _tier),
_ => _rng.Next(1, 3)
};
@@ -223,12 +225,12 @@ public class DungeonGenerator
int x = room.X + 1 + _rng.Next(room.Width - 2);
int y = room.Y + 1 + _rng.Next(room.Height - 2);
- var spawn = new MobSpawn
+ var spawn = new DungeonMobSpawn
{
Id = layout.MobSpawns.Count + 1,
X = x,
Y = y,
- MobType = room.Type == RoomType.Boss ? MobSpawnType.Boss : MobSpawnType.Normal,
+ MobType = room.Type == DungeonRoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal,
RoomIndex = rooms.IndexOf(room)
};
@@ -239,15 +241,15 @@ public class DungeonGenerator
layout.TotalMobs = layout.MobSpawns.Count;
}
- private void GenerateChestSpawns(List rooms, DungeonLayout layout)
+ private void GenerateChestSpawns(List rooms, DungeonLayout layout)
{
foreach (var room in rooms)
{
int chestCount = room.Type switch
{
- RoomType.Treasure => _rng.Next(2, 4),
- RoomType.Boss => 1, // Guaranteed chest after boss
- RoomType.Combat => _rng.NextDouble() < 0.3 ? 1 : 0, // 30% chance
+ DungeonRoomType.Treasure => _rng.Next(2, 4),
+ DungeonRoomType.Boss => 1, // Guaranteed chest after boss
+ DungeonRoomType.Combat => _rng.NextDouble() < 0.3 ? 1 : 0, // 30% chance
_ => 0
};
@@ -256,12 +258,12 @@ public class DungeonGenerator
int x = room.X + 1 + _rng.Next(room.Width - 2);
int y = room.Y + 1 + _rng.Next(room.Height - 2);
- var chest = new ChestSpawn
+ var chest = new DungeonChestSpawn
{
Id = layout.ChestSpawns.Count + 1,
X = x,
Y = y,
- ChestType = room.Type == RoomType.Boss ? ChestType.Boss : ChestType.Normal,
+ ChestType = room.Type == DungeonRoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal,
RoomIndex = rooms.IndexOf(room)
};
@@ -272,166 +274,3 @@ public class DungeonGenerator
layout.TotalChests = layout.ChestSpawns.Count;
}
}
-
-// Data structures
-
-public class DungeonLayout
-{
- public int Seed { get; set; }
- public int Tier { get; set; }
- public int Width { get; set; }
- public int Height { get; set; }
- public int TileSize { get; set; }
-
- public int[,] Tiles { get; set; } = new int[0, 0];
- public List Rooms { get; set; } = new();
- public Point SpawnPoint { get; set; }
- public Point? ExitPosition { get; set; } // Set when dungeon is cleared
-
- public List MobSpawns { get; set; } = new();
- public List ChestSpawns { get; set; } = new();
-
- public int TotalMobs { get; set; }
- public int TotalChests { get; set; }
-
- // Serialize tiles to string for DB storage
- public string SerializeTiles()
- {
- var rows = new List();
- for (int y = 0; y < Height; y++)
- {
- var row = new char[Width];
- for (int x = 0; x < Width; x++)
- {
- row[x] = Tiles[x, y] == 1 ? '.' : '#';
- }
- rows.Add(new string(row));
- }
- return string.Join("\n", rows);
- }
-
- public void DeserializeTiles(string data)
- {
- var rows = data.Split('\n');
- Height = rows.Length;
- Width = rows.Length > 0 ? rows[0].Length : 0;
- Tiles = new int[Width, Height];
-
- for (int y = 0; y < Height; y++)
- {
- for (int x = 0; x < Width && x < rows[y].Length; x++)
- {
- Tiles[x, y] = rows[y][x] == '.' ? 1 : 0;
- }
- }
- }
-
- public string ToJson()
- {
- return JsonSerializer.Serialize(new
- {
- seed = Seed,
- tier = Tier,
- width = Width,
- height = Height,
- tileSize = TileSize,
- tiles = SerializeTiles(),
- spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
- rooms = Rooms.Select(r => new
- {
- x = r.X, y = r.Y, w = r.Width, h = r.Height,
- type = r.Type.ToString()
- }),
- mobs = MobSpawns.Select(m => new
- {
- id = m.Id, x = m.X, y = m.Y,
- type = m.MobType.ToString(),
- roomIndex = m.RoomIndex
- }),
- chests = ChestSpawns.Select(c => new
- {
- id = c.Id, x = c.X, y = c.Y,
- type = c.ChestType.ToString(),
- roomIndex = c.RoomIndex
- })
- });
- }
-}
-
-public class Room
-{
- public int X { get; set; }
- public int Y { get; set; }
- public int Width { get; set; }
- public int Height { get; set; }
- public RoomType Type { get; set; } = RoomType.Combat;
-
- public int CenterX => X + Width / 2;
- public int CenterY => Y + Height / 2;
-
- public Room() { }
-
- public Room(int x, int y, int width, int height)
- {
- X = x; Y = y; Width = width; Height = height;
- }
-
- public bool Intersects(Room other, int padding = 0)
- {
- return X - padding < other.X + other.Width + padding &&
- X + Width + padding > other.X - padding &&
- Y - padding < other.Y + other.Height + padding &&
- Y + Height + padding > other.Y - padding;
- }
-}
-
-public struct Point
-{
- public int X { get; set; }
- public int Y { get; set; }
-
- public Point(int x, int y) { X = x; Y = y; }
-}
-
-public class MobSpawn
-{
- public int Id { get; set; }
- public int X { get; set; }
- public int Y { get; set; }
- public MobSpawnType MobType { get; set; }
- public int RoomIndex { get; set; }
- public bool IsAlive { get; set; } = true;
-}
-
-public class ChestSpawn
-{
- public int Id { get; set; }
- public int X { get; set; }
- public int Y { get; set; }
- public ChestType ChestType { get; set; }
- public int RoomIndex { get; set; }
- public bool IsOpened { get; set; } = false;
-}
-
-public enum RoomType
-{
- Entrance,
- Combat,
- Treasure,
- Boss,
- Empty
-}
-
-public enum MobSpawnType
-{
- Normal,
- Elite,
- Boss
-}
-
-public enum ChestType
-{
- Normal,
- Rare,
- Boss
-}
diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs
new file mode 100644
index 0000000..e9ee4be
--- /dev/null
+++ b/Game/Dungeon/DungeonHandler.cs
@@ -0,0 +1,745 @@
+using System.Collections.Concurrent;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Server.Data;
+using Server.Data.Entities;
+using Server.Data.Enums;
+using Server.Networking;
+using Server.Networking.Handling;
+using Server.Networking.Messages;
+using Server.Services.Auth;
+using SystemRevivalServer.Networking.Messages;
+
+namespace Server.Game.Dungeon;
+
+///
+/// Handles dungeon crawler game messages via the server's message router
+/// Implements IClientMessageHandler for integration with existing infrastructure
+///
+public sealed class DungeonHandler : IClientMessageHandler
+{
+ private readonly ILogger _log;
+ private readonly ISessionRegistry _sessions;
+ private readonly IMessageSerializer _ser;
+ private readonly IServiceScopeFactory _scopeFactory;
+
+ // Player state tracking (keyed by connection ID)
+ private readonly ConcurrentDictionary _playerSessions = new();
+
+ // Active dungeon instances
+ private readonly ConcurrentDictionary _dungeons = new();
+
+ // Mob definitions cache
+ private Dictionary _mobDefinitions = new();
+ private bool _initialized = false;
+
+ // Tick management
+ private Timer? _tickTimer;
+ private long _currentTick = 0;
+
+ public DungeonHandler(
+ ILogger log,
+ ISessionRegistry sessions,
+ IMessageSerializer ser,
+ IServiceScopeFactory scopeFactory)
+ {
+ _log = log;
+ _sessions = sessions;
+ _ser = ser;
+ _scopeFactory = scopeFactory;
+ }
+
+ public IReadOnlyCollection SupportedOpCodes => new[]
+ {
+ DungeonOpCodes.HUB_STATE,
+ DungeonOpCodes.STAT_ALLOCATE,
+ DungeonOpCodes.DUNGEON_ENTER,
+ DungeonOpCodes.DUNGEON_LEAVE,
+ DungeonOpCodes.DUNGEON_INPUT_MOVE,
+ DungeonOpCodes.DUNGEON_INPUT_ATTACK,
+ DungeonOpCodes.DUNGEON_INPUT_PICKUP,
+ DungeonOpCodes.DUNGEON_INPUT_CHEST,
+ DungeonOpCodes.ESCAPE_START,
+ DungeonOpCodes.ESCAPE_CANCEL
+ };
+
+ public async Task InitializeAsync()
+ {
+ if (_initialized) return;
+
+ await LoadMobDefinitionsAsync();
+
+ // Start tick loop (20 ticks per second)
+ _tickTimer = new Timer(TickAll, null, 0, 50);
+
+ _initialized = true;
+ _log.LogInformation("DungeonHandler initialized with {MobCount} mob definitions", _mobDefinitions.Count);
+ }
+
+ private async Task LoadMobDefinitionsAsync()
+ {
+ using var scope = _scopeFactory.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+
+ var mobs = await db.Set()
+ .Where(m => m.IsEnabled)
+ .ToListAsync();
+
+ if (mobs.Count == 0)
+ {
+ // Seed default mobs
+ var defaults = DefaultDungeonMobs.GetDefaultMobs();
+ db.Set().AddRange(defaults);
+ await db.SaveChangesAsync();
+ mobs = defaults;
+ _log.LogInformation("Seeded {Count} default mob definitions", defaults.Count);
+ }
+
+ _mobDefinitions = mobs.ToDictionary(m => m.Id);
+ }
+
+ public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ // Ensure initialized
+ if (!_initialized)
+ {
+ await InitializeAsync();
+ }
+
+ // All dungeon operations require authentication
+ if (!_sessions.TryGet(connection.Id, out var accountId, out _))
+ {
+ await SendErrorAsync(connection, "auth_required", ct);
+ return;
+ }
+
+ // Get or create player session
+ var session = await GetOrCreateSessionAsync(connection, accountId, ct);
+ if (session == null)
+ {
+ await SendErrorAsync(connection, "no_character", ct);
+ return;
+ }
+
+ try
+ {
+ switch (opCode)
+ {
+ case DungeonOpCodes.HUB_STATE:
+ await HandleHubStateRequest(connection, session, ct);
+ break;
+
+ case DungeonOpCodes.STAT_ALLOCATE:
+ await HandleStatAllocate(connection, session, payload, ct);
+ break;
+
+ case DungeonOpCodes.DUNGEON_ENTER:
+ await HandleDungeonEnter(connection, session, payload, ct);
+ break;
+
+ case DungeonOpCodes.DUNGEON_LEAVE:
+ await HandleDungeonLeave(connection, session, ct);
+ break;
+
+ case DungeonOpCodes.DUNGEON_INPUT_MOVE:
+ HandleInputMove(session, payload);
+ break;
+
+ case DungeonOpCodes.DUNGEON_INPUT_ATTACK:
+ HandleInputAttack(session, payload);
+ break;
+
+ case DungeonOpCodes.DUNGEON_INPUT_PICKUP:
+ HandleInputPickup(session, payload);
+ break;
+
+ case DungeonOpCodes.DUNGEON_INPUT_CHEST:
+ HandleInputChest(session, payload);
+ break;
+
+ case DungeonOpCodes.ESCAPE_START:
+ HandleEscapeStart(session);
+ break;
+
+ case DungeonOpCodes.ESCAPE_CANCEL:
+ HandleEscapeCancel(session);
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ _log.LogError(ex, "Error handling dungeon opcode {OpCode} for account {AccountId}", opCode, accountId);
+ await SendErrorAsync(connection, "internal_error", ct);
+ }
+ }
+
+ private async Task GetOrCreateSessionAsync(IConnection connection, ulong accountId, CancellationToken ct)
+ {
+ if (_playerSessions.TryGetValue(connection.Id, out var existing))
+ {
+ return existing;
+ }
+
+ // Load character from database
+ using var scope = _scopeFactory.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+
+ var character = await db.Set()
+ .FirstOrDefaultAsync(c => c.AccountId == accountId && !c.IsDeleted, ct);
+
+ if (character == null)
+ {
+ // Auto-create a character for this account
+ character = new DungeonCharacter
+ {
+ AccountId = accountId,
+ Name = $"Hero_{accountId}",
+ Level = 1,
+ UnspentStatPoints = 5,
+ Strength = 1,
+ Intelligence = 1,
+ Wisdom = 1,
+ Endurance = 1,
+ Dexterity = 1
+ };
+
+ db.Set().Add(character);
+ await db.SaveChangesAsync(ct);
+ _log.LogInformation("Created new dungeon character for account {AccountId}", accountId);
+ }
+
+ var session = new DungeonPlayerSession
+ {
+ ConnectionId = connection.Id,
+ Connection = connection,
+ AccountId = accountId,
+ CharacterId = character.Id,
+ Character = character,
+ State = PlayerState.InHub
+ };
+
+ _playerSessions[connection.Id] = session;
+ return session;
+ }
+
+ private async Task HandleHubStateRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
+ {
+ var hubState = GetHubState(session.Character);
+ await SendAsync(connection, DungeonOpCodes.HUB_STATE, hubState, ct);
+ }
+
+ private async Task HandleStatAllocate(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ var request = _ser.Deserialize(payload);
+ if (string.IsNullOrEmpty(request.Stat)) return;
+
+ var character = session.Character;
+ if (character.UnspentStatPoints <= 0) return;
+
+ switch (request.Stat.ToLower())
+ {
+ case "strength": character.Strength++; break;
+ case "intelligence": character.Intelligence++; break;
+ case "wisdom": character.Wisdom++; break;
+ case "endurance": character.Endurance++; break;
+ case "dexterity": character.Dexterity++; break;
+ default: return;
+ }
+
+ character.UnspentStatPoints--;
+
+ // Save to database
+ using var scope = _scopeFactory.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ db.Attach(character);
+ db.Entry(character).Property(c => c.Strength).IsModified = true;
+ db.Entry(character).Property(c => c.Intelligence).IsModified = true;
+ db.Entry(character).Property(c => c.Wisdom).IsModified = true;
+ db.Entry(character).Property(c => c.Endurance).IsModified = true;
+ db.Entry(character).Property(c => c.Dexterity).IsModified = true;
+ db.Entry(character).Property(c => c.UnspentStatPoints).IsModified = true;
+ await db.SaveChangesAsync(ct);
+
+ await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(character), ct);
+ }
+
+ private async Task HandleDungeonEnter(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct)
+ {
+ if (session.State == PlayerState.InDungeon)
+ {
+ await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct);
+ return;
+ }
+
+ var request = _ser.Deserialize(payload);
+ int tier = Math.Clamp(request.Tier, 1, 10);
+
+ // Create new dungeon instance
+ var dungeonId = Guid.NewGuid();
+ int seed = Random.Shared.Next();
+
+ var layout = DungeonGenerator.Generate(seed, tier);
+ var simulation = new DungeonSimulation(layout, tier, _mobDefinitions);
+
+ var instance = new DungeonInstance
+ {
+ Id = dungeonId,
+ Tier = tier,
+ Seed = seed,
+ Simulation = simulation,
+ CreatedAt = DateTime.UtcNow
+ };
+
+ _dungeons[dungeonId] = instance;
+
+ // Add player to dungeon
+ var spawnPos = layout.Rooms[0]; // Entrance room
+ var player = new PlayerInstance
+ {
+ CharacterId = session.CharacterId,
+ CharacterName = session.Character.Name,
+ X = spawnPos.CenterX * 32,
+ Y = spawnPos.CenterY * 32,
+ Health = session.Character.CurrentHealth,
+ MaxHealth = DungeonCharacterStats.GetMaxHealth(session.Character),
+ Mana = session.Character.CurrentMana,
+ MaxMana = DungeonCharacterStats.GetMaxMana(session.Character),
+ Stamina = DungeonCharacterStats.GetMaxStamina(session.Character),
+ MaxStamina = DungeonCharacterStats.GetMaxStamina(session.Character),
+ MoveSpeed = DungeonCharacterStats.GetMoveSpeed(session.Character),
+ AttackSpeed = DungeonCharacterStats.GetAttackSpeed(session.Character),
+ Strength = session.Character.Strength,
+ Intelligence = session.Character.Intelligence
+ };
+
+ simulation.Players[session.CharacterId] = player;
+
+ // Update session state
+ session.State = PlayerState.InDungeon;
+ session.CurrentDungeonId = dungeonId;
+ session.PlayerInstance = player;
+
+ _log.LogInformation("Player {Name} entered dungeon tier {Tier}", session.Character.Name, tier);
+
+ await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new
+ {
+ ok = true,
+ dungeonId = dungeonId.ToString(),
+ tier,
+ seed,
+ width = layout.Width,
+ height = layout.Height
+ }, ct);
+ }
+
+ private async Task HandleDungeonLeave(IConnection connection, DungeonPlayerSession session, CancellationToken ct)
+ {
+ if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue)
+ {
+ return;
+ }
+
+ await RemoveFromDungeonAsync(session, false, ct);
+
+ await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), ct);
+ }
+
+ private void HandleInputMove(DungeonPlayerSession session, ReadOnlyMemory payload)
+ {
+ if (session.PlayerInstance == null) return;
+
+ var input = _ser.Deserialize(payload);
+ session.PlayerInstance.InputX = input.X;
+ session.PlayerInstance.InputY = input.Y;
+ }
+
+ private void HandleInputAttack(DungeonPlayerSession session, ReadOnlyMemory payload)
+ {
+ if (session.PlayerInstance == null) return;
+
+ var input = _ser.Deserialize(payload);
+ session.PlayerInstance.AttackTargetId = input.TargetId;
+ session.PlayerInstance.WantsToAttack = true;
+ }
+
+ private void HandleInputPickup(DungeonPlayerSession session, ReadOnlyMemory payload)
+ {
+ if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
+ if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
+
+ var input = _ser.Deserialize(payload);
+
+ if (dungeon.Simulation.DroppedItems.TryRemove((int)input.ItemId, out var item))
+ {
+ // TODO: Add to player inventory
+ _log.LogDebug("Player {Name} picked up item {ItemId}", session.Character.Name, item.ItemDefinitionId);
+ }
+ }
+
+ private void HandleInputChest(DungeonPlayerSession session, ReadOnlyMemory payload)
+ {
+ if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
+ if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
+
+ var input = _ser.Deserialize(payload);
+
+ if (dungeon.Simulation.Chests.TryGetValue((int)input.ChestId, out var chest) && !chest.IsOpened)
+ {
+ chest.IsOpened = true;
+ // TODO: Generate loot
+ _log.LogDebug("Player {Name} opened chest {ChestId}", session.Character.Name, chest.Id);
+ }
+ }
+
+ private void HandleEscapeStart(DungeonPlayerSession session)
+ {
+ if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return;
+ if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return;
+
+ // Check if at exit
+ var layout = dungeon.Simulation.Layout;
+ if (layout.ExitPosition == null) return;
+
+ var player = session.PlayerInstance;
+ if (player == null) return;
+
+ float exitX = layout.ExitPosition.Value.X * 32 + 16;
+ float exitY = layout.ExitPosition.Value.Y * 32 + 16;
+ float dist = MathF.Sqrt((player.X - exitX) * (player.X - exitX) + (player.Y - exitY) * (player.Y - exitY));
+
+ if (dist < 48) // Within range
+ {
+ session.IsEscaping = true;
+ session.EscapeStartTick = _currentTick;
+ }
+ }
+
+ private void HandleEscapeCancel(DungeonPlayerSession session)
+ {
+ session.IsEscaping = false;
+ }
+
+ private void TickAll(object? state)
+ {
+ _currentTick++;
+
+ foreach (var (dungeonId, instance) in _dungeons)
+ {
+ try
+ {
+ var result = instance.Simulation.Tick(_currentTick);
+
+ // Send state to all players in this dungeon
+ var playersInDungeon = _playerSessions.Values
+ .Where(s => s.CurrentDungeonId == dungeonId && s.State == PlayerState.InDungeon)
+ .ToList();
+
+ foreach (var session in playersInDungeon)
+ {
+ // Check escape completion (5 seconds = 100 ticks)
+ if (session.IsEscaping && _currentTick - session.EscapeStartTick >= 100)
+ {
+ _ = CompleteEscapeAsync(session);
+ continue;
+ }
+
+ // Check if player died
+ if (session.PlayerInstance != null && !session.PlayerInstance.IsAlive)
+ {
+ _ = HandlePlayerDeathAsync(session);
+ continue;
+ }
+
+ _ = SendDungeonStateAsync(session, result);
+ }
+
+ // Cleanup empty dungeons
+ if (playersInDungeon.Count == 0 && (DateTime.UtcNow - instance.CreatedAt).TotalMinutes > 5)
+ {
+ _dungeons.TryRemove(dungeonId, out _);
+ }
+ }
+ catch (Exception ex)
+ {
+ _log.LogError(ex, "Error ticking dungeon {DungeonId}", dungeonId);
+ }
+ }
+ }
+
+ private async Task SendDungeonStateAsync(DungeonPlayerSession session, TickResult? tickResult)
+ {
+ var dungeon = _dungeons.GetValueOrDefault(session.CurrentDungeonId!.Value);
+ if (dungeon == null) return;
+
+ var sim = dungeon.Simulation;
+
+ var state = new
+ {
+ tick = _currentTick,
+ phase = sim.Phase.ToString().ToLower(),
+
+ tiles = sim.Layout.Tiles,
+
+ players = sim.Players.Values.Select(p => new
+ {
+ id = p.CharacterId,
+ name = p.CharacterName,
+ x = p.X,
+ y = p.Y,
+ rotation = p.Rotation,
+ health = (int)p.Health,
+ maxHealth = (int)p.MaxHealth,
+ mana = (int)p.Mana,
+ maxMana = (int)p.MaxMana,
+ stamina = (int)p.Stamina,
+ maxStamina = (int)p.MaxStamina,
+ isAlive = p.IsAlive,
+ isInCombat = p.IsInCombat
+ }),
+
+ mobs = sim.Mobs.Values.Where(m => m.IsAlive).Select(m => new
+ {
+ id = m.Id,
+ name = m.Name,
+ x = m.X,
+ y = m.Y,
+ rotation = m.Rotation,
+ health = m.Health,
+ maxHealth = m.MaxHealth,
+ state = m.State.ToString().ToLower(),
+ spriteSheet = m.SpriteSheet,
+ spriteWidth = m.SpriteWidth,
+ spriteHeight = m.SpriteHeight,
+ tintColor = m.TintColor
+ }),
+
+ chests = sim.Chests.Values.Select(c => new
+ {
+ id = c.Id,
+ x = c.X,
+ y = c.Y,
+ opened = c.IsOpened
+ }),
+
+ droppedItems = sim.DroppedItems.Values.Select(i => new
+ {
+ id = i.Id,
+ itemId = i.ItemDefinitionId,
+ quantity = i.Quantity,
+ x = i.X,
+ y = i.Y
+ }),
+
+ events = tickResult == null ? null : new
+ {
+ damage = tickResult.DamageEvents.Select(e => new
+ {
+ sourceType = e.SourceType.ToString().ToLower(),
+ sourceId = e.SourceId,
+ targetType = e.TargetType.ToString().ToLower(),
+ targetId = e.TargetId,
+ damage = e.Damage
+ }),
+ deaths = tickResult.DeathEvents.Select(e => new
+ {
+ entityType = e.EntityType.ToString().ToLower(),
+ entityId = e.EntityId,
+ entityName = e.EntityName,
+ killerType = e.KillerType.ToString().ToLower(),
+ killerId = e.KillerId,
+ killerName = e.KillerName,
+ xp = e.XpReward
+ })
+ },
+
+ exitPosition = sim.Layout.ExitPosition != null ? new
+ {
+ x = sim.Layout.ExitPosition.Value.X * 32 + 16,
+ y = sim.Layout.ExitPosition.Value.Y * 32 + 16
+ } : null
+ };
+
+ await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, state, CancellationToken.None);
+ }
+
+ private async Task CompleteEscapeAsync(DungeonPlayerSession session)
+ {
+ session.IsEscaping = false;
+
+ await SendAsync(session.Connection, DungeonOpCodes.ESCAPE_SUCCESS, new { }, CancellationToken.None);
+ await RemoveFromDungeonAsync(session, true, CancellationToken.None);
+ await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
+ }
+
+ private async Task HandlePlayerDeathAsync(DungeonPlayerSession session)
+ {
+ await RemoveFromDungeonAsync(session, false, CancellationToken.None);
+
+ // Reset health on death
+ session.Character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(session.Character);
+ session.Character.CurrentMana = DungeonCharacterStats.GetMaxMana(session.Character);
+ session.Character.TotalDeaths++;
+
+ using var scope = _scopeFactory.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ db.Attach(session.Character);
+ db.Entry(session.Character).State = EntityState.Modified;
+ await db.SaveChangesAsync();
+
+ await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None);
+ }
+
+ private async Task RemoveFromDungeonAsync(DungeonPlayerSession session, bool extracted, CancellationToken ct)
+ {
+ if (!session.CurrentDungeonId.HasValue) return;
+
+ if (_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
+ {
+ dungeon.Simulation.Players.TryRemove(session.CharacterId, out var player);
+
+ if (player != null)
+ {
+ await SaveCharacterStateAsync(session.Character, player, extracted, ct);
+ }
+ }
+
+ session.State = PlayerState.InHub;
+ session.CurrentDungeonId = null;
+ session.PlayerInstance = null;
+ session.IsEscaping = false;
+ }
+
+ private async Task SaveCharacterStateAsync(DungeonCharacter character, PlayerInstance player, bool extracted, CancellationToken ct)
+ {
+ using var scope = _scopeFactory.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+
+ // Add XP earned
+ character.Experience += player.XpGained;
+ character.TotalKills += player.MobsKilled;
+ character.PlayersKilled += player.PlayersKilled;
+
+ if (extracted)
+ {
+ character.DungeonsCompleted++;
+ character.CurrentHealth = (int)player.Health;
+ character.CurrentMana = (int)player.Mana;
+ }
+ else
+ {
+ character.TotalDeaths++;
+ character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(character);
+ character.CurrentMana = DungeonCharacterStats.GetMaxMana(character);
+ }
+
+ // Check for level up
+ while (character.Experience >= LevelSystem.GetTotalXpForLevel(character.Level + 1))
+ {
+ character.Level++;
+ character.UnspentStatPoints += 5;
+ }
+
+ character.LastPlayedAt = DateTime.UtcNow;
+
+ db.Attach(character);
+ db.Entry(character).State = EntityState.Modified;
+ await db.SaveChangesAsync(ct);
+
+ _log.LogInformation("Saved character {Name}: Level {Level}, XP {Xp}, Extracted={Extracted}",
+ character.Name, character.Level, character.Experience, extracted);
+ }
+
+ private object GetHubState(DungeonCharacter character)
+ {
+ return new
+ {
+ character = new
+ {
+ id = character.Id,
+ name = character.Name,
+ level = character.Level,
+ xp = character.Experience,
+ xpNext = LevelSystem.GetXpForLevel(character.Level + 1),
+ unspentPoints = character.UnspentStatPoints,
+ strength = character.Strength,
+ intelligence = character.Intelligence,
+ wisdom = character.Wisdom,
+ endurance = character.Endurance,
+ dexterity = character.Dexterity,
+ maxHealth = DungeonCharacterStats.GetMaxHealth(character),
+ maxMana = DungeonCharacterStats.GetMaxMana(character),
+ maxStamina = DungeonCharacterStats.GetMaxStamina(character)
+ }
+ };
+ }
+
+ private async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct)
+ {
+ try
+ {
+ var payloadBytes = _ser.Serialize(payload);
+ var msg = new ServerMessage(opCode, payloadBytes);
+ var wire = _ser.Serialize(msg);
+ await connection.SendAsync(wire, ct);
+ }
+ catch (Exception ex)
+ {
+ _log.LogWarning(ex, "Failed to send message to connection {Id}", connection.Id);
+ }
+ }
+
+ private async Task SendErrorAsync(IConnection connection, string error, CancellationToken ct)
+ {
+ await SendAsync(connection, OpCodes.ERROR, new { error }, ct);
+ }
+
+ ///
+ /// Called when a connection is closed - cleanup session
+ ///
+ public void OnDisconnect(Guid connectionId)
+ {
+ if (_playerSessions.TryRemove(connectionId, out var session))
+ {
+ if (session.CurrentDungeonId.HasValue)
+ {
+ _ = RemoveFromDungeonAsync(session, false, CancellationToken.None);
+ }
+ _log.LogInformation("Dungeon session cleaned up for connection {Id}", connectionId);
+ }
+ }
+}
+
+// Request/Input DTOs
+
+public class StatAllocateRequest
+{
+ public string Stat { get; set; } = "";
+}
+
+public class DungeonEnterRequest
+{
+ public int Tier { get; set; } = 1;
+}
+
+public class MoveInput
+{
+ public float X { get; set; }
+ public float Y { get; set; }
+}
+
+public class AttackInput
+{
+ public ulong TargetId { get; set; }
+}
+
+public class PickupInput
+{
+ public ulong ItemId { get; set; }
+}
+
+public class ChestInput
+{
+ public ulong ChestId { get; set; }
+}
diff --git a/Game/Dungeon/DungeonInstance.cs b/Game/Dungeon/DungeonInstance.cs
new file mode 100644
index 0000000..9cba7ee
--- /dev/null
+++ b/Game/Dungeon/DungeonInstance.cs
@@ -0,0 +1,13 @@
+namespace Server.Game.Dungeon;
+
+///
+/// Represents an active dungeon instance
+///
+public class DungeonInstance
+{
+ public Guid Id { get; set; }
+ public int Tier { get; set; }
+ public int Seed { get; set; }
+ public DungeonSimulation Simulation { get; set; } = null!;
+ public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
+}
diff --git a/Game/Dungeon/DungeonLayout.cs b/Game/Dungeon/DungeonLayout.cs
new file mode 100644
index 0000000..06d0e54
--- /dev/null
+++ b/Game/Dungeon/DungeonLayout.cs
@@ -0,0 +1,89 @@
+using System.Text.Json;
+
+namespace Server.Game.Dungeon;
+
+///
+/// Contains the generated dungeon layout data
+///
+public class DungeonLayout
+{
+ public int Seed { get; set; }
+ public int Tier { get; set; }
+ public int Width { get; set; }
+ public int Height { get; set; }
+ public int TileSize { get; set; }
+
+ public int[,] Tiles { get; set; } = new int[0, 0];
+ public List Rooms { get; set; } = new();
+ public DungeonPoint SpawnPoint { get; set; }
+ public DungeonPoint? ExitPosition { get; set; } // Set when dungeon is cleared
+
+ public List MobSpawns { get; set; } = new();
+ public List ChestSpawns { get; set; } = new();
+
+ public int TotalMobs { get; set; }
+ public int TotalChests { get; set; }
+
+ // Serialize tiles to string for DB storage
+ public string SerializeTiles()
+ {
+ var rows = new List();
+ for (int y = 0; y < Height; y++)
+ {
+ var row = new char[Width];
+ for (int x = 0; x < Width; x++)
+ {
+ row[x] = Tiles[x, y] == 1 ? '.' : '#';
+ }
+ rows.Add(new string(row));
+ }
+ return string.Join("\n", rows);
+ }
+
+ public void DeserializeTiles(string data)
+ {
+ var rows = data.Split('\n');
+ Height = rows.Length;
+ Width = rows.Length > 0 ? rows[0].Length : 0;
+ Tiles = new int[Width, Height];
+
+ for (int y = 0; y < Height; y++)
+ {
+ for (int x = 0; x < Width && x < rows[y].Length; x++)
+ {
+ Tiles[x, y] = rows[y][x] == '.' ? 1 : 0;
+ }
+ }
+ }
+
+ public string ToJson()
+ {
+ return JsonSerializer.Serialize(new
+ {
+ seed = Seed,
+ tier = Tier,
+ width = Width,
+ height = Height,
+ tileSize = TileSize,
+ tiles = SerializeTiles(),
+ spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
+ rooms = Rooms.Select(r => new
+ {
+ x = r.X, y = r.Y, w = r.Width, h = r.Height,
+ type = r.Type.ToString()
+ }),
+ mobs = MobSpawns.Select(m => new
+ {
+ id = m.Id, x = m.X, y = m.Y,
+ type = m.MobType.ToString(),
+ roomIndex = m.RoomIndex
+ }),
+ chests = ChestSpawns.Select(c => new
+ {
+ id = c.Id, x = c.X, y = c.Y,
+ type = c.ChestType.ToString(),
+ roomIndex = c.RoomIndex
+ })
+ });
+ }
+}
diff --git a/Game/Dungeon/DungeonMobSpawn.cs b/Game/Dungeon/DungeonMobSpawn.cs
new file mode 100644
index 0000000..4379fe4
--- /dev/null
+++ b/Game/Dungeon/DungeonMobSpawn.cs
@@ -0,0 +1,18 @@
+namespace Server.Game.Dungeon;
+
+public class DungeonMobSpawn
+{
+ public int Id { get; set; }
+ public int X { get; set; }
+ public int Y { get; set; }
+ public DungeonMobSpawnType MobType { get; set; }
+ public int RoomIndex { get; set; }
+ public bool IsAlive { get; set; } = true;
+}
+
+public enum DungeonMobSpawnType
+{
+ Normal,
+ Elite,
+ Boss
+}
diff --git a/Game/Dungeon/DungeonPlayerSession.cs b/Game/Dungeon/DungeonPlayerSession.cs
new file mode 100644
index 0000000..d88ba13
--- /dev/null
+++ b/Game/Dungeon/DungeonPlayerSession.cs
@@ -0,0 +1,24 @@
+using Server.Data.Entities;
+using Server.Data.Enums;
+using Server.Networking;
+
+namespace Server.Game.Dungeon;
+
+///
+/// Tracks a player's dungeon session state
+///
+public class DungeonPlayerSession
+{
+ public Guid ConnectionId { get; set; }
+ public IConnection Connection { get; set; } = null!;
+ public ulong AccountId { get; set; }
+ public ulong CharacterId { get; set; }
+ public DungeonCharacter Character { get; set; } = null!;
+
+ public PlayerState State { get; set; } = PlayerState.InHub;
+ public Guid? CurrentDungeonId { get; set; }
+ public PlayerInstance? PlayerInstance { get; set; }
+
+ public bool IsEscaping { get; set; }
+ public long EscapeStartTick { get; set; }
+}
diff --git a/Game/Dungeon/DungeonPoint.cs b/Game/Dungeon/DungeonPoint.cs
new file mode 100644
index 0000000..763f2e1
--- /dev/null
+++ b/Game/Dungeon/DungeonPoint.cs
@@ -0,0 +1,9 @@
+namespace Server.Game.Dungeon;
+
+public struct DungeonPoint
+{
+ public int X { get; set; }
+ public int Y { get; set; }
+
+ public DungeonPoint(int x, int y) { X = x; Y = y; }
+}
diff --git a/Game/Dungeon/DungeonRoom.cs b/Game/Dungeon/DungeonRoom.cs
new file mode 100644
index 0000000..187ae29
--- /dev/null
+++ b/Game/Dungeon/DungeonRoom.cs
@@ -0,0 +1,37 @@
+namespace Server.Game.Dungeon;
+
+public class DungeonRoom
+{
+ public int X { get; set; }
+ public int Y { get; set; }
+ public int Width { get; set; }
+ public int Height { get; set; }
+ public DungeonRoomType Type { get; set; } = DungeonRoomType.Combat;
+
+ public int CenterX => X + Width / 2;
+ public int CenterY => Y + Height / 2;
+
+ public DungeonRoom() { }
+
+ public DungeonRoom(int x, int y, int width, int height)
+ {
+ X = x; Y = y; Width = width; Height = height;
+ }
+
+ public bool Intersects(DungeonRoom other, int padding = 0)
+ {
+ return X - padding < other.X + other.Width + padding &&
+ X + Width + padding > other.X - padding &&
+ Y - padding < other.Y + other.Height + padding &&
+ Y + Height + padding > other.Y - padding;
+ }
+}
+
+public enum DungeonRoomType
+{
+ Entrance,
+ Combat,
+ Treasure,
+ Boss,
+ Empty
+}
diff --git a/Game/Dungeon/DungeonSimulation.cs b/Game/Dungeon/DungeonSimulation.cs
index df89839..8a5e456 100644
--- a/Game/Dungeon/DungeonSimulation.cs
+++ b/Game/Dungeon/DungeonSimulation.cs
@@ -1,17 +1,16 @@
using System.Collections.Concurrent;
-using DungeonCrawler.Data.Entities;
+using Server.Data.Entities;
+using Server.Data.Enums;
-namespace DungeonCrawler.Game.Dungeon;
+namespace Server.Game.Dungeon;
///
/// Runtime simulation for an active dungeon instance
///
public class DungeonSimulation
{
- public Guid Id { get; }
- public int Tier { get; }
- public int Seed { get; }
public DungeonLayout Layout { get; }
+ public int Tier { get; }
// Tick rate
public const int TicksPerSecond = 20;
@@ -29,48 +28,27 @@ public class DungeonSimulation
// Combat tracking
private readonly List _pendingDamageEvents = new();
private readonly List _pendingDeathEvents = new();
- private readonly List _pendingLootEvents = new();
private int _nextDroppedItemId = 1;
- private readonly object _lock = new();
+ private readonly Dictionary _mobDefinitions;
- // Mob definitions cache
- private readonly Dictionary _mobDefinitions;
-
- public DungeonSimulation(Guid id, int tier, int seed, Dictionary mobDefinitions)
+ public DungeonSimulation(DungeonLayout layout, int tier, Dictionary mobDefinitions)
{
- Id = id;
+ Layout = layout;
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
- };
- }
+ InitializeChests();
}
private void SpawnMobs()
{
+ var rng = new Random(Layout.Seed);
+
foreach (var mobSpawn in Layout.MobSpawns)
{
- // Pick appropriate mob definition based on spawn type and tier
- var mobDef = SelectMobDefinition(mobSpawn.MobType);
+ var mobDef = SelectMobDefinition(mobSpawn.MobType, rng);
if (mobDef == null) continue;
var stats = mobDef.GetStatsForTier(Tier);
@@ -97,7 +75,22 @@ public class DungeonSimulation
}
}
- private MobDefinition? SelectMobDefinition(MobSpawnType spawnType)
+ 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)
@@ -105,67 +98,33 @@ public class DungeonSimulation
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(),
+ 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)
{
- // Fallback to any mob for this tier
- candidates = _mobDefinitions.Values
- .Where(m => m.IsEnabled && m.MinTier <= Tier)
- .ToList();
+ 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)];
- }
-
- ///
- /// Add a player to the dungeon
- ///
- 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;
+ return candidates.Count == 0 ? null : candidates[rng.Next(candidates.Count)];
}
///
/// Process one simulation tick
///
- public TickResult Tick()
+ public TickResult Tick(long tick)
{
- if (Phase != DungeonPhase.Active)
- return new TickResult();
+ CurrentTick = tick;
- CurrentTick++;
+ if (Phase != DungeonPhase.Active)
+ return new TickResult { Phase = Phase };
_pendingDamageEvents.Clear();
_pendingDeathEvents.Clear();
- _pendingLootEvents.Clear();
// Update all mobs (AI)
foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
@@ -173,7 +132,7 @@ public class DungeonSimulation
UpdateMob(mob);
}
- // Update players (regeneration, status effects)
+ // Update players (movement, regeneration)
foreach (var player in Players.Values.Where(p => p.IsAlive))
{
UpdatePlayer(player);
@@ -183,7 +142,6 @@ public class DungeonSimulation
if (Mobs.Values.All(m => !m.IsAlive))
{
Phase = DungeonPhase.Cleared;
- // Spawn exit
SpawnExit();
}
@@ -191,7 +149,6 @@ public class DungeonSimulation
{
DamageEvents = new List(_pendingDamageEvents),
DeathEvents = new List(_pendingDeathEvents),
- LootEvents = new List(_pendingLootEvents),
Phase = Phase
};
}
@@ -214,91 +171,55 @@ public class DungeonSimulation
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);
- }
+ mob.State = MobState.Idle;
+ mob.TargetId = null;
}
}
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
+ int damage = mob.Stats.PhysicalDamage + mob.Stats.MagicDamage;
player.Health -= damage;
+ player.IsInCombat = true;
player.LastCombatTick = CurrentTick;
_pendingDamageEvents.Add(new DamageEvent
@@ -307,11 +228,9 @@ public class DungeonSimulation
SourceId = mob.Id,
TargetType = EntityType.Player,
TargetId = (int)player.CharacterId,
- Damage = damage,
- DamageType = DamageType.Physical
+ Damage = damage
});
- // Check death
if (player.Health <= 0)
{
player.Health = 0;
@@ -321,299 +240,117 @@ public class DungeonSimulation
{
EntityType = EntityType.Player,
EntityId = (int)player.CharacterId,
+ EntityName = player.CharacterName,
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);
- }
-
- ///
- /// Player attacks - called from input handler
- ///
- 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))
+ // Process movement input
+ if (player.InputX != 0 || player.InputY != 0)
{
- float dist = Distance(player.X, player.Y, mob.X, mob.Y);
- if (dist > attackRange) continue;
+ float speed = player.MoveSpeed * TickDelta;
+ float newX = player.X + player.InputX * speed;
+ float newY = player.Y + player.InputY * speed;
- // Check angle
- float angleToMob = MathF.Atan2(mob.Y - player.Y, mob.X - player.X);
- float angleDiff = NormalizeAngle(angleToMob - aimAngle);
+ if (CanMoveTo(newX, player.Y)) player.X = newX;
+ if (CanMoveTo(player.X, newY)) player.Y = newY;
- if (MathF.Abs(angleDiff) > attackArc) continue;
-
- // Hit!
- int actualDamage = mob.Stats.CalculateDamage(damage, DamageType.Physical);
- mob.Health -= actualDamage;
-
- _pendingDamageEvents.Add(new DamageEvent
+ if (player.InputX != 0 || player.InputY != 0)
{
- 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);
+ player.Rotation = MathF.Atan2(player.InputY, player.InputX);
}
-
- // Only hit one mob per swing (for melee)
- // TODO: Make this configurable for cleave weapons
- break;
+ }
+
+ // 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);
}
}
- ///
- /// Player attacks another player (PvP)
- ///
- public void PlayerAttackPlayer(ulong attackerId, ulong targetId, float aimAngle)
+ private void TryPlayerAttack(PlayerInstance player, ulong targetId)
{
- if (!Players.TryGetValue(attackerId, out var attacker) || !attacker.IsAlive)
- return;
- if (!Players.TryGetValue(targetId, out var target) || !target.IsAlive)
+ if (!Mobs.TryGetValue((int)targetId, out var mob) || !mob.IsAlive)
return;
- // Check attack cooldown
- float attackInterval = 1f / attacker.Stats.AttackSpeed;
- if (CurrentTick - attacker.LastAttackTick < (long)(attackInterval * TicksPerSecond))
- return;
+ float dist = Distance(player.X, player.Y, mob.X, mob.Y);
+ if (dist > 60) return; // Out of range
- attacker.LastAttackTick = CurrentTick;
- attacker.LastCombatTick = CurrentTick;
- target.LastCombatTick = CurrentTick;
+ // Calculate damage
+ int damage = (int)(10 * (1 + player.Strength * 0.05f));
- 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;
+ mob.Health -= damage;
+ player.IsInCombat = true;
+ player.LastCombatTick = CurrentTick;
_pendingDamageEvents.Add(new DamageEvent
{
SourceType = EntityType.Player,
- SourceId = (int)attackerId,
- TargetType = EntityType.Player,
- TargetId = (int)targetId,
- Damage = damage,
- DamageType = DamageType.Physical,
- IsPvP = true
+ SourceId = (int)player.CharacterId,
+ TargetType = EntityType.Mob,
+ TargetId = mob.Id,
+ Damage = damage
});
- if (target.Health <= 0)
+ if (mob.Health <= 0)
{
- target.Health = 0;
- target.IsAlive = false;
- attacker.PlayersKilled++;
+ mob.Health = 0;
+ mob.IsAlive = false;
+ mob.State = MobState.Dead;
+
+ player.XpGained += mob.Stats.XpReward;
+ player.MobsKilled++;
_pendingDeathEvents.Add(new DeathEvent
{
- EntityType = EntityType.Player,
- EntityId = (int)targetId,
+ EntityType = EntityType.Mob,
+ EntityId = mob.Id,
+ EntityName = mob.Name,
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
+ KillerId = (int)player.CharacterId,
+ KillerName = player.CharacterName,
+ XpReward = mob.Stats.XpReward
});
}
}
- 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)
+ // Spawn exit at boss room location
+ if (Layout.Rooms.Count > 0)
{
- Layout.ExitPosition = new Point(lastRoom.CenterX, lastRoom.CenterY);
+ var bossRoom = Layout.Rooms.LastOrDefault(r => r.Type == DungeonRoomType.Boss)
+ ?? Layout.Rooms[^1];
+ Layout.ExitPosition = new DungeonPoint(bossRoom.CenterX, bossRoom.CenterY);
}
}
- ///
- /// Player picks up an item
- ///
- public bool TryPickupItem(ulong characterId, int droppedItemId)
+ public bool CanMoveTo(float x, float y)
{
- if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive)
+ int tileX = (int)(x / 32);
+ int tileY = (int)(y / 32);
+
+ if (tileX < 0 || tileX >= Layout.Width || tileY < 0 || tileY >= Layout.Height)
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;
+ return Layout.Tiles[tileX, tileY] == 1;
}
- ///
- /// Player opens a chest
- ///
- 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;
@@ -628,202 +365,18 @@ public class DungeonSimulation
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 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 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 DamageEvents { get; set; } = new();
- public List DeathEvents { get; set; } = new();
- public List 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
diff --git a/Game/Dungeon/MobInstance.cs b/Game/Dungeon/MobInstance.cs
new file mode 100644
index 0000000..0e9361a
--- /dev/null
+++ b/Game/Dungeon/MobInstance.cs
@@ -0,0 +1,47 @@
+using Server.Data.Entities;
+using Server.Data.Enums;
+
+namespace Server.Game.Dungeon;
+
+///
+/// Runtime instance of a mob in a dungeon
+///
+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 DungeonMobCombatStats 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";
+}
+
+public enum MobState
+{
+ Idle,
+ Chasing,
+ Attacking,
+ Returning,
+ Fleeing,
+ Dead
+}
diff --git a/Game/Dungeon/PlayerInstance.cs b/Game/Dungeon/PlayerInstance.cs
new file mode 100644
index 0000000..e5f8b0c
--- /dev/null
+++ b/Game/Dungeon/PlayerInstance.cs
@@ -0,0 +1,43 @@
+namespace Server.Game.Dungeon;
+
+///
+/// Runtime instance of a player in a dungeon
+///
+public class PlayerInstance
+{
+ public ulong CharacterId { get; set; }
+ public string CharacterName { 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 float MoveSpeed { get; set; } = 100f;
+ public float AttackSpeed { get; set; } = 1f;
+ public int Strength { get; set; }
+ public int Intelligence { get; set; }
+
+ public bool IsAlive { get; set; } = true;
+ public bool IsInCombat { get; set; }
+
+ // 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 (set by handler)
+ public float InputX { get; set; }
+ public float InputY { get; set; }
+ public bool WantsToAttack { get; set; }
+ public ulong? AttackTargetId { get; set; }
+}
diff --git a/Game/Dungeon/TickResult.cs b/Game/Dungeon/TickResult.cs
new file mode 100644
index 0000000..bfbad12
--- /dev/null
+++ b/Game/Dungeon/TickResult.cs
@@ -0,0 +1,38 @@
+using Server.Data.Enums;
+
+namespace Server.Game.Dungeon;
+
+public class TickResult
+{
+ public List DamageEvents { get; set; } = new();
+ public List DeathEvents { 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 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 enum EntityType
+{
+ Player,
+ Mob,
+ Chest
+}
diff --git a/Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs b/Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs
new file mode 100644
index 0000000..d9ce79c
--- /dev/null
+++ b/Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs
@@ -0,0 +1,1439 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Metadata;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Server.Data;
+
+#nullable disable
+
+namespace SystemRevivalServer.Migrations
+{
+ [DbContext(typeof(GameDbContext))]
+ [Migration("20251206230532_AddDungeonCrawlerEntities")]
+ partial class AddDungeonCrawlerEntities
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "9.0.10")
+ .HasAnnotation("Relational:MaxIdentifierLength", 64);
+
+ MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder);
+
+ modelBuilder.Entity("Server.Data.Account", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("BannedUntil")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("Email")
+ .HasMaxLength(255)
+ .HasColumnType("varchar(255)");
+
+ b.Property("IsBanned")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("PasswordHash")
+ .IsRequired()
+ .HasColumnType("varbinary(64)");
+
+ b.Property("PasswordSalt")
+ .IsRequired()
+ .HasColumnType("varbinary(32)");
+
+ b.Property("Role")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("int")
+ .HasDefaultValue(0);
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Username")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Email")
+ .IsUnique();
+
+ b.HasIndex("Username")
+ .IsUnique();
+
+ b.ToTable("accounts", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonCharacter", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("BossesKilled")
+ .HasColumnType("int");
+
+ b.Property("CreatedAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CurrentHealth")
+ .HasColumnType("int");
+
+ b.Property("CurrentMana")
+ .HasColumnType("int");
+
+ b.Property("Dexterity")
+ .HasColumnType("int");
+
+ b.Property("DungeonsCompleted")
+ .HasColumnType("int");
+
+ b.Property("Endurance")
+ .HasColumnType("int");
+
+ b.Property("EquippedAccessory")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedBoots")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedChest")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedGloves")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedHead")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedLegs")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedOffhand")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("EquippedWeapon")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("Experience")
+ .HasColumnType("bigint");
+
+ b.Property("Intelligence")
+ .HasColumnType("int");
+
+ b.Property("IsDeleted")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("LastPlayedAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("Level")
+ .HasColumnType("int");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.Property("PlayersKilled")
+ .HasColumnType("int");
+
+ b.Property("Strength")
+ .HasColumnType("int");
+
+ b.Property("TotalDeaths")
+ .HasColumnType("int");
+
+ b.Property("TotalKills")
+ .HasColumnType("int");
+
+ b.Property("UnspentStatPoints")
+ .HasColumnType("int");
+
+ b.Property("Wisdom")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId");
+
+ b.ToTable("dungeon_characters");
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonCharacterItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AcquiredAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("CharacterId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("DefinitionId")
+ .HasColumnType("int");
+
+ b.Property("ItemDefinitionId")
+ .HasColumnType("int");
+
+ b.Property("Quantity")
+ .HasColumnType("int");
+
+ b.Property("SlotIndex")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CharacterId");
+
+ b.HasIndex("DefinitionId");
+
+ b.ToTable("dungeon_character_items");
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonItemDefinition", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("int");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("Armor")
+ .HasColumnType("int");
+
+ b.Property("AttackRange")
+ .HasColumnType("float");
+
+ b.Property("BonusDexterity")
+ .HasColumnType("int");
+
+ b.Property("BonusEndurance")
+ .HasColumnType("int");
+
+ b.Property("BonusHealth")
+ .HasColumnType("int");
+
+ b.Property("BonusIntelligence")
+ .HasColumnType("int");
+
+ b.Property("BonusMana")
+ .HasColumnType("int");
+
+ b.Property("BonusStrength")
+ .HasColumnType("int");
+
+ b.Property("BonusWisdom")
+ .HasColumnType("int");
+
+ b.Property("DamageType")
+ .HasColumnType("int");
+
+ b.Property("Description")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("EquipSlot")
+ .HasColumnType("int");
+
+ b.Property("HealAmount")
+ .HasColumnType("int");
+
+ b.Property("IsEnabled")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("IsTeleportScroll")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("MagicResist")
+ .HasColumnType("int");
+
+ b.Property("ManaRestore")
+ .HasColumnType("int");
+
+ b.Property("MaxDamage")
+ .HasColumnType("int");
+
+ b.Property("MaxStack")
+ .HasColumnType("int");
+
+ b.Property("MinDamage")
+ .HasColumnType("int");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("Rarity")
+ .HasColumnType("int");
+
+ b.Property("RequiredDexterity")
+ .HasColumnType("int");
+
+ b.Property("RequiredIntelligence")
+ .HasColumnType("int");
+
+ b.Property("RequiredLevel")
+ .HasColumnType("int");
+
+ b.Property("RequiredStrength")
+ .HasColumnType("int");
+
+ b.Property("RequiredWisdom")
+ .HasColumnType("int");
+
+ b.Property("SpriteId")
+ .HasColumnType("int");
+
+ b.Property("Stackable")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("StaminaRestore")
+ .HasColumnType("int");
+
+ b.Property("TeachesSpellId")
+ .HasColumnType("int");
+
+ b.Property("Type")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.ToTable("dungeon_item_definitions");
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonLearnedSpell", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CharacterId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("DefinitionId")
+ .HasColumnType("int");
+
+ b.Property("LearnedAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("SpellDefinitionId")
+ .HasColumnType("int");
+
+ b.Property("SpellLevel")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CharacterId");
+
+ b.HasIndex("DefinitionId");
+
+ b.ToTable("dungeon_learned_spells");
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonMobDefinition", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("int");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AbilitiesJson")
+ .IsRequired()
+ .HasMaxLength(1024)
+ .HasColumnType("varchar(1024)");
+
+ b.Property("AggroRange")
+ .HasColumnType("float");
+
+ b.Property("AnimationSpeed")
+ .HasColumnType("float");
+
+ b.Property("ArmorPerTier")
+ .HasColumnType("float");
+
+ b.Property("AttackFrames")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("AttackRange")
+ .HasColumnType("float");
+
+ b.Property("AttackSpeed")
+ .HasColumnType("float");
+
+ b.Property("BaseArmor")
+ .HasColumnType("int");
+
+ b.Property("BaseHealth")
+ .HasColumnType("int");
+
+ b.Property("BaseMagicDamage")
+ .HasColumnType("int");
+
+ b.Property("BaseMagicResist")
+ .HasColumnType("int");
+
+ b.Property("BaseMana")
+ .HasColumnType("int");
+
+ b.Property("BasePhysicalDamage")
+ .HasColumnType("int");
+
+ b.Property("BaseXp")
+ .HasColumnType("int");
+
+ b.Property("Category")
+ .HasColumnType("int");
+
+ b.Property("DamagePerTier")
+ .HasColumnType("float");
+
+ b.Property("DeathFrames")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("Description")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("DropChanceMultiplier")
+ .HasColumnType("float");
+
+ b.Property("HealthPerTier")
+ .HasColumnType("float");
+
+ b.Property("IdleFrames")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("IsEnabled")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("LeashRange")
+ .HasColumnType("float");
+
+ b.Property("LootTableId")
+ .HasColumnType("int");
+
+ b.Property("MaxTier")
+ .HasColumnType("int");
+
+ b.Property("MinTier")
+ .HasColumnType("int");
+
+ b.Property("MoveSpeed")
+ .HasColumnType("float");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("ResistancesJson")
+ .IsRequired()
+ .HasMaxLength(1024)
+ .HasColumnType("varchar(1024)");
+
+ b.Property("SpriteHeight")
+ .HasColumnType("int");
+
+ b.Property("SpriteIndex")
+ .HasColumnType("int");
+
+ b.Property("SpriteSheet")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("varchar(128)");
+
+ b.Property("SpriteWidth")
+ .HasColumnType("int");
+
+ b.Property("TintColor")
+ .IsRequired()
+ .HasMaxLength(16)
+ .HasColumnType("varchar(16)");
+
+ b.Property("Type")
+ .HasColumnType("int");
+
+ b.Property("WalkFrames")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("XpPerTier")
+ .HasColumnType("float");
+
+ b.HasKey("Id");
+
+ b.ToTable("dungeon_mob_definitions");
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonSpellDefinition", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("int");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AreaOfEffect")
+ .HasColumnType("float");
+
+ b.Property("BaseDamage")
+ .HasColumnType("int");
+
+ b.Property("BaseHealing")
+ .HasColumnType("int");
+
+ b.Property("Cooldown")
+ .HasColumnType("float");
+
+ b.Property("Description")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("EffectColor")
+ .IsRequired()
+ .HasColumnType("longtext");
+
+ b.Property("IsEnabled")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("IsShield")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("IsTeleport")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("ManaCost")
+ .HasColumnType("int");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("Range")
+ .HasColumnType("float");
+
+ b.Property("RequiredIntelligence")
+ .HasColumnType("int");
+
+ b.Property("RequiredLevel")
+ .HasColumnType("int");
+
+ b.Property("RequiredWisdom")
+ .HasColumnType("int");
+
+ b.Property("ShieldAmount")
+ .HasColumnType("int");
+
+ b.Property("SpriteId")
+ .HasColumnType("int");
+
+ b.Property("Type")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.ToTable("dungeon_spell_definitions");
+ });
+
+ modelBuilder.Entity("Server.Data.Entities.DungeonStashItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CharacterId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("DefinitionId")
+ .HasColumnType("int");
+
+ b.Property("ItemDefinitionId")
+ .HasColumnType("int");
+
+ b.Property("Quantity")
+ .HasColumnType("int");
+
+ b.Property("SlotIndex")
+ .HasColumnType("int");
+
+ b.Property("StoredAt")
+ .HasColumnType("datetime(6)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("CharacterId");
+
+ b.HasIndex("DefinitionId");
+
+ b.ToTable("dungeon_stash_items");
+ });
+
+ modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CharacterId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("ItemTemplateId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("SlotCode")
+ .HasColumnType("tinyint unsigned");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("ItemTemplateId");
+
+ b.HasIndex("CharacterId", "SlotCode")
+ .IsUnique();
+
+ b.ToTable("equipment", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.GameItem", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("int");
+
+ b.Property("AmmoType")
+ .HasColumnType("int");
+
+ b.Property("Category")
+ .HasColumnType("int");
+
+ b.Property("CraftCost")
+ .HasColumnType("int");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("Damage")
+ .HasColumnType("int");
+
+ b.Property("DamageReduction")
+ .HasColumnType("float");
+
+ b.Property("DashCooldown")
+ .HasColumnType("float");
+
+ b.Property("DashDistance")
+ .HasColumnType("float");
+
+ b.Property("Description")
+ .IsRequired()
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.Property("ExplosionRadius")
+ .HasColumnType("float");
+
+ b.Property("FireRate")
+ .HasColumnType("float");
+
+ b.Property("HarvestMultiplier")
+ .HasColumnType("float");
+
+ b.Property("HealAmount")
+ .HasColumnType("int");
+
+ b.Property("HealthBonus")
+ .HasColumnType("int");
+
+ b.Property