diff --git a/Game/Dungeon/DungeonGameHandler.cs b/Game/Dungeon/DungeonGameHandler.cs
new file mode 100644
index 0000000..3c9f9bd
--- /dev/null
+++ b/Game/Dungeon/DungeonGameHandler.cs
@@ -0,0 +1,729 @@
+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
new file mode 100644
index 0000000..dea6570
--- /dev/null
+++ b/Game/Dungeon/DungeonGenerator.cs
@@ -0,0 +1,437 @@
+using System.Text.Json;
+
+namespace DungeonCrawler.Game.Dungeon;
+
+///
+/// Procedural dungeon generator using BSP (Binary Space Partition) + room placement
+///
+public class DungeonGenerator
+{
+ private readonly Random _rng;
+ private readonly int _seed;
+
+ // Generation parameters
+ private readonly int _tier;
+ private readonly int _tileSize = 32;
+
+ // Tier-based scaling
+ private int MinRooms => 5 + (_tier * 2);
+ private int MaxRooms => 8 + (_tier * 3);
+ private int MinRoomSize => 5; // In tiles
+ private int MaxRoomSize => 12;
+ private int MapWidth => 50 + (_tier * 10); // In tiles
+ private int MapHeight => 50 + (_tier * 10);
+
+ public DungeonGenerator(int seed, int tier)
+ {
+ _seed = seed;
+ _tier = Math.Max(1, tier);
+ _rng = new Random(seed);
+ }
+
+ public DungeonLayout Generate()
+ {
+ var layout = new DungeonLayout
+ {
+ Seed = _seed,
+ Tier = _tier,
+ Width = MapWidth,
+ Height = MapHeight,
+ TileSize = _tileSize
+ };
+
+ // Initialize tile map (0 = wall, 1 = floor)
+ layout.Tiles = new int[MapWidth, MapHeight];
+
+ // Generate rooms
+ int roomCount = _rng.Next(MinRooms, MaxRooms + 1);
+ var rooms = new List();
+ int attempts = 0;
+ int maxAttempts = roomCount * 20;
+
+ while (rooms.Count < roomCount && attempts < maxAttempts)
+ {
+ attempts++;
+
+ int w = _rng.Next(MinRoomSize, MaxRoomSize + 1);
+ int h = _rng.Next(MinRoomSize, MaxRoomSize + 1);
+ int x = _rng.Next(2, MapWidth - w - 2);
+ int y = _rng.Next(2, MapHeight - h - 2);
+
+ var newRoom = new Room(x, y, w, h);
+
+ // Check for overlap with existing rooms (with padding)
+ bool overlaps = rooms.Any(r => newRoom.Intersects(r, padding: 2));
+
+ if (!overlaps)
+ {
+ rooms.Add(newRoom);
+ CarveRoom(layout.Tiles, newRoom);
+ }
+ }
+
+ // Sort rooms by distance from top-left for corridor generation
+ rooms = rooms.OrderBy(r => r.CenterX + r.CenterY).ToList();
+
+ // Connect rooms with corridors
+ for (int i = 0; i < rooms.Count - 1; i++)
+ {
+ ConnectRooms(layout.Tiles, rooms[i], rooms[i + 1]);
+ }
+
+ // Optionally add some extra connections for loops
+ for (int i = 0; i < rooms.Count / 3; i++)
+ {
+ int a = _rng.Next(rooms.Count);
+ int b = _rng.Next(rooms.Count);
+ if (a != b)
+ {
+ ConnectRooms(layout.Tiles, rooms[a], rooms[b]);
+ }
+ }
+
+ // Assign room types
+ AssignRoomTypes(rooms, layout);
+
+ // Place spawn point (first room)
+ layout.SpawnPoint = new Point(rooms[0].CenterX, rooms[0].CenterY);
+ rooms[0].Type = RoomType.Entrance;
+
+ // Generate mob spawns
+ GenerateMobSpawns(rooms, layout);
+
+ // Generate chest spawns
+ GenerateChestSpawns(rooms, layout);
+
+ // Store rooms
+ layout.Rooms = rooms;
+
+ return layout;
+ }
+
+ private void CarveRoom(int[,] tiles, Room room)
+ {
+ for (int x = room.X; x < room.X + room.Width; x++)
+ {
+ for (int y = room.Y; y < room.Y + room.Height; y++)
+ {
+ tiles[x, y] = 1; // Floor
+ }
+ }
+ }
+
+ private void ConnectRooms(int[,] tiles, Room a, Room b)
+ {
+ int x = a.CenterX;
+ int y = a.CenterY;
+ int targetX = b.CenterX;
+ int targetY = b.CenterY;
+
+ // L-shaped corridor (horizontal then vertical, or vice versa)
+ if (_rng.Next(2) == 0)
+ {
+ // Horizontal first
+ CarveHorizontalTunnel(tiles, x, targetX, y);
+ CarveVerticalTunnel(tiles, y, targetY, targetX);
+ }
+ else
+ {
+ // Vertical first
+ CarveVerticalTunnel(tiles, y, targetY, x);
+ CarveHorizontalTunnel(tiles, x, targetX, targetY);
+ }
+ }
+
+ private void CarveHorizontalTunnel(int[,] tiles, int x1, int x2, int y)
+ {
+ int minX = Math.Min(x1, x2);
+ int maxX = Math.Max(x1, x2);
+
+ for (int x = minX; x <= maxX; x++)
+ {
+ if (x >= 0 && x < tiles.GetLength(0) && y >= 0 && y < tiles.GetLength(1))
+ {
+ tiles[x, y] = 1;
+ // Make corridor 2 tiles wide
+ if (y + 1 < tiles.GetLength(1)) tiles[x, y + 1] = 1;
+ }
+ }
+ }
+
+ private void CarveVerticalTunnel(int[,] tiles, int y1, int y2, int x)
+ {
+ int minY = Math.Min(y1, y2);
+ int maxY = Math.Max(y1, y2);
+
+ for (int y = minY; y <= maxY; y++)
+ {
+ if (x >= 0 && x < tiles.GetLength(0) && y >= 0 && y < tiles.GetLength(1))
+ {
+ tiles[x, y] = 1;
+ // Make corridor 2 tiles wide
+ if (x + 1 < tiles.GetLength(0)) tiles[x + 1, y] = 1;
+ }
+ }
+ }
+
+ private void AssignRoomTypes(List rooms, DungeonLayout layout)
+ {
+ if (rooms.Count == 0) return;
+
+ // First room is entrance (already set)
+ // Last room is boss room
+ if (rooms.Count > 1)
+ {
+ rooms[^1].Type = RoomType.Boss;
+ }
+
+ // Assign some treasure rooms (10-20% of rooms)
+ int treasureCount = Math.Max(1, rooms.Count / 6);
+ var availableRooms = rooms.Skip(1).Take(rooms.Count - 2).ToList();
+
+ for (int i = 0; i < treasureCount && availableRooms.Count > 0; i++)
+ {
+ int idx = _rng.Next(availableRooms.Count);
+ availableRooms[idx].Type = RoomType.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)
+ {
+ foreach (var room in rooms)
+ {
+ if (room.Type == RoomType.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),
+ _ => _rng.Next(1, 3)
+ };
+
+ for (int i = 0; i < mobCount; i++)
+ {
+ // Random position within room (with margin)
+ int x = room.X + 1 + _rng.Next(room.Width - 2);
+ int y = room.Y + 1 + _rng.Next(room.Height - 2);
+
+ var spawn = new MobSpawn
+ {
+ Id = layout.MobSpawns.Count + 1,
+ X = x,
+ Y = y,
+ MobType = room.Type == RoomType.Boss ? MobSpawnType.Boss : MobSpawnType.Normal,
+ RoomIndex = rooms.IndexOf(room)
+ };
+
+ layout.MobSpawns.Add(spawn);
+ }
+ }
+
+ layout.TotalMobs = layout.MobSpawns.Count;
+ }
+
+ 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
+ _ => 0
+ };
+
+ for (int i = 0; i < chestCount; i++)
+ {
+ int x = room.X + 1 + _rng.Next(room.Width - 2);
+ int y = room.Y + 1 + _rng.Next(room.Height - 2);
+
+ var chest = new ChestSpawn
+ {
+ Id = layout.ChestSpawns.Count + 1,
+ X = x,
+ Y = y,
+ ChestType = room.Type == RoomType.Boss ? ChestType.Boss : ChestType.Normal,
+ RoomIndex = rooms.IndexOf(room)
+ };
+
+ layout.ChestSpawns.Add(chest);
+ }
+ }
+
+ 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/DungeonSimulation.cs b/Game/Dungeon/DungeonSimulation.cs
new file mode 100644
index 0000000..df89839
--- /dev/null
+++ b/Game/Dungeon/DungeonSimulation.cs
@@ -0,0 +1,834 @@
+using System.Collections.Concurrent;
+using DungeonCrawler.Data.Entities;
+
+namespace DungeonCrawler.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; }
+
+ // Tick rate
+ public const int TicksPerSecond = 20;
+ public const float TickDelta = 1f / TicksPerSecond;
+
+ public long CurrentTick { get; private set; }
+ public DungeonPhase Phase { get; private set; } = DungeonPhase.Active;
+
+ // Entities
+ public ConcurrentDictionary Players { get; } = new();
+ public ConcurrentDictionary Mobs { get; } = new();
+ public ConcurrentDictionary Chests { get; } = new();
+ public ConcurrentDictionary DroppedItems { get; } = new();
+
+ // 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();
+
+ // Mob definitions cache
+ private readonly Dictionary _mobDefinitions;
+
+ public DungeonSimulation(Guid id, int tier, int seed, Dictionary mobDefinitions)
+ {
+ Id = id;
+ Tier = tier;
+ Seed = seed;
+ _mobDefinitions = mobDefinitions;
+
+ // Generate dungeon layout
+ var generator = new DungeonGenerator(seed, tier);
+ Layout = generator.Generate();
+
+ // Spawn mobs from layout
+ SpawnMobs();
+
+ // Initialize chests
+ foreach (var chestSpawn in Layout.ChestSpawns)
+ {
+ Chests[chestSpawn.Id] = new ChestInstance
+ {
+ Id = chestSpawn.Id,
+ X = chestSpawn.X * 32 + 16, // Center of tile
+ Y = chestSpawn.Y * 32 + 16,
+ Type = chestSpawn.ChestType,
+ IsOpened = false
+ };
+ }
+ }
+
+ private void SpawnMobs()
+ {
+ foreach (var mobSpawn in Layout.MobSpawns)
+ {
+ // Pick appropriate mob definition based on spawn type and tier
+ var mobDef = SelectMobDefinition(mobSpawn.MobType);
+ if (mobDef == null) continue;
+
+ var stats = mobDef.GetStatsForTier(Tier);
+
+ Mobs[mobSpawn.Id] = new MobInstance
+ {
+ Id = mobSpawn.Id,
+ DefinitionId = mobDef.Id,
+ Name = mobDef.Name,
+ X = mobSpawn.X * 32 + 16,
+ Y = mobSpawn.Y * 32 + 16,
+ SpawnX = mobSpawn.X * 32 + 16,
+ SpawnY = mobSpawn.Y * 32 + 16,
+ Health = stats.MaxHealth,
+ MaxHealth = stats.MaxHealth,
+ Stats = stats,
+ State = MobState.Idle,
+ SpriteSheet = mobDef.SpriteSheet,
+ SpriteWidth = mobDef.SpriteWidth,
+ SpriteHeight = mobDef.SpriteHeight,
+ TintColor = mobDef.TintColor,
+ Type = mobDef.Type
+ };
+ }
+ }
+
+ private MobDefinition? SelectMobDefinition(MobSpawnType spawnType)
+ {
+ var candidates = _mobDefinitions.Values
+ .Where(m => m.IsEnabled && m.MinTier <= Tier && m.MaxTier >= Tier)
+ .ToList();
+
+ if (candidates.Count == 0) return null;
+
+ // Filter by spawn type
+ candidates = spawnType switch
+ {
+ MobSpawnType.Boss => candidates.Where(m => m.Type == MobType.Boss).ToList(),
+ MobSpawnType.Elite => candidates.Where(m => m.Type == MobType.Elite || m.Type == MobType.Miniboss).ToList(),
+ _ => candidates.Where(m => m.Type == MobType.Normal || m.Type == MobType.Swarm).ToList()
+ };
+
+ if (candidates.Count == 0)
+ {
+ // Fallback to any mob for this tier
+ candidates = _mobDefinitions.Values
+ .Where(m => m.IsEnabled && m.MinTier <= Tier)
+ .ToList();
+ }
+
+ if (candidates.Count == 0) return null;
+
+ // Random selection (could add weights later)
+ var rng = new Random(Seed + Layout.MobSpawns.Count);
+ return candidates[rng.Next(candidates.Count)];
+ }
+
+ ///
+ /// 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;
+ }
+
+ ///
+ /// Process one simulation tick
+ ///
+ public TickResult Tick()
+ {
+ if (Phase != DungeonPhase.Active)
+ return new TickResult();
+
+ CurrentTick++;
+
+ _pendingDamageEvents.Clear();
+ _pendingDeathEvents.Clear();
+ _pendingLootEvents.Clear();
+
+ // Update all mobs (AI)
+ foreach (var mob in Mobs.Values.Where(m => m.IsAlive))
+ {
+ UpdateMob(mob);
+ }
+
+ // Update players (regeneration, status effects)
+ foreach (var player in Players.Values.Where(p => p.IsAlive))
+ {
+ UpdatePlayer(player);
+ }
+
+ // Check dungeon completion
+ if (Mobs.Values.All(m => !m.IsAlive))
+ {
+ Phase = DungeonPhase.Cleared;
+ // Spawn exit
+ SpawnExit();
+ }
+
+ return new TickResult
+ {
+ DamageEvents = new List(_pendingDamageEvents),
+ DeathEvents = new List(_pendingDeathEvents),
+ LootEvents = new List(_pendingLootEvents),
+ Phase = Phase
+ };
+ }
+
+ private void UpdateMob(MobInstance mob)
+ {
+ // Find closest player
+ PlayerInstance? target = null;
+ float closestDist = float.MaxValue;
+
+ foreach (var player in Players.Values.Where(p => p.IsAlive))
+ {
+ float dist = Distance(mob.X, mob.Y, player.X, player.Y);
+ if (dist < closestDist)
+ {
+ closestDist = dist;
+ target = player;
+ }
+ }
+
+ if (target == null)
+ {
+ // No players - return to spawn
+ mob.State = MobState.Returning;
+ mob.TargetId = null;
+ MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f);
+ return;
+ }
+
+ // Check if in aggro range
+ if (closestDist <= mob.Stats.AggroRange)
+ {
+ mob.TargetId = target.CharacterId;
+
+ // Check leash range
+ float distFromSpawn = Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY);
+ if (distFromSpawn > mob.Stats.LeashRange)
+ {
+ // Too far from spawn, return
+ mob.State = MobState.Returning;
+ mob.TargetId = null;
+ MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed);
+
+ // Heal while returning
+ mob.Health = Math.Min(mob.MaxHealth, mob.Health + (int)(mob.MaxHealth * 0.02f));
+ return;
+ }
+
+ // In attack range?
+ if (closestDist <= mob.Stats.AttackRange)
+ {
+ mob.State = MobState.Attacking;
+
+ // Check attack cooldown
+ float attackInterval = 1f / mob.Stats.AttackSpeed;
+ if (CurrentTick - mob.LastAttackTick >= (long)(attackInterval * TicksPerSecond))
+ {
+ // Attack!
+ MobAttackPlayer(mob, target);
+ mob.LastAttackTick = CurrentTick;
+ }
+ }
+ else
+ {
+ // Chase
+ mob.State = MobState.Chasing;
+ MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed);
+ }
+ }
+ else
+ {
+ // Out of aggro range
+ if (mob.State == MobState.Chasing || mob.State == MobState.Attacking)
+ {
+ // Lost target, return
+ mob.State = MobState.Returning;
+ mob.TargetId = null;
+ }
+ else
+ {
+ mob.State = MobState.Idle;
+ }
+
+ // Return to spawn if not at spawn
+ if (Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY) > 5)
+ {
+ MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f);
+ }
+ }
+ }
+
+ private void MobAttackPlayer(MobInstance mob, PlayerInstance player)
+ {
+ // Calculate damage
+ int damage = mob.Stats.PhysicalDamage;
+
+ // Apply player armor reduction
+ if (player.Stats.Armor > 0)
+ {
+ float reduction = player.Stats.Armor / (float)(player.Stats.Armor + 100);
+ damage = (int)(damage * (1f - reduction));
+ }
+
+ damage = Math.Max(1, damage); // Minimum 1 damage
+
+ // Apply damage
+ player.Health -= damage;
+ player.LastCombatTick = CurrentTick;
+
+ _pendingDamageEvents.Add(new DamageEvent
+ {
+ SourceType = EntityType.Mob,
+ SourceId = mob.Id,
+ TargetType = EntityType.Player,
+ TargetId = (int)player.CharacterId,
+ Damage = damage,
+ DamageType = DamageType.Physical
+ });
+
+ // Check death
+ if (player.Health <= 0)
+ {
+ player.Health = 0;
+ player.IsAlive = false;
+
+ _pendingDeathEvents.Add(new DeathEvent
+ {
+ EntityType = EntityType.Player,
+ EntityId = (int)player.CharacterId,
+ KillerType = EntityType.Mob,
+ KillerId = mob.Id,
+ EntityName = player.Name,
+ KillerName = mob.Name
+ });
+
+ // Drop player's inventory (mob holds it)
+ mob.HeldLoot.AddRange(player.Inventory);
+ player.Inventory.Clear();
+ }
+ }
+
+ private void UpdatePlayer(PlayerInstance player)
+ {
+ // Check if out of combat (for escape teleport)
+ float secondsSinceCombat = (CurrentTick - player.LastCombatTick) / (float)TicksPerSecond;
+ player.IsInCombat = secondsSinceCombat < 5f; // 5 seconds to leave combat
+
+ // Regeneration (only out of combat or reduced in combat)
+ float regenMultiplier = player.IsInCombat ? 0.2f : 1f;
+ float regenRate = player.Stats.RegenRate * regenMultiplier * TickDelta;
+
+ player.Health = Math.Min(player.MaxHealth, player.Health + regenRate * 2);
+ player.Mana = Math.Min(player.MaxMana, player.Mana + regenRate);
+ player.Stamina = Math.Min(player.MaxStamina, player.Stamina + regenRate * 3);
+ }
+
+ ///
+ /// 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))
+ {
+ float dist = Distance(player.X, player.Y, mob.X, mob.Y);
+ if (dist > attackRange) continue;
+
+ // Check angle
+ float angleToMob = MathF.Atan2(mob.Y - player.Y, mob.X - player.X);
+ float angleDiff = NormalizeAngle(angleToMob - aimAngle);
+
+ if (MathF.Abs(angleDiff) > attackArc) continue;
+
+ // Hit!
+ int actualDamage = mob.Stats.CalculateDamage(damage, DamageType.Physical);
+ mob.Health -= actualDamage;
+
+ _pendingDamageEvents.Add(new DamageEvent
+ {
+ SourceType = EntityType.Player,
+ SourceId = (int)characterId,
+ TargetType = EntityType.Mob,
+ TargetId = mob.Id,
+ Damage = actualDamage,
+ DamageType = DamageType.Physical
+ });
+
+ // Check death
+ if (mob.Health <= 0)
+ {
+ MobDeath(mob, player);
+ }
+
+ // Only hit one mob per swing (for melee)
+ // TODO: Make this configurable for cleave weapons
+ break;
+ }
+ }
+
+ ///
+ /// Player attacks another player (PvP)
+ ///
+ public void PlayerAttackPlayer(ulong attackerId, ulong targetId, float aimAngle)
+ {
+ if (!Players.TryGetValue(attackerId, out var attacker) || !attacker.IsAlive)
+ return;
+ if (!Players.TryGetValue(targetId, out var target) || !target.IsAlive)
+ return;
+
+ // Check attack cooldown
+ float attackInterval = 1f / attacker.Stats.AttackSpeed;
+ if (CurrentTick - attacker.LastAttackTick < (long)(attackInterval * TicksPerSecond))
+ return;
+
+ attacker.LastAttackTick = CurrentTick;
+ attacker.LastCombatTick = CurrentTick;
+ target.LastCombatTick = CurrentTick;
+
+ float attackRange = attacker.WeaponRange > 0 ? attacker.WeaponRange : 50f;
+ float dist = Distance(attacker.X, attacker.Y, target.X, target.Y);
+ if (dist > attackRange) return;
+
+ int baseDamage = attacker.WeaponDamage > 0 ? attacker.WeaponDamage : 5 + attacker.Stats.Strength;
+ int damage = (int)(baseDamage * attacker.Stats.PhysicalDamageMultiplier);
+
+ // Apply target armor
+ if (target.Stats.Armor > 0)
+ {
+ float reduction = target.Stats.Armor / (float)(target.Stats.Armor + 100);
+ damage = (int)(damage * (1f - reduction));
+ }
+
+ damage = Math.Max(1, damage);
+ target.Health -= damage;
+
+ _pendingDamageEvents.Add(new DamageEvent
+ {
+ SourceType = EntityType.Player,
+ SourceId = (int)attackerId,
+ TargetType = EntityType.Player,
+ TargetId = (int)targetId,
+ Damage = damage,
+ DamageType = DamageType.Physical,
+ IsPvP = true
+ });
+
+ if (target.Health <= 0)
+ {
+ target.Health = 0;
+ target.IsAlive = false;
+ attacker.PlayersKilled++;
+
+ _pendingDeathEvents.Add(new DeathEvent
+ {
+ EntityType = EntityType.Player,
+ EntityId = (int)targetId,
+ KillerType = EntityType.Player,
+ KillerId = (int)attackerId,
+ EntityName = target.Name,
+ KillerName = attacker.Name,
+ IsPvP = true
+ });
+
+ // Transfer inventory to killer
+ attacker.Inventory.AddRange(target.Inventory);
+ target.Inventory.Clear();
+ }
+ }
+
+ private void MobDeath(MobInstance mob, PlayerInstance killer)
+ {
+ mob.Health = 0;
+ mob.IsAlive = false;
+ mob.State = MobState.Dead;
+
+ _pendingDeathEvents.Add(new DeathEvent
+ {
+ EntityType = EntityType.Mob,
+ EntityId = mob.Id,
+ KillerType = EntityType.Player,
+ KillerId = (int)killer.CharacterId,
+ EntityName = mob.Name,
+ KillerName = killer.Name,
+ XpReward = mob.Stats.XpReward
+ });
+
+ // Award XP
+ int xp = (int)(mob.Stats.XpReward * killer.Stats.XpBonus);
+ killer.XpGained += xp;
+
+ // Drop loot (including any player loot the mob was holding)
+ DropMobLoot(mob);
+ }
+
+ private void DropMobLoot(MobInstance mob)
+ {
+ // Drop any held player loot
+ foreach (var item in mob.HeldLoot)
+ {
+ CreateDroppedItem(mob.X, mob.Y, item);
+ }
+ mob.HeldLoot.Clear();
+
+ // TODO: Roll loot table for mob drops
+ // For now, just create some placeholder loot
+ if (mob.Type == MobType.Boss)
+ {
+ // Guaranteed drop from boss
+ _pendingLootEvents.Add(new LootEvent
+ {
+ X = mob.X,
+ Y = mob.Y,
+ MobId = mob.Id,
+ MobName = mob.Name,
+ IsBoss = true
+ });
+ }
+ }
+
+ private void CreateDroppedItem(float x, float y, ItemDrop item)
+ {
+ int id = _nextDroppedItemId++;
+ DroppedItems[id] = new DroppedItem
+ {
+ Id = id,
+ ItemDefinitionId = item.ItemDefinitionId,
+ Quantity = item.Quantity,
+ X = x + (new Random().NextSingle() - 0.5f) * 30,
+ Y = y + (new Random().NextSingle() - 0.5f) * 30,
+ DroppedAtTick = CurrentTick
+ };
+ }
+
+ private void SpawnExit()
+ {
+ // Spawn exit at boss room or last room
+ var lastRoom = Layout.Rooms.LastOrDefault();
+ if (lastRoom != null)
+ {
+ Layout.ExitPosition = new Point(lastRoom.CenterX, lastRoom.CenterY);
+ }
+ }
+
+ ///
+ /// Player picks up an item
+ ///
+ public bool TryPickupItem(ulong characterId, int droppedItemId)
+ {
+ if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive)
+ return false;
+
+ if (!DroppedItems.TryRemove(droppedItemId, out var item))
+ return false;
+
+ // Check distance
+ if (Distance(player.X, player.Y, item.X, item.Y) > 60)
+ {
+ // Too far, put item back
+ DroppedItems[droppedItemId] = item;
+ return false;
+ }
+
+ // Add to inventory
+ player.Inventory.Add(new ItemDrop
+ {
+ ItemDefinitionId = item.ItemDefinitionId,
+ Quantity = item.Quantity
+ });
+
+ return true;
+ }
+
+ ///
+ /// 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;
+ float dy = targetY - mob.Y;
+ float dist = MathF.Sqrt(dx * dx + dy * dy);
+
+ if (dist < 1) return;
+
+ float moveAmount = speed * TickDelta;
+ if (moveAmount > dist) moveAmount = dist;
+
+ float newX = mob.X + (dx / dist) * moveAmount;
+ float newY = mob.Y + (dy / dist) * moveAmount;
+
+ // Check collision with walls
+ if (CanMoveTo(newX, mob.Y)) mob.X = newX;
+ if (CanMoveTo(mob.X, newY)) mob.Y = newY;
+
+ // Update facing direction
+ mob.Rotation = MathF.Atan2(dy, dx);
+ }
+
+ public bool CanMoveTo(float x, float y)
+ {
+ int tileX = (int)(x / 32);
+ int tileY = (int)(y / 32);
+
+ if (tileX < 0 || tileX >= Layout.Width || tileY < 0 || tileY >= Layout.Height)
+ return false;
+
+ return Layout.Tiles[tileX, tileY] == 1;
+ }
+
+ private static float Distance(float x1, float y1, float x2, float y2)
+ {
+ float dx = x2 - x1;
+ float dy = y2 - y1;
+ return MathF.Sqrt(dx * dx + dy * dy);
+ }
+
+ private static float NormalizeAngle(float angle)
+ {
+ while (angle > MathF.PI) angle -= MathF.PI * 2;
+ while (angle < -MathF.PI) angle += MathF.PI * 2;
+ return angle;
+ }
+}
+
+// Runtime instances
+
+public class PlayerInstance
+{
+ public ulong CharacterId { get; set; }
+ public string Name { get; set; } = "";
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float Rotation { get; set; }
+
+ public float Health { get; set; }
+ public float MaxHealth { get; set; }
+ public float Mana { get; set; }
+ public float MaxMana { get; set; }
+ public float Stamina { get; set; }
+ public float MaxStamina { get; set; }
+
+ public bool IsAlive { get; set; } = true;
+ public bool IsInCombat { get; set; }
+
+ public CharacterCombatStats Stats { get; set; } = new();
+
+ // Equipped weapon stats
+ public int WeaponDamage { get; set; }
+ public float WeaponRange { get; set; }
+ public DamageType WeaponDamageType { get; set; } = DamageType.Physical;
+
+ // Inventory (items being carried)
+ public List 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
+{
+ Active,
+ Cleared,
+ Abandoned
+}
diff --git a/Migrations/20251205131939_DungeonDiver.Designer.cs b/Migrations/20251205131939_DungeonDiver.Designer.cs
new file mode 100644
index 0000000..79b806d
--- /dev/null
+++ b/Migrations/20251205131939_DungeonDiver.Designer.cs
@@ -0,0 +1,836 @@
+//
+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("20251205131939_DungeonDiver")]
+ partial class DungeonDiver
+ {
+ ///
+ 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.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("IsEnabled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("tinyint(1)")
+ .HasDefaultValue(true);
+
+ b.Property("LootValue")
+ .HasColumnType("int");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("PelletCount")
+ .HasColumnType("int");
+
+ b.Property("ProjectileSpeed")
+ .HasColumnType("float");
+
+ b.Property("Range")
+ .HasColumnType("float");
+
+ b.Property("ScanCooldown")
+ .HasColumnType("float");
+
+ b.Property("ScanRadius")
+ .HasColumnType("float");
+
+ b.Property("ShieldBoostDuration")
+ .HasColumnType("float");
+
+ b.Property("ShieldDuration")
+ .HasColumnType("float");
+
+ b.Property("ShieldHealth")
+ .HasColumnType("int");
+
+ b.Property("SpeedBoostDuration")
+ .HasColumnType("float");
+
+ b.Property("SpeedMultiplier")
+ .HasColumnType("float");
+
+ b.Property("SpeedPenalty")
+ .HasColumnType("float");
+
+ b.Property("Spread")
+ .HasColumnType("float");
+
+ b.Property("Stackable")
+ .HasColumnType("tinyint(1)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("Category");
+
+ b.HasIndex("IsEnabled");
+
+ b.ToTable("game_items", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.GameRecipe", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("int");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("EnergyCost")
+ .HasColumnType("int");
+
+ b.Property("IsEnabled")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("tinyint(1)")
+ .HasDefaultValue(true);
+
+ b.Property("RareCost")
+ .HasColumnType("int");
+
+ b.Property("ResultItemId")
+ .HasColumnType("int");
+
+ b.Property("ScrapCost")
+ .HasColumnType("int");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("IsEnabled");
+
+ b.HasIndex("ResultItemId");
+
+ b.ToTable("game_recipes", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.InventoryItem", 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("Quantity")
+ .HasColumnType("int unsigned");
+
+ b.Property("SlotIndex")
+ .HasColumnType("int unsigned");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("CharacterId");
+
+ b.HasIndex("ItemTemplateId");
+
+ b.HasIndex("CharacterId", "SlotIndex")
+ .IsUnique();
+
+ b.ToTable("inventories", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.ItemTemplate", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("ItemType")
+ .HasColumnType("tinyint unsigned");
+
+ b.Property("MaxStack")
+ .HasColumnType("int unsigned");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("Rarity")
+ .HasColumnType("tinyint unsigned");
+
+ b.Property("StatsJson")
+ .HasColumnType("json");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Weight")
+ .HasColumnType("int unsigned");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Name")
+ .IsUnique();
+
+ b.ToTable("item_templates", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.MatchHistory", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("DamageDealt")
+ .HasColumnType("int");
+
+ b.Property("DamageTaken")
+ .HasColumnType("int");
+
+ b.Property("Deaths")
+ .HasColumnType("int");
+
+ b.Property("EloAfter")
+ .HasColumnType("int");
+
+ b.Property("EloChange")
+ .HasColumnType("int");
+
+ b.Property("EnergyCollected")
+ .HasColumnType("int");
+
+ b.Property("ItemsCrafted")
+ .HasColumnType("int");
+
+ b.Property("Kills")
+ .HasColumnType("int");
+
+ b.Property("MatchDurationSeconds")
+ .HasColumnType("int");
+
+ b.Property("MatchId")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.Property("Placement")
+ .HasColumnType("int");
+
+ b.Property("PlayedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("RareCollected")
+ .HasColumnType("int");
+
+ b.Property("Result")
+ .HasColumnType("int");
+
+ b.Property("ScrapCollected")
+ .HasColumnType("int");
+
+ b.Property("SurvivalTimeSeconds")
+ .HasColumnType("int");
+
+ b.Property("TotalPlayers")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId");
+
+ b.HasIndex("MatchId");
+
+ b.HasIndex("PlayedAt");
+
+ b.ToTable("match_history", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Old_Character", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("AppearanceJson")
+ .HasColumnType("json");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("FacingDeg")
+ .HasColumnType("float");
+
+ b.Property("HpCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("HpMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("Level")
+ .HasColumnType("int unsigned");
+
+ b.Property("MpCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("MpMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.Property("PosX")
+ .HasColumnType("double");
+
+ b.Property("PosY")
+ .HasColumnType("double");
+
+ b.Property("PosZ")
+ .HasColumnType("double");
+
+ b.Property("StaminaCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("StaminaMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatDexterity")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatEndurance")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatIntelligence")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatStrength")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatWisdom")
+ .HasColumnType("int unsigned");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Xp")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("ZoneId")
+ .HasColumnType("bigint unsigned");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId")
+ .IsUnique();
+
+ b.HasIndex("ZoneId");
+
+ b.ToTable("characters", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.PlayerStats", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("Deaths")
+ .HasColumnType("int");
+
+ b.Property("Elo")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("int")
+ .HasDefaultValue(1000);
+
+ b.Property("Extractions")
+ .HasColumnType("int");
+
+ b.Property("ItemsCrafted")
+ .HasColumnType("int");
+
+ b.Property("Kills")
+ .HasColumnType("int");
+
+ b.Property("LongestSurvivalSeconds")
+ .HasColumnType("int");
+
+ b.Property("Losses")
+ .HasColumnType("int");
+
+ b.Property("MatchesPlayed")
+ .HasColumnType("int");
+
+ b.Property("TotalDamageDealt")
+ .HasColumnType("bigint");
+
+ b.Property("TotalDamageTaken")
+ .HasColumnType("bigint");
+
+ b.Property("TotalEnergyCollected")
+ .HasColumnType("bigint");
+
+ b.Property("TotalPlayTimeSeconds")
+ .HasColumnType("bigint");
+
+ b.Property("TotalRareCollected")
+ .HasColumnType("bigint");
+
+ b.Property("TotalScrapCollected")
+ .HasColumnType("bigint");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.Property("Wins")
+ .HasColumnType("int");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId")
+ .IsUnique();
+
+ b.ToTable("player_stats", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Session", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("CreatedIp")
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("RevokedAt")
+ .HasColumnType("datetime(6)");
+
+ b.Property("TokenHash")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("varchar(128)");
+
+ b.Property("UserAgent")
+ .HasMaxLength(256)
+ .HasColumnType("varchar(256)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId");
+
+ b.HasIndex("TokenHash")
+ .IsUnique();
+
+ b.ToTable("sessions", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.Zone", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("MaxX")
+ .HasColumnType("double");
+
+ b.Property("MaxY")
+ .HasColumnType("double");
+
+ b.Property("MaxZ")
+ .HasColumnType("double");
+
+ b.Property("MinX")
+ .HasColumnType("double");
+
+ b.Property("MinY")
+ .HasColumnType("double");
+
+ b.Property("MinZ")
+ .HasColumnType("double");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("varchar(64)");
+
+ b.Property("UpdatedAt")
+ .ValueGeneratedOnAddOrUpdate()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
+
+ b.HasKey("Id");
+
+ b.HasIndex("Name")
+ .IsUnique();
+
+ b.ToTable("zones", (string)null);
+ });
+
+ modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
+ {
+ b.HasOne("Server.Data.Old_Character", "Old_Character")
+ .WithMany()
+ .HasForeignKey("CharacterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
+ .WithMany()
+ .HasForeignKey("ItemTemplateId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired();
+
+ b.Navigation("ItemTemplate");
+
+ b.Navigation("Old_Character");
+ });
+
+ modelBuilder.Entity("Server.Data.GameRecipe", b =>
+ {
+ b.HasOne("Server.Data.GameItem", "ResultItem")
+ .WithMany()
+ .HasForeignKey("ResultItemId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("ResultItem");
+ });
+
+ modelBuilder.Entity("Server.Data.InventoryItem", b =>
+ {
+ b.HasOne("Server.Data.Old_Character", "Old_Character")
+ .WithMany()
+ .HasForeignKey("CharacterId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
+ .WithMany()
+ .HasForeignKey("ItemTemplateId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired();
+
+ b.Navigation("ItemTemplate");
+
+ b.Navigation("Old_Character");
+ });
+
+ modelBuilder.Entity("Server.Data.MatchHistory", b =>
+ {
+ b.HasOne("Server.Data.Account", "Account")
+ .WithMany()
+ .HasForeignKey("AccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Account");
+ });
+
+ modelBuilder.Entity("Server.Data.Old_Character", b =>
+ {
+ b.HasOne("Server.Data.Account", "Account")
+ .WithMany("Characters")
+ .HasForeignKey("AccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Server.Data.Zone", "Zone")
+ .WithMany()
+ .HasForeignKey("ZoneId")
+ .OnDelete(DeleteBehavior.Restrict)
+ .IsRequired();
+
+ b.Navigation("Account");
+
+ b.Navigation("Zone");
+ });
+
+ modelBuilder.Entity("Server.Data.PlayerStats", b =>
+ {
+ b.HasOne("Server.Data.Account", "Account")
+ .WithOne()
+ .HasForeignKey("Server.Data.PlayerStats", "AccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Account");
+ });
+
+ modelBuilder.Entity("Server.Data.Session", b =>
+ {
+ b.HasOne("Server.Data.Account", "Account")
+ .WithMany("Sessions")
+ .HasForeignKey("AccountId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Account");
+ });
+
+ modelBuilder.Entity("Server.Data.Account", b =>
+ {
+ b.Navigation("Characters");
+
+ b.Navigation("Sessions");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Migrations/20251205131939_DungeonDiver.cs b/Migrations/20251205131939_DungeonDiver.cs
new file mode 100644
index 0000000..6110fdd
--- /dev/null
+++ b/Migrations/20251205131939_DungeonDiver.cs
@@ -0,0 +1,22 @@
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace SystemRevivalServer.Migrations
+{
+ ///
+ public partial class DungeonDiver : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+
+ }
+ }
+}
diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs
index d2044b7..e76c785 100644
--- a/Migrations/GameDbContextModelSnapshot.cs
+++ b/Migrations/GameDbContextModelSnapshot.cs
@@ -81,101 +81,6 @@ namespace SystemRevivalServer.Migrations
b.ToTable("accounts", (string)null);
});
- modelBuilder.Entity("Server.Data.Character", b =>
- {
- b.Property("Id")
- .ValueGeneratedOnAdd()
- .HasColumnType("bigint unsigned");
-
- MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
-
- b.Property("AccountId")
- .HasColumnType("bigint unsigned");
-
- b.Property("AppearanceJson")
- .HasColumnType("json");
-
- b.Property("CreatedAt")
- .ValueGeneratedOnAdd()
- .HasColumnType("datetime(6)")
- .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
-
- b.Property("FacingDeg")
- .HasColumnType("float");
-
- b.Property("HpCurrent")
- .HasColumnType("int unsigned");
-
- b.Property("HpMax")
- .HasColumnType("int unsigned");
-
- b.Property("Level")
- .HasColumnType("int unsigned");
-
- b.Property("MpCurrent")
- .HasColumnType("int unsigned");
-
- b.Property("MpMax")
- .HasColumnType("int unsigned");
-
- b.Property("Name")
- .IsRequired()
- .HasMaxLength(32)
- .HasColumnType("varchar(32)");
-
- b.Property("PosX")
- .HasColumnType("double");
-
- b.Property("PosY")
- .HasColumnType("double");
-
- b.Property("PosZ")
- .HasColumnType("double");
-
- b.Property("StaminaCurrent")
- .HasColumnType("int unsigned");
-
- b.Property("StaminaMax")
- .HasColumnType("int unsigned");
-
- b.Property("StatDexterity")
- .HasColumnType("int unsigned");
-
- b.Property("StatEndurance")
- .HasColumnType("int unsigned");
-
- b.Property("StatIntelligence")
- .HasColumnType("int unsigned");
-
- b.Property("StatStrength")
- .HasColumnType("int unsigned");
-
- b.Property("StatWisdom")
- .HasColumnType("int unsigned");
-
- b.Property("UpdatedAt")
- .ValueGeneratedOnAddOrUpdate()
- .HasColumnType("datetime(6)")
- .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
-
- MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt"));
-
- b.Property("Xp")
- .HasColumnType("bigint unsigned");
-
- b.Property("ZoneId")
- .HasColumnType("bigint unsigned");
-
- b.HasKey("Id");
-
- b.HasIndex("AccountId")
- .IsUnique();
-
- b.HasIndex("ZoneId");
-
- b.ToTable("characters", (string)null);
- });
-
modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
{
b.Property("Id")
@@ -546,6 +451,101 @@ namespace SystemRevivalServer.Migrations
b.ToTable("match_history", (string)null);
});
+ modelBuilder.Entity("Server.Data.Old_Character", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("bigint unsigned");
+
+ MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id"));
+
+ b.Property("AccountId")
+ .HasColumnType("bigint unsigned");
+
+ b.Property("AppearanceJson")
+ .HasColumnType("json");
+
+ b.Property("CreatedAt")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("datetime(6)")
+ .HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
+
+ b.Property("FacingDeg")
+ .HasColumnType("float");
+
+ b.Property("HpCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("HpMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("Level")
+ .HasColumnType("int unsigned");
+
+ b.Property("MpCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("MpMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("varchar(32)");
+
+ b.Property("PosX")
+ .HasColumnType("double");
+
+ b.Property("PosY")
+ .HasColumnType("double");
+
+ b.Property("PosZ")
+ .HasColumnType("double");
+
+ b.Property("StaminaCurrent")
+ .HasColumnType("int unsigned");
+
+ b.Property("StaminaMax")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatDexterity")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatEndurance")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatIntelligence")
+ .HasColumnType("int unsigned");
+
+ b.Property("StatStrength")
+ .HasColumnType("int unsigned");
+
+ b.Property