diff --git a/Game/World/WorldHandler.Combat.cs b/Game/World/WorldHandler.Combat.cs index ed7934d..be07d42 100644 --- a/Game/World/WorldHandler.Combat.cs +++ b/Game/World/WorldHandler.Combat.cs @@ -288,27 +288,140 @@ public sealed partial class WorldHandler return; } - // Award gold based on mob tier - int goldDrop = Math.Max(1, mob.Stats.XpReward / 2); + // Use LootService to generate loot from configured loot tables + var lootResult = _lootService.GenerateMobLoot(mob.DefinitionId, 1, 1.0f); + + // Fallback gold if loot table has no gold: use XP-based formula + long goldDrop = lootResult.Gold > 0 ? lootResult.Gold : Math.Max(1, mob.Stats.XpReward / 2); + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct); if (character != null) { character.Gold += goldDrop; + + // Add item drops to character inventory + foreach (var drop in lootResult.Items) + { + await AddWorldItemToInventoryAsync(db, s.CharacterId, drop.ItemDefinitionId, drop.Quantity, ct); + } + await db.SaveChangesAsync(ct); } // Mark mob as looted (it will be cleaned up eventually) mob.LootEmptiedAtTick = zoneSim.CurrentTick; + var lootItems = lootResult.Items.Select(d => new + { + itemDefinitionId = d.ItemDefinitionId, + itemName = d.Item?.Name ?? $"Item {d.ItemDefinitionId}", + quantity = d.Quantity + }).ToArray(); + await _broadcast.SendAsync(conn, OpCodes.WORLD_MOB_LOOT_RESULT, new { success = true, mobId = mob.Id, gold = goldDrop, - items = Array.Empty() // TODO: Loot table integration in future + items = lootItems }, ct); } + private async Task HandleWorldRespawnAsync(IConnection conn, WorldSessionState s, CancellationToken ct) + { + var zoneKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + if (!_activeZones.TryGetValue(zoneKey, out var zoneSim)) return; + + if (!zoneSim.Players.TryGetValue(s.CharacterId, out var playerCombat)) + return; + + // Must actually be dead to respawn + if (playerCombat.IsAlive) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_RESPAWN_RESULT, new + { + success = false, + error = "not_dead" + }, ct); + return; + } + + // Respawn at zone center (tile center of chunk 0,0) + var region = await _cache.GetRegionAsync(s.RegionId, ct); + if (region == null) return; + + float spawnX = WorldMovementService.WorldPxX(region, s.ZoneX, 0, region.ChunkWidthTiles / 2); + float spawnY = WorldMovementService.WorldPxY(region, s.ZoneY, 0, region.ChunkHeightTiles / 2); + + // Reset combat state + playerCombat.Health = playerCombat.MaxHealth; + playerCombat.IsAlive = true; + playerCombat.IsInCombat = false; + playerCombat.IsInvulnerable = true; + playerCombat.InvulnerabilityTimer = RespawnInvulnerabilitySeconds; + playerCombat.StatusEffects.Clear(); + + // Move player to spawn position + s.X = spawnX; + s.Y = spawnY; + s.VelX = 0; + s.VelY = 0; + s.IsMoving = false; + + // Update chunk position + var (pzX, pzY, pcX, pcY) = WorldMovementService.ToChunkPos(region, spawnX, spawnY); + s.ChunkX = pcX; + s.ChunkY = pcY; + + // Increment death counter + _ = IncrementDeathCounterAsync(s.CharacterId); + + await _broadcast.SendAsync(conn, OpCodes.WORLD_RESPAWN_RESULT, new + { + success = true, + x = spawnX, + y = spawnY, + health = playerCombat.Health, + maxHealth = playerCombat.MaxHealth, + invulnerableSeconds = RespawnInvulnerabilitySeconds + }, ct); + + // Broadcast to other players + foreach (var player in zoneSim.Players.Values) + { + if (player.CharacterId == s.CharacterId) continue; + await _broadcast.SendAsync(player.Session.Connection, OpCodes.WORLD_COMBAT_STATE, new + { + events = new[] { new + { + type = "PlayerRespawn", + targetPlayerId = s.CharacterId, + x = spawnX, + y = spawnY + }} + }, ct); + } + } + + private async Task IncrementDeathCounterAsync(ulong characterId) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == characterId); + if (character != null) + { + character.TotalDeaths++; + await db.SaveChangesAsync(); + } + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to increment death counter for character {CharacterId}", characterId); + } + } + private async Task AwardXpAsync(ulong characterId, int xpAmount) { if (xpAmount <= 0) return; diff --git a/Game/World/WorldHandler.Npcs.cs b/Game/World/WorldHandler.Npcs.cs index cadf656..5248646 100644 --- a/Game/World/WorldHandler.Npcs.cs +++ b/Game/World/WorldHandler.Npcs.cs @@ -191,6 +191,12 @@ public sealed partial class WorldHandler return; } + if (string.Equals(req.Action, "sell", StringComparison.OrdinalIgnoreCase)) + { + await HandleWorldNpcShopSellAsync(conn, s, npc, req, ct); + return; + } + if (!string.Equals(req.Action, "buy", StringComparison.OrdinalIgnoreCase)) { await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new @@ -559,4 +565,97 @@ public sealed partial class WorldHandler await db.SaveChangesAsync(ct); } + + /// + /// Handle selling an item from the player's inventory to an NPC shop. + /// SlotIndex refers to the player's inventory slot to sell from. + /// Sell price is 25% of the item's base buy price (or PriceGold from shop if found there). + /// + private async Task HandleWorldNpcShopSellAsync( + IConnection conn, WorldSessionState s, + NpcInstance npc, WorldNpcShopActionRequest req, CancellationToken ct) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // Find the item in the player's inventory at the specified slot + var inventoryItem = await db.DungeonCharacterItems + .Include(i => i.ItemDefinition) + .FirstOrDefaultAsync(i => i.CharacterId == s.CharacterId && + i.SlotIndex == req.SlotIndex && + !i.IsEquipped, ct); + + if (inventoryItem == null || inventoryItem.ItemDefinition == null) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new + { + success = false, + error = "item_not_found" + }, ct); + return; + } + + var quantity = Math.Max(1, Math.Min(req.Quantity, inventoryItem.Quantity)); + + // Calculate sell price: check if this item type is in the shop's catalog for a reference price + long pricePerUnit = 0; + if (npc.ShopId.HasValue) + { + var shopEntry = await db.DungeonNpcShopItems + .FirstOrDefaultAsync(si => si.ShopId == npc.ShopId.Value && + si.ItemDefinitionId == inventoryItem.ItemDefinitionId, ct); + if (shopEntry != null) + { + pricePerUnit = shopEntry.PriceGold / 4; // 25% of shop buy price + } + } + + // Fallback: 25% of a base price formula if not in shop + if (pricePerUnit <= 0) + { + // Base price heuristic: item level * rarity multiplier + pricePerUnit = Math.Max(1, inventoryItem.ItemDefinition.RequiredLevel * 2); + } + + long totalGold = pricePerUnit * quantity; + + var character = await db.DungeonCharacters.FirstOrDefaultAsync(c => c.Id == s.CharacterId, ct); + if (character == null) + { + await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new + { + success = false, + error = "character_not_found" + }, ct); + return; + } + + // Remove quantity from inventory + inventoryItem.Quantity -= quantity; + if (inventoryItem.Quantity <= 0) + { + db.DungeonCharacterItems.Remove(inventoryItem); + } + + // Award gold + character.Gold += totalGold; + await db.SaveChangesAsync(ct); + + await _broadcast.SendAsync(conn, OpCodes.WORLD_NPC_SHOP_RESULT, new + { + success = true, + npcId = npc.Id, + action = "sell", + itemDefinitionId = inventoryItem.ItemDefinitionId, + quantity, + totalPrice = totalGold, + remainingGold = character.Gold + }, ct); + + // Re-send updated shop state + if (npc.ShopId.HasValue) + { + await SendWorldNpcShopStateAsync(conn, npc.ShopId.Value, ct); + } + } } diff --git a/Game/World/WorldHandler.cs b/Game/World/WorldHandler.cs index 479e857..7521fcc 100644 --- a/Game/World/WorldHandler.cs +++ b/Game/World/WorldHandler.cs @@ -18,6 +18,7 @@ public sealed partial class WorldHandler : IClientMessageHandler { private const int TileSize = 32; private const float TickDeltaSeconds = 0.1f; // 10Hz + private const float RespawnInvulnerabilitySeconds = 3.0f; private static readonly TimeSpan NeutralInputGrace = TimeSpan.FromMilliseconds(180); private static readonly TimeSpan DirectionalPriorityGrace = TimeSpan.FromMilliseconds(450); @@ -28,6 +29,7 @@ public sealed partial class WorldHandler : IClientMessageHandler private readonly WorldMovementService _movement; private readonly WorldBroadcastService _broadcast; private readonly WorldEditDeltaHub _deltaHub; + private readonly LootService _lootService; private readonly ConcurrentDictionary _players = new(); private readonly ConcurrentDictionary _portalCooldownByCharacter = new(); @@ -36,6 +38,9 @@ public sealed partial class WorldHandler : IClientMessageHandler // Zone simulations (keyed by "{regionId}:{zoneX}:{zoneY}:{zoneZ}") private readonly ConcurrentDictionary _activeZones = new(); + // PvP flag cache per zone (keyed by zone key) + private readonly ConcurrentDictionary _zonePvpFlags = new(); + // Mob/NPC definition caches (loaded once at init) private Dictionary _mobDefinitions = new(); private Dictionary _npcDefinitions = new(); @@ -52,7 +57,8 @@ public sealed partial class WorldHandler : IClientMessageHandler WorldChunkCache cache, WorldMovementService movement, WorldBroadcastService broadcast, - WorldEditDeltaHub deltaHub) + WorldEditDeltaHub deltaHub, + LootService lootService) { _log = log; _sessions = sessions; @@ -61,6 +67,7 @@ public sealed partial class WorldHandler : IClientMessageHandler _movement = movement; _broadcast = broadcast; _deltaHub = deltaHub; + _lootService = lootService; var debugInputEnv = Environment.GetEnvironmentVariable("WORLD_INPUT_DEBUG"); _debugInput = !string.IsNullOrWhiteSpace(debugInputEnv) && @@ -75,6 +82,7 @@ public sealed partial class WorldHandler : IClientMessageHandler // World combat OpCodes.WORLD_ATTACK, OpCodes.WORLD_MOB_LOOT_REQUEST, + OpCodes.WORLD_RESPAWN_REQUEST, // World NPC OpCodes.WORLD_NPC_INTERACT, OpCodes.WORLD_NPC_DIALOG_SELECT, @@ -165,6 +173,9 @@ public sealed partial class WorldHandler : IClientMessageHandler case OpCodes.WORLD_MOB_LOOT_REQUEST: await HandleWorldMobLootAsync(connection, session, payload, ct); break; + case OpCodes.WORLD_RESPAWN_REQUEST: + await HandleWorldRespawnAsync(connection, session, ct); + break; // NPC case OpCodes.WORLD_NPC_INTERACT: await HandleWorldNpcInteract(connection, session, payload, ct); @@ -454,11 +465,23 @@ public sealed partial class WorldHandler : IClientMessageHandler .ToArray(); } + // Check PvP flag for current zone + var isPvp = false; + if (zoneSim != null) + { + isPvp = zoneSim.IsPvpEnabled; + } + else + { + var pvpKey = WorldChunkCache.ZoneKey(s.RegionId, s.ZoneX, s.ZoneY, s.ZoneZ); + _zonePvpFlags.TryGetValue(pvpKey, out isPvp); + } + await _broadcast.SendAsync(s.Connection, OpCodes.WORLD_STATE, new { tick, ackSeq = s.Seq, - self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, chunkX = s.ChunkX, chunkY = s.ChunkY }, + self = new { x = s.X, y = s.Y, velocityX = s.VelX, velocityY = s.VelY, regionId = s.RegionId, zoneX = s.ZoneX, zoneY = s.ZoneY, zoneZ = s.ZoneZ, chunkX = s.ChunkX, chunkY = s.ChunkY, isPvp }, players = VisiblePlayers(s).Select(p => new { id = p.CharacterId, name = p.Name, x = p.X, y = p.Y, facing = p.Facing, speed = p.Speed, isMoving = p.IsMoving, regionId = p.RegionId, zoneX = p.ZoneX, zoneY = p.ZoneY, chunkX = p.ChunkX, chunkY = p.ChunkY }), mobs = nearbyMobs, npcs = nearbyNpcs, @@ -553,14 +576,101 @@ public sealed partial class WorldHandler : IClientMessageHandler if (!zoneSim.Players.ContainsKey(s.CharacterId)) { var combatState = new WorldPlayerCombatState(s); - // Initialize with basic stats (character stats would come from DB/gear) - // For now use defaults — Phase 4 will flesh out stat loading from gear + await InitializePlayerCombatStateAsync(combatState, s.CharacterId, ct); + zoneSim.AddPlayer(combatState); + } + } + } + + /// + /// Load real character stats + gear bonuses from DB to initialize player combat state. + /// + private async Task InitializePlayerCombatStateAsync(WorldPlayerCombatState combatState, ulong characterId, CancellationToken ct) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var character = await db.DungeonCharacters + .AsNoTracking() + .FirstOrDefaultAsync(c => c.Id == characterId, ct); + + if (character == null) + { + // Fallback to defaults combatState.InitializeFromCharacter( strength: 10, intelligence: 10, endurance: 10, dexterity: 10, armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical", resistances: new Dictionary()); - zoneSim.AddPlayer(combatState); + return; } + + // Load equipped items with their definitions and crafted bonuses + var equippedItems = await db.DungeonCharacterItems + .AsNoTracking() + .Include(i => i.ItemDefinition) + .Include(i => i.CraftedItem) + .Where(i => i.CharacterId == characterId && i.IsEquipped) + .ToListAsync(ct); + + // Sum gear stat bonuses + int gearStr = 0, gearInt = 0, gearEnd = 0, gearDex = 0, gearHealth = 0; + int gearArmor = 0; + string weaponDamageType = "physical"; + var equippedDefs = new List(); + + foreach (var item in equippedItems) + { + if (item.ItemDefinition == null) continue; + equippedDefs.Add(item.ItemDefinition); + + var (str, intel, wis, end, dex, health, mana) = item.GetTotalStats(item.ItemDefinition); + gearStr += str; + gearInt += intel; + gearEnd += end; + gearDex += dex; + gearHealth += health; + gearArmor += item.ItemDefinition.Armor; + + // Check if this is the weapon (equipped weapon slot) + if (item.EquipSlot == DataServer.Data.Enums.DungeonEquipmentSlot.MainHand && + !string.IsNullOrEmpty(item.ItemDefinition.DamageTypeKey)) + { + weaponDamageType = item.ItemDefinition.DamageTypeKey; + } + } + + // Total stats = base character + gear + int totalStr = character.Strength + gearStr; + int totalInt = character.Intelligence + gearInt; + int totalEnd = character.Endurance + gearEnd; + int totalDex = character.Dexterity + gearDex; + + // Max health from Endurance formula + gear bonus health + int maxHealth = (50 + (totalEnd * 10)) + gearHealth; + + // Merge innate + gear resistances + var resistances = CombatCalculator.CalculatePlayerTotalResistances( + character.Resistances, equippedDefs); + + combatState.InitializeFromCharacter( + strength: totalStr, + intelligence: totalInt, + endurance: totalEnd, + dexterity: totalDex, + armor: gearArmor, + maxHealth: maxHealth, + weaponDamageTypeKey: weaponDamageType, + resistances: resistances); + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to load combat stats for character {CharacterId}, using defaults", characterId); + combatState.InitializeFromCharacter( + strength: 10, intelligence: 10, endurance: 10, dexterity: 10, + armor: 0, maxHealth: 100, weaponDamageTypeKey: "physical", + resistances: new Dictionary()); } } @@ -578,6 +688,24 @@ public sealed partial class WorldHandler : IClientMessageHandler var zoneSim = new WorldZoneSimulation(zoneKey, regionId, zoneX, zoneY, zoneZ, _cache); zoneSim.SetRegion(region); + // Load PvP flag from DB + try + { + using var pvpScope = _scopeFactory.CreateScope(); + var pvpDb = pvpScope.ServiceProvider.GetRequiredService(); + var zone = await pvpDb.WorldZones.AsNoTracking() + .FirstOrDefaultAsync(z => z.RegionId == regionId && z.ZoneX == zoneX && z.ZoneY == zoneY && z.ZoneZ == zoneZ, ct); + if (zone != null) + { + zoneSim.IsPvpEnabled = zone.IsPvpEnabled; + _zonePvpFlags[zoneKey] = zone.IsPvpEnabled; + } + } + catch (Exception ex) + { + _log.LogWarning(ex, "Failed to load PvP flag for zone {ZoneKey}", zoneKey); + } + // Collect mob and NPC spawns from all chunks in this zone var mobSpawns = new List<(WorldChunkMobSpawnData, int, int)>(); var npcSpawns = new List<(NpcInstance, int, int)>(); diff --git a/Game/World/client_fixes.md b/Game/World/client_fixes.md index 98f67f3..88fd43a 100644 --- a/Game/World/client_fixes.md +++ b/Game/World/client_fixes.md @@ -32,7 +32,9 @@ These are **null** when no zone simulation is active, so guard against null. "velocityX": 120.0, "velocityY": 0.0, "regionId": 1, "zoneX": 0, "zoneY": 0, - "chunkX": 5, "chunkY": 3 + "zoneZ": 0, // NEW - current Z-level + "chunkX": 5, "chunkY": 3, + "isPvp": false // NEW - true if zone is PvP-enabled }, "players": [ ... ], "mobs": [ // NEW - nullable @@ -113,11 +115,13 @@ building (Z-level change) will make other ground-level players disappear. | 721 | WORLD_ATTACK | C -> S | Player attacks mob or player | | 722 | WORLD_MOB_LOOT_REQUEST | C -> S | Loot a dead mob | | 723 | WORLD_MOB_LOOT_RESULT | S -> C | Loot contents | +| 724 | WORLD_RESPAWN_REQUEST | C -> S | Request respawn after death | +| 725 | WORLD_RESPAWN_RESULT | S -> C | Respawn result + new position | | 740 | WORLD_NPC_INTERACT | C -> S | Start NPC interaction | | 741 | WORLD_NPC_INTERACT_STATE | S -> C | NPC metadata + dialog/shop state | | 742 | WORLD_NPC_DIALOG_SELECT | C -> S | Choose a dialog option | | 743 | WORLD_NPC_DIALOG_RESULT | S -> C | Dialog option outcome | -| 744 | WORLD_NPC_SHOP_ACTION | C -> S | Buy from NPC shop | +| 744 | WORLD_NPC_SHOP_ACTION | C -> S | Buy/sell from NPC shop | | 745 | WORLD_NPC_SHOP_RESULT | S -> C | Shop transaction result | | 750 | WORLD_OBJECT_INTERACT | C -> S | Interact with world object | | 751 | WORLD_OBJECT_INTERACT_RESULT | S -> C | Object interaction result | @@ -171,6 +175,7 @@ array. Each event has a `type` string field. | `PvpDamage` | sourcePlayerId, targetPlayerId, damage, damageTypeKey, x, y | Player hits player (PvP) | | `PlayerDeath` | targetPlayerId, sourcePlayerId, x, y, isPvpKill | Player killed (PvP) | | `AttackFailed` | error | Attack rejected | +| `PlayerRespawn` | targetPlayerId, x, y | Player respawned (broadcast to others) | `AttackFailed` error values: `"stunned"`, `"dead"`, `"target_not_found"`, `"out_of_range"`, `"pvp_disabled_in_zone"`, `"target_invulnerable"` @@ -217,13 +222,65 @@ Server validates: mob is dead, within 128px, exists. "success": true, "mobId": 1, "gold": 75, - "items": [] + "items": [ + { + "itemDefinitionId": 42, + "itemName": "Healing Potion", + "quantity": 2 + } + ] } ``` Error cases: `"mob_not_found"`, `"mob_still_alive"`, `"too_far"` -Items array is currently empty (loot tables not yet integrated). Gold is `XpReward / 2`. +Loot is generated from mob loot tables via `LootService`. Gold uses the loot table's +gold drop, or falls back to `XpReward / 2`. Items are added to the player's inventory +server-side automatically. The client should display the loot popup to confirm what +was received. + +### 3.4 Death and Respawn (724/725) C -> S / S -> C + +When a player dies (from mob or PvP), a `PlayerDeath` event is broadcast. +The dead player cannot move or attack. To respawn, the client sends: + +**Request (724 WORLD_RESPAWN_REQUEST):** +```json +{} +``` + +No payload needed (server knows who is requesting from the connection). + +**Response (725 WORLD_RESPAWN_RESULT):** +```json +{ + "success": true, + "x": 1024.0, + "y": 512.0, + "health": 100, + "maxHealth": 100, + "invulnerableSeconds": 3.0 +} +``` + +On respawn: +- Player teleports to zone spawn point (center of chunk 0,0 in current zone). +- Health is fully restored. +- 3-second invulnerability (immune to all damage). +- All status effects (stuns, roots, DOTs) are cleared. +- No item or XP loss (overworld is less punishing than dungeon). +- `TotalDeaths` counter incremented server-side. +- A `PlayerRespawn` event is broadcast to other players in the zone. + +Error cases: `"not_dead"` (player is still alive) + +The client should: +- [ ] Show death screen / overlay when receiving `PlayerDeath` event +- [ ] Show "Respawn" button +- [ ] On click, send WORLD_RESPAWN_REQUEST (724) +- [ ] On success, move player to new x/y, restore health bar +- [ ] Show invulnerability visual (shield/glow) for `invulnerableSeconds` +- [ ] Handle `PlayerRespawn` events for other players (teleport their sprite) --- @@ -350,8 +407,6 @@ Error cases on 743: `"npc_dialog_unavailable"`, `"invalid_option"`, `"condition_ } ``` -Only `"buy"` is currently supported. - **Response (745 WORLD_NPC_SHOP_RESULT):** ```json { @@ -371,6 +426,39 @@ On success, the server also re-sends the full shop state on opcode **741** Error cases on 745: `"npc_shop_unavailable"`, `"unsupported_shop_action"`, `"shop_item_not_found"`, `"out_of_stock"`, `"character_not_found"`, `"not_enough_gold"` (includes `requiredGold` + `currentGold`), `"inventory_full"` +### 4.4 Selling to a Shop (744/745) + +**Request (744 WORLD_NPC_SHOP_ACTION):** +```json +{ + "npcId": 1, + "action": "sell", + "slotIndex": 3, + "quantity": 1 +} +``` + +`slotIndex` refers to the player's **inventory slot** (0-29), not the shop slot. + +**Response (745 WORLD_NPC_SHOP_RESULT):** +```json +{ + "success": true, + "npcId": 1, + "action": "sell", + "itemDefinitionId": 15, + "quantity": 1, + "totalPrice": 12, + "remainingGold": 512 +} +``` + +Sell price is 25% of the shop's buy price for that item (if the shop sells it), +otherwise a base price heuristic (`requiredLevel * 2`). Items are removed from +inventory server-side. Equipped items cannot be sold (only unequipped inventory items). + +Error cases: `"item_not_found"`, `"character_not_found"` + --- ## 5. World Object Interaction @@ -563,20 +651,37 @@ Portal cooldown is **0.8 seconds** (8 server ticks), enforced server-side. - [ ] Building interior: same zone XY but different Z = different tile set - [ ] Track current `zoneZ` client-side (from `self` in WORLD_STATE) +### Death/Respawn +- [ ] Show death screen on `PlayerDeath` event (from mob or PvP) +- [ ] Show "Respawn" button on death screen +- [ ] Send WORLD_RESPAWN_REQUEST (724) on click +- [ ] Register handler for opcode 725 (WORLD_RESPAWN_RESULT) +- [ ] On respawn success: move player, restore health, show invulnerability +- [ ] Handle `PlayerRespawn` events for other players + ### PvP -- [ ] Visual indicator when entering a PvP-enabled zone (server does not send zone flags yet -- use hardcoded zone list or future opcode) +- [ ] Read `isPvp` flag from `self` in WORLD_STATE (sent every tick) +- [ ] Visual indicator when entering a PvP-enabled zone - [ ] Player click/tap in PvP zone -> send WORLD_ATTACK with `targetType: "player"` - [ ] Handle `PvpDamage` and `PlayerDeath` with `isPvpKill: true` events - [ ] Invulnerability visual (shield icon) when defender `isInvulnerable` +### Shop Selling +- [ ] Add "Sell" tab/button to shop UI +- [ ] Show player inventory items with sell prices +- [ ] Send WORLD_NPC_SHOP_ACTION with `action: "sell"`, `slotIndex` = inventory slot +- [ ] Update gold counter from response `remainingGold` + --- ## 8. Known Limitations / TODOs -- **Loot tables not integrated**: WORLD_MOB_LOOT_RESULT `items` array is always empty. Only gold drops currently. -- **Player combat stats hardcoded**: EnsurePlayersInZoneSimsAsync uses default stats (str=10, int=10, etc). Real gear-based stats not loaded yet. -- **No zone PvP flag sent to client**: The client has no way to know if a zone is PvP-enabled. Will need a future opcode or flag in chunk/zone data. -- **Object broken state not persisted**: Breakable objects reset on server restart. -- **Sell action not implemented**: WORLD_NPC_SHOP_ACTION only supports `"buy"`. -- **No world death/respawn flow**: PlayerDeath events are broadcast but there is no respawn opcode or flow yet. +- ~~**Loot tables not integrated**~~: **FIXED** - Mob loot now uses `LootService` with configured loot tables. Items + gold are generated and added to inventory. +- ~~**Player combat stats hardcoded**~~: **FIXED** - Player stats now loaded from `DungeonCharacter` + equipped gear (armor, resistances, stat bonuses from items + crafted bonuses). +- ~~**No zone PvP flag sent to client**~~: **FIXED** - `self.isPvp` is now included in every WORLD_STATE tick. Also `self.zoneZ` added. +- ~~**Sell action not implemented**~~: **FIXED** - WORLD_NPC_SHOP_ACTION now supports `"sell"`. Sell price = 25% of shop buy price. +- ~~**No world death/respawn flow**~~: **FIXED** - New opcodes 724/725 (WORLD_RESPAWN_REQUEST/RESULT). 3s invulnerability, zone spawn point, death counter. +- **Object broken state not persisted**: Breakable objects reset on server restart. (Design choice - low priority.) - **Mob AI abilities**: Mobs use the dungeon AI system (10 behavior patterns) but world mob abilities haven't been extensively tested. +- **Player stats not refreshed on gear change**: If the player equips/unequips gear while in a zone, the `WorldPlayerCombatState` is not updated until they re-enter the zone. A future "refresh stats" flow would be needed. +- **Respawn location is always zone center**: Currently respawns at chunk 0,0 center. A more sophisticated system could use the nearest safe NPC or designated spawn point. diff --git a/Networking/Messages/OpCodes.cs b/Networking/Messages/OpCodes.cs index 15f5fde..555eca1 100644 --- a/Networking/Messages/OpCodes.cs +++ b/Networking/Messages/OpCodes.cs @@ -155,6 +155,12 @@ public static class OpCodes /// Server -> Client: Shop action result public const int WORLD_NPC_SHOP_RESULT = 745; + /// Client -> Server: Request respawn after death + public const int WORLD_RESPAWN_REQUEST = 724; + + /// Server -> Client: Respawn result (new position, invulnerability) + public const int WORLD_RESPAWN_RESULT = 725; + // ===== World Object (750-759) ===== /// Client -> Server: Interact with world object