Fix Deathchests

This commit is contained in:
dingo
2025-12-17 12:49:34 -05:00
parent 959590b030
commit fe594fce80
7 changed files with 4589 additions and 45 deletions
+801 -45
View File
@@ -71,7 +71,12 @@ public sealed class DungeonHandler : IClientMessageHandler
DungeonOpCodes.USE_ITEM,
DungeonOpCodes.DROP_ITEM,
DungeonOpCodes.CHAT_SEND,
DungeonOpCodes.HOTBAR_ASSIGN
DungeonOpCodes.HOTBAR_ASSIGN,
// Loot chest operations
DungeonOpCodes.LOOT_CHEST_OPEN,
DungeonOpCodes.LOOT_CHEST_TAKE_ITEM,
DungeonOpCodes.LOOT_CHEST_TAKE_ALL,
DungeonOpCodes.LOOT_CHEST_CLOSE
};
public async Task InitializeAsync()
@@ -172,19 +177,19 @@ public sealed class DungeonHandler : IClientMessageHandler
case DungeonOpCodes.DUNGEON_INPUT_PORTAL:
await HandlePortalUse(connection, session, payload, ct);
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;
@@ -194,6 +199,20 @@ public sealed class DungeonHandler : IClientMessageHandler
case DungeonOpCodes.HOTBAR_ASSIGN:
await HandleHotbarAssign(connection, session, payload, ct);
break;
// Loot chest operations
case DungeonOpCodes.LOOT_CHEST_OPEN:
await HandleLootChestOpen(connection, session, payload, ct);
break;
case DungeonOpCodes.LOOT_CHEST_TAKE_ITEM:
await HandleLootChestTakeItem(connection, session, payload, ct);
break;
case DungeonOpCodes.LOOT_CHEST_TAKE_ALL:
await HandleLootChestTakeAll(connection, session, payload, ct);
break;
case DungeonOpCodes.LOOT_CHEST_CLOSE:
await HandleLootChestClose(connection, session, payload, ct);
break;
}
}
catch (Exception ex)
@@ -655,7 +674,7 @@ public sealed class DungeonHandler : IClientMessageHandler
{
var result = instance.Simulation.Tick(_currentTick);
// Process mob death events for loot generation
// Process death events for loot generation
if (result.DeathEvents != null)
{
foreach (var death in result.DeathEvents)
@@ -665,6 +684,11 @@ public sealed class DungeonHandler : IClientMessageHandler
// Fire and forget loot generation (async in sync context)
_ = ProcessMobDeathLootAsync(instance, death);
}
else if (death.EntityType == EntityType.Player)
{
// Player died - transfer loot to killer
_ = ProcessPlayerDeathLootTransferAsync(instance, death);
}
}
}
@@ -716,7 +740,7 @@ public sealed class DungeonHandler : IClientMessageHandler
}
}
/// <summary>
/// Process loot when a mob dies
/// Process loot when a mob dies - includes normal loot roll plus any carried player loot
/// </summary>
private async Task ProcessMobDeathLootAsync(DungeonInstance dungeon, DeathEvent death)
{
@@ -737,20 +761,70 @@ public sealed class DungeonHandler : IClientMessageHandler
var loot = _lootService.GenerateMobLoot(
mob.DefinitionId,
dungeon.Tier,
1.0f // Can multiply by mob's DropChanceMultiplier if stored
1.0f
);
if (loot.Count == 0)
// Collect all items to give (normal loot + carried player loot)
var allItems = new List<LootDrop>(loot);
long totalGold = 0;
// Add any carried player loot from player kills
if (mob.HasCarriedLoot)
{
_log.LogInformation("Mob {MobName} was carrying loot from {Count} player kills",
mob.Name, mob.CarriedPlayerLoot.Count);
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
foreach (var carried in mob.CarriedPlayerLoot)
{
totalGold += carried.Gold;
// Convert carried items to LootDrops
foreach (var item in carried.Items)
{
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == item.ItemDefinitionId);
if (itemDef != null)
{
allItems.Add(new LootDrop
{
ItemDefinitionId = item.ItemDefinitionId,
Item = itemDef,
Quantity = item.Quantity
});
}
}
}
// Clear the carried loot from the mob
mob.CarriedPlayerLoot.Clear();
}
if (allItems.Count == 0 && totalGold == 0)
return;
// Add loot to player's inventory
await AddLootToInventoryAsync(killerSession, loot);
// Try to add loot to player's inventory, get overflow
var (addedItems, overflowItems, overflowGold) = await AddLootToInventoryWithOverflowAsync(
killerSession, allItems, totalGold);
// Send loot popup to the player
await SendLootPopupAsync(killerSession, loot);
// Send loot popup for items that were added directly
if (addedItems.Count > 0)
{
await SendLootPopupAsync(killerSession, addedItems);
}
_log.LogDebug("Player {Player} received {Count} items from {Mob}",
killerSession.Character.Name, loot.Count, mob.Name);
// If there's overflow, spawn a personal loot chest
if (overflowItems.Count > 0 || overflowGold > 0)
{
await SpawnLootChestAsync(dungeon, killerSession, overflowItems, overflowGold,
mob.X, mob.Y, null, mob.DefinitionId);
}
_log.LogDebug("Player {Player} received {Count} items and {Gold} gold from {Mob}",
killerSession.Character.Name, addedItems.Count, totalGold - overflowGold, mob.Name);
}
catch (Exception ex)
{
@@ -759,21 +833,194 @@ public sealed class DungeonHandler : IClientMessageHandler
}
/// <summary>
/// Adds loot directly to player's inventory in the database
/// Process player death - transfer inventory and 10% gold to killer
/// </summary>
private async Task AddLootToInventoryAsync(DungeonPlayerSession session, List<LootDrop> loot)
private async Task ProcessPlayerDeathLootTransferAsync(DungeonInstance dungeon, DeathEvent death)
{
try
{
var victimSession = _playerSessions.Values
.FirstOrDefault(s => s.CharacterId == (ulong)death.EntityId);
if (victimSession == null)
return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get victim's inventory (non-equipped items only)
var victimInventory = await db.Set<DungeonCharacterItem>()
.Include(i => i.ItemDefinition)
.Where(i => i.CharacterId == victimSession.CharacterId && !i.IsEquipped)
.ToListAsync();
// Calculate gold to transfer (10%)
var victim = await db.DungeonCharacters.FindAsync(victimSession.CharacterId);
if (victim == null) return;
long goldToTransfer = (long)(victim.Gold * 0.10);
// Build the loot package
var lootItems = victimInventory.Select(i => new CarriedLootItem
{
ItemDefinitionId = i.ItemDefinitionId,
Quantity = i.Quantity
}).ToList();
var carriedLoot = new CarriedLoot
{
VictimCharacterId = victimSession.CharacterId,
VictimName = victim.Name,
Items = lootItems,
Gold = goldToTransfer
};
// Remove items from victim's inventory
db.Set<DungeonCharacterItem>().RemoveRange(victimInventory);
// Deduct gold from victim
victim.Gold -= goldToTransfer;
await db.SaveChangesAsync();
// Send notification to victim about what they lost
await SendDeathLootLostNotificationAsync(victimSession, victimInventory, goldToTransfer);
_log.LogInformation("Player {Victim} died to {KillerType} {KillerId}. Lost {ItemCount} items and {Gold} gold",
victim.Name, death.KillerType, death.KillerId, victimInventory.Count, goldToTransfer);
// Transfer loot based on killer type
if (death.KillerType == EntityType.Mob)
{
// Mob killed player - mob now carries the loot
if (dungeon.Simulation.Mobs.TryGetValue(death.KillerId, out var killerMob))
{
killerMob.CarriedPlayerLoot.Add(carriedLoot);
_log.LogInformation("Mob {MobName} is now carrying loot from {Victim}",
killerMob.Name, victim.Name);
}
}
else if (death.KillerType == EntityType.Player)
{
// Player killed player - transfer directly
var killerSession = _playerSessions.Values
.FirstOrDefault(s => s.CharacterId == (ulong)death.KillerId);
if (killerSession != null)
{
await TransferPlayerLootToPlayerAsync(dungeon, killerSession, carriedLoot,
victimSession.PlayerInstance?.X ?? 0, victimSession.PlayerInstance?.Y ?? 0);
}
}
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing player death loot transfer");
}
}
/// <summary>
/// Transfer carried loot directly to a player (from PvP kill)
/// </summary>
private async Task TransferPlayerLootToPlayerAsync(DungeonInstance dungeon, DungeonPlayerSession killer,
CarriedLoot loot, float x, float y)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Convert carried items to LootDrops
var lootDrops = new List<LootDrop>();
foreach (var item in loot.Items)
{
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == item.ItemDefinitionId);
if (itemDef != null)
{
lootDrops.Add(new LootDrop
{
ItemDefinitionId = item.ItemDefinitionId,
Item = itemDef,
Quantity = item.Quantity
});
}
}
// Try to add to killer's inventory
var (addedItems, overflowItems, overflowGold) = await AddLootToInventoryWithOverflowAsync(
killer, lootDrops, loot.Gold);
if (addedItems.Count > 0)
{
await SendLootPopupAsync(killer, addedItems);
}
// Spawn chest for overflow
if (overflowItems.Count > 0 || overflowGold > 0)
{
await SpawnLootChestAsync(dungeon, killer, overflowItems, overflowGold, x, y,
loot.VictimCharacterId, null);
}
_log.LogInformation("Player {Killer} received loot from killing {Victim}: {Items} items, {Gold} gold",
killer.Character.Name, loot.VictimName, loot.Items.Count, loot.Gold);
}
/// <summary>
/// Send notification to victim about what they lost on death
/// </summary>
private async Task SendDeathLootLostNotificationAsync(DungeonPlayerSession victim,
List<DungeonCharacterItem> lostItems, long lostGold)
{
var itemsData = lostItems.Select(i => new
{
name = i.ItemDefinition?.Name ?? "Unknown",
quantity = i.Quantity,
rarity = i.ItemDefinition?.Rarity.ToString() ?? "Common"
});
await SendAsync(victim.Connection, DungeonOpCodes.PLAYER_DEATH_LOOT_LOST, new
{
items = itemsData,
gold = lostGold,
message = $"You died and lost {lostItems.Count} items and {lostGold} gold!"
}, CancellationToken.None);
}
/// <summary>
/// Add loot to inventory, returning what was added and what overflowed
/// </summary>
private async Task<(List<LootDrop> added, List<LootDrop> overflow, long overflowGold)>
AddLootToInventoryWithOverflowAsync(DungeonPlayerSession session, List<LootDrop> loot, long gold)
{
var added = new List<LootDrop>();
var overflow = new List<LootDrop>();
long overflowGold = 0;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get existing inventory items
var existingItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId)
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.ToListAsync();
int nextSlot = existingItems.Count > 0
? existingItems.Max(i => i.SlotIndex) + 1
: 0;
// Find used slots
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
// Find next available slot
int FindNextSlot()
{
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
usedSlots.Add(i);
return i;
}
}
return -1; // Full
}
foreach (var drop in loot)
{
@@ -784,39 +1031,512 @@ public sealed class DungeonHandler : IClientMessageHandler
if (existingStack != null && drop.Item.Stackable)
{
// Add to existing stack
existingStack.Quantity = Math.Min(
existingStack.Quantity + drop.Quantity,
drop.Item.MaxStack
);
int spaceInStack = drop.Item.MaxStack - existingStack.Quantity;
int toAdd = Math.Min(drop.Quantity, spaceInStack);
if (toAdd > 0)
{
existingStack.Quantity += toAdd;
added.Add(new LootDrop
{
ItemDefinitionId = drop.ItemDefinitionId,
Item = drop.Item,
Quantity = toAdd
});
}
int remaining = drop.Quantity - toAdd;
if (remaining > 0)
{
// Overflow the rest
overflow.Add(new LootDrop
{
ItemDefinitionId = drop.ItemDefinitionId,
Item = drop.Item,
Quantity = remaining
});
}
}
else
{
// Check if inventory is full (30 slots)
if (nextSlot >= 30)
int nextSlot = FindNextSlot();
if (nextSlot >= 0)
{
// TODO: Drop item on ground instead
_log.LogWarning("Player {Name} inventory full, item {Item} not added",
session.Character.Name, drop.Item.Name);
continue;
// Create new inventory entry
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = drop.ItemDefinitionId,
Quantity = drop.Quantity,
SlotIndex = nextSlot
};
db.Set<DungeonCharacterItem>().Add(newItem);
existingItems.Add(newItem);
added.Add(drop);
}
// Create new inventory entry
var newItem = new DungeonCharacterItem
else
{
CharacterId = session.CharacterId,
ItemDefinitionId = drop.ItemDefinitionId,
Quantity = drop.Quantity,
SlotIndex = nextSlot++
};
db.Set<DungeonCharacterItem>().Add(newItem);
existingItems.Add(newItem);
// Inventory full - overflow
overflow.Add(drop);
}
}
}
// Handle gold
var character = await db.DungeonCharacters.FindAsync(session.CharacterId);
if (character != null)
{
character.Gold += gold;
}
await db.SaveChangesAsync();
return (added, overflow, overflowGold);
}
/// <summary>
/// Spawn a personal loot chest for overflow items
/// </summary>
private async Task SpawnLootChestAsync(DungeonInstance dungeon, DungeonPlayerSession owner,
List<LootDrop> items, long gold, float x, float y, ulong? victimCharacterId, int? victimMobId)
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Create database record for auditing
var deathChest = new DeathChest
{
DungeonInstanceId = dungeon.Id,
OwnerCharacterId = owner.CharacterId,
VictimCharacterId = victimCharacterId,
VictimMobDefinitionId = victimMobId,
X = x,
Y = y,
GoldAmount = gold,
CreatedAt = DateTime.UtcNow
};
db.DeathChests.Add(deathChest);
await db.SaveChangesAsync();
// Add items to chest
int slotIndex = 0;
foreach (var item in items)
{
var chestItem = new DeathChestItem
{
DeathChestId = deathChest.Id,
ItemDefinitionId = item.ItemDefinitionId,
Quantity = item.Quantity,
SlotIndex = slotIndex++
};
db.DeathChestItems.Add(chestItem);
}
await db.SaveChangesAsync();
// Create runtime instance
var lootChest = new LootChestInstance
{
Id = dungeon.Simulation.GetNextLootChestId(),
DatabaseId = deathChest.Id,
X = x,
Y = y,
OwnerCharacterId = owner.CharacterId,
Gold = gold,
Items = items.Select((item, idx) => new LootChestItem
{
SlotIndex = idx,
ItemDefinitionId = item.ItemDefinitionId,
Quantity = item.Quantity
}).ToList()
};
dungeon.Simulation.LootChests.TryAdd(lootChest.Id, lootChest);
// Notify the owner about the chest
await SendAsync(owner.Connection, DungeonOpCodes.LOOT_CHEST_SPAWNED, new
{
chestId = lootChest.Id,
x = lootChest.X,
y = lootChest.Y,
itemCount = lootChest.Items.Count,
gold = lootChest.Gold,
message = "A loot chest appeared with your overflow items!"
}, CancellationToken.None);
_log.LogInformation("Spawned loot chest {ChestId} for player {Player} with {Items} items and {Gold} gold at ({X}, {Y})",
lootChest.Id, owner.Character.Name, items.Count, gold, x, y);
}
/// <summary>
/// Adds loot directly to player's inventory in the database (legacy - kept for compatibility)
/// </summary>
private async Task AddLootToInventoryAsync(DungeonPlayerSession session, List<LootDrop> loot)
{
var (_, _, _) = await AddLootToInventoryWithOverflowAsync(session, loot, 0);
}
#region Loot Chest Handlers
/// <summary>
/// Handle opening a loot chest
/// </summary>
private async Task HandleLootChestOpen(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestOpenRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
{
await SendErrorAsync(connection, "Chest not found", ct);
return;
}
// Check ownership
if (chest.OwnerCharacterId != session.CharacterId)
{
await SendErrorAsync(connection, "This chest doesn't belong to you", ct);
return;
}
// Check distance
if (session.PlayerInstance != null)
{
float dist = MathF.Sqrt(
MathF.Pow(session.PlayerInstance.X - chest.X, 2) +
MathF.Pow(session.PlayerInstance.Y - chest.Y, 2));
if (dist > 96) // Interaction range
{
await SendErrorAsync(connection, "Too far from chest", ct);
return;
}
}
chest.IsOpen = true;
// Load item definitions for display
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var itemDefIds = chest.Items.Select(i => i.ItemDefinitionId).Distinct().ToList();
var itemDefs = await db.Set<DungeonItemDefinition>()
.Where(d => itemDefIds.Contains(d.Id))
.ToDictionaryAsync(d => d.Id, ct);
// Build chest state
var chestItems = new object?[100];
foreach (var item in chest.Items)
{
if (itemDefs.TryGetValue(item.ItemDefinitionId, out var def))
{
chestItems[item.SlotIndex] = new
{
slotIndex = item.SlotIndex,
definitionId = def.Id,
name = def.Name,
description = def.Description,
type = def.Type.ToString(),
rarity = def.Rarity.ToString(),
quantity = item.Quantity,
spriteId = def.SpriteId
};
}
}
await SendAsync(connection, DungeonOpCodes.LOOT_CHEST_STATE, new
{
chestId = chest.Id,
gold = chest.Gold,
items = chestItems,
slots = 100
}, ct);
}
/// <summary>
/// Handle taking a single item from loot chest
/// </summary>
private async Task HandleLootChestTakeItem(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestTakeItemRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
return;
if (chest.OwnerCharacterId != session.CharacterId)
return;
// Find the item in chest
var chestItem = chest.Items.FirstOrDefault(i => i.SlotIndex == request.SlotIndex);
if (chestItem == null)
{
await SendErrorAsync(connection, "Item not found in chest", ct);
return;
}
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get item definition
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct);
if (itemDef == null) return;
// Get player's current inventory
var existingItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.ToListAsync(ct);
// Find an available slot
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
int targetSlot = request.TargetSlotIndex;
if (targetSlot < 0 || targetSlot >= 30 || usedSlots.Contains(targetSlot))
{
// Find first available slot
targetSlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
targetSlot = i;
break;
}
}
}
if (targetSlot < 0)
{
await SendErrorAsync(connection, "Inventory full", ct);
return;
}
// Add to player inventory
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = chestItem.ItemDefinitionId,
Quantity = chestItem.Quantity,
SlotIndex = targetSlot
};
db.Set<DungeonCharacterItem>().Add(newItem);
// Update database chest item as taken
var dbChestItem = await db.DeathChestItems
.FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId &&
i.SlotIndex == request.SlotIndex &&
!i.IsTaken, ct);
if (dbChestItem != null)
{
dbChestItem.IsTaken = true;
dbChestItem.TakenAt = DateTime.UtcNow;
}
await db.SaveChangesAsync(ct);
// Remove from runtime chest
chest.Items.Remove(chestItem);
// Check if chest is now empty
await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, ct);
// Send updated states
await HandleInventoryRequest(connection, session, ct);
await HandleLootChestOpen(connection, session, payload, ct); // Resend chest state
}
/// <summary>
/// Handle taking all items from loot chest
/// </summary>
private async Task HandleLootChestTakeAll(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestTakeAllRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (!dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
return;
if (chest.OwnerCharacterId != session.CharacterId)
return;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<GameDbContext>();
// Get player's current inventory
var existingItems = await db.Set<DungeonCharacterItem>()
.Where(i => i.CharacterId == session.CharacterId && !i.IsEquipped)
.ToListAsync(ct);
var usedSlots = existingItems.Select(i => i.SlotIndex).ToHashSet();
var itemsTaken = new List<LootChestItem>();
var takenLoot = new List<LootDrop>();
// Try to take each item
foreach (var chestItem in chest.Items.ToList())
{
// Find available slot
int targetSlot = -1;
for (int i = 0; i < 30; i++)
{
if (!usedSlots.Contains(i))
{
targetSlot = i;
usedSlots.Add(i);
break;
}
}
if (targetSlot < 0)
break; // Inventory full
// Get item definition for popup
var itemDef = await db.Set<DungeonItemDefinition>()
.FirstOrDefaultAsync(d => d.Id == chestItem.ItemDefinitionId, ct);
// Add to player inventory
var newItem = new DungeonCharacterItem
{
CharacterId = session.CharacterId,
ItemDefinitionId = chestItem.ItemDefinitionId,
Quantity = chestItem.Quantity,
SlotIndex = targetSlot
};
db.Set<DungeonCharacterItem>().Add(newItem);
// Update database chest item as taken
var dbChestItem = await db.DeathChestItems
.FirstOrDefaultAsync(i => i.DeathChestId == chest.DatabaseId &&
i.SlotIndex == chestItem.SlotIndex &&
!i.IsTaken, ct);
if (dbChestItem != null)
{
dbChestItem.IsTaken = true;
dbChestItem.TakenAt = DateTime.UtcNow;
}
itemsTaken.Add(chestItem);
if (itemDef != null)
{
takenLoot.Add(new LootDrop
{
ItemDefinitionId = chestItem.ItemDefinitionId,
Item = itemDef,
Quantity = chestItem.Quantity
});
}
}
// Take gold
if (chest.Gold > 0)
{
var character = await db.DungeonCharacters.FindAsync(new object[] { session.CharacterId }, ct);
if (character != null)
{
character.Gold += chest.Gold;
// Update database chest
var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct);
if (dbChest != null)
{
dbChest.GoldAmount = 0;
}
chest.Gold = 0;
}
}
await db.SaveChangesAsync(ct);
// Remove taken items from runtime chest
foreach (var item in itemsTaken)
{
chest.Items.Remove(item);
}
// Send loot popup
if (takenLoot.Count > 0)
{
await SendLootPopupAsync(session, takenLoot);
}
// Check if chest is now empty
await CheckAndRemoveEmptyChestAsync(db, dungeon, chest, ct);
// Send updated inventory
await HandleInventoryRequest(connection, session, ct);
// If chest still has items, send updated state
if (!chest.IsEmpty)
{
var openPayload = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(
new LootChestOpenRequest { ChestId = request.ChestId });
await HandleLootChestOpen(connection, session, openPayload, ct);
}
}
/// <summary>
/// Handle closing a loot chest
/// </summary>
private async Task HandleLootChestClose(IConnection connection, DungeonPlayerSession session, ReadOnlyMemory<byte> payload, CancellationToken ct)
{
var json = System.Text.Encoding.UTF8.GetString(payload.Span);
var request = System.Text.Json.JsonSerializer.Deserialize<LootChestCloseRequest>(json);
if (request == null) return;
if (!session.CurrentDungeonId.HasValue ||
!_dungeons.TryGetValue(session.CurrentDungeonId.Value, out var dungeon))
return;
if (dungeon.Simulation.LootChests.TryGetValue(request.ChestId, out var chest))
{
if (chest.OwnerCharacterId == session.CharacterId)
{
chest.IsOpen = false;
}
}
}
/// <summary>
/// Check if a chest is empty and remove it if so
/// </summary>
private async Task CheckAndRemoveEmptyChestAsync(GameDbContext db, DungeonInstance dungeon, LootChestInstance chest, CancellationToken ct)
{
if (chest.IsEmpty)
{
// Update database
var dbChest = await db.DeathChests.FindAsync(new object[] { chest.DatabaseId }, ct);
if (dbChest != null)
{
dbChest.IsEmpty = true;
dbChest.EmptiedAt = DateTime.UtcNow;
await db.SaveChangesAsync(ct);
}
// Remove from runtime
dungeon.Simulation.LootChests.TryRemove(chest.Id, out _);
_log.LogInformation("Loot chest {ChestId} emptied and removed", chest.Id);
}
}
#endregion
/// <summary>
/// Sends loot popup to client showing what they received
/// </summary>
@@ -1208,6 +1928,19 @@ public sealed class DungeonHandler : IClientMessageHandler
type = p.Type.ToString().ToLower()
}),
// Loot chests are only visible to their owner
lootChests = sim.LootChests.Values
.Where(c => c.OwnerCharacterId == session.CharacterId)
.Select(c => new
{
id = c.Id,
x = c.X,
y = c.Y,
itemCount = c.Items.Count,
gold = c.Gold,
isOpen = c.IsOpen
}),
events = tickResult == null ? null : new
{
damage = tickResult.DamageEvents.Select(e => new
@@ -1369,7 +2102,8 @@ public sealed class DungeonHandler : IClientMessageHandler
dexterity = character.Dexterity,
maxHealth = DungeonCharacterStats.GetMaxHealth(character),
maxMana = DungeonCharacterStats.GetMaxMana(character),
maxStamina = DungeonCharacterStats.GetMaxStamina(character)
maxStamina = DungeonCharacterStats.GetMaxStamina(character),
gold = character.Gold
}
};
}
@@ -1429,7 +2163,7 @@ public sealed class DungeonHandler : IClientMessageHandler
// In dungeon - broadcast to all players in same dungeon
foreach (var player in dungeon.Simulation.Players.Values)
{
await SendAsync(_playerSessions.Values.Where(p => p.CharacterId == player.CharacterId).FirstOrDefault().Connection, DungeonOpCodes.CHAT_MESSAGE, new
{
sender = senderName,
@@ -1454,7 +2188,7 @@ public sealed class DungeonHandler : IClientMessageHandler
_log.LogDebug("Chat from {Player}: {Message}", senderName, message);
}
/// <summary>
/// Broadcast a system message to all players in a dungeon
/// </summary>
@@ -1543,3 +2277,25 @@ public class PortalUseRequest
{
public int PortalId { get; set; }
}
public class LootChestOpenRequest
{
public int ChestId { get; set; }
}
public class LootChestTakeItemRequest
{
public int ChestId { get; set; }
public int SlotIndex { get; set; }
public int TargetSlotIndex { get; set; } // Where to put it in player inventory (-1 for auto)
}
public class LootChestTakeAllRequest
{
public int ChestId { get; set; }
}
public class LootChestCloseRequest
{
public int ChestId { get; set; }
}