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("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") @@ -720,7 +720,67 @@ namespace SystemRevivalServer.Migrations b.ToTable("zones", (string)null); }); - modelBuilder.Entity("Server.Data.Character", b => + 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") @@ -739,66 +799,6 @@ namespace SystemRevivalServer.Migrations b.Navigation("Zone"); }); - modelBuilder.Entity("Server.Data.EquipmentSlot", b => - { - b.HasOne("Server.Data.Character", "Character") - .WithMany() - .HasForeignKey("CharacterId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") - .WithMany() - .HasForeignKey("ItemTemplateId") - .OnDelete(DeleteBehavior.Restrict) - .IsRequired(); - - b.Navigation("Character"); - - b.Navigation("ItemTemplate"); - }); - - 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.Character", "Character") - .WithMany() - .HasForeignKey("CharacterId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") - .WithMany() - .HasForeignKey("ItemTemplateId") - .OnDelete(DeleteBehavior.Restrict) - .IsRequired(); - - b.Navigation("Character"); - - b.Navigation("ItemTemplate"); - }); - - 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.PlayerStats", b => { b.HasOne("Server.Data.Account", "Account") diff --git a/Services/Characters/CharacterService.cs b/Services/Characters/CharacterService.cs index 9971425..3ef70a9 100644 --- a/Services/Characters/CharacterService.cs +++ b/Services/Characters/CharacterService.cs @@ -12,13 +12,13 @@ public sealed class CharacterService : ICharacterService public CharacterService(ILogger log, ICharactersRepository repo) { _log = log; _repo = repo; } - public async Task<(bool ok, string? error, Character[] list)> ListAsync(ulong accountId, CancellationToken ct) + public async Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct) { var one = await _repo.FindByAccountAsync(accountId, ct); - return (true, null, one is null ? Array.Empty() : new[] { one }); + return (true, null, one is null ? Array.Empty() : new[] { one }); } - public async Task<(bool ok, string? error, Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct) + public async Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct) { if (string.IsNullOrWhiteSpace(name) || name.Length is < 3 or > 32) return (false, "invalid_name", null!); @@ -35,7 +35,7 @@ public sealed class CharacterService : ICharacterService var now = DateTime.UtcNow; - var c = new Character + var c = new Old_Character { AccountId = accountId, Name = name, @@ -72,7 +72,7 @@ public sealed class CharacterService : ICharacterService return (true, null, created); } - public async Task<(bool ok, string? error, Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct) + public async Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct) { var c = await _repo.FindByIdAsync(characterId, ct); if (c is null || c.AccountId != accountId) diff --git a/Services/Characters/ICharacterRepository.cs b/Services/Characters/ICharacterRepository.cs index 3440a04..7d820d7 100644 --- a/Services/Characters/ICharacterRepository.cs +++ b/Services/Characters/ICharacterRepository.cs @@ -4,10 +4,10 @@ namespace Server.Data; public interface ICharactersRepository { - Task FindByIdAsync(ulong id, CancellationToken ct); - Task FindByNameAsync(string name, CancellationToken ct); - Task FindByAccountAsync(ulong accountId, CancellationToken ct); // 1 char / account (unique) - Task AddAsync(Character c, CancellationToken ct); + Task FindByIdAsync(ulong id, CancellationToken ct); + Task FindByNameAsync(string name, CancellationToken ct); + Task FindByAccountAsync(ulong accountId, CancellationToken ct); // 1 char / account (unique) + Task AddAsync(Old_Character c, CancellationToken ct); Task SaveAsync(CancellationToken ct); } @@ -16,16 +16,16 @@ public sealed class CharactersRepository : ICharactersRepository private readonly GameDbContext _db; public CharactersRepository(GameDbContext db) => _db = db; - public Task FindByIdAsync(ulong id, CancellationToken ct) => + public Task FindByIdAsync(ulong id, CancellationToken ct) => _db.Characters.FirstOrDefaultAsync(x => x.Id == id, ct); - public Task FindByNameAsync(string name, CancellationToken ct) => + public Task FindByNameAsync(string name, CancellationToken ct) => _db.Characters.FirstOrDefaultAsync(x => x.Name == name, ct); - public Task FindByAccountAsync(ulong accountId, CancellationToken ct) => + public Task FindByAccountAsync(ulong accountId, CancellationToken ct) => _db.Characters.FirstOrDefaultAsync(x => x.AccountId == accountId, ct); - public async Task AddAsync(Character c, CancellationToken ct) + public async Task AddAsync(Old_Character c, CancellationToken ct) { _db.Characters.Add(c); await _db.SaveChangesAsync(ct); diff --git a/Services/Characters/ICharacterService.cs b/Services/Characters/ICharacterService.cs index cd34b03..bc4df5d 100644 --- a/Services/Characters/ICharacterService.cs +++ b/Services/Characters/ICharacterService.cs @@ -4,7 +4,7 @@ namespace Server.Services.Characters; public interface ICharacterService { - Task<(bool ok, string? error, Character[] list)> ListAsync(ulong accountId, CancellationToken ct); - Task<(bool ok, string? error, Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct); - Task<(bool ok, string? error, Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct); + Task<(bool ok, string? error, Old_Character[] list)> ListAsync(ulong accountId, CancellationToken ct); + Task<(bool ok, string? error, Old_Character created)> CreateAsync(ulong accountId, string name, CancellationToken ct); + Task<(bool ok, string? error, Old_Character selected)> SelectAsync(ulong accountId, ulong characterId, CancellationToken ct); } diff --git a/Services/World/WorldService.cs b/Services/World/WorldService.cs index 5e84734..eb108ce 100644 --- a/Services/World/WorldService.cs +++ b/Services/World/WorldService.cs @@ -36,7 +36,7 @@ public sealed class WorldService : IWorldService { // Prefer Redis presence; fallback to DB row. var pos = await _presence.GetAsync(characterId, ct); - Character? row; + Old_Character? row; if (pos is null) { diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index 372c9b9..8e94d25 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -9,7 +9,7 @@ public sealed class GameDbContext : DbContext public DbSet Accounts => Set(); public DbSet Sessions => Set(); - public DbSet Characters => Set(); + public DbSet Characters => Set(); public DbSet Zones => Set(); public DbSet ItemTemplates => Set(); public DbSet Inventory => Set(); diff --git a/data/entities/Account.cs b/data/entities/Account.cs index fd62b95..c8a092f 100644 --- a/data/entities/Account.cs +++ b/data/entities/Account.cs @@ -20,7 +20,7 @@ public sealed class Account public DateTime UpdatedAt { get; set; } public ICollection Sessions { get; set; } = new List(); - public ICollection Characters { get; set; } = new List(); + public ICollection Characters { get; set; } = new List(); // Helper methods public bool IsAdmin => Role == AccountRole.Admin || Role == AccountRole.SuperAdmin; diff --git a/data/entities/Character.cs b/data/entities/Character.cs index 75712ae..7583220 100644 --- a/data/entities/Character.cs +++ b/data/entities/Character.cs @@ -1,64 +1,186 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Builders; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; -namespace Server.Data; +namespace DungeonCrawler.Data.Entities; -public sealed class Character +/// +/// Derived stats calculator - used at runtime +/// +public static class CharacterStats { - public ulong Id { get; set; } - public ulong AccountId { get; set; } - public string Name { get; set; } = ""; - - public uint Level { get; set; } = 1; - public ulong Xp { get; set; } = 0; - - public uint StatStrength { get; set; } = 1; - public uint StatDexterity { get; set; } = 1; - public uint StatWisdom { get; set; } = 1; - public uint StatIntelligence { get; set; } = 1; - public uint StatEndurance { get; set; } = 1; - - public uint HpCurrent { get; set; } = 10; - public uint HpMax { get; set; } = 10; - public uint MpCurrent { get; set; } = 0; - public uint MpMax { get; set; } = 0; - public uint StaminaCurrent { get; set; } = 0; - public uint StaminaMax { get; set; } = 0; - - public ulong ZoneId { get; set; } - public double PosX { get; set; } - public double PosY { get; set; } - public double PosZ { get; set; } - public float FacingDeg { get; set; } - - // store as JSON in MySQL 8 - public string? AppearanceJson { get; set; } - - public DateTime CreatedAt { get; set; } - public DateTime UpdatedAt { get; set; } - - public Account? Account { get; set; } - public Zone? Zone { get; set; } -} - -public sealed class CharacterConfig : IEntityTypeConfiguration -{ - public void Configure(EntityTypeBuilder e) + public static int GetMaxHealth(Character c) => 50 + (c.Endurance * 10); + public static int GetMaxMana(Character c) => 20 + (c.Wisdom * 8); + public static int GetMaxStamina(Character c) => 50 + (c.Endurance * 5); + public static float GetXpBonus(Character c) => 1.0f + (c.Wisdom * 0.02f); + public static float GetMoveSpeed(Character c) => 100f + (c.Dexterity * 2f); + public static float GetAttackSpeed(Character c) => 1.0f + (c.Dexterity * 0.02f); + public static float GetRegenRate(Character c) => 1.0f + (c.Endurance * 0.1f); + + /// + /// Calculate combat stats including equipment bonuses + /// + public static CharacterCombatStats GetCombatStats(Character c, List? equippedItems = null) { - e.ToTable("characters"); - e.HasKey(x => x.Id); - e.Property(x => x.Id).ValueGeneratedOnAdd(); - e.Property(x => x.Name).HasMaxLength(32).IsRequired(); + var stats = new CharacterCombatStats + { + Strength = c.Strength, + Intelligence = c.Intelligence, + Wisdom = c.Wisdom, + Endurance = c.Endurance, + Dexterity = c.Dexterity + }; + + if (equippedItems != null) + { + foreach (var item in equippedItems) + { + stats.Strength += item.BonusStrength; + stats.Intelligence += item.BonusIntelligence; + stats.Wisdom += item.BonusWisdom; + stats.Endurance += item.BonusEndurance; + stats.Dexterity += item.BonusDexterity; + stats.BonusHealth += item.BonusHealth; + stats.BonusMana += item.BonusMana; + stats.Armor += item.Armor; + stats.MagicResist += item.MagicResist; + } + } + + stats.MaxHealth = 50 + (stats.Endurance * 10) + stats.BonusHealth; + stats.MaxMana = 20 + (stats.Wisdom * 8) + stats.BonusMana; + stats.MaxStamina = 50 + (stats.Endurance * 5); + stats.MoveSpeed = 100f + (stats.Dexterity * 2f); + stats.AttackSpeed = 1.0f + (stats.Dexterity * 0.02f); + stats.RegenRate = 1.0f + (stats.Endurance * 0.1f); + stats.PhysicalDamageMultiplier = 1.0f + (stats.Strength * 0.05f); + stats.SpellDamageMultiplier = 1.0f + (stats.Intelligence * 0.05f); + stats.XpBonus = 1.0f + (stats.Wisdom * 0.02f); + + return stats; + } +} - e.HasIndex(x => x.AccountId).IsUnique(); // 1 character per account (change later if needed) - e.HasIndex(x => x.ZoneId); +public class CharacterCombatStats +{ + public int Strength { get; set; } + public int Intelligence { get; set; } + public int Wisdom { get; set; } + public int Endurance { get; set; } + public int Dexterity { get; set; } + public int MaxHealth { get; set; } + public int MaxMana { get; set; } + public int MaxStamina { get; set; } + public int BonusHealth { get; set; } + public int BonusMana { get; set; } + public int Armor { get; set; } + public int MagicResist { get; set; } + public float MoveSpeed { get; set; } + public float AttackSpeed { get; set; } + public float RegenRate { get; set; } + public float PhysicalDamageMultiplier { get; set; } + public float SpellDamageMultiplier { get; set; } + public float XpBonus { get; set; } +} - e.Property(x => x.AppearanceJson).HasColumnType("json"); - e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); - e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") - .ValueGeneratedOnAddOrUpdate(); +/// +/// Persistent player character with stats and equipment +/// +[Table("characters")] +public class Character +{ + [Key] + public ulong Id { get; set; } + + [Required] + public ulong AccountId { get; set; } + + [Required] + [MaxLength(32)] + public string Name { get; set; } = ""; + + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime LastPlayedAt { get; set; } = DateTime.UtcNow; + + // Progression + public int Level { get; set; } = 1; + public long Experience { get; set; } = 0; + public int UnspentStatPoints { get; set; } = 5; // Start with 5 points + + // Core Stats (5 points per level to distribute) + public int Strength { get; set; } = 1; // Physical damage, heavy equipment + public int Intelligence { get; set; } = 1; // Spell damage, magical equipment + public int Wisdom { get; set; } = 1; // Max mana, XP bonus, spell learning + public int Endurance { get; set; } = 1; // Max HP, max stamina, regen rate + public int Dexterity { get; set; } = 1; // Move speed, attack speed, light equipment + + // Derived stats (calculated from base stats) + [NotMapped] public int MaxHealth => 50 + (Endurance * 10); + [NotMapped] public int MaxMana => 20 + (Wisdom * 8); + [NotMapped] public int MaxStamina => 50 + (Endurance * 5); + [NotMapped] public float XpBonus => 1.0f + (Wisdom * 0.02f); // 2% per WIS + [NotMapped] public float MoveSpeed => 100f + (Dexterity * 2f); + [NotMapped] public float AttackSpeed => 1.0f + (Dexterity * 0.02f); + [NotMapped] public float RegenRate => 1.0f + (Endurance * 0.1f); // HP/Mana/Stamina regen multiplier + + // Current state (saved on logout/death) + public int CurrentHealth { get; set; } = 50; + public int CurrentMana { get; set; } = 20; + + // Equipment slots (ItemId references, null = empty) + public ulong? EquippedWeapon { get; set; } + public ulong? EquippedOffhand { get; set; } + public ulong? EquippedHead { get; set; } + public ulong? EquippedChest { get; set; } + public ulong? EquippedLegs { get; set; } + public ulong? EquippedBoots { get; set; } + public ulong? EquippedGloves { get; set; } + public ulong? EquippedAccessory { get; set; } + + // Lifetime stats + public int TotalKills { get; set; } + public int TotalDeaths { get; set; } + public int PlayersKilled { get; set; } + public int DungeonsCompleted { get; set; } + public int BossesKilled { get; set; } + + // Soft delete + public bool IsDeleted { get; set; } = false; + + // Navigation + public virtual Account? Account { get; set; } + public virtual ICollection Inventory { get; set; } = new List(); + public virtual ICollection Stash { get; set; } = new List(); + public virtual ICollection LearnedSpells { get; set; } = new List(); +} - e.HasOne(x => x.Account).WithMany(a => a.Characters).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade); - e.HasOne(x => x.Zone).WithMany().HasForeignKey(x => x.ZoneId).OnDelete(DeleteBehavior.Restrict); +/// +/// Experience required per level (exponential curve) +/// +public static class LevelSystem +{ + public static long GetXpForLevel(int level) + { + // Base 100 XP for level 2, scaling exponentially + return (long)(100 * Math.Pow(1.15, level - 1)); + } + + public static long GetTotalXpForLevel(int level) + { + long total = 0; + for (int i = 1; i < level; i++) + total += GetXpForLevel(i); + return total; + } + + public static int GetLevelForXp(long totalXp) + { + int level = 1; + long xpNeeded = 0; + while (xpNeeded <= totalXp) + { + xpNeeded += GetXpForLevel(level); + if (xpNeeded <= totalXp) level++; + } + return level; } } diff --git a/data/entities/Dungeon.cs b/data/entities/Dungeon.cs new file mode 100644 index 0000000..f754610 --- /dev/null +++ b/data/entities/Dungeon.cs @@ -0,0 +1,132 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace DungeonCrawler.Data.Entities; + +/// +/// Active dungeon instance (persists until cleared) +/// +[Table("dungeon_instances")] +public class DungeonInstance +{ + [Key] + public Guid Id { get; set; } = Guid.NewGuid(); + + public int Tier { get; set; } = 1; + public int Seed { get; set; } // For regenerating the same layout + + public DungeonStatus Status { get; set; } = DungeonStatus.Active; + + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public DateTime? CompletedAt { get; set; } + + // Dungeon state + public int TotalRooms { get; set; } + public int ClearedRooms { get; set; } + public int TotalMobs { get; set; } + public int RemainingMobs { get; set; } + public int TotalChests { get; set; } + public int OpenedChests { get; set; } + + // Serialized dungeon data (rooms, corridors, mob positions) + [MaxLength(65536)] + public string LayoutJson { get; set; } = "{}"; + + // Track who's been here + public virtual ICollection Visits { get; set; } = new List(); +} + +/// +/// Tracks character visits to dungeons +/// +[Table("dungeon_visits")] +public class DungeonVisit +{ + [Key] + public ulong Id { get; set; } + + public Guid DungeonId { get; set; } + public ulong CharacterId { get; set; } + + public DateTime EnteredAt { get; set; } = DateTime.UtcNow; + public DateTime? LeftAt { get; set; } + + public VisitOutcome Outcome { get; set; } = VisitOutcome.InProgress; + + public int MobsKilled { get; set; } + public int ChestsOpened { get; set; } + public int PlayersKilled { get; set; } + + // Navigation + public virtual DungeonInstance? Dungeon { get; set; } + public virtual Character? Character { get; set; } +} + + + +/// +/// Loot table for mobs and chests +/// +[Table("loot_tables")] +public class LootTable +{ + [Key] + public int Id { get; set; } + + [MaxLength(64)] + public string Name { get; set; } = ""; + + public LootSourceType SourceType { get; set; } + public int MinTier { get; set; } = 1; + + public virtual ICollection Entries { get; set; } = new List(); +} + +/// +/// Individual entry in a loot table +/// +[Table("loot_table_entries")] +public class LootTableEntry +{ + [Key] + public int Id { get; set; } + + public int LootTableId { get; set; } + public int ItemDefinitionId { get; set; } + + public float DropChance { get; set; } = 0.1f; // 0.0 - 1.0 + public int MinQuantity { get; set; } = 1; + public int MaxQuantity { get; set; } = 1; + + // Weight for weighted random selection + public int Weight { get; set; } = 100; + + // Navigation + public virtual LootTable? LootTable { get; set; } + public virtual ItemDefinition? ItemDefinition { get; set; } +} + +// Enums + +public enum DungeonStatus +{ + Active, // In progress + Completed, // All mobs dead, exit available + Abandoned // Cleanup candidate +} + +public enum VisitOutcome +{ + InProgress, + Extracted, // Left via exit/teleport + Died, + Disconnected +} + + +public enum LootSourceType +{ + Mob, + Chest, + Boss +} diff --git a/data/entities/EquipmentSlot.cs b/data/entities/EquipmentSlot.cs index 938330c..3eba9dd 100644 --- a/data/entities/EquipmentSlot.cs +++ b/data/entities/EquipmentSlot.cs @@ -12,7 +12,7 @@ public sealed class EquipmentSlot public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } - public Character? Character { get; set; } + public Old_Character? Old_Character { get; set; } public ItemTemplate? ItemTemplate { get; set; } } @@ -28,7 +28,7 @@ public sealed class EquipmentSlotConfig : IEntityTypeConfiguration x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") .ValueGeneratedOnAddOrUpdate(); - e.HasOne(x => x.Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); + e.HasOne(x => x.Old_Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict); } } diff --git a/data/entities/InventoryItem.cs b/data/entities/InventoryItem.cs index abd9d20..8bf1817 100644 --- a/data/entities/InventoryItem.cs +++ b/data/entities/InventoryItem.cs @@ -13,7 +13,7 @@ public sealed class InventoryItem public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } - public Character? Character { get; set; } + public Old_Character? Old_Character { get; set; } public ItemTemplate? ItemTemplate { get; set; } } @@ -30,7 +30,7 @@ public sealed class InventoryItemConfig : IEntityTypeConfiguration x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") .ValueGeneratedOnAddOrUpdate(); - e.HasOne(x => x.Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); + e.HasOne(x => x.Old_Character).WithMany().HasForeignKey(x => x.CharacterId).OnDelete(DeleteBehavior.Cascade); e.HasOne(x => x.ItemTemplate).WithMany().HasForeignKey(x => x.ItemTemplateId).OnDelete(DeleteBehavior.Restrict); } } diff --git a/data/entities/Items.cs b/data/entities/Items.cs new file mode 100644 index 0000000..9c393d0 --- /dev/null +++ b/data/entities/Items.cs @@ -0,0 +1,236 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace DungeonCrawler.Data.Entities; + +/// +/// Item template/definition - what an item IS +/// +[Table("item_definitions")] +public class ItemDefinition +{ + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + [MaxLength(256)] + public string Description { get; set; } = ""; + + public ItemType Type { get; set; } + public ItemRarity Rarity { get; set; } = ItemRarity.Common; + public EquipmentSlot? EquipSlot { get; set; } // Null if not equippable + + // Stat requirements to equip/use + public int RequiredStrength { get; set; } = 0; + public int RequiredIntelligence { get; set; } = 0; + public int RequiredWisdom { get; set; } = 0; + public int RequiredDexterity { get; set; } = 0; + public int RequiredLevel { get; set; } = 1; + + // Stat bonuses when equipped + public int BonusStrength { get; set; } = 0; + public int BonusIntelligence { get; set; } = 0; + public int BonusWisdom { get; set; } = 0; + public int BonusEndurance { get; set; } = 0; + public int BonusDexterity { get; set; } = 0; + public int BonusHealth { get; set; } = 0; + public int BonusMana { get; set; } = 0; + + // Weapon stats + public int MinDamage { get; set; } = 0; + public int MaxDamage { get; set; } = 0; + public float AttackRange { get; set; } = 0; // 0 = melee + public DamageType DamageType { get; set; } = DamageType.Physical; + + // Armor stats + public int Armor { get; set; } = 0; + public int MagicResist { get; set; } = 0; + + // Consumable effects + public int HealAmount { get; set; } = 0; + public int ManaRestore { get; set; } = 0; + public int StaminaRestore { get; set; } = 0; + + // Special + public bool IsTeleportScroll { get; set; } = false; + public int? TeachesSpellId { get; set; } // For spell tomes + + // Stacking + public bool Stackable { get; set; } = false; + public int MaxStack { get; set; } = 1; + + // Visuals + public int SpriteId { get; set; } = 0; + + public bool IsEnabled { get; set; } = true; +} + +/// +/// Actual item instance owned by a character (inventory or equipped) +/// +[Table("character_items")] +public class CharacterItem +{ + [Key] + public ulong Id { get; set; } + + public ulong CharacterId { get; set; } + public int ItemDefinitionId { get; set; } + + public int Quantity { get; set; } = 1; + public int SlotIndex { get; set; } // Inventory position (0-29 for example) + + public DateTime AcquiredAt { get; set; } = DateTime.UtcNow; + + // Navigation + public virtual Character? Character { get; set; } + public virtual ItemDefinition? Definition { get; set; } +} + +/// +/// Items stored in character's stash (safe storage in hub) +/// +[Table("stash_items")] +public class StashItem +{ + [Key] + public ulong Id { get; set; } + + public ulong CharacterId { get; set; } + public int ItemDefinitionId { get; set; } + + public int Quantity { get; set; } = 1; + public int SlotIndex { get; set; } + + public DateTime StoredAt { get; set; } = DateTime.UtcNow; + + // Navigation + public virtual Character? Character { get; set; } + public virtual ItemDefinition? Definition { get; set; } +} + +/// +/// Spell definition - learnable abilities +/// +[Table("spell_definitions")] +public class SpellDefinition +{ + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + [MaxLength(256)] + public string Description { get; set; } = ""; + + public SpellType Type { get; set; } + + // Requirements + public int RequiredWisdom { get; set; } = 1; + public int RequiredIntelligence { get; set; } = 0; + public int RequiredLevel { get; set; } = 1; + + // Costs + public int ManaCost { get; set; } = 10; + public float Cooldown { get; set; } = 1.0f; // Seconds + + // Effects + public int BaseDamage { get; set; } = 0; // Scales with INT + public int BaseHealing { get; set; } = 0; // Scales with WIS + public float Range { get; set; } = 100f; + public float AreaOfEffect { get; set; } = 0; // 0 = single target + + // Special + public bool IsTeleport { get; set; } = false; + public bool IsShield { get; set; } = false; + public int ShieldAmount { get; set; } = 0; + + // Visuals + public int SpriteId { get; set; } = 0; + public string EffectColor { get; set; } = "#ffffff"; + + public bool IsEnabled { get; set; } = true; +} + +/// +/// Spells a character has learned +/// +[Table("learned_spells")] +public class LearnedSpell +{ + [Key] + public ulong Id { get; set; } + + public ulong CharacterId { get; set; } + public int SpellDefinitionId { get; set; } + + public DateTime LearnedAt { get; set; } = DateTime.UtcNow; + + // Could add spell levels/upgrades later + public int SpellLevel { get; set; } = 1; + + // Navigation + public virtual Character? Character { get; set; } + public virtual SpellDefinition? Definition { get; set; } +} + +// Enums + +public enum ItemType +{ + Weapon, + Armor, + Accessory, + Consumable, + SpellTome, + Material, + Key, + TeleportScroll +} + +public enum ItemRarity +{ + Common = 0, + Uncommon = 1, + Rare = 2, + Epic = 3, + Legendary = 4 +} + +public enum EquipmentSlot +{ + Weapon, + Offhand, + Head, + Chest, + Legs, + Boots, + Gloves, + Accessory +} + +public enum DamageType +{ + Physical, + Fire, + Ice, + Lightning, + Poison, + Holy, + Dark +} + +public enum SpellType +{ + Damage, + Healing, + Buff, + Debuff, + Utility, + Summon +} diff --git a/data/entities/MobDefinition.cs b/data/entities/MobDefinition.cs new file mode 100644 index 0000000..34dd442 --- /dev/null +++ b/data/entities/MobDefinition.cs @@ -0,0 +1,438 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json; + +namespace DungeonCrawler.Data.Entities; + +/// +/// Monster/NPC template definition stored in database +/// +[Table("mob_definitions")] +public class MobDefinition +{ + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(64)] + public string Name { get; set; } = ""; + + [MaxLength(256)] + public string Description { get; set; } = ""; + + public MobType Type { get; set; } = MobType.Normal; + public MobCategory Category { get; set; } = MobCategory.Undead; + + public int MinTier { get; set; } = 1; // Minimum dungeon tier to spawn + public int MaxTier { get; set; } = 99; // Maximum tier (for progression gating) + + // Base Combat Stats + public int BaseHealth { get; set; } = 50; + public int BaseMana { get; set; } = 0; + public int BasePhysicalDamage { get; set; } = 5; + public int BaseMagicDamage { get; set; } = 0; + public int BaseArmor { get; set; } = 0; + public int BaseMagicResist { get; set; } = 0; + + // Movement & Combat + public float MoveSpeed { get; set; } = 60f; + public float AttackRange { get; set; } = 40f; // Melee range ~40, ranged 150+ + public float AttackSpeed { get; set; } = 1.0f; // Attacks per second + public float AggroRange { get; set; } = 150f; // Detection radius + public float LeashRange { get; set; } = 400f; // Max chase distance before reset + + // Scaling per dungeon tier (multipliers) + public float HealthPerTier { get; set; } = 1.2f; + public float DamagePerTier { get; set; } = 1.15f; + public float ArmorPerTier { get; set; } = 1.1f; + + // Experience & Loot + public int BaseXp { get; set; } = 10; + public float XpPerTier { get; set; } = 1.25f; + public int LootTableId { get; set; } = 0; // Reference to loot_tables + public float DropChanceMultiplier { get; set; } = 1.0f; + + /// + /// JSON block for resistances/weaknesses + /// Example: {"fire": -0.25, "ice": 0.5, "poison": 1.0} + /// Negative = weakness (takes more damage), Positive = resistance (takes less), 1.0 = immune + /// + [MaxLength(1024)] + public string ResistancesJson { get; set; } = "{}"; + + /// + /// JSON block for special abilities/behaviors + /// Example: {"canFlee": true, "fleeHealthPercent": 0.2, "callsForHelp": true} + /// + [MaxLength(1024)] + public string AbilitiesJson { get; set; } = "{}"; + + // Visuals - reference to sprite/animation + [MaxLength(128)] + public string SpriteSheet { get; set; } = "mobs/skeleton.png"; + public int SpriteIndex { get; set; } = 0; // Index in spritesheet + public int SpriteWidth { get; set; } = 32; + public int SpriteHeight { get; set; } = 32; + + [MaxLength(16)] + public string TintColor { get; set; } = "#ffffff"; // Color tint for variants + + // Animation frames (JSON array of frame indices) + [MaxLength(256)] + public string IdleFrames { get; set; } = "[0]"; + [MaxLength(256)] + public string WalkFrames { get; set; } = "[0,1,2,3]"; + [MaxLength(256)] + public string AttackFrames { get; set; } = "[4,5]"; + [MaxLength(256)] + public string DeathFrames { get; set; } = "[6,7]"; + + public float AnimationSpeed { get; set; } = 8f; // Frames per second + + public bool IsEnabled { get; set; } = true; + + // Helper methods for JSON parsing + [NotMapped] + public Dictionary Resistances + { + get + { + try { return JsonSerializer.Deserialize>(ResistancesJson) ?? new(); } + catch { return new(); } + } + set { ResistancesJson = JsonSerializer.Serialize(value); } + } + + [NotMapped] + public Dictionary Abilities + { + get + { + try { return JsonSerializer.Deserialize>(AbilitiesJson) ?? new(); } + catch { return new(); } + } + set { AbilitiesJson = JsonSerializer.Serialize(value); } + } + + /// + /// Calculate scaled stats for a specific dungeon tier + /// + public MobCombatStats GetStatsForTier(int tier) + { + float tierMultiplier = (float)Math.Pow(1.0 + (tier - MinTier) * 0.1, 1.0); + + return new MobCombatStats + { + MaxHealth = (int)(BaseHealth * Math.Pow(HealthPerTier, tier - 1)), + PhysicalDamage = (int)(BasePhysicalDamage * Math.Pow(DamagePerTier, tier - 1)), + MagicDamage = (int)(BaseMagicDamage * Math.Pow(DamagePerTier, tier - 1)), + Armor = (int)(BaseArmor * Math.Pow(ArmorPerTier, tier - 1)), + MagicResist = (int)(BaseMagicResist * Math.Pow(ArmorPerTier, tier - 1)), + MoveSpeed = MoveSpeed, + AttackRange = AttackRange, + AttackSpeed = AttackSpeed, + AggroRange = AggroRange, + LeashRange = LeashRange, + XpReward = (int)(BaseXp * Math.Pow(XpPerTier, tier - 1)), + Resistances = Resistances + }; + } +} + +/// +/// Runtime combat stats for a mob instance +/// +public class MobCombatStats +{ + public int MaxHealth { get; set; } + public int PhysicalDamage { get; set; } + public int MagicDamage { get; set; } + public int Armor { get; set; } + public int MagicResist { get; set; } + public float MoveSpeed { get; set; } + public float AttackRange { get; set; } + public float AttackSpeed { get; set; } + public float AggroRange { get; set; } + public float LeashRange { get; set; } + public int XpReward { get; set; } + public Dictionary Resistances { get; set; } = new(); + + /// + /// Calculate damage after resistances + /// + public int CalculateDamage(int rawDamage, DamageType damageType) + { + string typeKey = damageType.ToString().ToLower(); + + // Check for resistance/weakness + if (Resistances.TryGetValue(typeKey, out float resistance)) + { + if (resistance >= 1.0f) return 0; // Immune + return (int)(rawDamage * (1.0f - resistance)); + } + + // Physical/Magic armor reduction + if (damageType == DamageType.Physical && Armor > 0) + { + // Armor formula: damage reduction = armor / (armor + 100) + float reduction = Armor / (float)(Armor + 100); + return (int)(rawDamage * (1.0f - reduction)); + } + + if (damageType != DamageType.Physical && MagicResist > 0) + { + float reduction = MagicResist / (float)(MagicResist + 100); + return (int)(rawDamage * (1.0f - reduction)); + } + + return rawDamage; + } +} + +public enum MobType +{ + Normal, // Standard enemy + Elite, // Stronger, better loot + Miniboss, // Mini-boss, guaranteed drop + Boss, // Floor boss, best loot + Swarm // Weak but spawns in groups +} + +public enum MobCategory +{ + Undead, // Skeletons, zombies, ghosts + Beast, // Wolves, spiders, bats + Demon, // Imps, demons + Humanoid, // Bandits, cultists + Elemental, // Fire/ice/lightning elementals + Construct, // Golems, animated armor + Dragon, // Dragons, drakes + Aberration // Slimes, mimics, eldritch +} + +// DamageType enum is defined in Items.cs + +/// +/// Default mob templates for seeding the database +/// +public static class DefaultMobs +{ + public static List GetDefaultMobs() => new() + { + // Tier 1 - Basic enemies + new MobDefinition + { + Id = 1, + Name = "Skeleton", + Description = "A reanimated pile of bones", + Type = MobType.Normal, + Category = MobCategory.Undead, + MinTier = 1, + BaseHealth = 40, + BasePhysicalDamage = 5, + BaseArmor = 5, + MoveSpeed = 55f, + AttackRange = 40f, + AttackSpeed = 0.8f, + AggroRange = 120f, + BaseXp = 15, + ResistancesJson = """{"poison": 1.0, "holy": -0.5}""", + SpriteSheet = "mobs/skeleton.png" + }, + new MobDefinition + { + Id = 2, + Name = "Zombie", + Description = "A shambling corpse", + Type = MobType.Normal, + Category = MobCategory.Undead, + MinTier = 1, + BaseHealth = 60, + BasePhysicalDamage = 8, + BaseArmor = 0, + MoveSpeed = 35f, + AttackRange = 35f, + AttackSpeed = 0.5f, + AggroRange = 100f, + BaseXp = 12, + ResistancesJson = """{"poison": 1.0, "fire": -0.25, "holy": -0.5}""", + SpriteSheet = "mobs/zombie.png" + }, + new MobDefinition + { + Id = 3, + Name = "Giant Rat", + Description = "An oversized rodent", + Type = MobType.Swarm, + Category = MobCategory.Beast, + MinTier = 1, + BaseHealth = 20, + BasePhysicalDamage = 3, + BaseArmor = 0, + MoveSpeed = 80f, + AttackRange = 30f, + AttackSpeed = 1.5f, + AggroRange = 80f, + BaseXp = 5, + ResistancesJson = """{"poison": 0.5}""", + SpriteSheet = "mobs/rat.png" + }, + new MobDefinition + { + Id = 4, + Name = "Giant Spider", + Description = "A venomous arachnid", + Type = MobType.Normal, + Category = MobCategory.Beast, + MinTier = 1, + BaseHealth = 35, + BasePhysicalDamage = 4, + BaseMagicDamage = 3, // Poison + BaseArmor = 2, + MoveSpeed = 70f, + AttackRange = 35f, + AttackSpeed = 1.2f, + AggroRange = 130f, + BaseXp = 18, + ResistancesJson = """{"poison": 1.0}""", + AbilitiesJson = """{"poisonOnHit": true, "poisonDamage": 2, "poisonDuration": 3}""", + SpriteSheet = "mobs/spider.png" + }, + + // Tier 1 Elite + new MobDefinition + { + Id = 10, + Name = "Skeleton Knight", + Description = "An armored skeleton warrior", + Type = MobType.Elite, + Category = MobCategory.Undead, + MinTier = 1, + BaseHealth = 120, + BasePhysicalDamage = 12, + BaseArmor = 20, + MoveSpeed = 50f, + AttackRange = 45f, + AttackSpeed = 0.7f, + AggroRange = 150f, + BaseXp = 50, + ResistancesJson = """{"poison": 1.0, "holy": -0.5, "physical": 0.1}""", + SpriteSheet = "mobs/skeleton_knight.png" + }, + + // Tier 1 Boss + new MobDefinition + { + Id = 100, + Name = "The Bone Lord", + Description = "A massive skeleton wielding dark magic", + Type = MobType.Boss, + Category = MobCategory.Undead, + MinTier = 1, + MaxTier = 2, + BaseHealth = 500, + BaseMana = 100, + BasePhysicalDamage = 20, + BaseMagicDamage = 15, + BaseArmor = 30, + BaseMagicResist = 20, + MoveSpeed = 40f, + AttackRange = 50f, + AttackSpeed = 0.6f, + AggroRange = 300f, + LeashRange = 800f, + BaseXp = 500, + ResistancesJson = """{"poison": 1.0, "dark": 0.5, "holy": -0.75}""", + AbilitiesJson = """{"summonSkeletons": true, "summonCount": 3, "summonCooldown": 15}""", + SpriteSheet = "mobs/bone_lord.png", + SpriteWidth = 64, + SpriteHeight = 64 + }, + + // Tier 2 - Intermediate enemies + new MobDefinition + { + Id = 20, + Name = "Imp", + Description = "A small demonic creature", + Type = MobType.Normal, + Category = MobCategory.Demon, + MinTier = 2, + BaseHealth = 45, + BaseMagicDamage = 8, + BaseMagicResist = 15, + MoveSpeed = 75f, + AttackRange = 100f, // Ranged + AttackSpeed = 1.0f, + AggroRange = 180f, + BaseXp = 25, + ResistancesJson = """{"fire": 0.75, "holy": -0.5}""", + SpriteSheet = "mobs/imp.png" + }, + new MobDefinition + { + Id = 21, + Name = "Cultist", + Description = "A dark magic practitioner", + Type = MobType.Normal, + Category = MobCategory.Humanoid, + MinTier = 2, + BaseHealth = 50, + BaseMagicDamage = 10, + BaseArmor = 5, + BaseMagicResist = 10, + MoveSpeed = 55f, + AttackRange = 120f, // Ranged + AttackSpeed = 0.8f, + AggroRange = 200f, + BaseXp = 30, + ResistancesJson = """{"dark": 0.25, "holy": -0.25}""", + SpriteSheet = "mobs/cultist.png" + }, + + // Tier 3 - Advanced enemies + new MobDefinition + { + Id = 30, + Name = "Stone Golem", + Description = "An animated statue", + Type = MobType.Elite, + Category = MobCategory.Construct, + MinTier = 3, + BaseHealth = 300, + BasePhysicalDamage = 25, + BaseArmor = 50, + BaseMagicResist = 30, + MoveSpeed = 30f, + AttackRange = 50f, + AttackSpeed = 0.4f, + AggroRange = 100f, + BaseXp = 100, + ResistancesJson = """{"poison": 1.0, "physical": 0.3, "lightning": -0.25}""", + SpriteSheet = "mobs/golem.png", + SpriteWidth = 48, + SpriteHeight = 48 + }, + new MobDefinition + { + Id = 31, + Name = "Fire Elemental", + Description = "A living flame", + Type = MobType.Normal, + Category = MobCategory.Elemental, + MinTier = 3, + BaseHealth = 80, + BaseMagicDamage = 18, + BaseMagicResist = 25, + MoveSpeed = 65f, + AttackRange = 80f, + AttackSpeed = 1.2f, + AggroRange = 160f, + BaseXp = 45, + ResistancesJson = """{"fire": 1.0, "ice": -0.75, "physical": 0.5}""", + AbilitiesJson = """{"burnOnHit": true, "burnDamage": 5, "burnDuration": 4}""", + SpriteSheet = "mobs/fire_elemental.png", + TintColor = "#ff6600" + } + }; +} diff --git a/data/entities/Old_Character.cs b/data/entities/Old_Character.cs new file mode 100644 index 0000000..20a4848 --- /dev/null +++ b/data/entities/Old_Character.cs @@ -0,0 +1,64 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +public sealed class Old_Character +{ + public ulong Id { get; set; } + public ulong AccountId { get; set; } + public string Name { get; set; } = ""; + + public uint Level { get; set; } = 1; + public ulong Xp { get; set; } = 0; + + public uint StatStrength { get; set; } = 1; + public uint StatDexterity { get; set; } = 1; + public uint StatWisdom { get; set; } = 1; + public uint StatIntelligence { get; set; } = 1; + public uint StatEndurance { get; set; } = 1; + + public uint HpCurrent { get; set; } = 10; + public uint HpMax { get; set; } = 10; + public uint MpCurrent { get; set; } = 0; + public uint MpMax { get; set; } = 0; + public uint StaminaCurrent { get; set; } = 0; + public uint StaminaMax { get; set; } = 0; + + public ulong ZoneId { get; set; } + public double PosX { get; set; } + public double PosY { get; set; } + public double PosZ { get; set; } + public float FacingDeg { get; set; } + + // store as JSON in MySQL 8 + public string? AppearanceJson { get; set; } + + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + public Account? Account { get; set; } + public Zone? Zone { get; set; } +} + +public sealed class CharacterConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("characters"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + e.Property(x => x.Name).HasMaxLength(32).IsRequired(); + + e.HasIndex(x => x.AccountId).IsUnique(); // 1 character per account (change later if needed) + e.HasIndex(x => x.ZoneId); + + e.Property(x => x.AppearanceJson).HasColumnType("json"); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + + e.HasOne(x => x.Account).WithMany(a => a.Characters).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade); + e.HasOne(x => x.Zone).WithMany().HasForeignKey(x => x.ZoneId).OnDelete(DeleteBehavior.Restrict); + } +}