From 311b55c7cca9f380794b082a7f086a1cc6e96718 Mon Sep 17 00:00:00 2001 From: dingo Date: Sat, 6 Dec 2025 18:06:03 -0500 Subject: [PATCH] big changes --- Game/Dungeon/ChestInstance.cs | 20 + Game/Dungeon/DungeonChestSpawn.cs | 18 + Game/Dungeon/DungeonGameHandler.cs | 729 --------- Game/Dungeon/DungeonGenerator.cs | 235 +-- Game/Dungeon/DungeonHandler.cs | 745 +++++++++ Game/Dungeon/DungeonInstance.cs | 13 + Game/Dungeon/DungeonLayout.cs | 89 + Game/Dungeon/DungeonMobSpawn.cs | 18 + Game/Dungeon/DungeonPlayerSession.cs | 24 + Game/Dungeon/DungeonPoint.cs | 9 + Game/Dungeon/DungeonRoom.cs | 37 + Game/Dungeon/DungeonSimulation.cs | 655 ++------ Game/Dungeon/MobInstance.cs | 47 + Game/Dungeon/PlayerInstance.cs | 43 + Game/Dungeon/TickResult.cs | 38 + ...0532_AddDungeonCrawlerEntities.Designer.cs | 1439 +++++++++++++++++ ...0251206230532_AddDungeonCrawlerEntities.cs | 354 ++++ Migrations/GameDbContextModelSnapshot.cs | 603 +++++++ Networking/Messages/DungeonOpCodes.cs | 35 + Program.cs | 3 + data/GameDbContext.cs | 11 +- data/entities/DefaultDungeonMobs.cs | 228 +++ data/entities/DungeonCharacter.cs | 75 + data/entities/DungeonCharacterCombatStats.cs | 23 + data/entities/DungeonCharacterItem.cs | 26 + data/entities/DungeonCharacterStats.cs | 58 + data/entities/DungeonItemDefinition.cs | 70 + data/entities/DungeonLearnedSpell.cs | 26 + data/entities/DungeonMobCombatStats.cs | 53 + data/entities/DungeonMobDefinition.cs | 139 ++ data/entities/DungeonSpellDefinition.cs | 50 + data/entities/DungeonStashItem.cs | 26 + data/entities/LevelSystem.cs | 33 + data/enums/DamageType.cs | 12 + data/enums/DungeonEquipmentSlot.cs | 13 + data/enums/ItemRarity.cs | 10 + data/enums/ItemType.cs | 13 + data/enums/MobCategory.cs | 13 + data/enums/MobType.cs | 10 + data/enums/PlayerState.cs | 7 + data/enums/SpellType.cs | 11 + 41 files changed, 4582 insertions(+), 1479 deletions(-) create mode 100644 Game/Dungeon/ChestInstance.cs create mode 100644 Game/Dungeon/DungeonChestSpawn.cs delete mode 100644 Game/Dungeon/DungeonGameHandler.cs create mode 100644 Game/Dungeon/DungeonHandler.cs create mode 100644 Game/Dungeon/DungeonInstance.cs create mode 100644 Game/Dungeon/DungeonLayout.cs create mode 100644 Game/Dungeon/DungeonMobSpawn.cs create mode 100644 Game/Dungeon/DungeonPlayerSession.cs create mode 100644 Game/Dungeon/DungeonPoint.cs create mode 100644 Game/Dungeon/DungeonRoom.cs create mode 100644 Game/Dungeon/MobInstance.cs create mode 100644 Game/Dungeon/PlayerInstance.cs create mode 100644 Game/Dungeon/TickResult.cs create mode 100644 Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs create mode 100644 Migrations/20251206230532_AddDungeonCrawlerEntities.cs create mode 100644 Networking/Messages/DungeonOpCodes.cs create mode 100644 data/entities/DefaultDungeonMobs.cs create mode 100644 data/entities/DungeonCharacter.cs create mode 100644 data/entities/DungeonCharacterCombatStats.cs create mode 100644 data/entities/DungeonCharacterItem.cs create mode 100644 data/entities/DungeonCharacterStats.cs create mode 100644 data/entities/DungeonItemDefinition.cs create mode 100644 data/entities/DungeonLearnedSpell.cs create mode 100644 data/entities/DungeonMobCombatStats.cs create mode 100644 data/entities/DungeonMobDefinition.cs create mode 100644 data/entities/DungeonSpellDefinition.cs create mode 100644 data/entities/DungeonStashItem.cs create mode 100644 data/entities/LevelSystem.cs create mode 100644 data/enums/DamageType.cs create mode 100644 data/enums/DungeonEquipmentSlot.cs create mode 100644 data/enums/ItemRarity.cs create mode 100644 data/enums/ItemType.cs create mode 100644 data/enums/MobCategory.cs create mode 100644 data/enums/MobType.cs create mode 100644 data/enums/PlayerState.cs create mode 100644 data/enums/SpellType.cs diff --git a/Game/Dungeon/ChestInstance.cs b/Game/Dungeon/ChestInstance.cs new file mode 100644 index 0000000..0314f84 --- /dev/null +++ b/Game/Dungeon/ChestInstance.cs @@ -0,0 +1,20 @@ +namespace Server.Game.Dungeon; + +public class ChestInstance +{ + public int Id { get; set; } + public float X { get; set; } + public float Y { get; set; } + public DungeonChestType Type { get; set; } + public bool IsOpened { get; set; } +} + +public class DroppedItem +{ + public int Id { get; set; } + public int ItemDefinitionId { get; set; } + public int Quantity { get; set; } + public float X { get; set; } + public float Y { get; set; } + public long DroppedAtTick { get; set; } +} diff --git a/Game/Dungeon/DungeonChestSpawn.cs b/Game/Dungeon/DungeonChestSpawn.cs new file mode 100644 index 0000000..d483e62 --- /dev/null +++ b/Game/Dungeon/DungeonChestSpawn.cs @@ -0,0 +1,18 @@ +namespace Server.Game.Dungeon; + +public class DungeonChestSpawn +{ + public int Id { get; set; } + public int X { get; set; } + public int Y { get; set; } + public DungeonChestType ChestType { get; set; } + public int RoomIndex { get; set; } + public bool IsOpened { get; set; } = false; +} + +public enum DungeonChestType +{ + Normal, + Rare, + Boss +} diff --git a/Game/Dungeon/DungeonGameHandler.cs b/Game/Dungeon/DungeonGameHandler.cs deleted file mode 100644 index 3c9f9bd..0000000 --- a/Game/Dungeon/DungeonGameHandler.cs +++ /dev/null @@ -1,729 +0,0 @@ -using System.Collections.Concurrent; -using System.Net.WebSockets; -using System.Text; -using System.Text.Json; -using DungeonCrawler.Data.Entities; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Server.Data; - -namespace DungeonCrawler.Game.Dungeon; - -/// -/// Manages WebSocket connections, dungeon instances, and game state -/// -public class DungeonGameHandler -{ - private readonly IServiceScopeFactory _scopeFactory; - private readonly ILogger _log; - private readonly JsonSerializerOptions _jsonOptions; - - // Active connections - private readonly ConcurrentDictionary _connections = new(); - - // Active dungeon instances - private readonly ConcurrentDictionary _dungeons = new(); - - // Mob definitions cache - private Dictionary _mobDefinitions = new(); - - // Tick timer - private Timer? _tickTimer; - - public DungeonGameHandler(IServiceScopeFactory scopeFactory, ILogger log) - { - _scopeFactory = scopeFactory; - _log = log; - _jsonOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - WriteIndented = false - }; - } - - public async Task StartAsync() - { - // Load mob definitions - await LoadMobDefinitionsAsync(); - - // Start tick loop (20 ticks per second) - _tickTimer = new Timer(TickAll, null, 0, 50); - - _log.LogInformation("DungeonGameHandler started with {MobCount} mob definitions", _mobDefinitions.Count); - } - - private async Task LoadMobDefinitionsAsync() - { - using var scope = _scopeFactory.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - var mobs = await db.Set() - .Where(m => m.IsEnabled) - .ToListAsync(); - - if (mobs.Count == 0) - { - // Seed default mobs - var defaults = DefaultMobs.GetDefaultMobs(); - db.Set().AddRange(defaults); - await db.SaveChangesAsync(); - mobs = defaults; - _log.LogInformation("Seeded {Count} default mob definitions", defaults.Count); - } - - _mobDefinitions = mobs.ToDictionary(m => m.Id); - } - - public async Task HandleConnectionAsync(WebSocket ws, ulong accountId, Character character) - { - var connection = new PlayerConnection - { - AccountId = accountId, - CharacterId = character.Id, - CharacterName = character.Name, - WebSocket = ws, - Character = character - }; - - _connections[character.Id] = connection; - - _log.LogInformation("Player {Name} connected (CharId: {CharId})", character.Name, character.Id); - - // Send initial state (hub) - await SendAsync(connection, OpCodes.HUB_STATE, GetHubState(character)); - - try - { - var buffer = new byte[4096]; - while (ws.State == WebSocketState.Open) - { - var result = await ws.ReceiveAsync(buffer, CancellationToken.None); - - if (result.MessageType == WebSocketMessageType.Close) - break; - - if (result.MessageType == WebSocketMessageType.Binary || - result.MessageType == WebSocketMessageType.Text) - { - await HandleMessageAsync(connection, buffer, result.Count); - } - } - } - catch (WebSocketException ex) - { - _log.LogWarning("WebSocket error for {Name}: {Error}", character.Name, ex.Message); - } - finally - { - await HandleDisconnectAsync(connection); - } - } - - private async Task HandleDisconnectAsync(PlayerConnection connection) - { - _connections.TryRemove(connection.CharacterId, out _); - - // Remove from dungeon if in one - if (connection.CurrentDungeonId.HasValue) - { - if (_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) - { - dungeon.Simulation.Players.TryRemove(connection.CharacterId, out var player); - - // Save character state - if (player != null) - { - await SaveCharacterStateAsync(connection.Character, player, false); - } - } - } - - _log.LogInformation("Player {Name} disconnected", connection.CharacterName); - } - - private async Task HandleMessageAsync(PlayerConnection connection, byte[] buffer, int length) - { - try - { - // Parse message (expecting JSON with OpCode and Payload) - var json = Encoding.UTF8.GetString(buffer, 0, length); - var msg = JsonSerializer.Deserialize(json, _jsonOptions); - - if (msg == null) return; - - switch (msg.OpCode) - { - case OpCodes.STAT_ALLOCATE: - await HandleStatAllocate(connection, msg.Payload); - break; - - case OpCodes.DUNGEON_ENTER: - await HandleDungeonEnter(connection, msg.Payload); - break; - - case OpCodes.DUNGEON_LEAVE: - await HandleDungeonLeave(connection); - break; - - case OpCodes.INPUT_MOVE: - HandleInputMove(connection, msg.Payload); - break; - - case OpCodes.INPUT_ATTACK: - HandleInputAttack(connection, msg.Payload); - break; - - case OpCodes.INPUT_PICKUP: - HandleInputPickup(connection, msg.Payload); - break; - - case OpCodes.INPUT_CHEST: - HandleInputChest(connection, msg.Payload); - break; - - case OpCodes.ESCAPE_START: - HandleEscapeStart(connection); - break; - - case OpCodes.ESCAPE_CANCEL: - HandleEscapeCancel(connection); - break; - } - } - catch (Exception ex) - { - _log.LogError(ex, "Error handling message from {Name}", connection.CharacterName); - } - } - - private async Task HandleStatAllocate(PlayerConnection connection, JsonElement payload) - { - var stat = payload.GetProperty("stat").GetString(); - if (string.IsNullOrEmpty(stat)) return; - - var character = connection.Character; - if (character.UnspentStatPoints <= 0) return; - - switch (stat.ToLower()) - { - case "strength": character.Strength++; break; - case "intelligence": character.Intelligence++; break; - case "wisdom": character.Wisdom++; break; - case "endurance": character.Endurance++; break; - case "dexterity": character.Dexterity++; break; - default: return; - } - - character.UnspentStatPoints--; - - // Save to database - using var scope = _scopeFactory.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - db.Attach(character); - db.Entry(character).Property(c => c.Strength).IsModified = true; - db.Entry(character).Property(c => c.Intelligence).IsModified = true; - db.Entry(character).Property(c => c.Wisdom).IsModified = true; - db.Entry(character).Property(c => c.Endurance).IsModified = true; - db.Entry(character).Property(c => c.Dexterity).IsModified = true; - db.Entry(character).Property(c => c.UnspentStatPoints).IsModified = true; - await db.SaveChangesAsync(); - - await SendAsync(connection, OpCodes.HUB_STATE, GetHubState(character)); - } - - private async Task HandleDungeonEnter(PlayerConnection connection, JsonElement payload) - { - int tier = payload.TryGetProperty("tier", out var t) ? t.GetInt32() : 1; - tier = Math.Clamp(tier, 1, 10); - - // Find or create dungeon - DungeonInstance? dungeon = null; - - // Look for existing incomplete dungeon at this tier - foreach (var d in _dungeons.Values) - { - if (d.Tier == tier && d.Simulation.Phase == DungeonPhase.Active) - { - dungeon = d; - break; - } - } - - if (dungeon == null) - { - // Create new dungeon - var id = Guid.NewGuid(); - var seed = Random.Shared.Next(); - var simulation = new DungeonSimulation(id, tier, seed, _mobDefinitions); - - dungeon = new DungeonInstance - { - Id = id, - Tier = tier, - Seed = seed, - Simulation = simulation - }; - - _dungeons[id] = dungeon; - _log.LogInformation("Created new Tier {Tier} dungeon: {Id}", tier, id); - } - - // Add player to dungeon - var character = connection.Character; - var stats = CharacterStats.GetCombatStats(character); - - // Spawn at entrance - var spawnX = dungeon.Simulation.Layout.SpawnPoint.X * 32 + 16; - var spawnY = dungeon.Simulation.Layout.SpawnPoint.Y * 32 + 16; - - var player = dungeon.Simulation.AddPlayer( - character.Id, - character.Name, - stats, - spawnX, - spawnY - ); - - connection.CurrentDungeonId = dungeon.Id; - connection.State = PlayerState.InDungeon; - - // Send dungeon layout and initial state - await SendAsync(connection, OpCodes.DUNGEON_ENTER_RESULT, new - { - ok = true, - dungeonId = dungeon.Id, - tier = tier, - layout = new - { - width = dungeon.Simulation.Layout.Width, - height = dungeon.Simulation.Layout.Height, - tiles = dungeon.Simulation.Layout.SerializeTiles(), - spawn = new { x = spawnX, y = spawnY } - } - }); - - // Send initial game state - await SendDungeonStateAsync(connection, dungeon); - } - - private async Task HandleDungeonLeave(PlayerConnection connection) - { - if (!connection.CurrentDungeonId.HasValue) return; - - if (_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) - { - if (dungeon.Simulation.Players.TryRemove(connection.CharacterId, out var player)) - { - // Save character with XP and any surviving inventory - await SaveCharacterStateAsync(connection.Character, player, true); - } - } - - connection.CurrentDungeonId = null; - connection.State = PlayerState.InHub; - - await SendAsync(connection, OpCodes.HUB_STATE, GetHubState(connection.Character)); - } - - private void HandleInputMove(PlayerConnection connection, JsonElement payload) - { - if (!connection.CurrentDungeonId.HasValue) return; - if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return; - if (!dungeon.Simulation.Players.TryGetValue(connection.CharacterId, out var player)) return; - if (!player.IsAlive) return; - - float dx = payload.TryGetProperty("dx", out var dxProp) ? dxProp.GetSingle() : 0; - float dy = payload.TryGetProperty("dy", out var dyProp) ? dyProp.GetSingle() : 0; - float aimAngle = payload.TryGetProperty("aimAngle", out var aProp) ? aProp.GetSingle() : 0; - - player.InputDx = Math.Clamp(dx, -1f, 1f); - player.InputDy = Math.Clamp(dy, -1f, 1f); - player.AimAngle = aimAngle; - } - - private void HandleInputAttack(PlayerConnection connection, JsonElement payload) - { - if (!connection.CurrentDungeonId.HasValue) return; - if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return; - - float aimAngle = payload.TryGetProperty("aimAngle", out var aProp) ? aProp.GetSingle() : 0; - - dungeon.Simulation.PlayerAttack(connection.CharacterId, aimAngle); - } - - private void HandleInputPickup(PlayerConnection connection, JsonElement payload) - { - if (!connection.CurrentDungeonId.HasValue) return; - if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return; - - int itemId = payload.TryGetProperty("itemId", out var idProp) ? idProp.GetInt32() : 0; - dungeon.Simulation.TryPickupItem(connection.CharacterId, itemId); - } - - private void HandleInputChest(PlayerConnection connection, JsonElement payload) - { - if (!connection.CurrentDungeonId.HasValue) return; - if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return; - - int chestId = payload.TryGetProperty("chestId", out var idProp) ? idProp.GetInt32() : 0; - dungeon.Simulation.TryOpenChest(connection.CharacterId, chestId); - } - - private void HandleEscapeStart(PlayerConnection connection) - { - if (!connection.CurrentDungeonId.HasValue) return; - if (!_dungeons.TryGetValue(connection.CurrentDungeonId.Value, out var dungeon)) return; - if (!dungeon.Simulation.Players.TryGetValue(connection.CharacterId, out var player)) return; - - // Can only escape if out of combat - if (!player.IsInCombat) - { - connection.IsEscaping = true; - connection.EscapeStartTick = dungeon.Simulation.CurrentTick; - } - } - - private void HandleEscapeCancel(PlayerConnection connection) - { - connection.IsEscaping = false; - connection.EscapeStartTick = 0; - } - - // Tick loop - private void TickAll(object? state) - { - foreach (var dungeon in _dungeons.Values) - { - try - { - TickDungeon(dungeon); - } - catch (Exception ex) - { - _log.LogError(ex, "Error ticking dungeon {Id}", dungeon.Id); - } - } - - // Cleanup empty dungeons - var emptyDungeons = _dungeons.Values - .Where(d => d.Simulation.Players.IsEmpty && - (DateTime.UtcNow - d.CreatedAt).TotalMinutes > 5) - .Select(d => d.Id) - .ToList(); - - foreach (var id in emptyDungeons) - { - _dungeons.TryRemove(id, out _); - _log.LogInformation("Removed empty dungeon {Id}", id); - } - } - - private void TickDungeon(DungeonInstance dungeon) - { - var sim = dungeon.Simulation; - - // Process player movement - foreach (var player in sim.Players.Values.Where(p => p.IsAlive)) - { - if (player.InputDx != 0 || player.InputDy != 0) - { - float speed = player.Stats.MoveSpeed * DungeonSimulation.TickDelta; - - // Normalize input - float len = MathF.Sqrt(player.InputDx * player.InputDx + player.InputDy * player.InputDy); - if (len > 0) - { - float dx = (player.InputDx / len) * speed; - float dy = (player.InputDy / len) * speed; - - if (sim.CanMoveTo(player.X + dx, player.Y)) player.X += dx; - if (sim.CanMoveTo(player.X, player.Y + dy)) player.Y += dy; - } - } - - player.Rotation = player.AimAngle; - } - - // Run simulation tick - var tickResult = sim.Tick(); - - // Check escape teleports - foreach (var conn in _connections.Values.Where(c => c.CurrentDungeonId == dungeon.Id && c.IsEscaping)) - { - if (sim.Players.TryGetValue(conn.CharacterId, out var player)) - { - if (player.IsInCombat) - { - conn.IsEscaping = false; - conn.EscapeStartTick = 0; - _ = SendAsync(conn, OpCodes.ESCAPE_INTERRUPTED, new { reason = "combat" }); - } - else - { - // Check if escape complete (2 minutes = 2400 ticks at 20 TPS) - long escapeTicks = sim.CurrentTick - conn.EscapeStartTick; - if (escapeTicks >= 2400) - { - // Successful escape! - conn.IsEscaping = false; - _ = HandleDungeonLeave(conn); - } - } - } - } - - // Broadcast state to all players in dungeon - foreach (var conn in _connections.Values.Where(c => c.CurrentDungeonId == dungeon.Id)) - { - _ = SendDungeonStateAsync(conn, dungeon, tickResult); - } - } - - private async Task SendDungeonStateAsync(PlayerConnection connection, DungeonInstance dungeon, TickResult? tickResult = null) - { - var sim = dungeon.Simulation; - - var state = new - { - tick = sim.CurrentTick, - phase = sim.Phase.ToString().ToLower(), - - players = sim.Players.Values.Select(p => new - { - id = p.CharacterId, - name = p.Name, - x = p.X, - y = p.Y, - rotation = p.Rotation, - health = (int)p.Health, - maxHealth = (int)p.MaxHealth, - mana = (int)p.Mana, - maxMana = (int)p.MaxMana, - stamina = (int)p.Stamina, - maxStamina = (int)p.MaxStamina, - isAlive = p.IsAlive, - isInCombat = p.IsInCombat - }), - - mobs = sim.Mobs.Values.Where(m => m.IsAlive).Select(m => new - { - id = m.Id, - name = m.Name, - x = m.X, - y = m.Y, - rotation = m.Rotation, - health = m.Health, - maxHealth = m.MaxHealth, - state = m.State.ToString().ToLower(), - spriteSheet = m.SpriteSheet, - spriteWidth = m.SpriteWidth, - spriteHeight = m.SpriteHeight, - tintColor = m.TintColor - }), - - chests = sim.Chests.Values.Select(c => new - { - id = c.Id, - x = c.X, - y = c.Y, - opened = c.IsOpened - }), - - droppedItems = sim.DroppedItems.Values.Select(i => new - { - id = i.Id, - itemId = i.ItemDefinitionId, - quantity = i.Quantity, - x = i.X, - y = i.Y - }), - - events = tickResult == null ? null : new - { - damage = tickResult.DamageEvents.Select(e => new - { - sourceType = e.SourceType.ToString().ToLower(), - sourceId = e.SourceId, - targetType = e.TargetType.ToString().ToLower(), - targetId = e.TargetId, - damage = e.Damage - }), - deaths = tickResult.DeathEvents.Select(e => new - { - entityType = e.EntityType.ToString().ToLower(), - entityId = e.EntityId, - entityName = e.EntityName, - killerType = e.KillerType.ToString().ToLower(), - killerId = e.KillerId, - killerName = e.KillerName, - xp = e.XpReward - }) - }, - - exitPosition = sim.Layout.ExitPosition != null ? new - { - x = sim.Layout.ExitPosition.Value.X * 32 + 16, - y = sim.Layout.ExitPosition.Value.Y * 32 + 16 - } : null - }; - - await SendAsync(connection, OpCodes.DUNGEON_STATE, state); - } - - private object GetHubState(Character character) - { - return new - { - character = new - { - id = character.Id, - name = character.Name, - level = character.Level, - xp = character.Experience, - xpNext = LevelSystem.GetXpForLevel(character.Level + 1), - unspentPoints = character.UnspentStatPoints, - strength = character.Strength, - intelligence = character.Intelligence, - wisdom = character.Wisdom, - endurance = character.Endurance, - dexterity = character.Dexterity, - maxHealth = CharacterStats.GetMaxHealth(character), - maxMana = CharacterStats.GetMaxMana(character), - maxStamina = CharacterStats.GetMaxStamina(character) - } - }; - } - - private async Task SaveCharacterStateAsync(Character character, PlayerInstance player, bool extracted) - { - using var scope = _scopeFactory.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - // Add XP earned - character.Experience += player.XpGained; - character.TotalKills += player.MobsKilled; - character.PlayersKilled += player.PlayersKilled; - - if (extracted) - { - character.DungeonsCompleted++; - // Save current health/mana (they extracted alive) - character.CurrentHealth = (int)player.Health; - character.CurrentMana = (int)player.Mana; - } - else - { - character.TotalDeaths++; - // Reset to full on death - character.CurrentHealth = CharacterStats.GetMaxHealth(character); - character.CurrentMana = CharacterStats.GetMaxMana(character); - } - - // Check for level up - while (character.Experience >= LevelSystem.GetTotalXpForLevel(character.Level + 1)) - { - character.Level++; - character.UnspentStatPoints += 5; - } - - character.LastPlayedAt = DateTime.UtcNow; - - db.Attach(character); - db.Entry(character).State = EntityState.Modified; - await db.SaveChangesAsync(); - - _log.LogInformation("Saved character {Name}: Level {Level}, XP {Xp}", - character.Name, character.Level, character.Experience); - } - - private async Task SendAsync(PlayerConnection connection, int opCode, object payload) - { - if (connection.WebSocket.State != WebSocketState.Open) return; - - try - { - var msg = new { opCode, payload }; - var json = JsonSerializer.Serialize(msg, _jsonOptions); - var bytes = Encoding.UTF8.GetBytes(json); - - await connection.WebSocket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None); - } - catch (Exception ex) - { - _log.LogWarning("Failed to send to {Name}: {Error}", connection.CharacterName, ex.Message); - } - } -} - -// Connection tracking - -public class PlayerConnection -{ - public ulong AccountId { get; set; } - public ulong CharacterId { get; set; } - public string CharacterName { get; set; } = ""; - public WebSocket WebSocket { get; set; } = null!; - public Character Character { get; set; } = null!; - - public PlayerState State { get; set; } = PlayerState.InHub; - public Guid? CurrentDungeonId { get; set; } - - public bool IsEscaping { get; set; } - public long EscapeStartTick { get; set; } -} - -public enum PlayerState -{ - InHub, - InDungeon -} - -public class DungeonInstance -{ - public Guid Id { get; set; } - public int Tier { get; set; } - public int Seed { get; set; } - public DungeonSimulation Simulation { get; set; } = null!; - public DateTime CreatedAt { get; set; } = DateTime.UtcNow; -} - -// Messages - -public class ClientMessage -{ - public int OpCode { get; set; } - public JsonElement Payload { get; set; } -} - -// OpCodes -public static class OpCodes -{ - // Hub - public const int HUB_STATE = 200; - public const int STAT_ALLOCATE = 201; - - // Dungeon - public const int DUNGEON_ENTER = 300; - public const int DUNGEON_ENTER_RESULT = 301; - public const int DUNGEON_STATE = 302; - public const int DUNGEON_LEAVE = 303; - - // Input - public const int INPUT_MOVE = 400; - public const int INPUT_ATTACK = 401; - public const int INPUT_PICKUP = 402; - public const int INPUT_CHEST = 403; - - // Escape - public const int ESCAPE_START = 450; - public const int ESCAPE_CANCEL = 451; - public const int ESCAPE_INTERRUPTED = 452; - public const int ESCAPE_SUCCESS = 453; - - // Events - public const int EVENT_DAMAGE = 500; - public const int EVENT_DEATH = 501; - public const int EVENT_LEVELUP = 502; - public const int EVENT_LOOT = 503; -} diff --git a/Game/Dungeon/DungeonGenerator.cs b/Game/Dungeon/DungeonGenerator.cs index dea6570..7fb66bc 100644 --- a/Game/Dungeon/DungeonGenerator.cs +++ b/Game/Dungeon/DungeonGenerator.cs @@ -1,16 +1,24 @@ -using System.Text.Json; - -namespace DungeonCrawler.Game.Dungeon; +namespace Server.Game.Dungeon; /// /// Procedural dungeon generator using BSP (Binary Space Partition) + room placement /// -public class DungeonGenerator +public static class DungeonGenerator +{ + /// + /// Generate a dungeon layout for the given seed and tier + /// + public static DungeonLayout Generate(int seed, int tier) + { + var generator = new DungeonGeneratorInstance(seed, tier); + return generator.Generate(); + } +} + +internal class DungeonGeneratorInstance { private readonly Random _rng; private readonly int _seed; - - // Generation parameters private readonly int _tier; private readonly int _tileSize = 32; @@ -22,7 +30,7 @@ public class DungeonGenerator private int MapWidth => 50 + (_tier * 10); // In tiles private int MapHeight => 50 + (_tier * 10); - public DungeonGenerator(int seed, int tier) + public DungeonGeneratorInstance(int seed, int tier) { _seed = seed; _tier = Math.Max(1, tier); @@ -45,7 +53,7 @@ public class DungeonGenerator // Generate rooms int roomCount = _rng.Next(MinRooms, MaxRooms + 1); - var rooms = new List(); + var rooms = new List(); int attempts = 0; int maxAttempts = roomCount * 20; @@ -58,7 +66,7 @@ public class DungeonGenerator int x = _rng.Next(2, MapWidth - w - 2); int y = _rng.Next(2, MapHeight - h - 2); - var newRoom = new Room(x, y, w, h); + var newRoom = new DungeonRoom(x, y, w, h); // Check for overlap with existing rooms (with padding) bool overlaps = rooms.Any(r => newRoom.Intersects(r, padding: 2)); @@ -94,8 +102,8 @@ public class DungeonGenerator AssignRoomTypes(rooms, layout); // Place spawn point (first room) - layout.SpawnPoint = new Point(rooms[0].CenterX, rooms[0].CenterY); - rooms[0].Type = RoomType.Entrance; + layout.SpawnPoint = new DungeonPoint(rooms[0].CenterX, rooms[0].CenterY); + rooms[0].Type = DungeonRoomType.Entrance; // Generate mob spawns GenerateMobSpawns(rooms, layout); @@ -109,7 +117,7 @@ public class DungeonGenerator return layout; } - private void CarveRoom(int[,] tiles, Room room) + private void CarveRoom(int[,] tiles, DungeonRoom room) { for (int x = room.X; x < room.X + room.Width; x++) { @@ -120,7 +128,7 @@ public class DungeonGenerator } } - private void ConnectRooms(int[,] tiles, Room a, Room b) + private void ConnectRooms(int[,] tiles, DungeonRoom a, DungeonRoom b) { int x = a.CenterX; int y = a.CenterY; @@ -174,7 +182,7 @@ public class DungeonGenerator } } - private void AssignRoomTypes(List rooms, DungeonLayout layout) + private void AssignRoomTypes(List rooms, DungeonLayout layout) { if (rooms.Count == 0) return; @@ -182,7 +190,7 @@ public class DungeonGenerator // Last room is boss room if (rooms.Count > 1) { - rooms[^1].Type = RoomType.Boss; + rooms[^1].Type = DungeonRoomType.Boss; } // Assign some treasure rooms (10-20% of rooms) @@ -192,28 +200,22 @@ public class DungeonGenerator for (int i = 0; i < treasureCount && availableRooms.Count > 0; i++) { int idx = _rng.Next(availableRooms.Count); - availableRooms[idx].Type = RoomType.Treasure; + availableRooms[idx].Type = DungeonRoomType.Treasure; availableRooms.RemoveAt(idx); } - - // Rest are combat rooms - foreach (var room in rooms.Where(r => r.Type == RoomType.Combat)) - { - // Already default - } } - private void GenerateMobSpawns(List rooms, DungeonLayout layout) + private void GenerateMobSpawns(List rooms, DungeonLayout layout) { foreach (var room in rooms) { - if (room.Type == RoomType.Entrance) continue; + if (room.Type == DungeonRoomType.Entrance) continue; int mobCount = room.Type switch { - RoomType.Boss => 1, // Just the boss - RoomType.Treasure => _rng.Next(1, 3), // Light guard - RoomType.Combat => _rng.Next(2, 5 + _tier), + DungeonRoomType.Boss => 1, // Just the boss + DungeonRoomType.Treasure => _rng.Next(1, 3), // Light guard + DungeonRoomType.Combat => _rng.Next(2, 5 + _tier), _ => _rng.Next(1, 3) }; @@ -223,12 +225,12 @@ public class DungeonGenerator int x = room.X + 1 + _rng.Next(room.Width - 2); int y = room.Y + 1 + _rng.Next(room.Height - 2); - var spawn = new MobSpawn + var spawn = new DungeonMobSpawn { Id = layout.MobSpawns.Count + 1, X = x, Y = y, - MobType = room.Type == RoomType.Boss ? MobSpawnType.Boss : MobSpawnType.Normal, + MobType = room.Type == DungeonRoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal, RoomIndex = rooms.IndexOf(room) }; @@ -239,15 +241,15 @@ public class DungeonGenerator layout.TotalMobs = layout.MobSpawns.Count; } - private void GenerateChestSpawns(List rooms, DungeonLayout layout) + private void GenerateChestSpawns(List rooms, DungeonLayout layout) { foreach (var room in rooms) { int chestCount = room.Type switch { - RoomType.Treasure => _rng.Next(2, 4), - RoomType.Boss => 1, // Guaranteed chest after boss - RoomType.Combat => _rng.NextDouble() < 0.3 ? 1 : 0, // 30% chance + DungeonRoomType.Treasure => _rng.Next(2, 4), + DungeonRoomType.Boss => 1, // Guaranteed chest after boss + DungeonRoomType.Combat => _rng.NextDouble() < 0.3 ? 1 : 0, // 30% chance _ => 0 }; @@ -256,12 +258,12 @@ public class DungeonGenerator int x = room.X + 1 + _rng.Next(room.Width - 2); int y = room.Y + 1 + _rng.Next(room.Height - 2); - var chest = new ChestSpawn + var chest = new DungeonChestSpawn { Id = layout.ChestSpawns.Count + 1, X = x, Y = y, - ChestType = room.Type == RoomType.Boss ? ChestType.Boss : ChestType.Normal, + ChestType = room.Type == DungeonRoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal, RoomIndex = rooms.IndexOf(room) }; @@ -272,166 +274,3 @@ public class DungeonGenerator layout.TotalChests = layout.ChestSpawns.Count; } } - -// Data structures - -public class DungeonLayout -{ - public int Seed { get; set; } - public int Tier { get; set; } - public int Width { get; set; } - public int Height { get; set; } - public int TileSize { get; set; } - - public int[,] Tiles { get; set; } = new int[0, 0]; - public List Rooms { get; set; } = new(); - public Point SpawnPoint { get; set; } - public Point? ExitPosition { get; set; } // Set when dungeon is cleared - - public List MobSpawns { get; set; } = new(); - public List ChestSpawns { get; set; } = new(); - - public int TotalMobs { get; set; } - public int TotalChests { get; set; } - - // Serialize tiles to string for DB storage - public string SerializeTiles() - { - var rows = new List(); - for (int y = 0; y < Height; y++) - { - var row = new char[Width]; - for (int x = 0; x < Width; x++) - { - row[x] = Tiles[x, y] == 1 ? '.' : '#'; - } - rows.Add(new string(row)); - } - return string.Join("\n", rows); - } - - public void DeserializeTiles(string data) - { - var rows = data.Split('\n'); - Height = rows.Length; - Width = rows.Length > 0 ? rows[0].Length : 0; - Tiles = new int[Width, Height]; - - for (int y = 0; y < Height; y++) - { - for (int x = 0; x < Width && x < rows[y].Length; x++) - { - Tiles[x, y] = rows[y][x] == '.' ? 1 : 0; - } - } - } - - public string ToJson() - { - return JsonSerializer.Serialize(new - { - seed = Seed, - tier = Tier, - width = Width, - height = Height, - tileSize = TileSize, - tiles = SerializeTiles(), - spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y }, - rooms = Rooms.Select(r => new - { - x = r.X, y = r.Y, w = r.Width, h = r.Height, - type = r.Type.ToString() - }), - mobs = MobSpawns.Select(m => new - { - id = m.Id, x = m.X, y = m.Y, - type = m.MobType.ToString(), - roomIndex = m.RoomIndex - }), - chests = ChestSpawns.Select(c => new - { - id = c.Id, x = c.X, y = c.Y, - type = c.ChestType.ToString(), - roomIndex = c.RoomIndex - }) - }); - } -} - -public class Room -{ - public int X { get; set; } - public int Y { get; set; } - public int Width { get; set; } - public int Height { get; set; } - public RoomType Type { get; set; } = RoomType.Combat; - - public int CenterX => X + Width / 2; - public int CenterY => Y + Height / 2; - - public Room() { } - - public Room(int x, int y, int width, int height) - { - X = x; Y = y; Width = width; Height = height; - } - - public bool Intersects(Room other, int padding = 0) - { - return X - padding < other.X + other.Width + padding && - X + Width + padding > other.X - padding && - Y - padding < other.Y + other.Height + padding && - Y + Height + padding > other.Y - padding; - } -} - -public struct Point -{ - public int X { get; set; } - public int Y { get; set; } - - public Point(int x, int y) { X = x; Y = y; } -} - -public class MobSpawn -{ - public int Id { get; set; } - public int X { get; set; } - public int Y { get; set; } - public MobSpawnType MobType { get; set; } - public int RoomIndex { get; set; } - public bool IsAlive { get; set; } = true; -} - -public class ChestSpawn -{ - public int Id { get; set; } - public int X { get; set; } - public int Y { get; set; } - public ChestType ChestType { get; set; } - public int RoomIndex { get; set; } - public bool IsOpened { get; set; } = false; -} - -public enum RoomType -{ - Entrance, - Combat, - Treasure, - Boss, - Empty -} - -public enum MobSpawnType -{ - Normal, - Elite, - Boss -} - -public enum ChestType -{ - Normal, - Rare, - Boss -} diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs new file mode 100644 index 0000000..e9ee4be --- /dev/null +++ b/Game/Dungeon/DungeonHandler.cs @@ -0,0 +1,745 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Server.Data; +using Server.Data.Entities; +using Server.Data.Enums; +using Server.Networking; +using Server.Networking.Handling; +using Server.Networking.Messages; +using Server.Services.Auth; +using SystemRevivalServer.Networking.Messages; + +namespace Server.Game.Dungeon; + +/// +/// Handles dungeon crawler game messages via the server's message router +/// Implements IClientMessageHandler for integration with existing infrastructure +/// +public sealed class DungeonHandler : IClientMessageHandler +{ + private readonly ILogger _log; + private readonly ISessionRegistry _sessions; + private readonly IMessageSerializer _ser; + private readonly IServiceScopeFactory _scopeFactory; + + // Player state tracking (keyed by connection ID) + private readonly ConcurrentDictionary _playerSessions = new(); + + // Active dungeon instances + private readonly ConcurrentDictionary _dungeons = new(); + + // Mob definitions cache + private Dictionary _mobDefinitions = new(); + private bool _initialized = false; + + // Tick management + private Timer? _tickTimer; + private long _currentTick = 0; + + public DungeonHandler( + ILogger log, + ISessionRegistry sessions, + IMessageSerializer ser, + IServiceScopeFactory scopeFactory) + { + _log = log; + _sessions = sessions; + _ser = ser; + _scopeFactory = scopeFactory; + } + + public IReadOnlyCollection SupportedOpCodes => new[] + { + DungeonOpCodes.HUB_STATE, + DungeonOpCodes.STAT_ALLOCATE, + DungeonOpCodes.DUNGEON_ENTER, + DungeonOpCodes.DUNGEON_LEAVE, + DungeonOpCodes.DUNGEON_INPUT_MOVE, + DungeonOpCodes.DUNGEON_INPUT_ATTACK, + DungeonOpCodes.DUNGEON_INPUT_PICKUP, + DungeonOpCodes.DUNGEON_INPUT_CHEST, + DungeonOpCodes.ESCAPE_START, + DungeonOpCodes.ESCAPE_CANCEL + }; + + public async Task InitializeAsync() + { + if (_initialized) return; + + await LoadMobDefinitionsAsync(); + + // Start tick loop (20 ticks per second) + _tickTimer = new Timer(TickAll, null, 0, 50); + + _initialized = true; + _log.LogInformation("DungeonHandler initialized with {MobCount} mob definitions", _mobDefinitions.Count); + } + + private async Task LoadMobDefinitionsAsync() + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var mobs = await db.Set() + .Where(m => m.IsEnabled) + .ToListAsync(); + + if (mobs.Count == 0) + { + // Seed default mobs + var defaults = DefaultDungeonMobs.GetDefaultMobs(); + db.Set().AddRange(defaults); + await db.SaveChangesAsync(); + mobs = defaults; + _log.LogInformation("Seeded {Count} default mob definitions", defaults.Count); + } + + _mobDefinitions = mobs.ToDictionary(m => m.Id); + } + + public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory payload, CancellationToken ct) + { + // Ensure initialized + if (!_initialized) + { + await InitializeAsync(); + } + + // All dungeon operations require authentication + if (!_sessions.TryGet(connection.Id, out var accountId, out _)) + { + await SendErrorAsync(connection, "auth_required", ct); + return; + } + + // Get or create player session + var session = await GetOrCreateSessionAsync(connection, accountId, ct); + if (session == null) + { + await SendErrorAsync(connection, "no_character", ct); + return; + } + + try + { + switch (opCode) + { + case DungeonOpCodes.HUB_STATE: + await HandleHubStateRequest(connection, session, ct); + break; + + case DungeonOpCodes.STAT_ALLOCATE: + await HandleStatAllocate(connection, session, payload, ct); + break; + + case DungeonOpCodes.DUNGEON_ENTER: + await HandleDungeonEnter(connection, session, payload, ct); + break; + + case DungeonOpCodes.DUNGEON_LEAVE: + await HandleDungeonLeave(connection, session, ct); + break; + + case DungeonOpCodes.DUNGEON_INPUT_MOVE: + HandleInputMove(session, payload); + break; + + case DungeonOpCodes.DUNGEON_INPUT_ATTACK: + HandleInputAttack(session, payload); + break; + + case DungeonOpCodes.DUNGEON_INPUT_PICKUP: + HandleInputPickup(session, payload); + break; + + case DungeonOpCodes.DUNGEON_INPUT_CHEST: + HandleInputChest(session, payload); + break; + + case DungeonOpCodes.ESCAPE_START: + HandleEscapeStart(session); + break; + + case DungeonOpCodes.ESCAPE_CANCEL: + HandleEscapeCancel(session); + break; + } + } + catch (Exception ex) + { + _log.LogError(ex, "Error handling dungeon opcode {OpCode} for account {AccountId}", opCode, accountId); + await SendErrorAsync(connection, "internal_error", ct); + } + } + + private async Task GetOrCreateSessionAsync(IConnection connection, ulong accountId, CancellationToken ct) + { + if (_playerSessions.TryGetValue(connection.Id, out var existing)) + { + return existing; + } + + // Load character from database + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var character = await db.Set() + .FirstOrDefaultAsync(c => c.AccountId == accountId && !c.IsDeleted, ct); + + if (character == null) + { + // Auto-create a character for this account + character = new DungeonCharacter + { + AccountId = accountId, + Name = $"Hero_{accountId}", + Level = 1, + UnspentStatPoints = 5, + Strength = 1, + Intelligence = 1, + Wisdom = 1, + Endurance = 1, + Dexterity = 1 + }; + + db.Set().Add(character); + await db.SaveChangesAsync(ct); + _log.LogInformation("Created new dungeon character for account {AccountId}", accountId); + } + + var session = new DungeonPlayerSession + { + ConnectionId = connection.Id, + Connection = connection, + AccountId = accountId, + CharacterId = character.Id, + Character = character, + State = PlayerState.InHub + }; + + _playerSessions[connection.Id] = session; + return session; + } + + private async Task HandleHubStateRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct) + { + var hubState = GetHubState(session.Character); + await SendAsync(connection, DungeonOpCodes.HUB_STATE, hubState, ct); + } + + private async Task HandleStatAllocate(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) + { + var request = _ser.Deserialize(payload); + if (string.IsNullOrEmpty(request.Stat)) return; + + var character = session.Character; + if (character.UnspentStatPoints <= 0) return; + + switch (request.Stat.ToLower()) + { + case "strength": character.Strength++; break; + case "intelligence": character.Intelligence++; break; + case "wisdom": character.Wisdom++; break; + case "endurance": character.Endurance++; break; + case "dexterity": character.Dexterity++; break; + default: return; + } + + character.UnspentStatPoints--; + + // Save to database + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Attach(character); + db.Entry(character).Property(c => c.Strength).IsModified = true; + db.Entry(character).Property(c => c.Intelligence).IsModified = true; + db.Entry(character).Property(c => c.Wisdom).IsModified = true; + db.Entry(character).Property(c => c.Endurance).IsModified = true; + db.Entry(character).Property(c => c.Dexterity).IsModified = true; + db.Entry(character).Property(c => c.UnspentStatPoints).IsModified = true; + await db.SaveChangesAsync(ct); + + await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(character), ct); + } + + private async Task HandleDungeonEnter(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory payload, CancellationToken ct) + { + if (session.State == PlayerState.InDungeon) + { + await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new { ok = false, error = "already_in_dungeon" }, ct); + return; + } + + var request = _ser.Deserialize(payload); + int tier = Math.Clamp(request.Tier, 1, 10); + + // Create new dungeon instance + var dungeonId = Guid.NewGuid(); + int seed = Random.Shared.Next(); + + var layout = DungeonGenerator.Generate(seed, tier); + var simulation = new DungeonSimulation(layout, tier, _mobDefinitions); + + var instance = new DungeonInstance + { + Id = dungeonId, + Tier = tier, + Seed = seed, + Simulation = simulation, + CreatedAt = DateTime.UtcNow + }; + + _dungeons[dungeonId] = instance; + + // Add player to dungeon + var spawnPos = layout.Rooms[0]; // Entrance room + var player = new PlayerInstance + { + CharacterId = session.CharacterId, + CharacterName = session.Character.Name, + X = spawnPos.CenterX * 32, + Y = spawnPos.CenterY * 32, + Health = session.Character.CurrentHealth, + MaxHealth = DungeonCharacterStats.GetMaxHealth(session.Character), + Mana = session.Character.CurrentMana, + MaxMana = DungeonCharacterStats.GetMaxMana(session.Character), + Stamina = DungeonCharacterStats.GetMaxStamina(session.Character), + MaxStamina = DungeonCharacterStats.GetMaxStamina(session.Character), + MoveSpeed = DungeonCharacterStats.GetMoveSpeed(session.Character), + AttackSpeed = DungeonCharacterStats.GetAttackSpeed(session.Character), + Strength = session.Character.Strength, + Intelligence = session.Character.Intelligence + }; + + simulation.Players[session.CharacterId] = player; + + // Update session state + session.State = PlayerState.InDungeon; + session.CurrentDungeonId = dungeonId; + session.PlayerInstance = player; + + _log.LogInformation("Player {Name} entered dungeon tier {Tier}", session.Character.Name, tier); + + await SendAsync(connection, DungeonOpCodes.DUNGEON_ENTER_RESULT, new + { + ok = true, + dungeonId = dungeonId.ToString(), + tier, + seed, + width = layout.Width, + height = layout.Height + }, ct); + } + + private async Task HandleDungeonLeave(IConnection connection, DungeonPlayerSession session, CancellationToken ct) + { + if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) + { + return; + } + + await RemoveFromDungeonAsync(session, false, ct); + + await SendAsync(connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), ct); + } + + private void HandleInputMove(DungeonPlayerSession session, ReadOnlyMemory payload) + { + if (session.PlayerInstance == null) return; + + var input = _ser.Deserialize(payload); + session.PlayerInstance.InputX = input.X; + session.PlayerInstance.InputY = input.Y; + } + + private void HandleInputAttack(DungeonPlayerSession session, ReadOnlyMemory payload) + { + if (session.PlayerInstance == null) return; + + var input = _ser.Deserialize(payload); + session.PlayerInstance.AttackTargetId = input.TargetId; + session.PlayerInstance.WantsToAttack = true; + } + + private void HandleInputPickup(DungeonPlayerSession session, ReadOnlyMemory payload) + { + if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return; + if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; + + var input = _ser.Deserialize(payload); + + if (dungeon.Simulation.DroppedItems.TryRemove((int)input.ItemId, out var item)) + { + // TODO: Add to player inventory + _log.LogDebug("Player {Name} picked up item {ItemId}", session.Character.Name, item.ItemDefinitionId); + } + } + + private void HandleInputChest(DungeonPlayerSession session, ReadOnlyMemory payload) + { + if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return; + if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; + + var input = _ser.Deserialize(payload); + + if (dungeon.Simulation.Chests.TryGetValue((int)input.ChestId, out var chest) && !chest.IsOpened) + { + chest.IsOpened = true; + // TODO: Generate loot + _log.LogDebug("Player {Name} opened chest {ChestId}", session.Character.Name, chest.Id); + } + } + + private void HandleEscapeStart(DungeonPlayerSession session) + { + if (session.State != PlayerState.InDungeon || !session.CurrentDungeonId.HasValue) return; + if (!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) return; + + // Check if at exit + var layout = dungeon.Simulation.Layout; + if (layout.ExitPosition == null) return; + + var player = session.PlayerInstance; + if (player == null) return; + + float exitX = layout.ExitPosition.Value.X * 32 + 16; + float exitY = layout.ExitPosition.Value.Y * 32 + 16; + float dist = MathF.Sqrt((player.X - exitX) * (player.X - exitX) + (player.Y - exitY) * (player.Y - exitY)); + + if (dist < 48) // Within range + { + session.IsEscaping = true; + session.EscapeStartTick = _currentTick; + } + } + + private void HandleEscapeCancel(DungeonPlayerSession session) + { + session.IsEscaping = false; + } + + private void TickAll(object? state) + { + _currentTick++; + + foreach (var (dungeonId, instance) in _dungeons) + { + try + { + var result = instance.Simulation.Tick(_currentTick); + + // Send state to all players in this dungeon + var playersInDungeon = _playerSessions.Values + .Where(s => s.CurrentDungeonId == dungeonId && s.State == PlayerState.InDungeon) + .ToList(); + + foreach (var session in playersInDungeon) + { + // Check escape completion (5 seconds = 100 ticks) + if (session.IsEscaping && _currentTick - session.EscapeStartTick >= 100) + { + _ = CompleteEscapeAsync(session); + continue; + } + + // Check if player died + if (session.PlayerInstance != null && !session.PlayerInstance.IsAlive) + { + _ = HandlePlayerDeathAsync(session); + continue; + } + + _ = SendDungeonStateAsync(session, result); + } + + // Cleanup empty dungeons + if (playersInDungeon.Count == 0 && (DateTime.UtcNow - instance.CreatedAt).TotalMinutes > 5) + { + _dungeons.TryRemove(dungeonId, out _); + } + } + catch (Exception ex) + { + _log.LogError(ex, "Error ticking dungeon {DungeonId}", dungeonId); + } + } + } + + private async Task SendDungeonStateAsync(DungeonPlayerSession session, TickResult? tickResult) + { + var dungeon = _dungeons.GetValueOrDefault(session.CurrentDungeonId!.Value); + if (dungeon == null) return; + + var sim = dungeon.Simulation; + + var state = new + { + tick = _currentTick, + phase = sim.Phase.ToString().ToLower(), + + tiles = sim.Layout.Tiles, + + players = sim.Players.Values.Select(p => new + { + id = p.CharacterId, + name = p.CharacterName, + x = p.X, + y = p.Y, + rotation = p.Rotation, + health = (int)p.Health, + maxHealth = (int)p.MaxHealth, + mana = (int)p.Mana, + maxMana = (int)p.MaxMana, + stamina = (int)p.Stamina, + maxStamina = (int)p.MaxStamina, + isAlive = p.IsAlive, + isInCombat = p.IsInCombat + }), + + mobs = sim.Mobs.Values.Where(m => m.IsAlive).Select(m => new + { + id = m.Id, + name = m.Name, + x = m.X, + y = m.Y, + rotation = m.Rotation, + health = m.Health, + maxHealth = m.MaxHealth, + state = m.State.ToString().ToLower(), + spriteSheet = m.SpriteSheet, + spriteWidth = m.SpriteWidth, + spriteHeight = m.SpriteHeight, + tintColor = m.TintColor + }), + + chests = sim.Chests.Values.Select(c => new + { + id = c.Id, + x = c.X, + y = c.Y, + opened = c.IsOpened + }), + + droppedItems = sim.DroppedItems.Values.Select(i => new + { + id = i.Id, + itemId = i.ItemDefinitionId, + quantity = i.Quantity, + x = i.X, + y = i.Y + }), + + events = tickResult == null ? null : new + { + damage = tickResult.DamageEvents.Select(e => new + { + sourceType = e.SourceType.ToString().ToLower(), + sourceId = e.SourceId, + targetType = e.TargetType.ToString().ToLower(), + targetId = e.TargetId, + damage = e.Damage + }), + deaths = tickResult.DeathEvents.Select(e => new + { + entityType = e.EntityType.ToString().ToLower(), + entityId = e.EntityId, + entityName = e.EntityName, + killerType = e.KillerType.ToString().ToLower(), + killerId = e.KillerId, + killerName = e.KillerName, + xp = e.XpReward + }) + }, + + exitPosition = sim.Layout.ExitPosition != null ? new + { + x = sim.Layout.ExitPosition.Value.X * 32 + 16, + y = sim.Layout.ExitPosition.Value.Y * 32 + 16 + } : null + }; + + await SendAsync(session.Connection, DungeonOpCodes.DUNGEON_STATE, state, CancellationToken.None); + } + + private async Task CompleteEscapeAsync(DungeonPlayerSession session) + { + session.IsEscaping = false; + + await SendAsync(session.Connection, DungeonOpCodes.ESCAPE_SUCCESS, new { }, CancellationToken.None); + await RemoveFromDungeonAsync(session, true, CancellationToken.None); + await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None); + } + + private async Task HandlePlayerDeathAsync(DungeonPlayerSession session) + { + await RemoveFromDungeonAsync(session, false, CancellationToken.None); + + // Reset health on death + session.Character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(session.Character); + session.Character.CurrentMana = DungeonCharacterStats.GetMaxMana(session.Character); + session.Character.TotalDeaths++; + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Attach(session.Character); + db.Entry(session.Character).State = EntityState.Modified; + await db.SaveChangesAsync(); + + await SendAsync(session.Connection, DungeonOpCodes.HUB_STATE, GetHubState(session.Character), CancellationToken.None); + } + + private async Task RemoveFromDungeonAsync(DungeonPlayerSession session, bool extracted, CancellationToken ct) + { + if (!session.CurrentDungeonId.HasValue) return; + + if (_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon)) + { + dungeon.Simulation.Players.TryRemove(session.CharacterId, out var player); + + if (player != null) + { + await SaveCharacterStateAsync(session.Character, player, extracted, ct); + } + } + + session.State = PlayerState.InHub; + session.CurrentDungeonId = null; + session.PlayerInstance = null; + session.IsEscaping = false; + } + + private async Task SaveCharacterStateAsync(DungeonCharacter character, PlayerInstance player, bool extracted, CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Add XP earned + character.Experience += player.XpGained; + character.TotalKills += player.MobsKilled; + character.PlayersKilled += player.PlayersKilled; + + if (extracted) + { + character.DungeonsCompleted++; + character.CurrentHealth = (int)player.Health; + character.CurrentMana = (int)player.Mana; + } + else + { + character.TotalDeaths++; + character.CurrentHealth = DungeonCharacterStats.GetMaxHealth(character); + character.CurrentMana = DungeonCharacterStats.GetMaxMana(character); + } + + // Check for level up + while (character.Experience >= LevelSystem.GetTotalXpForLevel(character.Level + 1)) + { + character.Level++; + character.UnspentStatPoints += 5; + } + + character.LastPlayedAt = DateTime.UtcNow; + + db.Attach(character); + db.Entry(character).State = EntityState.Modified; + await db.SaveChangesAsync(ct); + + _log.LogInformation("Saved character {Name}: Level {Level}, XP {Xp}, Extracted={Extracted}", + character.Name, character.Level, character.Experience, extracted); + } + + private object GetHubState(DungeonCharacter character) + { + return new + { + character = new + { + id = character.Id, + name = character.Name, + level = character.Level, + xp = character.Experience, + xpNext = LevelSystem.GetXpForLevel(character.Level + 1), + unspentPoints = character.UnspentStatPoints, + strength = character.Strength, + intelligence = character.Intelligence, + wisdom = character.Wisdom, + endurance = character.Endurance, + dexterity = character.Dexterity, + maxHealth = DungeonCharacterStats.GetMaxHealth(character), + maxMana = DungeonCharacterStats.GetMaxMana(character), + maxStamina = DungeonCharacterStats.GetMaxStamina(character) + } + }; + } + + private async Task SendAsync(IConnection connection, int opCode, object payload, CancellationToken ct) + { + try + { + var payloadBytes = _ser.Serialize(payload); + var msg = new ServerMessage(opCode, payloadBytes); + var wire = _ser.Serialize(msg); + await connection.SendAsync(wire, ct); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to send message to connection {Id}", connection.Id); + } + } + + private async Task SendErrorAsync(IConnection connection, string error, CancellationToken ct) + { + await SendAsync(connection, OpCodes.ERROR, new { error }, ct); + } + + /// + /// Called when a connection is closed - cleanup session + /// + public void OnDisconnect(Guid connectionId) + { + if (_playerSessions.TryRemove(connectionId, out var session)) + { + if (session.CurrentDungeonId.HasValue) + { + _ = RemoveFromDungeonAsync(session, false, CancellationToken.None); + } + _log.LogInformation("Dungeon session cleaned up for connection {Id}", connectionId); + } + } +} + +// Request/Input DTOs + +public class StatAllocateRequest +{ + public string Stat { get; set; } = ""; +} + +public class DungeonEnterRequest +{ + public int Tier { get; set; } = 1; +} + +public class MoveInput +{ + public float X { get; set; } + public float Y { get; set; } +} + +public class AttackInput +{ + public ulong TargetId { get; set; } +} + +public class PickupInput +{ + public ulong ItemId { get; set; } +} + +public class ChestInput +{ + public ulong ChestId { get; set; } +} diff --git a/Game/Dungeon/DungeonInstance.cs b/Game/Dungeon/DungeonInstance.cs new file mode 100644 index 0000000..9cba7ee --- /dev/null +++ b/Game/Dungeon/DungeonInstance.cs @@ -0,0 +1,13 @@ +namespace Server.Game.Dungeon; + +/// +/// Represents an active dungeon instance +/// +public class DungeonInstance +{ + public Guid Id { get; set; } + public int Tier { get; set; } + public int Seed { get; set; } + public DungeonSimulation Simulation { get; set; } = null!; + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} diff --git a/Game/Dungeon/DungeonLayout.cs b/Game/Dungeon/DungeonLayout.cs new file mode 100644 index 0000000..06d0e54 --- /dev/null +++ b/Game/Dungeon/DungeonLayout.cs @@ -0,0 +1,89 @@ +using System.Text.Json; + +namespace Server.Game.Dungeon; + +/// +/// Contains the generated dungeon layout data +/// +public class DungeonLayout +{ + public int Seed { get; set; } + public int Tier { get; set; } + public int Width { get; set; } + public int Height { get; set; } + public int TileSize { get; set; } + + public int[,] Tiles { get; set; } = new int[0, 0]; + public List Rooms { get; set; } = new(); + public DungeonPoint SpawnPoint { get; set; } + public DungeonPoint? ExitPosition { get; set; } // Set when dungeon is cleared + + public List MobSpawns { get; set; } = new(); + public List ChestSpawns { get; set; } = new(); + + public int TotalMobs { get; set; } + public int TotalChests { get; set; } + + // Serialize tiles to string for DB storage + public string SerializeTiles() + { + var rows = new List(); + for (int y = 0; y < Height; y++) + { + var row = new char[Width]; + for (int x = 0; x < Width; x++) + { + row[x] = Tiles[x, y] == 1 ? '.' : '#'; + } + rows.Add(new string(row)); + } + return string.Join("\n", rows); + } + + public void DeserializeTiles(string data) + { + var rows = data.Split('\n'); + Height = rows.Length; + Width = rows.Length > 0 ? rows[0].Length : 0; + Tiles = new int[Width, Height]; + + for (int y = 0; y < Height; y++) + { + for (int x = 0; x < Width && x < rows[y].Length; x++) + { + Tiles[x, y] = rows[y][x] == '.' ? 1 : 0; + } + } + } + + public string ToJson() + { + return JsonSerializer.Serialize(new + { + seed = Seed, + tier = Tier, + width = Width, + height = Height, + tileSize = TileSize, + tiles = SerializeTiles(), + spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y }, + rooms = Rooms.Select(r => new + { + x = r.X, y = r.Y, w = r.Width, h = r.Height, + type = r.Type.ToString() + }), + mobs = MobSpawns.Select(m => new + { + id = m.Id, x = m.X, y = m.Y, + type = m.MobType.ToString(), + roomIndex = m.RoomIndex + }), + chests = ChestSpawns.Select(c => new + { + id = c.Id, x = c.X, y = c.Y, + type = c.ChestType.ToString(), + roomIndex = c.RoomIndex + }) + }); + } +} diff --git a/Game/Dungeon/DungeonMobSpawn.cs b/Game/Dungeon/DungeonMobSpawn.cs new file mode 100644 index 0000000..4379fe4 --- /dev/null +++ b/Game/Dungeon/DungeonMobSpawn.cs @@ -0,0 +1,18 @@ +namespace Server.Game.Dungeon; + +public class DungeonMobSpawn +{ + public int Id { get; set; } + public int X { get; set; } + public int Y { get; set; } + public DungeonMobSpawnType MobType { get; set; } + public int RoomIndex { get; set; } + public bool IsAlive { get; set; } = true; +} + +public enum DungeonMobSpawnType +{ + Normal, + Elite, + Boss +} diff --git a/Game/Dungeon/DungeonPlayerSession.cs b/Game/Dungeon/DungeonPlayerSession.cs new file mode 100644 index 0000000..d88ba13 --- /dev/null +++ b/Game/Dungeon/DungeonPlayerSession.cs @@ -0,0 +1,24 @@ +using Server.Data.Entities; +using Server.Data.Enums; +using Server.Networking; + +namespace Server.Game.Dungeon; + +/// +/// Tracks a player's dungeon session state +/// +public class DungeonPlayerSession +{ + public Guid ConnectionId { get; set; } + public IConnection Connection { get; set; } = null!; + public ulong AccountId { get; set; } + public ulong CharacterId { get; set; } + public DungeonCharacter Character { get; set; } = null!; + + public PlayerState State { get; set; } = PlayerState.InHub; + public Guid? CurrentDungeonId { get; set; } + public PlayerInstance? PlayerInstance { get; set; } + + public bool IsEscaping { get; set; } + public long EscapeStartTick { get; set; } +} diff --git a/Game/Dungeon/DungeonPoint.cs b/Game/Dungeon/DungeonPoint.cs new file mode 100644 index 0000000..763f2e1 --- /dev/null +++ b/Game/Dungeon/DungeonPoint.cs @@ -0,0 +1,9 @@ +namespace Server.Game.Dungeon; + +public struct DungeonPoint +{ + public int X { get; set; } + public int Y { get; set; } + + public DungeonPoint(int x, int y) { X = x; Y = y; } +} diff --git a/Game/Dungeon/DungeonRoom.cs b/Game/Dungeon/DungeonRoom.cs new file mode 100644 index 0000000..187ae29 --- /dev/null +++ b/Game/Dungeon/DungeonRoom.cs @@ -0,0 +1,37 @@ +namespace Server.Game.Dungeon; + +public class DungeonRoom +{ + public int X { get; set; } + public int Y { get; set; } + public int Width { get; set; } + public int Height { get; set; } + public DungeonRoomType Type { get; set; } = DungeonRoomType.Combat; + + public int CenterX => X + Width / 2; + public int CenterY => Y + Height / 2; + + public DungeonRoom() { } + + public DungeonRoom(int x, int y, int width, int height) + { + X = x; Y = y; Width = width; Height = height; + } + + public bool Intersects(DungeonRoom other, int padding = 0) + { + return X - padding < other.X + other.Width + padding && + X + Width + padding > other.X - padding && + Y - padding < other.Y + other.Height + padding && + Y + Height + padding > other.Y - padding; + } +} + +public enum DungeonRoomType +{ + Entrance, + Combat, + Treasure, + Boss, + Empty +} diff --git a/Game/Dungeon/DungeonSimulation.cs b/Game/Dungeon/DungeonSimulation.cs index df89839..8a5e456 100644 --- a/Game/Dungeon/DungeonSimulation.cs +++ b/Game/Dungeon/DungeonSimulation.cs @@ -1,17 +1,16 @@ using System.Collections.Concurrent; -using DungeonCrawler.Data.Entities; +using Server.Data.Entities; +using Server.Data.Enums; -namespace DungeonCrawler.Game.Dungeon; +namespace Server.Game.Dungeon; /// /// Runtime simulation for an active dungeon instance /// public class DungeonSimulation { - public Guid Id { get; } - public int Tier { get; } - public int Seed { get; } public DungeonLayout Layout { get; } + public int Tier { get; } // Tick rate public const int TicksPerSecond = 20; @@ -29,48 +28,27 @@ public class DungeonSimulation // Combat tracking private readonly List _pendingDamageEvents = new(); private readonly List _pendingDeathEvents = new(); - private readonly List _pendingLootEvents = new(); private int _nextDroppedItemId = 1; - private readonly object _lock = new(); + private readonly Dictionary _mobDefinitions; - // Mob definitions cache - private readonly Dictionary _mobDefinitions; - - public DungeonSimulation(Guid id, int tier, int seed, Dictionary mobDefinitions) + public DungeonSimulation(DungeonLayout layout, int tier, Dictionary mobDefinitions) { - Id = id; + Layout = layout; Tier = tier; - Seed = seed; _mobDefinitions = mobDefinitions; - // Generate dungeon layout - var generator = new DungeonGenerator(seed, tier); - Layout = generator.Generate(); - - // Spawn mobs from layout SpawnMobs(); - - // Initialize chests - foreach (var chestSpawn in Layout.ChestSpawns) - { - Chests[chestSpawn.Id] = new ChestInstance - { - Id = chestSpawn.Id, - X = chestSpawn.X * 32 + 16, // Center of tile - Y = chestSpawn.Y * 32 + 16, - Type = chestSpawn.ChestType, - IsOpened = false - }; - } + InitializeChests(); } private void SpawnMobs() { + var rng = new Random(Layout.Seed); + foreach (var mobSpawn in Layout.MobSpawns) { - // Pick appropriate mob definition based on spawn type and tier - var mobDef = SelectMobDefinition(mobSpawn.MobType); + var mobDef = SelectMobDefinition(mobSpawn.MobType, rng); if (mobDef == null) continue; var stats = mobDef.GetStatsForTier(Tier); @@ -97,7 +75,22 @@ public class DungeonSimulation } } - private MobDefinition? SelectMobDefinition(MobSpawnType spawnType) + private void InitializeChests() + { + foreach (var chestSpawn in Layout.ChestSpawns) + { + Chests[chestSpawn.Id] = new ChestInstance + { + Id = chestSpawn.Id, + X = chestSpawn.X * 32 + 16, + Y = chestSpawn.Y * 32 + 16, + Type = chestSpawn.ChestType, + IsOpened = false + }; + } + } + + private DungeonMobDefinition? SelectMobDefinition(DungeonMobSpawnType spawnType, Random rng) { var candidates = _mobDefinitions.Values .Where(m => m.IsEnabled && m.MinTier <= Tier && m.MaxTier >= Tier) @@ -105,67 +98,33 @@ public class DungeonSimulation if (candidates.Count == 0) return null; - // Filter by spawn type candidates = spawnType switch { - MobSpawnType.Boss => candidates.Where(m => m.Type == MobType.Boss).ToList(), - MobSpawnType.Elite => candidates.Where(m => m.Type == MobType.Elite || m.Type == MobType.Miniboss).ToList(), + DungeonMobSpawnType.Boss => candidates.Where(m => m.Type == MobType.Boss).ToList(), + DungeonMobSpawnType.Elite => candidates.Where(m => m.Type == MobType.Elite || m.Type == MobType.Miniboss).ToList(), _ => candidates.Where(m => m.Type == MobType.Normal || m.Type == MobType.Swarm).ToList() }; if (candidates.Count == 0) { - // Fallback to any mob for this tier - candidates = _mobDefinitions.Values - .Where(m => m.IsEnabled && m.MinTier <= Tier) - .ToList(); + candidates = _mobDefinitions.Values.Where(m => m.IsEnabled && m.MinTier <= Tier).ToList(); } - if (candidates.Count == 0) return null; - - // Random selection (could add weights later) - var rng = new Random(Seed + Layout.MobSpawns.Count); - return candidates[rng.Next(candidates.Count)]; - } - - /// - /// Add a player to the dungeon - /// - public PlayerInstance AddPlayer(ulong characterId, string name, CharacterCombatStats stats, float x, float y) - { - var player = new PlayerInstance - { - CharacterId = characterId, - Name = name, - X = x, - Y = y, - Health = stats.MaxHealth, - MaxHealth = stats.MaxHealth, - Mana = stats.MaxMana, - MaxMana = stats.MaxMana, - Stamina = stats.MaxStamina, - MaxStamina = stats.MaxStamina, - Stats = stats, - IsAlive = true - }; - - Players[characterId] = player; - return player; + return candidates.Count == 0 ? null : candidates[rng.Next(candidates.Count)]; } /// /// Process one simulation tick /// - public TickResult Tick() + public TickResult Tick(long tick) { - if (Phase != DungeonPhase.Active) - return new TickResult(); + CurrentTick = tick; - CurrentTick++; + if (Phase != DungeonPhase.Active) + return new TickResult { Phase = Phase }; _pendingDamageEvents.Clear(); _pendingDeathEvents.Clear(); - _pendingLootEvents.Clear(); // Update all mobs (AI) foreach (var mob in Mobs.Values.Where(m => m.IsAlive)) @@ -173,7 +132,7 @@ public class DungeonSimulation UpdateMob(mob); } - // Update players (regeneration, status effects) + // Update players (movement, regeneration) foreach (var player in Players.Values.Where(p => p.IsAlive)) { UpdatePlayer(player); @@ -183,7 +142,6 @@ public class DungeonSimulation if (Mobs.Values.All(m => !m.IsAlive)) { Phase = DungeonPhase.Cleared; - // Spawn exit SpawnExit(); } @@ -191,7 +149,6 @@ public class DungeonSimulation { DamageEvents = new List(_pendingDamageEvents), DeathEvents = new List(_pendingDeathEvents), - LootEvents = new List(_pendingLootEvents), Phase = Phase }; } @@ -214,91 +171,55 @@ public class DungeonSimulation if (target == null) { - // No players - return to spawn mob.State = MobState.Returning; mob.TargetId = null; MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f); return; } - // Check if in aggro range if (closestDist <= mob.Stats.AggroRange) { mob.TargetId = target.CharacterId; - // Check leash range float distFromSpawn = Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY); if (distFromSpawn > mob.Stats.LeashRange) { - // Too far from spawn, return mob.State = MobState.Returning; mob.TargetId = null; MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed); - - // Heal while returning mob.Health = Math.Min(mob.MaxHealth, mob.Health + (int)(mob.MaxHealth * 0.02f)); return; } - // In attack range? if (closestDist <= mob.Stats.AttackRange) { mob.State = MobState.Attacking; - // Check attack cooldown float attackInterval = 1f / mob.Stats.AttackSpeed; if (CurrentTick - mob.LastAttackTick >= (long)(attackInterval * TicksPerSecond)) { - // Attack! MobAttackPlayer(mob, target); mob.LastAttackTick = CurrentTick; } } else { - // Chase mob.State = MobState.Chasing; MoveToward(mob, target.X, target.Y, mob.Stats.MoveSpeed); } } else { - // Out of aggro range - if (mob.State == MobState.Chasing || mob.State == MobState.Attacking) - { - // Lost target, return - mob.State = MobState.Returning; - mob.TargetId = null; - } - else - { - mob.State = MobState.Idle; - } - - // Return to spawn if not at spawn - if (Distance(mob.X, mob.Y, mob.SpawnX, mob.SpawnY) > 5) - { - MoveToward(mob, mob.SpawnX, mob.SpawnY, mob.Stats.MoveSpeed * 0.5f); - } + mob.State = MobState.Idle; + mob.TargetId = null; } } private void MobAttackPlayer(MobInstance mob, PlayerInstance player) { - // Calculate damage - int damage = mob.Stats.PhysicalDamage; - - // Apply player armor reduction - if (player.Stats.Armor > 0) - { - float reduction = player.Stats.Armor / (float)(player.Stats.Armor + 100); - damage = (int)(damage * (1f - reduction)); - } - - damage = Math.Max(1, damage); // Minimum 1 damage - - // Apply damage + int damage = mob.Stats.PhysicalDamage + mob.Stats.MagicDamage; player.Health -= damage; + player.IsInCombat = true; player.LastCombatTick = CurrentTick; _pendingDamageEvents.Add(new DamageEvent @@ -307,11 +228,9 @@ public class DungeonSimulation SourceId = mob.Id, TargetType = EntityType.Player, TargetId = (int)player.CharacterId, - Damage = damage, - DamageType = DamageType.Physical + Damage = damage }); - // Check death if (player.Health <= 0) { player.Health = 0; @@ -321,299 +240,117 @@ public class DungeonSimulation { EntityType = EntityType.Player, EntityId = (int)player.CharacterId, + EntityName = player.CharacterName, KillerType = EntityType.Mob, KillerId = mob.Id, - EntityName = player.Name, KillerName = mob.Name }); - - // Drop player's inventory (mob holds it) - mob.HeldLoot.AddRange(player.Inventory); - player.Inventory.Clear(); } } private void UpdatePlayer(PlayerInstance player) { - // Check if out of combat (for escape teleport) - float secondsSinceCombat = (CurrentTick - player.LastCombatTick) / (float)TicksPerSecond; - player.IsInCombat = secondsSinceCombat < 5f; // 5 seconds to leave combat - - // Regeneration (only out of combat or reduced in combat) - float regenMultiplier = player.IsInCombat ? 0.2f : 1f; - float regenRate = player.Stats.RegenRate * regenMultiplier * TickDelta; - - player.Health = Math.Min(player.MaxHealth, player.Health + regenRate * 2); - player.Mana = Math.Min(player.MaxMana, player.Mana + regenRate); - player.Stamina = Math.Min(player.MaxStamina, player.Stamina + regenRate * 3); - } - - /// - /// Player attacks - called from input handler - /// - public void PlayerAttack(ulong characterId, float aimAngle) - { - if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive) - return; - - // Check attack cooldown - float attackInterval = 1f / player.Stats.AttackSpeed; - if (CurrentTick - player.LastAttackTick < (long)(attackInterval * TicksPerSecond)) - return; - - player.LastAttackTick = CurrentTick; - player.LastCombatTick = CurrentTick; - - // Get attack range and damage from equipped weapon (or use base) - float attackRange = player.WeaponRange > 0 ? player.WeaponRange : 50f; - int baseDamage = player.WeaponDamage > 0 ? player.WeaponDamage : 5 + player.Stats.Strength; - - // Apply damage multiplier - int damage = (int)(baseDamage * player.Stats.PhysicalDamageMultiplier); - - // Find mobs in attack arc - float attackArc = 0.5f; // radians (~30 degrees) - - foreach (var mob in Mobs.Values.Where(m => m.IsAlive)) + // Process movement input + if (player.InputX != 0 || player.InputY != 0) { - float dist = Distance(player.X, player.Y, mob.X, mob.Y); - if (dist > attackRange) continue; + float speed = player.MoveSpeed * TickDelta; + float newX = player.X + player.InputX * speed; + float newY = player.Y + player.InputY * speed; - // Check angle - float angleToMob = MathF.Atan2(mob.Y - player.Y, mob.X - player.X); - float angleDiff = NormalizeAngle(angleToMob - aimAngle); + if (CanMoveTo(newX, player.Y)) player.X = newX; + if (CanMoveTo(player.X, newY)) player.Y = newY; - if (MathF.Abs(angleDiff) > attackArc) continue; - - // Hit! - int actualDamage = mob.Stats.CalculateDamage(damage, DamageType.Physical); - mob.Health -= actualDamage; - - _pendingDamageEvents.Add(new DamageEvent + if (player.InputX != 0 || player.InputY != 0) { - SourceType = EntityType.Player, - SourceId = (int)characterId, - TargetType = EntityType.Mob, - TargetId = mob.Id, - Damage = actualDamage, - DamageType = DamageType.Physical - }); - - // Check death - if (mob.Health <= 0) - { - MobDeath(mob, player); + player.Rotation = MathF.Atan2(player.InputY, player.InputX); } - - // Only hit one mob per swing (for melee) - // TODO: Make this configurable for cleave weapons - break; + } + + // Process attack + if (player.WantsToAttack && player.AttackTargetId.HasValue) + { + TryPlayerAttack(player, player.AttackTargetId.Value); + player.WantsToAttack = false; + } + + // Regeneration (out of combat) + if (CurrentTick - player.LastCombatTick > TicksPerSecond * 5) + { + player.IsInCombat = false; + player.Health = Math.Min(player.MaxHealth, player.Health + 0.5f); + player.Mana = Math.Min(player.MaxMana, player.Mana + 0.3f); + player.Stamina = Math.Min(player.MaxStamina, player.Stamina + 1f); } } - /// - /// Player attacks another player (PvP) - /// - public void PlayerAttackPlayer(ulong attackerId, ulong targetId, float aimAngle) + private void TryPlayerAttack(PlayerInstance player, ulong targetId) { - if (!Players.TryGetValue(attackerId, out var attacker) || !attacker.IsAlive) - return; - if (!Players.TryGetValue(targetId, out var target) || !target.IsAlive) + if (!Mobs.TryGetValue((int)targetId, out var mob) || !mob.IsAlive) return; - // Check attack cooldown - float attackInterval = 1f / attacker.Stats.AttackSpeed; - if (CurrentTick - attacker.LastAttackTick < (long)(attackInterval * TicksPerSecond)) - return; + float dist = Distance(player.X, player.Y, mob.X, mob.Y); + if (dist > 60) return; // Out of range - attacker.LastAttackTick = CurrentTick; - attacker.LastCombatTick = CurrentTick; - target.LastCombatTick = CurrentTick; + // Calculate damage + int damage = (int)(10 * (1 + player.Strength * 0.05f)); - float attackRange = attacker.WeaponRange > 0 ? attacker.WeaponRange : 50f; - float dist = Distance(attacker.X, attacker.Y, target.X, target.Y); - if (dist > attackRange) return; - - int baseDamage = attacker.WeaponDamage > 0 ? attacker.WeaponDamage : 5 + attacker.Stats.Strength; - int damage = (int)(baseDamage * attacker.Stats.PhysicalDamageMultiplier); - - // Apply target armor - if (target.Stats.Armor > 0) - { - float reduction = target.Stats.Armor / (float)(target.Stats.Armor + 100); - damage = (int)(damage * (1f - reduction)); - } - - damage = Math.Max(1, damage); - target.Health -= damage; + mob.Health -= damage; + player.IsInCombat = true; + player.LastCombatTick = CurrentTick; _pendingDamageEvents.Add(new DamageEvent { SourceType = EntityType.Player, - SourceId = (int)attackerId, - TargetType = EntityType.Player, - TargetId = (int)targetId, - Damage = damage, - DamageType = DamageType.Physical, - IsPvP = true + SourceId = (int)player.CharacterId, + TargetType = EntityType.Mob, + TargetId = mob.Id, + Damage = damage }); - if (target.Health <= 0) + if (mob.Health <= 0) { - target.Health = 0; - target.IsAlive = false; - attacker.PlayersKilled++; + mob.Health = 0; + mob.IsAlive = false; + mob.State = MobState.Dead; + + player.XpGained += mob.Stats.XpReward; + player.MobsKilled++; _pendingDeathEvents.Add(new DeathEvent { - EntityType = EntityType.Player, - EntityId = (int)targetId, + EntityType = EntityType.Mob, + EntityId = mob.Id, + EntityName = mob.Name, KillerType = EntityType.Player, - KillerId = (int)attackerId, - EntityName = target.Name, - KillerName = attacker.Name, - IsPvP = true - }); - - // Transfer inventory to killer - attacker.Inventory.AddRange(target.Inventory); - target.Inventory.Clear(); - } - } - - private void MobDeath(MobInstance mob, PlayerInstance killer) - { - mob.Health = 0; - mob.IsAlive = false; - mob.State = MobState.Dead; - - _pendingDeathEvents.Add(new DeathEvent - { - EntityType = EntityType.Mob, - EntityId = mob.Id, - KillerType = EntityType.Player, - KillerId = (int)killer.CharacterId, - EntityName = mob.Name, - KillerName = killer.Name, - XpReward = mob.Stats.XpReward - }); - - // Award XP - int xp = (int)(mob.Stats.XpReward * killer.Stats.XpBonus); - killer.XpGained += xp; - - // Drop loot (including any player loot the mob was holding) - DropMobLoot(mob); - } - - private void DropMobLoot(MobInstance mob) - { - // Drop any held player loot - foreach (var item in mob.HeldLoot) - { - CreateDroppedItem(mob.X, mob.Y, item); - } - mob.HeldLoot.Clear(); - - // TODO: Roll loot table for mob drops - // For now, just create some placeholder loot - if (mob.Type == MobType.Boss) - { - // Guaranteed drop from boss - _pendingLootEvents.Add(new LootEvent - { - X = mob.X, - Y = mob.Y, - MobId = mob.Id, - MobName = mob.Name, - IsBoss = true + KillerId = (int)player.CharacterId, + KillerName = player.CharacterName, + XpReward = mob.Stats.XpReward }); } } - private void CreateDroppedItem(float x, float y, ItemDrop item) - { - int id = _nextDroppedItemId++; - DroppedItems[id] = new DroppedItem - { - Id = id, - ItemDefinitionId = item.ItemDefinitionId, - Quantity = item.Quantity, - X = x + (new Random().NextSingle() - 0.5f) * 30, - Y = y + (new Random().NextSingle() - 0.5f) * 30, - DroppedAtTick = CurrentTick - }; - } - private void SpawnExit() { - // Spawn exit at boss room or last room - var lastRoom = Layout.Rooms.LastOrDefault(); - if (lastRoom != null) + // Spawn exit at boss room location + if (Layout.Rooms.Count > 0) { - Layout.ExitPosition = new Point(lastRoom.CenterX, lastRoom.CenterY); + var bossRoom = Layout.Rooms.LastOrDefault(r => r.Type == DungeonRoomType.Boss) + ?? Layout.Rooms[^1]; + Layout.ExitPosition = new DungeonPoint(bossRoom.CenterX, bossRoom.CenterY); } } - /// - /// Player picks up an item - /// - public bool TryPickupItem(ulong characterId, int droppedItemId) + public bool CanMoveTo(float x, float y) { - if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive) + int tileX = (int)(x / 32); + int tileY = (int)(y / 32); + + if (tileX < 0 || tileX >= Layout.Width || tileY < 0 || tileY >= Layout.Height) return false; - if (!DroppedItems.TryRemove(droppedItemId, out var item)) - return false; - - // Check distance - if (Distance(player.X, player.Y, item.X, item.Y) > 60) - { - // Too far, put item back - DroppedItems[droppedItemId] = item; - return false; - } - - // Add to inventory - player.Inventory.Add(new ItemDrop - { - ItemDefinitionId = item.ItemDefinitionId, - Quantity = item.Quantity - }); - - return true; + return Layout.Tiles[tileX, tileY] == 1; } - /// - /// Player opens a chest - /// - public bool TryOpenChest(ulong characterId, int chestId) - { - if (!Players.TryGetValue(characterId, out var player) || !player.IsAlive) - return false; - - if (!Chests.TryGetValue(chestId, out var chest) || chest.IsOpened) - return false; - - // Check distance - if (Distance(player.X, player.Y, chest.X, chest.Y) > 60) - return false; - - chest.IsOpened = true; - - // TODO: Roll loot table - _pendingLootEvents.Add(new LootEvent - { - X = chest.X, - Y = chest.Y, - ChestId = chestId, - ChestType = chest.Type - }); - - return true; - } - - // Movement helpers private void MoveToward(MobInstance mob, float targetX, float targetY, float speed) { float dx = targetX - mob.X; @@ -628,202 +365,18 @@ public class DungeonSimulation float newX = mob.X + (dx / dist) * moveAmount; float newY = mob.Y + (dy / dist) * moveAmount; - // Check collision with walls if (CanMoveTo(newX, mob.Y)) mob.X = newX; if (CanMoveTo(mob.X, newY)) mob.Y = newY; - // Update facing direction mob.Rotation = MathF.Atan2(dy, dx); } - public bool CanMoveTo(float x, float y) - { - int tileX = (int)(x / 32); - int tileY = (int)(y / 32); - - if (tileX < 0 || tileX >= Layout.Width || tileY < 0 || tileY >= Layout.Height) - return false; - - return Layout.Tiles[tileX, tileY] == 1; - } - private static float Distance(float x1, float y1, float x2, float y2) { float dx = x2 - x1; float dy = y2 - y1; return MathF.Sqrt(dx * dx + dy * dy); } - - private static float NormalizeAngle(float angle) - { - while (angle > MathF.PI) angle -= MathF.PI * 2; - while (angle < -MathF.PI) angle += MathF.PI * 2; - return angle; - } -} - -// Runtime instances - -public class PlayerInstance -{ - public ulong CharacterId { get; set; } - public string Name { get; set; } = ""; - public float X { get; set; } - public float Y { get; set; } - public float Rotation { get; set; } - - public float Health { get; set; } - public float MaxHealth { get; set; } - public float Mana { get; set; } - public float MaxMana { get; set; } - public float Stamina { get; set; } - public float MaxStamina { get; set; } - - public bool IsAlive { get; set; } = true; - public bool IsInCombat { get; set; } - - public CharacterCombatStats Stats { get; set; } = new(); - - // Equipped weapon stats - public int WeaponDamage { get; set; } - public float WeaponRange { get; set; } - public DamageType WeaponDamageType { get; set; } = DamageType.Physical; - - // Inventory (items being carried) - public List Inventory { get; set; } = new(); - - // Session stats - public int XpGained { get; set; } - public int MobsKilled { get; set; } - public int PlayersKilled { get; set; } - - // Tick tracking - public long LastAttackTick { get; set; } - public long LastCombatTick { get; set; } - - // Input state - public float InputDx { get; set; } - public float InputDy { get; set; } - public float AimAngle { get; set; } -} - -public class MobInstance -{ - public int Id { get; set; } - public int DefinitionId { get; set; } - public string Name { get; set; } = ""; - - public float X { get; set; } - public float Y { get; set; } - public float Rotation { get; set; } - public float SpawnX { get; set; } - public float SpawnY { get; set; } - - public int Health { get; set; } - public int MaxHealth { get; set; } - public bool IsAlive { get; set; } = true; - - public MobCombatStats Stats { get; set; } = new(); - public MobState State { get; set; } = MobState.Idle; - public MobType Type { get; set; } - - public ulong? TargetId { get; set; } - public long LastAttackTick { get; set; } - - // Visual - public string SpriteSheet { get; set; } = ""; - public int SpriteWidth { get; set; } = 32; - public int SpriteHeight { get; set; } = 32; - public string TintColor { get; set; } = "#ffffff"; - - // Loot being held (from killed players) - public List HeldLoot { get; set; } = new(); -} - -public enum MobState -{ - Idle, - Chasing, - Attacking, - Returning, - Fleeing, - Dead -} - -public class ChestInstance -{ - public int Id { get; set; } - public float X { get; set; } - public float Y { get; set; } - public ChestType Type { get; set; } - public bool IsOpened { get; set; } -} - -public class DroppedItem -{ - public int Id { get; set; } - public int ItemDefinitionId { get; set; } - public int Quantity { get; set; } - public float X { get; set; } - public float Y { get; set; } - public long DroppedAtTick { get; set; } -} - -public class ItemDrop -{ - public int ItemDefinitionId { get; set; } - public int Quantity { get; set; } -} - -// Events - -public class TickResult -{ - public List DamageEvents { get; set; } = new(); - public List DeathEvents { get; set; } = new(); - public List LootEvents { get; set; } = new(); - public DungeonPhase Phase { get; set; } -} - -public class DamageEvent -{ - public EntityType SourceType { get; set; } - public int SourceId { get; set; } - public EntityType TargetType { get; set; } - public int TargetId { get; set; } - public int Damage { get; set; } - public DamageType DamageType { get; set; } - public bool IsPvP { get; set; } -} - -public class DeathEvent -{ - public EntityType EntityType { get; set; } - public int EntityId { get; set; } - public EntityType KillerType { get; set; } - public int KillerId { get; set; } - public string EntityName { get; set; } = ""; - public string KillerName { get; set; } = ""; - public int XpReward { get; set; } - public bool IsPvP { get; set; } -} - -public class LootEvent -{ - public float X { get; set; } - public float Y { get; set; } - public int? MobId { get; set; } - public string? MobName { get; set; } - public int? ChestId { get; set; } - public ChestType? ChestType { get; set; } - public bool IsBoss { get; set; } -} - -public enum EntityType -{ - Player, - Mob, - Chest } public enum DungeonPhase diff --git a/Game/Dungeon/MobInstance.cs b/Game/Dungeon/MobInstance.cs new file mode 100644 index 0000000..0e9361a --- /dev/null +++ b/Game/Dungeon/MobInstance.cs @@ -0,0 +1,47 @@ +using Server.Data.Entities; +using Server.Data.Enums; + +namespace Server.Game.Dungeon; + +/// +/// Runtime instance of a mob in a dungeon +/// +public class MobInstance +{ + public int Id { get; set; } + public int DefinitionId { get; set; } + public string Name { get; set; } = ""; + + public float X { get; set; } + public float Y { get; set; } + public float Rotation { get; set; } + public float SpawnX { get; set; } + public float SpawnY { get; set; } + + public int Health { get; set; } + public int MaxHealth { get; set; } + public bool IsAlive { get; set; } = true; + + public DungeonMobCombatStats Stats { get; set; } = new(); + public MobState State { get; set; } = MobState.Idle; + public MobType Type { get; set; } + + public ulong? TargetId { get; set; } + public long LastAttackTick { get; set; } + + // Visual + public string SpriteSheet { get; set; } = ""; + public int SpriteWidth { get; set; } = 32; + public int SpriteHeight { get; set; } = 32; + public string TintColor { get; set; } = "#ffffff"; +} + +public enum MobState +{ + Idle, + Chasing, + Attacking, + Returning, + Fleeing, + Dead +} diff --git a/Game/Dungeon/PlayerInstance.cs b/Game/Dungeon/PlayerInstance.cs new file mode 100644 index 0000000..e5f8b0c --- /dev/null +++ b/Game/Dungeon/PlayerInstance.cs @@ -0,0 +1,43 @@ +namespace Server.Game.Dungeon; + +/// +/// Runtime instance of a player in a dungeon +/// +public class PlayerInstance +{ + public ulong CharacterId { get; set; } + public string CharacterName { get; set; } = ""; + public float X { get; set; } + public float Y { get; set; } + public float Rotation { get; set; } + + public float Health { get; set; } + public float MaxHealth { get; set; } + public float Mana { get; set; } + public float MaxMana { get; set; } + public float Stamina { get; set; } + public float MaxStamina { get; set; } + + public float MoveSpeed { get; set; } = 100f; + public float AttackSpeed { get; set; } = 1f; + public int Strength { get; set; } + public int Intelligence { get; set; } + + public bool IsAlive { get; set; } = true; + public bool IsInCombat { get; set; } + + // Session stats + public int XpGained { get; set; } + public int MobsKilled { get; set; } + public int PlayersKilled { get; set; } + + // Tick tracking + public long LastAttackTick { get; set; } + public long LastCombatTick { get; set; } + + // Input state (set by handler) + public float InputX { get; set; } + public float InputY { get; set; } + public bool WantsToAttack { get; set; } + public ulong? AttackTargetId { get; set; } +} diff --git a/Game/Dungeon/TickResult.cs b/Game/Dungeon/TickResult.cs new file mode 100644 index 0000000..bfbad12 --- /dev/null +++ b/Game/Dungeon/TickResult.cs @@ -0,0 +1,38 @@ +using Server.Data.Enums; + +namespace Server.Game.Dungeon; + +public class TickResult +{ + public List DamageEvents { get; set; } = new(); + public List DeathEvents { get; set; } = new(); + public DungeonPhase Phase { get; set; } +} + +public class DamageEvent +{ + public EntityType SourceType { get; set; } + public int SourceId { get; set; } + public EntityType TargetType { get; set; } + public int TargetId { get; set; } + public int Damage { get; set; } + public DamageType DamageType { get; set; } +} + +public class DeathEvent +{ + public EntityType EntityType { get; set; } + public int EntityId { get; set; } + public EntityType KillerType { get; set; } + public int KillerId { get; set; } + public string EntityName { get; set; } = ""; + public string KillerName { get; set; } = ""; + public int XpReward { get; set; } +} + +public enum EntityType +{ + Player, + Mob, + Chest +} diff --git a/Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs b/Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs new file mode 100644 index 0000000..d9ce79c --- /dev/null +++ b/Migrations/20251206230532_AddDungeonCrawlerEntities.Designer.cs @@ -0,0 +1,1439 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Server.Data; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + [DbContext(typeof(GameDbContext))] + [Migration("20251206230532_AddDungeonCrawlerEntities")] + partial class AddDungeonCrawlerEntities + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("Role") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(0); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("BossesKilled") + .HasColumnType("int"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)"); + + b.Property("CurrentHealth") + .HasColumnType("int"); + + b.Property("CurrentMana") + .HasColumnType("int"); + + b.Property("Dexterity") + .HasColumnType("int"); + + b.Property("DungeonsCompleted") + .HasColumnType("int"); + + b.Property("Endurance") + .HasColumnType("int"); + + b.Property("EquippedAccessory") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedBoots") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedChest") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedGloves") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedHead") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedLegs") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedOffhand") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedWeapon") + .HasColumnType("bigint unsigned"); + + b.Property("Experience") + .HasColumnType("bigint"); + + b.Property("Intelligence") + .HasColumnType("int"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastPlayedAt") + .HasColumnType("datetime(6)"); + + b.Property("Level") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PlayersKilled") + .HasColumnType("int"); + + b.Property("Strength") + .HasColumnType("int"); + + b.Property("TotalDeaths") + .HasColumnType("int"); + + b.Property("TotalKills") + .HasColumnType("int"); + + b.Property("UnspentStatPoints") + .HasColumnType("int"); + + b.Property("Wisdom") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.ToTable("dungeon_characters"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacterItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AcquiredAt") + .HasColumnType("datetime(6)"); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("DefinitionId") + .HasColumnType("int"); + + b.Property("ItemDefinitionId") + .HasColumnType("int"); + + b.Property("Quantity") + .HasColumnType("int"); + + b.Property("SlotIndex") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("DefinitionId"); + + b.ToTable("dungeon_character_items"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonItemDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("Armor") + .HasColumnType("int"); + + b.Property("AttackRange") + .HasColumnType("float"); + + b.Property("BonusDexterity") + .HasColumnType("int"); + + b.Property("BonusEndurance") + .HasColumnType("int"); + + b.Property("BonusHealth") + .HasColumnType("int"); + + b.Property("BonusIntelligence") + .HasColumnType("int"); + + b.Property("BonusMana") + .HasColumnType("int"); + + b.Property("BonusStrength") + .HasColumnType("int"); + + b.Property("BonusWisdom") + .HasColumnType("int"); + + b.Property("DamageType") + .HasColumnType("int"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EquipSlot") + .HasColumnType("int"); + + b.Property("HealAmount") + .HasColumnType("int"); + + b.Property("IsEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("IsTeleportScroll") + .HasColumnType("tinyint(1)"); + + b.Property("MagicResist") + .HasColumnType("int"); + + b.Property("ManaRestore") + .HasColumnType("int"); + + b.Property("MaxDamage") + .HasColumnType("int"); + + b.Property("MaxStack") + .HasColumnType("int"); + + b.Property("MinDamage") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("int"); + + b.Property("RequiredDexterity") + .HasColumnType("int"); + + b.Property("RequiredIntelligence") + .HasColumnType("int"); + + b.Property("RequiredLevel") + .HasColumnType("int"); + + b.Property("RequiredStrength") + .HasColumnType("int"); + + b.Property("RequiredWisdom") + .HasColumnType("int"); + + b.Property("SpriteId") + .HasColumnType("int"); + + b.Property("Stackable") + .HasColumnType("tinyint(1)"); + + b.Property("StaminaRestore") + .HasColumnType("int"); + + b.Property("TeachesSpellId") + .HasColumnType("int"); + + b.Property("Type") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("dungeon_item_definitions"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonLearnedSpell", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("DefinitionId") + .HasColumnType("int"); + + b.Property("LearnedAt") + .HasColumnType("datetime(6)"); + + b.Property("SpellDefinitionId") + .HasColumnType("int"); + + b.Property("SpellLevel") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("DefinitionId"); + + b.ToTable("dungeon_learned_spells"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonMobDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AbilitiesJson") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("AggroRange") + .HasColumnType("float"); + + b.Property("AnimationSpeed") + .HasColumnType("float"); + + b.Property("ArmorPerTier") + .HasColumnType("float"); + + b.Property("AttackFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("AttackRange") + .HasColumnType("float"); + + b.Property("AttackSpeed") + .HasColumnType("float"); + + b.Property("BaseArmor") + .HasColumnType("int"); + + b.Property("BaseHealth") + .HasColumnType("int"); + + b.Property("BaseMagicDamage") + .HasColumnType("int"); + + b.Property("BaseMagicResist") + .HasColumnType("int"); + + b.Property("BaseMana") + .HasColumnType("int"); + + b.Property("BasePhysicalDamage") + .HasColumnType("int"); + + b.Property("BaseXp") + .HasColumnType("int"); + + b.Property("Category") + .HasColumnType("int"); + + b.Property("DamagePerTier") + .HasColumnType("float"); + + b.Property("DeathFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("DropChanceMultiplier") + .HasColumnType("float"); + + b.Property("HealthPerTier") + .HasColumnType("float"); + + b.Property("IdleFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LeashRange") + .HasColumnType("float"); + + b.Property("LootTableId") + .HasColumnType("int"); + + b.Property("MaxTier") + .HasColumnType("int"); + + b.Property("MinTier") + .HasColumnType("int"); + + b.Property("MoveSpeed") + .HasColumnType("float"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ResistancesJson") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("SpriteHeight") + .HasColumnType("int"); + + b.Property("SpriteIndex") + .HasColumnType("int"); + + b.Property("SpriteSheet") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("SpriteWidth") + .HasColumnType("int"); + + b.Property("TintColor") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("Type") + .HasColumnType("int"); + + b.Property("WalkFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("XpPerTier") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("dungeon_mob_definitions"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonSpellDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AreaOfEffect") + .HasColumnType("float"); + + b.Property("BaseDamage") + .HasColumnType("int"); + + b.Property("BaseHealing") + .HasColumnType("int"); + + b.Property("Cooldown") + .HasColumnType("float"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EffectColor") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("IsEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("IsShield") + .HasColumnType("tinyint(1)"); + + b.Property("IsTeleport") + .HasColumnType("tinyint(1)"); + + b.Property("ManaCost") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Range") + .HasColumnType("float"); + + b.Property("RequiredIntelligence") + .HasColumnType("int"); + + b.Property("RequiredLevel") + .HasColumnType("int"); + + b.Property("RequiredWisdom") + .HasColumnType("int"); + + b.Property("ShieldAmount") + .HasColumnType("int"); + + b.Property("SpriteId") + .HasColumnType("int"); + + b.Property("Type") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("dungeon_spell_definitions"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonStashItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("DefinitionId") + .HasColumnType("int"); + + b.Property("ItemDefinitionId") + .HasColumnType("int"); + + b.Property("Quantity") + .HasColumnType("int"); + + b.Property("SlotIndex") + .HasColumnType("int"); + + b.Property("StoredAt") + .HasColumnType("datetime(6)"); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("DefinitionId"); + + b.ToTable("dungeon_stash_items"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.GameItem", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("AmmoType") + .HasColumnType("int"); + + b.Property("Category") + .HasColumnType("int"); + + b.Property("CraftCost") + .HasColumnType("int"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Damage") + .HasColumnType("int"); + + b.Property("DamageReduction") + .HasColumnType("float"); + + b.Property("DashCooldown") + .HasColumnType("float"); + + b.Property("DashDistance") + .HasColumnType("float"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("ExplosionRadius") + .HasColumnType("float"); + + b.Property("FireRate") + .HasColumnType("float"); + + b.Property("HarvestMultiplier") + .HasColumnType("float"); + + b.Property("HealAmount") + .HasColumnType("int"); + + b.Property("HealthBonus") + .HasColumnType("int"); + + b.Property("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.Entities.DungeonCharacter", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany() + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacterItem", b => + { + b.HasOne("Server.Data.Entities.DungeonCharacter", "Character") + .WithMany("Inventory") + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Entities.DungeonItemDefinition", "Definition") + .WithMany() + .HasForeignKey("DefinitionId"); + + b.Navigation("Character"); + + b.Navigation("Definition"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonLearnedSpell", b => + { + b.HasOne("Server.Data.Entities.DungeonCharacter", "Character") + .WithMany("LearnedSpells") + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Entities.DungeonSpellDefinition", "Definition") + .WithMany() + .HasForeignKey("DefinitionId"); + + b.Navigation("Character"); + + b.Navigation("Definition"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonStashItem", b => + { + b.HasOne("Server.Data.Entities.DungeonCharacter", "Character") + .WithMany("Stash") + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Entities.DungeonItemDefinition", "Definition") + .WithMany() + .HasForeignKey("DefinitionId"); + + b.Navigation("Character"); + + b.Navigation("Definition"); + }); + + 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"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacter", b => + { + b.Navigation("Inventory"); + + b.Navigation("LearnedSpells"); + + b.Navigation("Stash"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20251206230532_AddDungeonCrawlerEntities.cs b/Migrations/20251206230532_AddDungeonCrawlerEntities.cs new file mode 100644 index 0000000..9f316d4 --- /dev/null +++ b/Migrations/20251206230532_AddDungeonCrawlerEntities.cs @@ -0,0 +1,354 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class AddDungeonCrawlerEntities : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "dungeon_characters", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + AccountId = table.Column(type: "bigint unsigned", nullable: false), + Name = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + CreatedAt = table.Column(type: "datetime(6)", nullable: false), + LastPlayedAt = table.Column(type: "datetime(6)", nullable: false), + Level = table.Column(type: "int", nullable: false), + Experience = table.Column(type: "bigint", nullable: false), + UnspentStatPoints = table.Column(type: "int", nullable: false), + Strength = table.Column(type: "int", nullable: false), + Intelligence = table.Column(type: "int", nullable: false), + Wisdom = table.Column(type: "int", nullable: false), + Endurance = table.Column(type: "int", nullable: false), + Dexterity = table.Column(type: "int", nullable: false), + CurrentHealth = table.Column(type: "int", nullable: false), + CurrentMana = table.Column(type: "int", nullable: false), + EquippedWeapon = table.Column(type: "bigint unsigned", nullable: true), + EquippedOffhand = table.Column(type: "bigint unsigned", nullable: true), + EquippedHead = table.Column(type: "bigint unsigned", nullable: true), + EquippedChest = table.Column(type: "bigint unsigned", nullable: true), + EquippedLegs = table.Column(type: "bigint unsigned", nullable: true), + EquippedBoots = table.Column(type: "bigint unsigned", nullable: true), + EquippedGloves = table.Column(type: "bigint unsigned", nullable: true), + EquippedAccessory = table.Column(type: "bigint unsigned", nullable: true), + TotalKills = table.Column(type: "int", nullable: false), + TotalDeaths = table.Column(type: "int", nullable: false), + PlayersKilled = table.Column(type: "int", nullable: false), + DungeonsCompleted = table.Column(type: "int", nullable: false), + BossesKilled = table.Column(type: "int", nullable: false), + IsDeleted = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_characters", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_characters_accounts_AccountId", + column: x => x.AccountId, + principalTable: "accounts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "dungeon_item_definitions", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Type = table.Column(type: "int", nullable: false), + Rarity = table.Column(type: "int", nullable: false), + EquipSlot = table.Column(type: "int", nullable: true), + RequiredStrength = table.Column(type: "int", nullable: false), + RequiredIntelligence = table.Column(type: "int", nullable: false), + RequiredWisdom = table.Column(type: "int", nullable: false), + RequiredDexterity = table.Column(type: "int", nullable: false), + RequiredLevel = table.Column(type: "int", nullable: false), + BonusStrength = table.Column(type: "int", nullable: false), + BonusIntelligence = table.Column(type: "int", nullable: false), + BonusWisdom = table.Column(type: "int", nullable: false), + BonusEndurance = table.Column(type: "int", nullable: false), + BonusDexterity = table.Column(type: "int", nullable: false), + BonusHealth = table.Column(type: "int", nullable: false), + BonusMana = table.Column(type: "int", nullable: false), + MinDamage = table.Column(type: "int", nullable: false), + MaxDamage = table.Column(type: "int", nullable: false), + AttackRange = table.Column(type: "float", nullable: false), + DamageType = table.Column(type: "int", nullable: false), + Armor = table.Column(type: "int", nullable: false), + MagicResist = table.Column(type: "int", nullable: false), + HealAmount = table.Column(type: "int", nullable: false), + ManaRestore = table.Column(type: "int", nullable: false), + StaminaRestore = table.Column(type: "int", nullable: false), + IsTeleportScroll = table.Column(type: "tinyint(1)", nullable: false), + TeachesSpellId = table.Column(type: "int", nullable: true), + Stackable = table.Column(type: "tinyint(1)", nullable: false), + MaxStack = table.Column(type: "int", nullable: false), + SpriteId = table.Column(type: "int", nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_item_definitions", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "dungeon_mob_definitions", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Type = table.Column(type: "int", nullable: false), + Category = table.Column(type: "int", nullable: false), + MinTier = table.Column(type: "int", nullable: false), + MaxTier = table.Column(type: "int", nullable: false), + BaseHealth = table.Column(type: "int", nullable: false), + BaseMana = table.Column(type: "int", nullable: false), + BasePhysicalDamage = table.Column(type: "int", nullable: false), + BaseMagicDamage = table.Column(type: "int", nullable: false), + BaseArmor = table.Column(type: "int", nullable: false), + BaseMagicResist = table.Column(type: "int", nullable: false), + MoveSpeed = table.Column(type: "float", nullable: false), + AttackRange = table.Column(type: "float", nullable: false), + AttackSpeed = table.Column(type: "float", nullable: false), + AggroRange = table.Column(type: "float", nullable: false), + LeashRange = table.Column(type: "float", nullable: false), + HealthPerTier = table.Column(type: "float", nullable: false), + DamagePerTier = table.Column(type: "float", nullable: false), + ArmorPerTier = table.Column(type: "float", nullable: false), + BaseXp = table.Column(type: "int", nullable: false), + XpPerTier = table.Column(type: "float", nullable: false), + LootTableId = table.Column(type: "int", nullable: false), + DropChanceMultiplier = table.Column(type: "float", nullable: false), + ResistancesJson = table.Column(type: "varchar(1024)", maxLength: 1024, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + AbilitiesJson = table.Column(type: "varchar(1024)", maxLength: 1024, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + SpriteSheet = table.Column(type: "varchar(128)", maxLength: 128, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + SpriteIndex = table.Column(type: "int", nullable: false), + SpriteWidth = table.Column(type: "int", nullable: false), + SpriteHeight = table.Column(type: "int", nullable: false), + TintColor = table.Column(type: "varchar(16)", maxLength: 16, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + IdleFrames = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + WalkFrames = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + AttackFrames = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + DeathFrames = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + AnimationSpeed = table.Column(type: "float", nullable: false), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_mob_definitions", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "dungeon_spell_definitions", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + Name = table.Column(type: "varchar(64)", maxLength: 64, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Description = table.Column(type: "varchar(256)", maxLength: 256, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + Type = table.Column(type: "int", nullable: false), + RequiredWisdom = table.Column(type: "int", nullable: false), + RequiredIntelligence = table.Column(type: "int", nullable: false), + RequiredLevel = table.Column(type: "int", nullable: false), + ManaCost = table.Column(type: "int", nullable: false), + Cooldown = table.Column(type: "float", nullable: false), + BaseDamage = table.Column(type: "int", nullable: false), + BaseHealing = table.Column(type: "int", nullable: false), + Range = table.Column(type: "float", nullable: false), + AreaOfEffect = table.Column(type: "float", nullable: false), + IsTeleport = table.Column(type: "tinyint(1)", nullable: false), + IsShield = table.Column(type: "tinyint(1)", nullable: false), + ShieldAmount = table.Column(type: "int", nullable: false), + SpriteId = table.Column(type: "int", nullable: false), + EffectColor = table.Column(type: "longtext", nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + IsEnabled = table.Column(type: "tinyint(1)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_spell_definitions", x => x.Id); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "dungeon_character_items", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + CharacterId = table.Column(type: "bigint unsigned", nullable: false), + ItemDefinitionId = table.Column(type: "int", nullable: false), + Quantity = table.Column(type: "int", nullable: false), + SlotIndex = table.Column(type: "int", nullable: false), + AcquiredAt = table.Column(type: "datetime(6)", nullable: false), + DefinitionId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_character_items", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_character_items_dungeon_characters_CharacterId", + column: x => x.CharacterId, + principalTable: "dungeon_characters", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_dungeon_character_items_dungeon_item_definitions_DefinitionId", + column: x => x.DefinitionId, + principalTable: "dungeon_item_definitions", + principalColumn: "Id"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "dungeon_stash_items", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + CharacterId = table.Column(type: "bigint unsigned", nullable: false), + ItemDefinitionId = table.Column(type: "int", nullable: false), + Quantity = table.Column(type: "int", nullable: false), + SlotIndex = table.Column(type: "int", nullable: false), + StoredAt = table.Column(type: "datetime(6)", nullable: false), + DefinitionId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_stash_items", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_stash_items_dungeon_characters_CharacterId", + column: x => x.CharacterId, + principalTable: "dungeon_characters", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_dungeon_stash_items_dungeon_item_definitions_DefinitionId", + column: x => x.DefinitionId, + principalTable: "dungeon_item_definitions", + principalColumn: "Id"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "dungeon_learned_spells", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + CharacterId = table.Column(type: "bigint unsigned", nullable: false), + SpellDefinitionId = table.Column(type: "int", nullable: false), + LearnedAt = table.Column(type: "datetime(6)", nullable: false), + SpellLevel = table.Column(type: "int", nullable: false), + DefinitionId = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_dungeon_learned_spells", x => x.Id); + table.ForeignKey( + name: "FK_dungeon_learned_spells_dungeon_characters_CharacterId", + column: x => x.CharacterId, + principalTable: "dungeon_characters", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_dungeon_learned_spells_dungeon_spell_definitions_DefinitionId", + column: x => x.DefinitionId, + principalTable: "dungeon_spell_definitions", + principalColumn: "Id"); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_character_items_CharacterId", + table: "dungeon_character_items", + column: "CharacterId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_character_items_DefinitionId", + table: "dungeon_character_items", + column: "DefinitionId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_characters_AccountId", + table: "dungeon_characters", + column: "AccountId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_learned_spells_CharacterId", + table: "dungeon_learned_spells", + column: "CharacterId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_learned_spells_DefinitionId", + table: "dungeon_learned_spells", + column: "DefinitionId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_stash_items_CharacterId", + table: "dungeon_stash_items", + column: "CharacterId"); + + migrationBuilder.CreateIndex( + name: "IX_dungeon_stash_items_DefinitionId", + table: "dungeon_stash_items", + column: "DefinitionId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "dungeon_character_items"); + + migrationBuilder.DropTable( + name: "dungeon_learned_spells"); + + migrationBuilder.DropTable( + name: "dungeon_mob_definitions"); + + migrationBuilder.DropTable( + name: "dungeon_stash_items"); + + migrationBuilder.DropTable( + name: "dungeon_spell_definitions"); + + migrationBuilder.DropTable( + name: "dungeon_characters"); + + migrationBuilder.DropTable( + name: "dungeon_item_definitions"); + } + } +} diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs index e76c785..f8ef1f3 100644 --- a/Migrations/GameDbContextModelSnapshot.cs +++ b/Migrations/GameDbContextModelSnapshot.cs @@ -81,6 +81,538 @@ namespace SystemRevivalServer.Migrations b.ToTable("accounts", (string)null); }); + modelBuilder.Entity("Server.Data.Entities.DungeonCharacter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("BossesKilled") + .HasColumnType("int"); + + b.Property("CreatedAt") + .HasColumnType("datetime(6)"); + + b.Property("CurrentHealth") + .HasColumnType("int"); + + b.Property("CurrentMana") + .HasColumnType("int"); + + b.Property("Dexterity") + .HasColumnType("int"); + + b.Property("DungeonsCompleted") + .HasColumnType("int"); + + b.Property("Endurance") + .HasColumnType("int"); + + b.Property("EquippedAccessory") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedBoots") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedChest") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedGloves") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedHead") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedLegs") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedOffhand") + .HasColumnType("bigint unsigned"); + + b.Property("EquippedWeapon") + .HasColumnType("bigint unsigned"); + + b.Property("Experience") + .HasColumnType("bigint"); + + b.Property("Intelligence") + .HasColumnType("int"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastPlayedAt") + .HasColumnType("datetime(6)"); + + b.Property("Level") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PlayersKilled") + .HasColumnType("int"); + + b.Property("Strength") + .HasColumnType("int"); + + b.Property("TotalDeaths") + .HasColumnType("int"); + + b.Property("TotalKills") + .HasColumnType("int"); + + b.Property("UnspentStatPoints") + .HasColumnType("int"); + + b.Property("Wisdom") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.ToTable("dungeon_characters"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacterItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AcquiredAt") + .HasColumnType("datetime(6)"); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("DefinitionId") + .HasColumnType("int"); + + b.Property("ItemDefinitionId") + .HasColumnType("int"); + + b.Property("Quantity") + .HasColumnType("int"); + + b.Property("SlotIndex") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("DefinitionId"); + + b.ToTable("dungeon_character_items"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonItemDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("Armor") + .HasColumnType("int"); + + b.Property("AttackRange") + .HasColumnType("float"); + + b.Property("BonusDexterity") + .HasColumnType("int"); + + b.Property("BonusEndurance") + .HasColumnType("int"); + + b.Property("BonusHealth") + .HasColumnType("int"); + + b.Property("BonusIntelligence") + .HasColumnType("int"); + + b.Property("BonusMana") + .HasColumnType("int"); + + b.Property("BonusStrength") + .HasColumnType("int"); + + b.Property("BonusWisdom") + .HasColumnType("int"); + + b.Property("DamageType") + .HasColumnType("int"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EquipSlot") + .HasColumnType("int"); + + b.Property("HealAmount") + .HasColumnType("int"); + + b.Property("IsEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("IsTeleportScroll") + .HasColumnType("tinyint(1)"); + + b.Property("MagicResist") + .HasColumnType("int"); + + b.Property("ManaRestore") + .HasColumnType("int"); + + b.Property("MaxDamage") + .HasColumnType("int"); + + b.Property("MaxStack") + .HasColumnType("int"); + + b.Property("MinDamage") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("int"); + + b.Property("RequiredDexterity") + .HasColumnType("int"); + + b.Property("RequiredIntelligence") + .HasColumnType("int"); + + b.Property("RequiredLevel") + .HasColumnType("int"); + + b.Property("RequiredStrength") + .HasColumnType("int"); + + b.Property("RequiredWisdom") + .HasColumnType("int"); + + b.Property("SpriteId") + .HasColumnType("int"); + + b.Property("Stackable") + .HasColumnType("tinyint(1)"); + + b.Property("StaminaRestore") + .HasColumnType("int"); + + b.Property("TeachesSpellId") + .HasColumnType("int"); + + b.Property("Type") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("dungeon_item_definitions"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonLearnedSpell", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("DefinitionId") + .HasColumnType("int"); + + b.Property("LearnedAt") + .HasColumnType("datetime(6)"); + + b.Property("SpellDefinitionId") + .HasColumnType("int"); + + b.Property("SpellLevel") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("DefinitionId"); + + b.ToTable("dungeon_learned_spells"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonMobDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AbilitiesJson") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("AggroRange") + .HasColumnType("float"); + + b.Property("AnimationSpeed") + .HasColumnType("float"); + + b.Property("ArmorPerTier") + .HasColumnType("float"); + + b.Property("AttackFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("AttackRange") + .HasColumnType("float"); + + b.Property("AttackSpeed") + .HasColumnType("float"); + + b.Property("BaseArmor") + .HasColumnType("int"); + + b.Property("BaseHealth") + .HasColumnType("int"); + + b.Property("BaseMagicDamage") + .HasColumnType("int"); + + b.Property("BaseMagicResist") + .HasColumnType("int"); + + b.Property("BaseMana") + .HasColumnType("int"); + + b.Property("BasePhysicalDamage") + .HasColumnType("int"); + + b.Property("BaseXp") + .HasColumnType("int"); + + b.Property("Category") + .HasColumnType("int"); + + b.Property("DamagePerTier") + .HasColumnType("float"); + + b.Property("DeathFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("DropChanceMultiplier") + .HasColumnType("float"); + + b.Property("HealthPerTier") + .HasColumnType("float"); + + b.Property("IdleFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("IsEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("LeashRange") + .HasColumnType("float"); + + b.Property("LootTableId") + .HasColumnType("int"); + + b.Property("MaxTier") + .HasColumnType("int"); + + b.Property("MinTier") + .HasColumnType("int"); + + b.Property("MoveSpeed") + .HasColumnType("float"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ResistancesJson") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("varchar(1024)"); + + b.Property("SpriteHeight") + .HasColumnType("int"); + + b.Property("SpriteIndex") + .HasColumnType("int"); + + b.Property("SpriteSheet") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("SpriteWidth") + .HasColumnType("int"); + + b.Property("TintColor") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("Type") + .HasColumnType("int"); + + b.Property("WalkFrames") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("XpPerTier") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("dungeon_mob_definitions"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonSpellDefinition", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AreaOfEffect") + .HasColumnType("float"); + + b.Property("BaseDamage") + .HasColumnType("int"); + + b.Property("BaseHealing") + .HasColumnType("int"); + + b.Property("Cooldown") + .HasColumnType("float"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.Property("EffectColor") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("IsEnabled") + .HasColumnType("tinyint(1)"); + + b.Property("IsShield") + .HasColumnType("tinyint(1)"); + + b.Property("IsTeleport") + .HasColumnType("tinyint(1)"); + + b.Property("ManaCost") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Range") + .HasColumnType("float"); + + b.Property("RequiredIntelligence") + .HasColumnType("int"); + + b.Property("RequiredLevel") + .HasColumnType("int"); + + b.Property("RequiredWisdom") + .HasColumnType("int"); + + b.Property("ShieldAmount") + .HasColumnType("int"); + + b.Property("SpriteId") + .HasColumnType("int"); + + b.Property("Type") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("dungeon_spell_definitions"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonStashItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("DefinitionId") + .HasColumnType("int"); + + b.Property("ItemDefinitionId") + .HasColumnType("int"); + + b.Property("Quantity") + .HasColumnType("int"); + + b.Property("SlotIndex") + .HasColumnType("int"); + + b.Property("StoredAt") + .HasColumnType("datetime(6)"); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("DefinitionId"); + + b.ToTable("dungeon_stash_items"); + }); + modelBuilder.Entity("Server.Data.EquipmentSlot", b => { b.Property("Id") @@ -720,6 +1252,68 @@ namespace SystemRevivalServer.Migrations b.ToTable("zones", (string)null); }); + modelBuilder.Entity("Server.Data.Entities.DungeonCharacter", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany() + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacterItem", b => + { + b.HasOne("Server.Data.Entities.DungeonCharacter", "Character") + .WithMany("Inventory") + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Entities.DungeonItemDefinition", "Definition") + .WithMany() + .HasForeignKey("DefinitionId"); + + b.Navigation("Character"); + + b.Navigation("Definition"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonLearnedSpell", b => + { + b.HasOne("Server.Data.Entities.DungeonCharacter", "Character") + .WithMany("LearnedSpells") + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Entities.DungeonSpellDefinition", "Definition") + .WithMany() + .HasForeignKey("DefinitionId"); + + b.Navigation("Character"); + + b.Navigation("Definition"); + }); + + modelBuilder.Entity("Server.Data.Entities.DungeonStashItem", b => + { + b.HasOne("Server.Data.Entities.DungeonCharacter", "Character") + .WithMany("Stash") + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Entities.DungeonItemDefinition", "Definition") + .WithMany() + .HasForeignKey("DefinitionId"); + + b.Navigation("Character"); + + b.Navigation("Definition"); + }); + modelBuilder.Entity("Server.Data.EquipmentSlot", b => { b.HasOne("Server.Data.Old_Character", "Old_Character") @@ -827,6 +1421,15 @@ namespace SystemRevivalServer.Migrations b.Navigation("Sessions"); }); + + modelBuilder.Entity("Server.Data.Entities.DungeonCharacter", b => + { + b.Navigation("Inventory"); + + b.Navigation("LearnedSpells"); + + b.Navigation("Stash"); + }); #pragma warning restore 612, 618 } } diff --git a/Networking/Messages/DungeonOpCodes.cs b/Networking/Messages/DungeonOpCodes.cs new file mode 100644 index 0000000..6bf6c80 --- /dev/null +++ b/Networking/Messages/DungeonOpCodes.cs @@ -0,0 +1,35 @@ +namespace SystemRevivalServer.Networking.Messages; + +/// +/// OpCodes for the dungeon crawler game mode +/// +public static class DungeonOpCodes +{ + // Hub (200-299) + public const int HUB_STATE = 200; + public const int STAT_ALLOCATE = 201; + + // Dungeon (300-399) + 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 (400-449) + public const int DUNGEON_INPUT_MOVE = 400; + public const int DUNGEON_INPUT_ATTACK = 401; + public const int DUNGEON_INPUT_PICKUP = 402; + public const int DUNGEON_INPUT_CHEST = 403; + + // Escape (450-499) + 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 (500-599) + 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/Program.cs b/Program.cs index 388f51f..09a692f 100644 --- a/Program.cs +++ b/Program.cs @@ -1,5 +1,6 @@ using System.Net; using System.Net.Sockets; +using Server.Game.Dungeon; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; @@ -56,6 +57,8 @@ builder.Services.AddSingleton(); // Void Scavengers game builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index 8e94d25..444e35b 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -1,5 +1,8 @@ using System.Security.Principal; using Microsoft.EntityFrameworkCore; +using Server.Data.Entities; +using Server.Data.Entities; +using Server.Data.Enums; namespace Server.Data; @@ -18,7 +21,13 @@ public sealed class GameDbContext : DbContext public DbSet MatchHistory => Set(); public DbSet GameItems => Set(); public DbSet GameRecipes => Set(); - + public DbSet DungeonCharacters => Set(); + public DbSet DungeonCharacterItems => Set(); + public DbSet DungeonStashItems => Set(); + public DbSet DungeonItemDefinitions => Set(); + public DbSet DungeonSpellDefinitions => Set(); + public DbSet DungeonLearnedSpells => Set(); + public DbSet DungeonMobDefinitions => Set(); protected override void OnModelCreating(ModelBuilder b) { b.ApplyConfigurationsFromAssembly(typeof(GameDbContext).Assembly); diff --git a/data/entities/DefaultDungeonMobs.cs b/data/entities/DefaultDungeonMobs.cs new file mode 100644 index 0000000..1c786f9 --- /dev/null +++ b/data/entities/DefaultDungeonMobs.cs @@ -0,0 +1,228 @@ +using Server.Data.Enums; + +namespace Server.Data.Entities; + +/// +/// Default mob templates for seeding the database +/// +public static class DefaultDungeonMobs +{ + public static List GetDefaultMobs() => new() + { + // Tier 1 - Basic enemies + new DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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 DungeonMobDefinition + { + 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/DungeonCharacter.cs b/data/entities/DungeonCharacter.cs new file mode 100644 index 0000000..c00ab7e --- /dev/null +++ b/data/entities/DungeonCharacter.cs @@ -0,0 +1,75 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// Persistent player character with stats and equipment for dungeon crawler +/// +[Table("dungeon_characters")] +public class DungeonCharacter +{ + [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(); +} diff --git a/data/entities/DungeonCharacterCombatStats.cs b/data/entities/DungeonCharacterCombatStats.cs new file mode 100644 index 0000000..b749ec7 --- /dev/null +++ b/data/entities/DungeonCharacterCombatStats.cs @@ -0,0 +1,23 @@ +namespace Server.Data.Entities; + +public class DungeonCharacterCombatStats +{ + 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; } +} diff --git a/data/entities/DungeonCharacterItem.cs b/data/entities/DungeonCharacterItem.cs new file mode 100644 index 0000000..76b51e5 --- /dev/null +++ b/data/entities/DungeonCharacterItem.cs @@ -0,0 +1,26 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// Actual item instance owned by a character (inventory or equipped) +/// +[Table("dungeon_character_items")] +public class DungeonCharacterItem +{ + [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 DungeonCharacter? Character { get; set; } + public virtual DungeonItemDefinition? Definition { get; set; } +} diff --git a/data/entities/DungeonCharacterStats.cs b/data/entities/DungeonCharacterStats.cs new file mode 100644 index 0000000..a0fd879 --- /dev/null +++ b/data/entities/DungeonCharacterStats.cs @@ -0,0 +1,58 @@ +namespace Server.Data.Entities; + +/// +/// Derived stats calculator - used at runtime +/// +public static class DungeonCharacterStats +{ + public static int GetMaxHealth(DungeonCharacter c) => 50 + (c.Endurance * 10); + public static int GetMaxMana(DungeonCharacter c) => 20 + (c.Wisdom * 8); + public static int GetMaxStamina(DungeonCharacter c) => 50 + (c.Endurance * 5); + public static float GetXpBonus(DungeonCharacter c) => 1.0f + (c.Wisdom * 0.02f); + public static float GetMoveSpeed(DungeonCharacter c) => 100f + (c.Dexterity * 2f); + public static float GetAttackSpeed(DungeonCharacter c) => 1.0f + (c.Dexterity * 0.02f); + public static float GetRegenRate(DungeonCharacter c) => 1.0f + (c.Endurance * 0.1f); + + /// + /// Calculate combat stats including equipment bonuses + /// + public static DungeonCharacterCombatStats GetCombatStats(DungeonCharacter c, List? equippedItems = null) + { + var stats = new DungeonCharacterCombatStats + { + 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; + } +} diff --git a/data/entities/DungeonItemDefinition.cs b/data/entities/DungeonItemDefinition.cs new file mode 100644 index 0000000..a947c49 --- /dev/null +++ b/data/entities/DungeonItemDefinition.cs @@ -0,0 +1,70 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Server.Data.Enums; + +namespace Server.Data.Entities; + +/// +/// Item template/definition - what an item IS +/// +[Table("dungeon_item_definitions")] +public class DungeonItemDefinition +{ + [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 DungeonEquipmentSlot? 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; +} diff --git a/data/entities/DungeonLearnedSpell.cs b/data/entities/DungeonLearnedSpell.cs new file mode 100644 index 0000000..fc6c8ee --- /dev/null +++ b/data/entities/DungeonLearnedSpell.cs @@ -0,0 +1,26 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// Spells a character has learned +/// +[Table("dungeon_learned_spells")] +public class DungeonLearnedSpell +{ + [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 DungeonCharacter? Character { get; set; } + public virtual DungeonSpellDefinition? Definition { get; set; } +} diff --git a/data/entities/DungeonMobCombatStats.cs b/data/entities/DungeonMobCombatStats.cs new file mode 100644 index 0000000..076f660 --- /dev/null +++ b/data/entities/DungeonMobCombatStats.cs @@ -0,0 +1,53 @@ +using Server.Data.Enums; + +namespace Server.Data.Entities; + +/// +/// Runtime combat stats for a mob instance +/// +public class DungeonMobCombatStats +{ + 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; + } +} diff --git a/data/entities/DungeonMobDefinition.cs b/data/entities/DungeonMobDefinition.cs new file mode 100644 index 0000000..fac4025 --- /dev/null +++ b/data/entities/DungeonMobDefinition.cs @@ -0,0 +1,139 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json; +using Server.Data.Enums; + +namespace Server.Data.Entities; + +/// +/// Monster/NPC template definition stored in database +/// +[Table("dungeon_mob_definitions")] +public class DungeonMobDefinition +{ + [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 DungeonMobCombatStats GetStatsForTier(int tier) + { + return new DungeonMobCombatStats + { + 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 + }; + } +} diff --git a/data/entities/DungeonSpellDefinition.cs b/data/entities/DungeonSpellDefinition.cs new file mode 100644 index 0000000..77d5b3f --- /dev/null +++ b/data/entities/DungeonSpellDefinition.cs @@ -0,0 +1,50 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Server.Data.Enums; + +namespace Server.Data.Entities; + +/// +/// Spell definition - learnable abilities +/// +[Table("dungeon_spell_definitions")] +public class DungeonSpellDefinition +{ + [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; +} diff --git a/data/entities/DungeonStashItem.cs b/data/entities/DungeonStashItem.cs new file mode 100644 index 0000000..3cad889 --- /dev/null +++ b/data/entities/DungeonStashItem.cs @@ -0,0 +1,26 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace Server.Data.Entities; + +/// +/// Items stored in character's stash (safe storage in hub) +/// +[Table("dungeon_stash_items")] +public class DungeonStashItem +{ + [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 DungeonCharacter? Character { get; set; } + public virtual DungeonItemDefinition? Definition { get; set; } +} diff --git a/data/entities/LevelSystem.cs b/data/entities/LevelSystem.cs new file mode 100644 index 0000000..3f1d587 --- /dev/null +++ b/data/entities/LevelSystem.cs @@ -0,0 +1,33 @@ +namespace Server.Data.Entities; + +/// +/// 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/enums/DamageType.cs b/data/enums/DamageType.cs new file mode 100644 index 0000000..e4b4b41 --- /dev/null +++ b/data/enums/DamageType.cs @@ -0,0 +1,12 @@ +namespace Server.Data.Enums; + +public enum DamageType +{ + Physical, + Fire, + Ice, + Lightning, + Poison, + Holy, + Dark +} diff --git a/data/enums/DungeonEquipmentSlot.cs b/data/enums/DungeonEquipmentSlot.cs new file mode 100644 index 0000000..24a2a72 --- /dev/null +++ b/data/enums/DungeonEquipmentSlot.cs @@ -0,0 +1,13 @@ +namespace Server.Data.Enums; + +public enum DungeonEquipmentSlot +{ + Weapon, + Offhand, + Head, + Chest, + Legs, + Boots, + Gloves, + Accessory +} diff --git a/data/enums/ItemRarity.cs b/data/enums/ItemRarity.cs new file mode 100644 index 0000000..d4150b3 --- /dev/null +++ b/data/enums/ItemRarity.cs @@ -0,0 +1,10 @@ +namespace Server.Data.Enums; + +public enum ItemRarity +{ + Common = 0, + Uncommon = 1, + Rare = 2, + Epic = 3, + Legendary = 4 +} diff --git a/data/enums/ItemType.cs b/data/enums/ItemType.cs new file mode 100644 index 0000000..eb716cf --- /dev/null +++ b/data/enums/ItemType.cs @@ -0,0 +1,13 @@ +namespace Server.Data.Enums; + +public enum ItemType +{ + Weapon, + Armor, + Accessory, + Consumable, + SpellTome, + Material, + Key, + TeleportScroll +} diff --git a/data/enums/MobCategory.cs b/data/enums/MobCategory.cs new file mode 100644 index 0000000..e646568 --- /dev/null +++ b/data/enums/MobCategory.cs @@ -0,0 +1,13 @@ +namespace Server.Data.Enums; + +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 +} diff --git a/data/enums/MobType.cs b/data/enums/MobType.cs new file mode 100644 index 0000000..f59b7f3 --- /dev/null +++ b/data/enums/MobType.cs @@ -0,0 +1,10 @@ +namespace Server.Data.Enums; + +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 +} diff --git a/data/enums/PlayerState.cs b/data/enums/PlayerState.cs new file mode 100644 index 0000000..2fd324d --- /dev/null +++ b/data/enums/PlayerState.cs @@ -0,0 +1,7 @@ +namespace Server.Data.Enums; + +public enum PlayerState +{ + InHub, + InDungeon +} diff --git a/data/enums/SpellType.cs b/data/enums/SpellType.cs new file mode 100644 index 0000000..0d8469d --- /dev/null +++ b/data/enums/SpellType.cs @@ -0,0 +1,11 @@ +namespace Server.Data.Enums; + +public enum SpellType +{ + Damage, + Healing, + Buff, + Debuff, + Utility, + Summon +}