More Dungeon Features

This commit is contained in:
dingo
2026-01-10 21:27:08 -05:00
parent ae1951f876
commit 13ee594e29
3 changed files with 649 additions and 243 deletions
+191 -4
View File
@@ -39,10 +39,6 @@ public partial class DungeonHandler
{
try
{
// Send them back to town
// Note: This is a simplified version - in production you'd want to
// properly handle player state transitions
//dungeon.Simulation.RemovePlayer(player.CharacterId);
Console.WriteLine("Remove Player - Not Implemented.");
}
catch { /* Ignore errors during cleanup */ }
@@ -171,6 +167,197 @@ public partial class DungeonHandler
return mob;
}
// ==================== TILE EDITING ====================
/// <summary>
/// Set a tile's walkability (admin action)
/// </summary>
public bool SetTileWalkable(Guid dungeonId, int x, int y, bool walkable)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
var layout = dungeon.LayoutV2;
if (layout == null)
return false;
if (x < 0 || x >= layout.Width || y < 0 || y >= layout.Height)
return false;
layout.Walkable[x, y] = walkable;
// Also update the Tiles array (0 = wall, 1 = floor typically)
layout.Tiles[x, y] = walkable ? 1 : 0;
return true;
}
/// <summary>
/// Set multiple tiles at once (for painting)
/// </summary>
public int SetTilesWalkable(Guid dungeonId, List<(int x, int y, bool walkable)> tiles)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return 0;
var layout = dungeon.LayoutV2;
if (layout == null)
return 0;
int count = 0;
foreach (var (x, y, walkable) in tiles)
{
if (x >= 0 && x < layout.Width && y >= 0 && y < layout.Height)
{
layout.Walkable[x, y] = walkable;
layout.Tiles[x, y] = walkable ? 1 : 0;
count++;
}
}
return count;
}
/// <summary>
/// Fill a rectangle with walkable or wall tiles
/// </summary>
public int FillTileRect(Guid dungeonId, int x1, int y1, int x2, int y2, bool walkable)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return 0;
var layout = dungeon.LayoutV2;
if (layout == null)
return 0;
int minX = Math.Max(0, Math.Min(x1, x2));
int maxX = Math.Min(layout.Width - 1, Math.Max(x1, x2));
int minY = Math.Max(0, Math.Min(y1, y2));
int maxY = Math.Min(layout.Height - 1, Math.Max(y1, y2));
int count = 0;
for (int x = minX; x <= maxX; x++)
{
for (int y = minY; y <= maxY; y++)
{
layout.Walkable[x, y] = walkable;
layout.Tiles[x, y] = walkable ? 1 : 0;
count++;
}
}
return count;
}
// ==================== PLAYER MANIPULATION ====================
/// <summary>
/// Get detailed player info (admin)
/// </summary>
public PlayerInstance? GetPlayer(Guid dungeonId, ulong characterId)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return null;
dungeon.Simulation.Players.TryGetValue(characterId, out var player);
return player;
}
/// <summary>
/// Teleport a player to a position
/// </summary>
public bool TeleportPlayer(Guid dungeonId, ulong characterId, float x, float y)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player))
return false;
player.X = x;
player.Y = y;
return true;
}
/// <summary>
/// Heal a player to full
/// </summary>
public bool HealPlayer(Guid dungeonId, ulong characterId)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player))
return false;
player.Health = player.MaxHealth;
player.Mana = player.MaxMana;
player.Stamina = player.MaxStamina;
player.StatusEffects.Clear();
return true;
}
/// <summary>
/// Kill a player (admin action)
/// </summary>
public bool KillPlayer(Guid dungeonId, ulong characterId)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player))
return false;
player.Health = 0;
player.IsAlive = false;
return true;
}
/// <summary>
/// Set player health to a specific value
/// </summary>
public bool SetPlayerHealth(Guid dungeonId, ulong characterId, float health)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player))
return false;
player.Health = Math.Clamp(health, 0, player.MaxHealth);
if (player.Health <= 0)
player.IsAlive = false;
return true;
}
/// <summary>
/// Remove a player from the dungeon (kick)
/// </summary>
public bool KickPlayer(Guid dungeonId, ulong characterId)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
return dungeon.Simulation.Players.TryRemove(characterId, out _);
}
/// <summary>
/// Give player invulnerability (god mode)
/// </summary>
public bool SetPlayerInvulnerable(Guid dungeonId, ulong characterId, bool invulnerable)
{
if (!_dungeons.TryGetValue(dungeonId, out var dungeon))
return false;
if (!dungeon.Simulation.Players.TryGetValue(characterId, out var player))
return false;
// Use a very high armor value for invulnerability
// This is a simple approach - a proper implementation would add an Invulnerable flag
player.Armor = invulnerable ? 999999 : 0;
return true;
}
}
/// <summary>
+386 -209
View File
@@ -1,5 +1,5 @@
@page "/admin/dungeons/view"
@model GameServices.Admin.Pages.Dungeons.ViewModel
@model Admin.Pages.Dungeons.ViewModel
@{
ViewData["Title"] = $"Dungeon View - Tier {Model.Dungeon?.Tier}";
}
@@ -14,13 +14,16 @@
}
.map-canvas {
image-rendering: pixelated;
cursor: crosshair;
}
.map-canvas.edit-mode { cursor: cell; }
.entity-dot {
position: absolute;
border-radius: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
transition: transform 0.1s;
pointer-events: auto;
}
.entity-dot:hover {
transform: translate(-50%, -50%) scale(1.5);
@@ -28,18 +31,20 @@
}
.player-dot {
background: #4ade80;
width: 10px;
height: 10px;
width: 12px;
height: 12px;
box-shadow: 0 0 6px #4ade80;
}
.player-dot.selected {
outline: 2px solid #fff;
outline-offset: 2px;
}
.mob-dot {
background: #f87171;
width: 8px;
height: 8px;
}
.mob-dot:hover {
box-shadow: 0 0 8px #f87171;
}
.mob-dot:hover { box-shadow: 0 0 8px #f87171; }
.boss-dot {
background: #fbbf24;
width: 12px;
@@ -56,32 +61,11 @@
border-radius: 8px;
padding: 12px;
}
.player-list-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
background: rgba(30, 30, 50, 0.5);
border-radius: 6px;
margin-bottom: 4px;
}
.health-bar {
height: 4px;
background: #374151;
border-radius: 2px;
overflow: hidden;
}
.health-bar-fill {
height: 100%;
background: linear-gradient(90deg, #ef4444, #22c55e);
transition: width 0.3s ease;
}
.mob-inspector {
.inspector {
background: rgba(20, 20, 40, 0.95);
border: 1px solid #4f46e5;
border-radius: 8px;
padding: 16px;
min-width: 280px;
}
.inspector-stat {
display: flex;
@@ -89,8 +73,33 @@
padding: 4px 0;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.inspector-stat:last-child {
border-bottom: none;
.inspector-stat:last-child { border-bottom: none; }
.health-bar {
height: 6px;
background: #374151;
border-radius: 3px;
overflow: hidden;
}
.health-bar-fill {
height: 100%;
background: linear-gradient(90deg, #ef4444, #22c55e);
transition: width 0.3s ease;
}
.tool-btn {
padding: 6px 10px;
border-radius: 6px;
font-size: 12px;
transition: all 0.15s;
}
.tool-btn.active {
background: #4f46e5;
color: white;
}
.edit-preview {
position: absolute;
pointer-events: none;
border: 2px dashed #4f46e5;
background: rgba(79, 70, 229, 0.3);
}
</style>
@@ -118,60 +127,77 @@ else
<div class="flex items-center gap-2 text-sm text-gray-400">
<div class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
<span id="refreshRate">500ms</span>
<button onclick="toggleAutoRefresh()" id="autoRefreshBtn" class="btn btn-sm btn-ghost ml-2">
<button onclick="toggleAutoRefresh()" id="autoRefreshBtn" class="btn btn-sm btn-secondary ml-2">
Auto: ON
</button>
</div>
</div>
<!-- Edit Tools -->
<div class="flex items-center gap-2 mb-3 p-2 bg-gray-800 rounded">
<span class="text-xs text-gray-400 mr-2">Edit Mode:</span>
<button onclick="setEditMode('none')" id="editNone" class="tool-btn active">🔍 View</button>
<button onclick="setEditMode('floor')" id="editFloor" class="tool-btn">🟦 Floor</button>
<button onclick="setEditMode('wall')" id="editWall" class="tool-btn">⬛ Wall</button>
<button onclick="setEditMode('fill')" id="editFill" class="tool-btn">📦 Fill Rect</button>
<span class="text-xs text-gray-500 ml-auto">Click/drag on map to edit</span>
</div>
<div class="dungeon-map" id="mapContainer" style="height: 500px;">
<canvas id="mapCanvas" class="map-canvas"></canvas>
<div id="entityOverlay"></div>
<div id="entityOverlay" style="pointer-events: none;"></div>
<div id="editPreview" class="edit-preview hidden"></div>
</div>
<div class="flex items-center justify-center gap-6 mt-3 text-xs text-gray-400">
<div class="flex items-center gap-1">
<div class="w-3 h-3 rounded-full bg-green-400"></div>
<span>Players</span>
<span>Players (click)</span>
</div>
<div class="flex items-center gap-1">
<div class="w-2 h-2 rounded-full bg-red-400"></div>
<span>Mobs (click to inspect)</span>
<span>Mobs (click)</span>
</div>
<div class="flex items-center gap-1">
<div class="w-3 h-3 rounded-full bg-yellow-400"></div>
<span>Boss</span>
</div>
<div class="flex items-center gap-1">
<div class="w-3 h-3 bg-blue-400"></div>
<div class="w-3 h-3 bg-blue-800"></div>
<span>Floor</span>
</div>
<div class="flex items-center gap-1">
<div class="w-3 h-3 bg-gray-900"></div>
<span>Wall</span>
</div>
</div>
</div>
<!-- Mob Inspector (shown when mob is selected) -->
<div id="mobInspector" class="mob-inspector mt-4 hidden">
<!-- Player Inspector -->
<div id="playerInspector" class="inspector mt-4 hidden">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold text-white" id="inspectorMobName">Mob Name</h3>
<button onclick="closeMobInspector()" class="text-gray-400 hover:text-white">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
</svg>
</button>
<h3 class="text-lg font-semibold text-green-400" id="playerInspectorName">Player Name</h3>
<button onclick="closePlayerInspector()" class="text-gray-400 hover:text-white">✕</button>
</div>
<div id="inspectorContent" class="space-y-1 text-sm">
<!-- Populated by JS -->
<div id="playerInspectorContent" class="space-y-1 text-sm"></div>
<div class="grid grid-cols-2 gap-2 mt-4">
<button onclick="healSelectedPlayer()" class="btn btn-success btn-sm">❤️ Heal Full</button>
<button onclick="teleportPlayerToClick()" id="teleportBtn" class="btn btn-secondary btn-sm">📍 Teleport</button>
<button onclick="toggleGodMode()" id="godModeBtn" class="btn btn-secondary btn-sm">🛡️ God Mode</button>
<button onclick="killSelectedPlayer()" class="btn btn-danger btn-sm">💀 Kill</button>
</div>
</div>
<!-- Mob Inspector -->
<div id="mobInspector" class="inspector mt-4 hidden">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold text-red-400" id="mobInspectorName">Mob Name</h3>
<button onclick="closeMobInspector()" class="text-gray-400 hover:text-white">✕</button>
</div>
<div id="mobInspectorContent" class="space-y-1 text-sm"></div>
<div class="flex gap-2 mt-4">
<button onclick="killSelectedMob()" class="btn btn-danger btn-sm flex-1">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
</svg>
Kill Mob
</button>
<button onclick="teleportToMob()" class="btn btn-secondary btn-sm flex-1">
📍 Copy Position
</button>
<button onclick="killSelectedMob()" class="btn btn-danger btn-sm flex-1">🗡️ Kill Mob</button>
<button onclick="copyMobPosition()" class="btn btn-secondary btn-sm flex-1">📍 Copy Pos</button>
</div>
</div>
</div>
@@ -195,8 +221,8 @@ else
<span class="text-white">@Model.Dungeon.LevelBracketMin - @Model.Dungeon.LevelBracketMax</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Seed</span>
<span class="text-white font-mono">@Model.Dungeon.Seed</span>
<span class="text-gray-400">Size</span>
<span class="text-white">@Model.MapWidth × @Model.MapHeight</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Phase</span>
@@ -204,14 +230,6 @@ else
@Model.Dungeon.Simulation.Phase
</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Creator</span>
<span class="text-white">@Model.Dungeon.CreatorName</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Created</span>
<span class="text-white">@Model.Dungeon.CreatedAt.ToString("HH:mm:ss")</span>
</div>
<div class="flex justify-between">
<span class="text-gray-400">Duration</span>
<span class="text-white" id="duration">@Model.Duration</span>
@@ -221,7 +239,7 @@ else
<!-- Stats -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Stats</h3>
<h3 class="text-lg font-semibold text-white mb-3">Live Stats</h3>
<div class="grid grid-cols-2 gap-3">
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold text-green-400" id="playerCount">@Model.Dungeon.Simulation.Players.Count</div>
@@ -229,17 +247,7 @@ else
</div>
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold text-red-400" id="mobCount">@Model.Dungeon.Simulation.Mobs.Values.Count(m => m.IsAlive)</div>
<div class="text-xs text-gray-400">Mobs Alive</div>
</div>
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold text-blue-400">@Model.RoomCount</div>
<div class="text-xs text-gray-400">Rooms</div>
</div>
<div class="text-center p-2 bg-gray-800/50 rounded">
<div class="text-2xl font-bold @(Model.Dungeon.BossKilled ? "text-yellow-400" : "text-gray-500")">
@(Model.Dungeon.BossKilled ? "✓" : "✗")
</div>
<div class="text-xs text-gray-400">Boss Killed</div>
<div class="text-xs text-gray-400">Mobs</div>
</div>
</div>
</div>
@@ -249,51 +257,39 @@ else
<h3 class="text-lg font-semibold text-white mb-3">Spawn Mob</h3>
<div class="space-y-2">
<select id="spawnMobSelect" class="input text-sm w-full">
<option value="">Select a mob...</option>
<option value="">Select mob...</option>
@foreach (var mob in Model.MobDefinitions)
{
<option value="@mob.Id">@mob.Name (T@mob.MinTier-@mob.MaxTier)</option>
}
</select>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="text-xs text-gray-400">X</label>
<input type="number" id="spawnX" class="input text-sm" placeholder="X pos" value="@(Model.MapWidth / 2 * 32)" />
</div>
<div>
<label class="text-xs text-gray-400">Y</label>
<input type="number" id="spawnY" class="input text-sm" placeholder="Y pos" value="@(Model.MapHeight / 2 * 32)" />
</div>
<input type="number" id="spawnX" class="input text-sm" placeholder="X" value="@(Model.MapWidth / 2 * 32)" />
<input type="number" id="spawnY" class="input text-sm" placeholder="Y" value="@(Model.MapHeight / 2 * 32)" />
</div>
<button onclick="spawnMob()" class="btn btn-success w-full text-sm">
<svg class="w-4 h-4 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
</svg>
Spawn Mob
</button>
<p class="text-xs text-gray-500">Click on map to set spawn position</p>
<button onclick="spawnMob()" class="btn btn-success w-full text-sm">+ Spawn Mob</button>
<p class="text-xs text-gray-500">Right-click map to set position</p>
</div>
</div>
<!-- Players -->
<!-- Players List -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Players (@Model.Dungeon.Simulation.Players.Count)</h3>
<div id="playerList" class="space-y-1 max-h-48 overflow-y-auto">
<h3 class="text-lg font-semibold text-white mb-3">Players</h3>
<div id="playerList" class="space-y-2 max-h-48 overflow-y-auto">
@foreach (var player in Model.Dungeon.Simulation.Players.Values)
{
var healthPct = player.MaxHealth > 0 ? (player.Health * 100 / player.MaxHealth) : 0;
<div class="player-list-item">
<div class="w-2 h-2 rounded-full bg-green-400"></div>
<div class="flex-1 min-w-0">
<div class="text-white text-sm truncate">@player.CharacterName</div>
<div class="health-bar mt-1">
<div class="health-bar-fill" style="width: @healthPct%"></div>
</div>
<div class="p-2 bg-gray-800/50 rounded cursor-pointer hover:bg-gray-700/50" onclick="selectPlayerById('@player.CharacterId')">
<div class="flex items-center justify-between">
<span class="text-white text-sm">@player.CharacterName</span>
<span class="text-xs text-gray-400">@((int)player.Health)/@((int)player.MaxHealth)</span>
</div>
<div class="health-bar mt-1">
<div class="health-bar-fill" style="width: @healthPct%"></div>
</div>
<div class="text-xs text-gray-400">@player.Health/@player.MaxHealth</div>
</div>
}
@if (Model.Dungeon.Simulation.Players.Count == 0)
@if (!Model.Dungeon.Simulation.Players.Any())
{
<div class="text-gray-500 text-sm text-center py-2">No players</div>
}
@@ -302,26 +298,26 @@ else
<!-- Actions -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Actions</h3>
<h3 class="text-lg font-semibold text-white mb-3">Dungeon Actions</h3>
<div class="space-y-2">
<form method="post" asp-page-handler="KillAllMobs">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Kill all mobs in this dungeon?')">
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Kill all mobs?')">
Kill All Mobs
</button>
</form>
<form method="post" asp-page-handler="CompleteDungeon">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Force complete this dungeon?')">
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Force complete?')">
Force Complete
</button>
</form>
<form method="post" asp-page-handler="Delete">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-danger w-full text-sm" onclick="return confirm('Delete this dungeon? All players will be removed.')">
<button type="submit" class="btn btn-danger w-full text-sm" onclick="return confirm('Delete dungeon?')">
Delete Dungeon
</button>
</form>
@@ -336,15 +332,26 @@ else
const dungeonId = '@Model.Dungeon?.Id';
const mapWidth = @(Model.MapWidth);
const mapHeight = @(Model.MapHeight);
const walkableData = @Html.Raw(Model.WalkableJson);
let walkableData = @Html.Raw(Model.WalkableJson);
const tileSize = 32;
let autoRefresh = true;
let refreshInterval;
let selectedMobId = null;
let currentMobs = [];
let mapScale = 4;
// Selection state
let selectedMobId = null;
let selectedPlayerId = null;
let currentMobs = [];
let currentPlayers = [];
// Edit mode
let editMode = 'none'; // none, floor, wall, fill
let isDrawing = false;
let fillStartX = -1, fillStartY = -1;
let teleportMode = false;
let godModeEnabled = false;
function initMap() {
const canvas = document.getElementById('mapCanvas');
const container = document.getElementById('mapContainer');
@@ -354,7 +361,7 @@ else
mapScale = Math.min(
(container.clientWidth - 20) / mapWidth,
(container.clientHeight - 20) / mapHeight,
8 // Max scale
8
);
canvas.width = mapWidth * mapScale;
@@ -362,125 +369,319 @@ else
canvas.style.width = canvas.width + 'px';
canvas.style.height = canvas.height + 'px';
// Draw tiles
drawMap(ctx);
setupCanvasEvents(canvas);
}
function drawMap(ctx) {
for (let y = 0; y < mapHeight; y++) {
for (let x = 0; x < mapWidth; x++) {
const idx = y * mapWidth + x;
const walkable = walkableData[idx];
ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
ctx.fillRect(x * mapScale, y * mapScale, mapScale, mapScale);
// Grid lines
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
ctx.strokeStyle = 'rgba(255,255,255,0.03)';
ctx.strokeRect(x * mapScale, y * mapScale, mapScale, mapScale);
}
}
// Store scale for entity positioning
canvas.dataset.scale = mapScale;
// Click handler for spawn position
canvas.onclick = function(e) {
}
function setupCanvasEvents(canvas) {
canvas.oncontextmenu = (e) => {
e.preventDefault();
const rect = canvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / mapScale) * tileSize + tileSize / 2;
const y = Math.floor((e.clientY - rect.top) / mapScale) * tileSize + tileSize / 2;
document.getElementById('spawnX').value = Math.round(x);
document.getElementById('spawnY').value = Math.round(y);
};
canvas.onmousedown = (e) => {
if (e.button !== 0) return;
const rect = canvas.getBoundingClientRect();
const tileX = Math.floor((e.clientX - rect.left) / mapScale);
const tileY = Math.floor((e.clientY - rect.top) / mapScale);
if (teleportMode && selectedPlayerId) {
teleportPlayer(tileX * tileSize + tileSize / 2, tileY * tileSize + tileSize / 2);
teleportMode = false;
document.getElementById('teleportBtn').classList.remove('btn-primary');
document.getElementById('teleportBtn').classList.add('btn-secondary');
return;
}
if (editMode === 'none') return;
if (editMode === 'fill') {
fillStartX = tileX;
fillStartY = tileY;
isDrawing = true;
} else {
isDrawing = true;
paintTile(tileX, tileY);
}
};
canvas.onmousemove = (e) => {
if (!isDrawing) return;
const rect = canvas.getBoundingClientRect();
const tileX = Math.floor((e.clientX - rect.left) / mapScale);
const tileY = Math.floor((e.clientY - rect.top) / mapScale);
if (editMode === 'fill') {
showFillPreview(fillStartX, fillStartY, tileX, tileY);
} else if (editMode !== 'none') {
paintTile(tileX, tileY);
}
};
canvas.onmouseup = (e) => {
if (!isDrawing) return;
isDrawing = false;
if (editMode === 'fill' && fillStartX >= 0) {
const rect = canvas.getBoundingClientRect();
const tileX = Math.floor((e.clientX - rect.left) / mapScale);
const tileY = Math.floor((e.clientY - rect.top) / mapScale);
fillRect(fillStartX, fillStartY, tileX, tileY);
hideFillPreview();
fillStartX = -1;
fillStartY = -1;
}
};
canvas.onmouseleave = () => {
isDrawing = false;
hideFillPreview();
};
}
function setEditMode(mode) {
editMode = mode;
document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
document.getElementById('edit' + mode.charAt(0).toUpperCase() + mode.slice(1))?.classList.add('active');
const canvas = document.getElementById('mapCanvas');
canvas.classList.toggle('edit-mode', mode !== 'none');
}
async function paintTile(x, y) {
if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight) return;
const walkable = editMode === 'floor';
try {
const resp = await fetch(`/admin/dungeons/view?handler=SetTile&id=${dungeonId}&x=${x}&y=${y}&walkable=${walkable}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
if (resp.ok) {
walkableData[y * mapWidth + x] = walkable;
const ctx = document.getElementById('mapCanvas').getContext('2d');
ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
ctx.fillRect(x * mapScale, y * mapScale, mapScale, mapScale);
}
} catch (e) { console.error('Paint failed:', e); }
}
async function fillRect(x1, y1, x2, y2) {
const walkable = editMode === 'fill' ? true : editMode === 'floor';
try {
const resp = await fetch(`/admin/dungeons/view?handler=FillRect&id=${dungeonId}&x1=${x1}&y1=${y1}&x2=${x2}&y2=${y2}&walkable=${walkable}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
if (resp.ok) {
// Update local data and redraw
const minX = Math.min(x1, x2), maxX = Math.max(x1, x2);
const minY = Math.min(y1, y2), maxY = Math.max(y1, y2);
const ctx = document.getElementById('mapCanvas').getContext('2d');
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
if (x >= 0 && x < mapWidth && y >= 0 && y < mapHeight) {
walkableData[y * mapWidth + x] = walkable;
ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
ctx.fillRect(x * mapScale, y * mapScale, mapScale, mapScale);
}
}
}
}
} catch (e) { console.error('Fill failed:', e); }
}
function showFillPreview(x1, y1, x2, y2) {
const preview = document.getElementById('editPreview');
const minX = Math.min(x1, x2), maxX = Math.max(x1, x2);
const minY = Math.min(y1, y2), maxY = Math.max(y1, y2);
preview.style.left = (minX * mapScale) + 'px';
preview.style.top = (minY * mapScale) + 'px';
preview.style.width = ((maxX - minX + 1) * mapScale) + 'px';
preview.style.height = ((maxY - minY + 1) * mapScale) + 'px';
preview.classList.remove('hidden');
}
function hideFillPreview() {
document.getElementById('editPreview').classList.add('hidden');
}
function updateEntities(players, mobs) {
const canvas = document.getElementById('mapCanvas');
const overlay = document.getElementById('entityOverlay');
if (!canvas || !overlay) return;
currentPlayers = players;
currentMobs = mobs;
const overlay = document.getElementById('entityOverlay');
overlay.innerHTML = '';
overlay.style.pointerEvents = 'none';
// Draw players
players.forEach(p => {
const div = document.createElement('div');
div.className = 'entity-dot player-dot';
div.className = 'entity-dot player-dot' + (p.id == selectedPlayerId ? ' selected' : '');
div.style.left = (p.x / tileSize * mapScale) + 'px';
div.style.top = (p.y / tileSize * mapScale) + 'px';
div.title = `${p.name} (${Math.round(p.x)}, ${Math.round(p.y)})`;
div.style.pointerEvents = 'auto';
div.title = p.name;
div.onclick = (e) => { e.stopPropagation(); selectPlayer(p); };
overlay.appendChild(div);
});
// Draw mobs
mobs.forEach(m => {
if (!m.alive) return;
const div = document.createElement('div');
div.className = 'entity-dot ' + (m.isBoss ? 'boss-dot' : 'mob-dot');
if (m.id === selectedMobId) div.classList.add('selected');
div.className = 'entity-dot ' + (m.isBoss ? 'boss-dot' : 'mob-dot') + (m.id == selectedMobId ? ' selected' : '');
div.style.left = (m.x / tileSize * mapScale) + 'px';
div.style.top = (m.y / tileSize * mapScale) + 'px';
div.title = `${m.name} - Click to inspect`;
div.dataset.mobId = m.id;
div.onclick = (e) => {
e.stopPropagation();
selectMob(m);
};
div.style.pointerEvents = 'auto';
div.title = m.name;
div.onclick = (e) => { e.stopPropagation(); selectMob(m); };
overlay.appendChild(div);
});
}
// Player inspection
function selectPlayer(player) {
selectedPlayerId = player.id;
selectedMobId = null;
closeMobInspector();
document.getElementById('playerInspector').classList.remove('hidden');
document.getElementById('playerInspectorName').textContent = player.name;
const healthPct = player.maxHealth > 0 ? Math.round(player.health / player.maxHealth * 100) : 0;
document.getElementById('playerInspectorContent').innerHTML = `
<div class="inspector-stat"><span class="text-gray-400">ID</span><span class="text-white font-mono text-xs">${player.id}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Health</span><span class="text-white">${Math.round(player.health)} / ${Math.round(player.maxHealth)} (${healthPct}%)</span></div>
<div class="inspector-stat"><span class="text-gray-400">Mana</span><span class="text-white">${Math.round(player.mana || 0)} / ${Math.round(player.maxMana || 0)}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Position</span><span class="text-white">${Math.round(player.x)}, ${Math.round(player.y)}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Alive</span><span class="${player.isAlive ? 'text-green-400' : 'text-red-400'}">${player.isAlive ? 'Yes' : 'No'}</span></div>
<div class="inspector-stat"><span class="text-gray-400">In Combat</span><span class="text-white">${player.isInCombat ? 'Yes' : 'No'}</span></div>
`;
updateEntities(currentPlayers, currentMobs);
}
function selectPlayerById(id) {
const player = currentPlayers.find(p => p.id == id);
if (player) selectPlayer(player);
}
function closePlayerInspector() {
selectedPlayerId = null;
document.getElementById('playerInspector').classList.add('hidden');
updateEntities(currentPlayers, currentMobs);
}
async function healSelectedPlayer() {
if (!selectedPlayerId) return;
try {
await fetch(`/admin/dungeons/view?handler=HealPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
fetchUpdate();
} catch (e) { alert('Failed to heal player'); }
}
function teleportPlayerToClick() {
if (!selectedPlayerId) return;
teleportMode = true;
document.getElementById('teleportBtn').classList.add('btn-primary');
document.getElementById('teleportBtn').classList.remove('btn-secondary');
alert('Click on the map to teleport player');
}
async function teleportPlayer(x, y) {
if (!selectedPlayerId) return;
try {
await fetch(`/admin/dungeons/view?handler=TeleportPlayer&id=${dungeonId}&playerId=${selectedPlayerId}&x=${x}&y=${y}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
fetchUpdate();
} catch (e) { alert('Failed to teleport'); }
}
async function toggleGodMode() {
if (!selectedPlayerId) return;
godModeEnabled = !godModeEnabled;
try {
await fetch(`/admin/dungeons/view?handler=SetGodMode&id=${dungeonId}&playerId=${selectedPlayerId}&enabled=${godModeEnabled}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
document.getElementById('godModeBtn').textContent = godModeEnabled ? '🛡️ God Mode ON' : '🛡️ God Mode';
document.getElementById('godModeBtn').classList.toggle('btn-primary', godModeEnabled);
} catch (e) { alert('Failed to toggle god mode'); }
}
async function killSelectedPlayer() {
if (!selectedPlayerId || !confirm('Kill this player?')) return;
try {
await fetch(`/admin/dungeons/view?handler=KillPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
closePlayerInspector();
fetchUpdate();
} catch (e) { alert('Failed to kill player'); }
}
// Mob inspection
function selectMob(mob) {
selectedMobId = mob.id;
selectedPlayerId = null;
closePlayerInspector();
// Update selection visual
document.querySelectorAll('.entity-dot').forEach(d => d.classList.remove('selected'));
document.querySelector(`[data-mob-id="${mob.id}"]`)?.classList.add('selected');
// Show inspector
const inspector = document.getElementById('mobInspector');
inspector.classList.remove('hidden');
document.getElementById('inspectorMobName').textContent = mob.name + (mob.isBoss ? ' ⭐' : '');
document.getElementById('inspectorContent').innerHTML = `
<div class="inspector-stat"><span class="text-gray-400">ID</span><span class="text-white font-mono text-xs">${mob.id}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Type</span><span class="text-white">${mob.type || 'Normal'}</span></div>
document.getElementById('mobInspector').classList.remove('hidden');
document.getElementById('mobInspectorName').textContent = mob.name + (mob.isBoss ? ' ⭐' : '');
document.getElementById('mobInspectorContent').innerHTML = `
<div class="inspector-stat"><span class="text-gray-400">ID</span><span class="text-white font-mono">${mob.id}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Health</span><span class="text-white">${mob.health} / ${mob.maxHealth}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Position</span><span class="text-white">${Math.round(mob.x)}, ${Math.round(mob.y)}</span></div>
<div class="inspector-stat"><span class="text-gray-400">State</span><span class="text-white">${mob.state || 'Unknown'}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Definition ID</span><span class="text-white">${mob.definitionId || 'N/A'}</span></div>
<div class="inspector-stat"><span class="text-gray-400">State</span><span class="text-white">${mob.state}</span></div>
<div class="inspector-stat"><span class="text-gray-400">Type</span><span class="text-white">${mob.type}</span></div>
`;
updateEntities(currentPlayers, currentMobs);
}
function closeMobInspector() {
selectedMobId = null;
document.getElementById('mobInspector').classList.add('hidden');
document.querySelectorAll('.entity-dot').forEach(d => d.classList.remove('selected'));
updateEntities(currentPlayers, currentMobs);
}
async function killSelectedMob() {
if (!selectedMobId) return;
try {
const resp = await fetch(`/admin/dungeons/view?handler=KillMob&id=${dungeonId}&mobId=${selectedMobId}`, {
await fetch(`/admin/dungeons/view?handler=KillMob&id=${dungeonId}&mobId=${selectedMobId}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
if (resp.ok) {
closeMobInspector();
fetchUpdate();
} else {
alert('Failed to kill mob');
}
} catch (e) {
console.error('Failed to kill mob:', e);
alert('Error killing mob');
}
closeMobInspector();
fetchUpdate();
} catch (e) { alert('Failed to kill mob'); }
}
function teleportToMob() {
const mob = currentMobs.find(m => m.id === selectedMobId);
function copyMobPosition() {
const mob = currentMobs.find(m => m.id == selectedMobId);
if (mob) {
navigator.clipboard.writeText(`${Math.round(mob.x)}, ${Math.round(mob.y)}`);
alert(`Position copied: ${Math.round(mob.x)}, ${Math.round(mob.y)}`);
}
}
@@ -488,28 +689,16 @@ else
const mobDefId = document.getElementById('spawnMobSelect').value;
const x = document.getElementById('spawnX').value;
const y = document.getElementById('spawnY').value;
if (!mobDefId) {
alert('Please select a mob to spawn');
return;
}
if (!mobDefId) { alert('Select a mob'); return; }
try {
const resp = await fetch(`/admin/dungeons/view?handler=SpawnMob&id=${dungeonId}&mobDefId=${mobDefId}&x=${x}&y=${y}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
if (resp.ok) {
fetchUpdate();
} else {
const text = await resp.text();
alert('Failed to spawn mob: ' + text);
}
} catch (e) {
console.error('Failed to spawn mob:', e);
alert('Error spawning mob');
}
if (resp.ok) fetchUpdate();
else alert('Failed to spawn mob');
} catch (e) { alert('Error spawning mob'); }
}
async function fetchUpdate() {
@@ -522,46 +711,34 @@ else
document.getElementById('duration').textContent = data.duration;
updateEntities(data.players, data.mobs);
// Update selected mob info if still selected
if (selectedPlayerId) {
const p = data.players.find(x => x.id == selectedPlayerId);
if (p) selectPlayer(p);
}
if (selectedMobId) {
const mob = data.mobs.find(m => m.id === selectedMobId);
if (mob && mob.alive) {
selectMob(mob);
} else {
closeMobInspector();
}
const m = data.mobs.find(x => x.id == selectedMobId);
if (m && m.alive) selectMob(m);
else closeMobInspector();
}
}
} catch (e) {
console.error('Failed to fetch update:', e);
}
} catch (e) { console.error('Update failed:', e); }
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
document.getElementById('autoRefreshBtn').textContent = 'Auto: ' + (autoRefresh ? 'ON' : 'OFF');
if (autoRefresh) {
refreshInterval = setInterval(fetchUpdate, 500);
} else {
clearInterval(refreshInterval);
}
if (autoRefresh) refreshInterval = setInterval(fetchUpdate, 500);
else clearInterval(refreshInterval);
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
initMap();
// Initial entity positions
const initialPlayers = @Html.Raw(Model.PlayersJson);
const initialMobs = @Html.Raw(Model.MobsJson);
updateEntities(initialPlayers, initialMobs);
// Start auto-refresh at 500ms (faster updates)
refreshInterval = setInterval(fetchUpdate, 500);
});
// Handle resize
window.addEventListener('resize', initMap);
</script>
}
+72 -30
View File
@@ -32,7 +32,6 @@ public class ViewModel : AdminPageModel
{
Dungeon = _dungeonHandler.GetDungeon(id);
// Load mob definitions for spawn dropdown
MobDefinitions = await _db.DungeonMobDefinitions
.Where(m => m.IsEnabled)
.OrderBy(m => m.Name)
@@ -43,41 +42,38 @@ public class ViewModel : AdminPageModel
Duration = FormatDuration(DateTime.UtcNow - Dungeon.CreatedAt);
RoomCount = Dungeon.LayoutV2?.Rooms?.Count ?? Dungeon.Simulation.Layout.Rooms.Count;
// Get map dimensions
var layout = Dungeon.LayoutV2;
if (layout != null)
{
MapWidth = layout.Width;
MapHeight = layout.Height;
// Flatten walkable array
var walkable = new List<bool>();
for (int y = 0; y < layout.Height; y++)
{
for (int x = 0; x < layout.Width; x++)
{
walkable.Add(layout.Walkable[x, y]);
}
}
WalkableJson = JsonSerializer.Serialize(walkable);
}
else
{
// Fallback for V1 layouts
MapWidth = 100;
MapHeight = 100;
WalkableJson = "[]";
}
// Serialize entity positions
PlayersJson = JsonSerializer.Serialize(
Dungeon.Simulation.Players.Values.Select(p => new
{
id = p.CharacterId.ToString(),
name = p.CharacterName,
x = p.X,
y = p.Y,
health = p.Health,
maxHealth = p.MaxHealth
maxHealth = p.MaxHealth,
mana = p.Mana,
maxMana = p.MaxMana,
isAlive = p.IsAlive,
isInCombat = p.IsInCombat
})
);
@@ -112,9 +108,16 @@ public class ViewModel : AdminPageModel
duration = FormatDuration(DateTime.UtcNow - dungeon.CreatedAt),
players = dungeon.Simulation.Players.Values.Select(p => new
{
id = p.CharacterId.ToString(),
name = p.CharacterName,
x = p.X,
y = p.Y
y = p.Y,
health = p.Health,
maxHealth = p.MaxHealth,
mana = p.Mana,
maxMana = p.MaxMana,
isAlive = p.IsAlive,
isInCombat = p.IsInCombat
}),
mobs = dungeon.Simulation.Mobs.Values.Select(m => new
{
@@ -133,6 +136,8 @@ public class ViewModel : AdminPageModel
});
}
// ==================== MOB HANDLERS ====================
public IActionResult OnPostKillMob(Guid id, int mobId)
{
var dungeon = _dungeonHandler.GetDungeon(id);
@@ -152,10 +157,8 @@ public class ViewModel : AdminPageModel
public IActionResult OnPostSpawnMob(Guid id, int mobDefId, float x, float y)
{
var mob = _dungeonHandler.SpawnMobInDungeon(id, mobDefId, x, y);
if (mob == null)
return new JsonResult(new { error = "Failed to spawn mob - dungeon or mob definition not found" }) { StatusCode = 400 };
return new JsonResult(new { error = "Failed to spawn mob" }) { StatusCode = 400 };
return new JsonResult(new { success = true, mobId = mob.Id });
}
@@ -169,36 +172,75 @@ public class ViewModel : AdminPageModel
mob.Health = 0;
mob.IsAlive = false;
}
TempData["Message"] = "All mobs killed.";
}
return RedirectToPage(new { id });
}
// ==================== TILE EDITING HANDLERS ====================
public IActionResult OnPostSetTile(Guid id, int x, int y, bool walkable)
{
var result = _dungeonHandler.SetTileWalkable(id, x, y, walkable);
return new JsonResult(new { success = result });
}
public IActionResult OnPostFillRect(Guid id, int x1, int y1, int x2, int y2, bool walkable)
{
var count = _dungeonHandler.FillTileRect(id, x1, y1, x2, y2, walkable);
return new JsonResult(new { success = count > 0, count });
}
// ==================== PLAYER HANDLERS ====================
public IActionResult OnPostHealPlayer(Guid id, string playerId)
{
if (!ulong.TryParse(playerId, out var charId))
return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
var result = _dungeonHandler.HealPlayer(id, charId);
return new JsonResult(new { success = result });
}
public IActionResult OnPostTeleportPlayer(Guid id, string playerId, float x, float y)
{
if (!ulong.TryParse(playerId, out var charId))
return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
var result = _dungeonHandler.TeleportPlayer(id, charId, x, y);
return new JsonResult(new { success = result });
}
public IActionResult OnPostKillPlayer(Guid id, string playerId)
{
if (!ulong.TryParse(playerId, out var charId))
return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
var result = _dungeonHandler.KillPlayer(id, charId);
return new JsonResult(new { success = result });
}
public IActionResult OnPostSetGodMode(Guid id, string playerId, bool enabled)
{
if (!ulong.TryParse(playerId, out var charId))
return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
var result = _dungeonHandler.SetPlayerInvulnerable(id, charId, enabled);
return new JsonResult(new { success = result });
}
// ==================== DUNGEON HANDLERS ====================
public IActionResult OnPostCompleteDungeon(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
if (dungeon != null)
{
dungeon.Simulation.ForceComplete();
TempData["Message"] = "Dungeon marked as completed.";
}
return RedirectToPage(new { id });
}
public IActionResult OnPostDelete(Guid id)
{
var result = _dungeonHandler.ForceCloseDungeon(id);
if (result)
{
TempData["Message"] = "Dungeon deleted.";
}
else
{
TempData["Error"] = "Failed to delete dungeon.";
}
_dungeonHandler.ForceCloseDungeon(id);
return RedirectToPage("/Dungeons/Index");
}