This commit is contained in:
dingo
2025-12-08 11:57:08 -05:00
parent 3755b13931
commit 17da6639cf
15 changed files with 3098 additions and 5 deletions
+151 -1
View File
@@ -38,16 +38,20 @@ public sealed class DungeonHandler : IClientMessageHandler
private Timer? _tickTimer;
private long _currentTick = 0;
//LootSystem
private LootService _lootService = null!;
public DungeonHandler(
ILogger<DungeonHandler> log,
ISessionRegistry sessions,
IMessageSerializer ser,
IServiceScopeFactory scopeFactory)
IServiceScopeFactory scopeFactory, LootService lootService)
{
_log = log;
_sessions = sessions;
_ser = ser;
_scopeFactory = scopeFactory;
_lootService = lootService;
}
public IReadOnlyCollection<int> SupportedOpCodes => new[]
@@ -69,6 +73,7 @@ public sealed class DungeonHandler : IClientMessageHandler
if (_initialized) return;
await LoadMobDefinitionsAsync();
await _lootService.InitializeAsync();
// Start tick loop (20 ticks per second)
_tickTimer = new Timer(TickAll, null, 0, 50);
@@ -521,6 +526,19 @@ public sealed class DungeonHandler : IClientMessageHandler
{
var result = instance.Simulation.Tick(_currentTick);
// Process mob death events for loot generation
if (result.DeathEvents != null)
{
foreach (var death in result.DeathEvents)
{
if (death.EntityType == EntityType.Mob && death.KillerType == EntityType.Player)
{
// Fire and forget loot generation (async in sync context)
_ = ProcessMobDeathLootAsync(instance, death);
}
}
}
// Send state to all players in this dungeon
var playersInDungeon = _playerSessions.Values
.Where(s => s.CurrentDungeonId == dungeonId && s.State == PlayerState.InDungeon)
@@ -557,6 +575,137 @@ public sealed class DungeonHandler : IClientMessageHandler
}
}
}
/// <summary>
/// Process loot when a mob dies
/// </summary>
private async Task ProcessMobDeathLootAsync(DungeonInstance dungeon, DeathEvent death)
{
try
{
// Find the mob that died (it's still in the dictionary but marked dead)
if (!dungeon.Simulation.Mobs.TryGetValue(death.EntityId, out var mob))
return;
// Find the player who killed it
var killerSession = _playerSessions.Values
.FirstOrDefault(s => s.CharacterId == (ulong)death.KillerId);
if (killerSession == null)
return;
// Generate loot from the mob's loot tables
var loot = _lootService.GenerateMobLoot(
mob.DefinitionId,
dungeon.Tier,
1.0f // Can multiply by mob's DropChanceMultiplier if stored
);
if (loot.Count == 0)
return;
// Add loot to player's inventory
await AddLootToInventoryAsync(killerSession, loot);
// Send loot popup to the player
await SendLootPopupAsync(killerSession, loot);
_log.LogDebug("Player {Player} received {Count} items from {Mob}",
killerSession.Character.Name, loot.Count, mob.Name);
}
catch (Exception ex)
{
_log.LogError(ex, "Error processing loot for mob death");
}
}
/// <summary>
/// Adds loot directly to player's inventory in the database
/// </summary>
private async Task AddLootToInventoryAsync(DungeonPlayerSession session, List<LootDrop> loot)
{
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)
.ToListAsync();
int nextSlot = existingItems.Count > 0
? existingItems.Max(i => i.SlotIndex) + 1
: 0;
foreach (var drop in loot)
{
// Check if item is stackable and already exists in inventory
var existingStack = existingItems.FirstOrDefault(i =>
i.ItemDefinitionId == drop.ItemDefinitionId &&
drop.Item.Stackable);
if (existingStack != null && drop.Item.Stackable)
{
// Add to existing stack
existingStack.Quantity = Math.Min(
existingStack.Quantity + drop.Quantity,
drop.Item.MaxStack
);
}
else
{
// Check if inventory is full (30 slots)
if (nextSlot >= 30)
{
// 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);
}
}
await db.SaveChangesAsync();
}
/// <summary>
/// Sends loot popup to client showing what they received
/// </summary>
private async Task SendLootPopupAsync(DungeonPlayerSession session, List<LootDrop> loot)
{
var lootData = loot.Select(l => new
{
id = l.ItemDefinitionId,
name = l.Item.Name,
description = l.Item.Description,
type = l.Item.Type.ToString(),
rarity = l.Item.Rarity.ToString(),
quantity = l.Quantity,
spriteId = l.Item.SpriteId,
// Include stats for display
armor = l.Item.Armor,
minDamage = l.Item.MinDamage,
maxDamage = l.Item.MaxDamage,
bonusHealth = l.Item.BonusHealth,
bonusMana = l.Item.BonusMana,
healAmount = l.Item.HealAmount,
manaRestore = l.Item.ManaRestore
});
await SendAsync(session.Connection, DungeonOpCodes.LOOT_RECEIVED, new
{
items = lootData
}, CancellationToken.None);
}
private async Task SendDungeonStateAsync(DungeonPlayerSession session, TickResult? tickResult)
{
@@ -799,6 +948,7 @@ public sealed class DungeonHandler : IClientMessageHandler
_log.LogInformation("Dungeon session cleaned up for connection {Id}", connectionId);
}
}
}
// Request/Input DTOs