diff --git a/Game/Dungeon/DungeonHandler.cs b/Game/Dungeon/DungeonHandler.cs index 06cffdf..ea5a334 100644 --- a/Game/Dungeon/DungeonHandler.cs +++ b/Game/Dungeon/DungeonHandler.cs @@ -170,6 +170,22 @@ public sealed class DungeonHandler : IClientMessageHandler case DungeonOpCodes.ESCAPE_CANCEL: HandleEscapeCancel(session); break; + + case DungeonOpCodes.INVENTORY_REQUEST: + await HandleInventoryRequest(connection, session, ct); + break; + + case DungeonOpCodes.EQUIP_ITEM: + await HandleEquipItem(connection, session, payload, ct); + break; + + case DungeonOpCodes.UNEQUIP_ITEM: + await HandleUnequipItem(connection, session, payload, ct); + break; + + case DungeonOpCodes.USE_ITEM: + await HandleUseItem(connection, session, payload, ct); + break; } } catch (Exception ex) @@ -707,6 +723,247 @@ public sealed class DungeonHandler : IClientMessageHandler }, CancellationToken.None); } + /// + /// Handle inventory request - sends current inventory and equipment + /// + private async Task HandleInventoryRequest(IConnection connection, DungeonPlayerSession session, CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Get all inventory items + var inventoryItems = await db.Set() + .Where(i => i.CharacterId == session.CharacterId) + .ToListAsync(ct); + + // Get item definitions for all items + var itemDefIds = inventoryItems.Select(i => i.ItemDefinitionId).Distinct().ToList(); + var itemDefs = await db.Set() + .Where(d => itemDefIds.Contains(d.Id)) + .ToDictionaryAsync(d => d.Id, ct); + + // Build inventory array (30 slots, null for empty) + var items = new object?[30]; + foreach (var invItem in inventoryItems.Where(i => !i.IsEquipped)) + { + if (invItem.SlotIndex >= 0 && invItem.SlotIndex < 30 && itemDefs.TryGetValue(invItem.ItemDefinitionId, out var def)) + { + items[invItem.SlotIndex] = new + { + id = invItem.Id, + definitionId = def.Id, + name = def.Name, + description = def.Description, + type = def.Type.ToString(), + rarity = def.Rarity.ToString(), + quantity = invItem.Quantity, + minDamage = def.MinDamage, + maxDamage = def.MaxDamage, + armor = def.Armor, + bonusHealth = def.BonusHealth, + bonusMana = def.BonusMana, + healAmount = def.HealAmount, + manaRestore = def.ManaRestore, + spriteId = def.SpriteId + }; + } + } + + // Build equipment map + var equipment = new Dictionary(); + foreach (var equippedItem in inventoryItems.Where(i => i.IsEquipped)) + { + if (itemDefs.TryGetValue(equippedItem.ItemDefinitionId, out var def)) + { + var slotName = equippedItem.EquipSlot?.ToString().ToLower() ?? "unknown"; + equipment[slotName] = new + { + id = equippedItem.Id, + definitionId = def.Id, + name = def.Name, + description = def.Description, + type = def.Type.ToString(), + rarity = def.Rarity.ToString(), + minDamage = def.MinDamage, + maxDamage = def.MaxDamage, + armor = def.Armor, + bonusHealth = def.BonusHealth, + bonusMana = def.BonusMana + }; + } + } + + await SendAsync(connection, DungeonOpCodes.INVENTORY_STATE, new + { + items, + equipment + }, ct); + } + + /// + /// Handle equip item request + /// + private async Task HandleEquipItem(IConnection connection, DungeonPlayerSession session, string payload, CancellationToken ct) + { + var request = System.Text.Json.JsonSerializer.Deserialize(payload); + if (request == null) return; + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Get the item to equip + var item = await db.Set() + .Include(i => i.ItemDefinition) + .FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SlotIndex && !i.IsEquipped, ct); + + if (item?.ItemDefinition == null) return; + + // Determine equipment slot based on item type + var equipSlot = GetEquipSlotForItem(item.ItemDefinition); + if (equipSlot == null) + { + _log.LogWarning("Cannot equip item {ItemName} - no valid equip slot", item.ItemDefinition.Name); + return; + } + + // Unequip any existing item in that slot + var existingEquipped = await db.Set() + .FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.IsEquipped && i.EquipSlot == equipSlot, ct); + + if (existingEquipped != null) + { + existingEquipped.IsEquipped = false; + existingEquipped.EquipSlot = null; + // Find first empty inventory slot + var usedSlots = await db.Set() + .Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped) + .Select(i => i.SlotIndex) + .ToListAsync(ct); + existingEquipped.SlotIndex = Enumerable.Range(0, 30).FirstOrDefault(s => !usedSlots.Contains(s)); + } + + // Equip the new item + item.IsEquipped = true; + item.EquipSlot = equipSlot; + item.SlotIndex = -1; // Not in regular inventory + + await db.SaveChangesAsync(ct); + + // Send updated inventory + await HandleInventoryRequest(connection, session, ct); + } + + /// + /// Handle unequip item request + /// + private async Task HandleUnequipItem(IConnection connection, DungeonPlayerSession session, string payload, CancellationToken ct) + { + var request = System.Text.Json.JsonSerializer.Deserialize(payload); + if (request == null) return; + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Parse the slot name to enum + if (!Enum.TryParse(request.Slot, true, out var equipSlot)) + return; + + var equippedItem = await db.Set() + .FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.IsEquipped && i.EquipSlot == equipSlot, ct); + + if (equippedItem == null) return; + + // Find first empty inventory slot + var usedSlots = await db.Set() + .Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped) + .Select(i => i.SlotIndex) + .ToListAsync(ct); + + var emptySlot = Enumerable.Range(0, 30).FirstOrDefault(s => !usedSlots.Contains(s)); + if (usedSlots.Count >= 30) + { + _log.LogWarning("Cannot unequip - inventory full"); + return; + } + + equippedItem.IsEquipped = false; + equippedItem.EquipSlot = null; + equippedItem.SlotIndex = emptySlot; + + await db.SaveChangesAsync(ct); + + // Send updated inventory + await HandleInventoryRequest(connection, session, ct); + } + + /// + /// Handle use item request (consumables) + /// + private async Task HandleUseItem(IConnection connection, DungeonPlayerSession session, string payload, CancellationToken ct) + { + var request = System.Text.Json.JsonSerializer.Deserialize(payload); + if (request == null) return; + + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var item = await db.Set() + .Include(i => i.ItemDefinition) + .FirstOrDefaultAsync(i => i.CharacterId == session.CharacterId && i.SlotIndex == request.SlotIndex && !i.IsEquipped, ct); + + if (item?.ItemDefinition == null) return; + + // Only consumables can be used + if (item.ItemDefinition.Type != ItemType.Consumable) return; + + // Apply effects + if (session.PlayerInstance != null) + { + if (item.ItemDefinition.HealAmount > 0) + { + session.PlayerInstance.Health = Math.Min( + session.PlayerInstance.Health + item.ItemDefinition.HealAmount, + session.PlayerInstance.MaxHealth + ); + } + if (item.ItemDefinition.ManaRestore > 0) + { + session.PlayerInstance.Mana = Math.Min( + session.PlayerInstance.Mana + item.ItemDefinition.ManaRestore, + session.PlayerInstance.MaxMana + ); + } + } + + // Decrease quantity or remove + item.Quantity--; + if (item.Quantity <= 0) + { + db.Set().Remove(item); + } + + await db.SaveChangesAsync(ct); + + // Send updated inventory + await HandleInventoryRequest(connection, session, ct); + } + + private DungeonEquipmentSlot? GetEquipSlotForItem(DungeonItemDefinition item) + { + return item.Type switch + { + ItemType.Weapon => item.EquipSlot ?? DungeonEquipmentSlot.Weapon, + ItemType.Armor => item.EquipSlot ?? DungeonEquipmentSlot.Chest, + ItemType.Accessory => DungeonEquipmentSlot.Ring1, + _ => null + }; + } + + // Request DTOs + private class EquipItemRequest { public int SlotIndex { get; set; } } + private class UnequipItemRequest { public string Slot { get; set; } = ""; } + private class UseItemRequest { public int SlotIndex { get; set; } } + private async Task SendDungeonStateAsync(DungeonPlayerSession session, TickResult? tickResult) { var dungeon = _dungeons.GetValueOrDefault(session.CurrentDungeonId!.Value); diff --git a/Networking/Messages/DungeonOpCodes.cs b/Networking/Messages/DungeonOpCodes.cs index 9a335fc..0b1a1a6 100644 --- a/Networking/Messages/DungeonOpCodes.cs +++ b/Networking/Messages/DungeonOpCodes.cs @@ -32,6 +32,13 @@ public static class DungeonOpCodes public const int EVENT_DEATH = 501; public const int EVENT_LEVELUP = 502; public const int EVENT_LOOT = 503; - public const int LOOT_RECEIVED = 160; + + // Inventory (250-259) + public const int INVENTORY_REQUEST = 250; + public const int INVENTORY_STATE = 251; + public const int EQUIP_ITEM = 252; + public const int UNEQUIP_ITEM = 253; + public const int USE_ITEM = 254; + public const int DROP_ITEM = 255; } diff --git a/data/entities/DungeonCharacterItem.cs b/data/entities/DungeonCharacterItem.cs index 76b51e5..1dc68ce 100644 --- a/data/entities/DungeonCharacterItem.cs +++ b/data/entities/DungeonCharacterItem.cs @@ -1,5 +1,6 @@ using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using Server.Data.Enums; namespace Server.Data.Entities; @@ -16,11 +17,15 @@ public class DungeonCharacterItem public int ItemDefinitionId { get; set; } public int Quantity { get; set; } = 1; - public int SlotIndex { get; set; } // Inventory position (0-29 for example) + public int SlotIndex { get; set; } // Inventory position (0-29 for example), -1 if equipped + + public bool IsEquipped { get; set; } = false; + public DungeonEquipmentSlot? EquipSlot { get; set; } public DateTime AcquiredAt { get; set; } = DateTime.UtcNow; // Navigation public virtual DungeonCharacter? Character { get; set; } - public virtual DungeonItemDefinition? Definition { get; set; } + [ForeignKey(nameof(ItemDefinitionId))] + public virtual DungeonItemDefinition? ItemDefinition { get; set; } }