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; }