dungeon templates phase 2

This commit is contained in:
dingo
2025-12-28 00:08:33 -05:00
parent 05d1e7038f
commit 6e7609d6e5
6 changed files with 770 additions and 1 deletions
@@ -0,0 +1,426 @@
@page "/admin/roomtemplates/edit"
@model RoomTemplates.EditModel
@using DataServer.Data.Entities
@{
ViewData["Title"] = Model.Room.Id == 0 ? "New Room Template" : $"Edit: {Model.Room.Name}";
var roomTypes = Enum.GetValues<RoomType>();
var tileTypes = Enum.GetValues<TileType>();
}
<div class="mb-4">
<a href="/admin/roomtemplates" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Room Templates</a>
</div>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded text-sm @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
<!-- Room Settings -->
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-4">Room Settings</h2>
<form method="post" id="roomForm">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Room.Id" />
<input type="hidden" asp-for="Room.TileDataJson" id="tileDataJson" />
<input type="hidden" asp-for="Room.SpawnPointsJson" id="spawnPointsJson" />
<input type="hidden" asp-for="Room.ConnectionPointsJson" id="connectionPointsJson" />
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Name</label>
<input type="text" asp-for="Room.Name" class="input w-full text-sm" placeholder="Treasure Room A" required />
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Type</label>
<select asp-for="Room.Type" class="input w-full text-sm">
@foreach (var t in roomTypes)
{
<option value="@((int)t)">@t</option>
}
</select>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Description</label>
<textarea asp-for="Room.Description" class="input w-full text-sm" rows="2" placeholder="Optional description"></textarea>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Tags</label>
<input type="text" asp-for="Room.Tags" class="input w-full text-sm" placeholder="treasure, medium, stone" />
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Width</label>
<input type="number" asp-for="Room.Width" class="input w-full text-sm" min="3" max="50" onchange="resizeGrid()" />
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Height</label>
<input type="number" asp-for="Room.Height" class="input w-full text-sm" min="3" max="50" onchange="resizeGrid()" />
</div>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Min Tier</label>
<input type="number" asp-for="Room.MinTier" class="input w-full text-sm" min="1" />
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Max Tier (0=∞)</label>
<input type="number" asp-for="Room.MaxTier" class="input w-full text-sm" min="0" />
</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-300 mb-1">Weight</label>
<input type="number" asp-for="Room.Weight" class="input w-full text-sm" min="1" />
<p class="text-xs text-gray-500 mt-1">Higher = more common in generation</p>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Room.IsEnabled" class="rounded" />
<label asp-for="Room.IsEnabled" class="text-gray-300 text-sm">Enabled</label>
</div>
<button type="submit" class="btn btn-primary w-full">
@(Model.Room.Id == 0 ? "Create Room" : "Save Changes")
</button>
</div>
</form>
</div>
<!-- Tile Palette -->
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-4">Tile Palette</h2>
@if (Model.TileMapSheets.Count == 0)
{
<p class="text-gray-400 text-sm">No tilemap sheets found. <a href="/admin/tilemaps" class="text-blue-400">Create one first.</a></p>
}
else
{
<!-- TileMap Sheet Selector -->
<div class="mb-3">
<select id="sheetSelector" class="input w-full text-sm" onchange="selectSheet(this.value)">
@foreach (var sheet in Model.TileMapSheets)
{
<option value="@sheet.Id">@sheet.Name (@(sheet.Tiles?.Count ?? 0) tiles)</option>
}
</select>
</div>
<!-- Type Filter -->
<div class="mb-3 flex flex-wrap gap-1">
<button onclick="filterTiles('all')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter active" data-filter="all">All</button>
<button onclick="filterTiles('Floor')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter" data-filter="Floor">Floor</button>
<button onclick="filterTiles('Wall')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter" data-filter="Wall">Wall</button>
<button onclick="filterTiles('Door')" class="px-2 py-0.5 text-xs rounded bg-gray-700 hover:bg-gray-600 tile-filter" data-filter="Door">Door</button>
</div>
<!-- Tile Grid -->
<div id="tilePalette" class="bg-gray-900 rounded p-2 overflow-auto" style="max-height: 50vh;">
<!-- Populated by JavaScript -->
</div>
<!-- Selected Tile Info -->
<div id="selectedTileInfo" class="mt-3 p-2 bg-gray-800 rounded text-xs hidden">
<span class="text-gray-400">Selected:</span>
<span id="selectedTileName" class="text-white ml-1">None</span>
</div>
<!-- Tools -->
<div class="mt-3 flex flex-wrap gap-2">
<button onclick="setTool('paint')" class="btn btn-secondary text-xs py-1 px-2 tool-btn active" data-tool="paint">🖌️ Paint</button>
<button onclick="setTool('erase')" class="btn btn-secondary text-xs py-1 px-2 tool-btn" data-tool="erase">🧹 Erase</button>
<button onclick="setTool('fill')" class="btn btn-secondary text-xs py-1 px-2 tool-btn" data-tool="fill">🪣 Fill</button>
<button onclick="clearAllTiles()" class="btn bg-red-600 hover:bg-red-700 text-xs py-1 px-2">Clear All</button>
</div>
}
</div>
<!-- Room Editor Canvas -->
<div class="card p-4 xl:col-span-1">
<div class="flex items-center justify-between mb-4">
<h2 class="text-lg font-semibold text-white">Room Editor</h2>
<span id="gridInfo" class="text-sm text-gray-400">@Model.Room.Width × @Model.Room.Height</span>
</div>
<div class="bg-gray-900 rounded p-2 overflow-auto" style="max-height: 70vh;">
<div id="roomCanvas" class="relative inline-block" style="image-rendering: pixelated;">
<!-- Grid will be rendered by JavaScript -->
</div>
</div>
<div class="mt-3 flex flex-wrap gap-2 text-xs">
<span class="text-gray-400">Click to place • Right-click to erase • Drag to paint</span>
</div>
</div>
</div>
@section Scripts {
<script>
// Configuration
const TILE_DISPLAY_SIZE = 24; // Display size of tiles in editor
let roomWidth = @Model.Room.Width;
let roomHeight = @Model.Room.Height;
let currentTool = 'paint';
let selectedTile = null;
let selectedSheetId = @(Model.TileMapSheets.FirstOrDefault()?.Id ?? 0);
let isMouseDown = false;
let currentFilter = 'all';
// Room data - array of tile placements
let roomTiles = @Html.Raw(Model.Room.TileDataJson ?? "[]");
// Tilemap sheets data
const sheets = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.TileMapSheets.Select(s => new {
s.Id, s.Name, s.CdnPath, s.TileWidth, s.TileHeight, s.SheetWidth, s.SheetHeight, s.Columns, s.Rows,
Tiles = (s.Tiles ?? new List<TileDefinition>()).Select(t => new { t.Id, t.FrameIndex, t.Name, Type = (int)t.Type, t.Tags, t.IsWalkable }).ToArray()
})));
const cdnBaseUrl = '@Model.CdnBaseUrl';
// Initialize
document.addEventListener('DOMContentLoaded', () => {
if (sheets.length > 0) {
selectSheet(sheets[0].Id);
}
renderRoomGrid();
});
function selectSheet(sheetId) {
selectedSheetId = parseInt(sheetId);
renderTilePalette();
}
function renderTilePalette() {
const sheet = sheets.find(s => s.Id === selectedSheetId);
if (!sheet) return;
const palette = document.getElementById('tilePalette');
const imgUrl = `${cdnBaseUrl}/${sheet.CdnPath}`;
let html = `<div class="grid gap-1" style="grid-template-columns: repeat(auto-fill, minmax(32px, 1fr));">`;
for (const tile of sheet.Tiles) {
if (currentFilter !== 'all' && tile.Type !== TileType[currentFilter]) continue;
const col = tile.FrameIndex % sheet.Columns;
const row = Math.floor(tile.FrameIndex / sheet.Columns);
const bgPos = `-${col * sheet.TileWidth}px -${row * sheet.TileHeight}px`;
const isSelected = selectedTile && selectedTile.id === tile.Id;
const borderClass = isSelected ? 'border-yellow-400 border-2' : 'border-gray-600 border';
html += `<div class="cursor-pointer ${borderClass} hover:border-yellow-300 transition-all"
onclick="selectTile(${tile.Id}, ${sheet.Id})"
title="${tile.Name || 'Tile ' + tile.FrameIndex} (${TileTypeName[tile.Type]})"
style="width: 32px; height: 32px; background-image: url('${imgUrl}'); background-position: ${bgPos}; background-size: ${sheet.SheetWidth}px ${sheet.SheetHeight}px;">
</div>`;
}
html += '</div>';
palette.innerHTML = html;
}
const TileType = { Floor: 0, Wall: 1, Door: 2, Water: 3, Lava: 4, Pit: 5, Stairs: 6, PlayerSpawn: 10, MobSpawn: 11, BossSpawn: 12, ChestSpawn: 13 };
const TileTypeName = { 0: 'Floor', 1: 'Wall', 2: 'Door', 3: 'Water', 4: 'Lava', 5: 'Pit', 6: 'Stairs', 10: 'PlayerSpawn', 11: 'MobSpawn', 12: 'BossSpawn', 13: 'ChestSpawn' };
function selectTile(tileId, sheetId) {
const sheet = sheets.find(s => s.Id === sheetId);
const tile = sheet?.Tiles.find(t => t.Id === tileId);
if (tile) {
selectedTile = { id: tile.Id, sheetId: sheetId, frameIndex: tile.FrameIndex, name: tile.Name || `Tile ${tile.FrameIndex}` };
document.getElementById('selectedTileInfo').classList.remove('hidden');
document.getElementById('selectedTileName').textContent = selectedTile.name;
renderTilePalette(); // Refresh to show selection
}
}
function filterTiles(filter) {
currentFilter = filter;
document.querySelectorAll('.tile-filter').forEach(b => b.classList.remove('active', 'bg-blue-600'));
document.querySelector(`.tile-filter[data-filter="${filter}"]`)?.classList.add('active', 'bg-blue-600');
renderTilePalette();
}
function setTool(tool) {
currentTool = tool;
document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active', 'bg-blue-600'));
document.querySelector(`.tool-btn[data-tool="${tool}"]`)?.classList.add('active', 'bg-blue-600');
}
function renderRoomGrid() {
const canvas = document.getElementById('roomCanvas');
const width = parseInt(document.getElementById('Room_Width').value) || roomWidth;
const height = parseInt(document.getElementById('Room_Height').value) || roomHeight;
roomWidth = width;
roomHeight = height;
document.getElementById('gridInfo').textContent = `${width} × ${height}`;
let html = `<div class="grid" style="grid-template-columns: repeat(${width}, ${TILE_DISPLAY_SIZE}px);">`;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const placement = roomTiles.find(t => t.X === x && t.Y === y);
let bgStyle = 'background-color: #1f2937;';
if (placement) {
// Find the tile and render it
for (const sheet of sheets) {
const tile = sheet.Tiles.find(t => t.Id === placement.TileDefinitionId);
if (tile) {
const col = tile.FrameIndex % sheet.Columns;
const row = Math.floor(tile.FrameIndex / sheet.Columns);
const scale = TILE_DISPLAY_SIZE / sheet.TileWidth;
bgStyle = `background-image: url('${cdnBaseUrl}/${sheet.CdnPath}'); background-position: -${col * sheet.TileWidth * scale}px -${row * sheet.TileHeight * scale}px; background-size: ${sheet.SheetWidth * scale}px ${sheet.SheetHeight * scale}px;`;
break;
}
}
}
html += `<div class="border border-gray-700/50 hover:border-blue-400 cursor-crosshair"
style="width: ${TILE_DISPLAY_SIZE}px; height: ${TILE_DISPLAY_SIZE}px; ${bgStyle}"
data-x="${x}" data-y="${y}"
onmousedown="handleTileClick(event, ${x}, ${y})"
onmouseenter="handleTileHover(event, ${x}, ${y})"
oncontextmenu="event.preventDefault(); eraseTile(${x}, ${y});">
</div>`;
}
}
html += '</div>';
canvas.innerHTML = html;
}
function handleTileClick(event, x, y) {
event.preventDefault();
isMouseDown = true;
if (event.button === 2 || currentTool === 'erase') {
eraseTile(x, y);
} else if (currentTool === 'fill') {
floodFill(x, y);
} else if (selectedTile) {
placeTile(x, y);
}
}
function handleTileHover(event, x, y) {
if (!isMouseDown) return;
if (currentTool === 'erase') {
eraseTile(x, y);
} else if (currentTool === 'paint' && selectedTile) {
placeTile(x, y);
}
}
document.addEventListener('mouseup', () => { isMouseDown = false; });
function placeTile(x, y) {
if (!selectedTile) return;
// Remove existing tile at this position
roomTiles = roomTiles.filter(t => !(t.X === x && t.Y === y));
// Add new tile
roomTiles.push({
X: x,
Y: y,
TileDefinitionId: selectedTile.id,
Layer: 0,
Rotation: 0,
FlipX: false,
FlipY: false
});
updateTileData();
renderRoomGrid();
}
function eraseTile(x, y) {
roomTiles = roomTiles.filter(t => !(t.X === x && t.Y === y));
updateTileData();
renderRoomGrid();
}
function floodFill(startX, startY) {
if (!selectedTile) return;
const existingTile = roomTiles.find(t => t.X === startX && t.Y === startY);
const targetTileId = existingTile?.TileDefinitionId ?? null;
if (targetTileId === selectedTile.id) return; // Already same tile
const stack = [[startX, startY]];
const visited = new Set();
while (stack.length > 0) {
const [x, y] = stack.pop();
const key = `${x},${y}`;
if (visited.has(key) || x < 0 || x >= roomWidth || y < 0 || y >= roomHeight) continue;
visited.add(key);
const tile = roomTiles.find(t => t.X === x && t.Y === y);
const currentTileId = tile?.TileDefinitionId ?? null;
if (currentTileId !== targetTileId) continue;
// Place tile
roomTiles = roomTiles.filter(t => !(t.X === x && t.Y === y));
roomTiles.push({
X: x, Y: y,
TileDefinitionId: selectedTile.id,
Layer: 0, Rotation: 0, FlipX: false, FlipY: false
});
stack.push([x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]);
}
updateTileData();
renderRoomGrid();
}
function clearAllTiles() {
if (!confirm('Clear all tiles from this room?')) return;
roomTiles = [];
updateTileData();
renderRoomGrid();
}
function resizeGrid() {
const newWidth = parseInt(document.getElementById('Room_Width').value) || 10;
const newHeight = parseInt(document.getElementById('Room_Height').value) || 10;
// Remove tiles outside new bounds
roomTiles = roomTiles.filter(t => t.X < newWidth && t.Y < newHeight);
roomWidth = newWidth;
roomHeight = newHeight;
updateTileData();
renderRoomGrid();
}
function updateTileData() {
document.getElementById('tileDataJson').value = JSON.stringify(roomTiles);
}
// Save on form submit
document.getElementById('roomForm').addEventListener('submit', () => {
updateTileData();
});
</script>
<style>
.tool-btn.active, .tile-filter.active { background-color: #2563eb !important; }
</style>
}
@@ -0,0 +1,138 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using DataServer.Data.Entities;
using System.Text.Json;
namespace Server.Services.Admin.Pages.RoomTemplates;
public class EditModel : AdminPageModel
{
private readonly GameDbContext _db;
private readonly IConfiguration _config;
public EditModel(GameDbContext db, IConfiguration config)
{
_db = db;
_config = config;
}
[BindProperty]
public RoomTemplate Room { get; set; } = new();
public List<TileMapSheet> TileMapSheets { get; set; } = new();
public List<TileDefinition> AllTiles { get; set; } = new();
public string CdnBaseUrl { get; set; } = "";
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task OnGetAsync(int? id)
{
CdnBaseUrl = _config["Cdn:BaseUrl"]?.TrimEnd('/') ?? "https://assets.aeternalisgames.com";
if (!CdnBaseUrl.EndsWith("/downloads")) CdnBaseUrl += "/downloads";
TileMapSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.Include(s => s.Tiles!.Where(t => t.IsEnabled))
.OrderBy(s => s.Name)
.ToListAsync();
AllTiles = TileMapSheets.SelectMany(s => s.Tiles ?? new List<TileDefinition>()).ToList();
if (id.HasValue)
{
var room = await _db.RoomTemplates.FindAsync(id.Value);
if (room != null)
{
Room = room;
}
}
else
{
Room = new RoomTemplate
{
Width = 10,
Height = 10,
MinTier = 1,
Weight = 100,
IsEnabled = true
};
}
}
public async Task<IActionResult> OnPostAsync()
{
CdnBaseUrl = _config["Cdn:BaseUrl"]?.TrimEnd('/') ?? "https://assets.aeternalisgames.com";
if (!CdnBaseUrl.EndsWith("/downloads")) CdnBaseUrl += "/downloads";
try
{
if (Room.Id == 0)
{
Room.CreatedAt = DateTime.UtcNow;
Room.UpdatedAt = DateTime.UtcNow;
_db.RoomTemplates.Add(Room);
await _db.SaveChangesAsync();
Message = $"Room template '{Room.Name}' created.";
return RedirectToPage(new { id = Room.Id });
}
else
{
var existing = await _db.RoomTemplates.FindAsync(Room.Id);
if (existing == null)
{
Message = "Room template not found.";
IsError = true;
return Page();
}
existing.Name = Room.Name;
existing.Description = Room.Description;
existing.Tags = Room.Tags;
existing.Type = Room.Type;
existing.Width = Room.Width;
existing.Height = Room.Height;
existing.MinTier = Room.MinTier;
existing.MaxTier = Room.MaxTier;
existing.Weight = Room.Weight;
existing.TileDataJson = Room.TileDataJson;
existing.SpawnPointsJson = Room.SpawnPointsJson;
existing.ConnectionPointsJson = Room.ConnectionPointsJson;
existing.IsEnabled = Room.IsEnabled;
existing.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
Room = existing;
Message = "Room template updated.";
}
}
catch (Exception ex)
{
Message = $"Error: {ex.Message}";
IsError = true;
}
TileMapSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.Include(s => s.Tiles!.Where(t => t.IsEnabled))
.OrderBy(s => s.Name)
.ToListAsync();
AllTiles = TileMapSheets.SelectMany(s => s.Tiles ?? new List<TileDefinition>()).ToList();
return Page();
}
public async Task<IActionResult> OnPostSaveTilesAsync(int roomId, string tileData)
{
var room = await _db.RoomTemplates.FindAsync(roomId);
if (room != null)
{
room.TileDataJson = tileData;
room.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync();
return new JsonResult(new { success = true });
}
return new JsonResult(new { success = false, error = "Room not found" });
}
}
@@ -0,0 +1,134 @@
@page "/admin/roomtemplates"
@model RoomTemplates.IndexModel
@using DataServer.Data.Entities
@{
ViewData["Title"] = "Room Templates";
}
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4 md:mb-6">
<div>
<h1 class="text-xl md:text-2xl font-bold text-white">Room Templates</h1>
<p class="text-gray-400 text-sm">Create and manage room layouts for dungeon generation</p>
</div>
<a href="/admin/roomtemplates/edit" class="btn btn-primary text-sm">+ New Room</a>
</div>
<!-- Room Type Filters -->
<div class="flex flex-wrap gap-2 mb-4">
<span class="text-gray-400 text-sm py-1">Filter:</span>
@foreach (var type in Enum.GetValues<RoomType>().Take(10))
{
var count = Model.Rooms.Count(r => r.Type == type);
if (count > 0)
{
<span class="px-2 py-1 text-xs rounded bg-gray-700 text-gray-300">@type (@count)</span>
}
}
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-4">
@foreach (var room in Model.Rooms)
{
<div class="card p-4">
<div class="flex justify-between items-start mb-3">
<div class="min-w-0 flex-1">
<h3 class="text-base md:text-lg font-semibold text-white truncate">@room.Name</h3>
<p class="text-xs text-gray-400">@room.Width×@room.Height tiles</p>
</div>
<div class="flex flex-col items-end gap-1 ml-2">
<span class="px-2 py-0.5 text-xs rounded @GetRoomTypeColor(room.Type)">@room.Type</span>
<span class="px-2 py-0.5 text-xs rounded @(room.IsEnabled ? "bg-green-900 text-green-300" : "bg-red-900 text-red-300")">
@(room.IsEnabled ? "On" : "Off")
</span>
</div>
</div>
@if (!string.IsNullOrEmpty(room.Description))
{
<p class="text-sm text-gray-400 mb-3 line-clamp-2">@room.Description</p>
}
<div class="grid grid-cols-2 gap-1 text-xs mb-3">
<div>
<span class="text-gray-500">Tier:</span>
<span class="text-gray-300">@room.MinTier - @(room.MaxTier == 0 ? "∞" : room.MaxTier.ToString())</span>
</div>
<div>
<span class="text-gray-500">Weight:</span>
<span class="text-gray-300">@room.Weight</span>
</div>
</div>
@if (!string.IsNullOrEmpty(room.Tags))
{
<div class="flex flex-wrap gap-1 mb-3">
@foreach (var tag in room.Tags.Split(',', StringSplitOptions.RemoveEmptyEntries).Take(4))
{
<span class="px-1.5 py-0.5 bg-blue-900/50 text-blue-300 text-xs rounded">@tag.Trim()</span>
}
</div>
}
<!-- Mini Preview -->
<div class="bg-gray-900 rounded p-2 mb-3 h-20 flex items-center justify-center">
@if (!string.IsNullOrEmpty(room.TileDataJson))
{
<span class="text-xs text-gray-500">@(CountTiles(room.TileDataJson)) tiles placed</span>
}
else
{
<span class="text-xs text-gray-500">No tiles placed</span>
}
</div>
<div class="flex gap-2">
<a href="/admin/roomtemplates/edit?id=@room.Id" class="btn btn-secondary flex-1 text-center text-sm py-1.5">Edit</a>
<form method="post" asp-page-handler="Duplicate" class="flex-shrink-0">
<input type="hidden" name="id" value="@room.Id" />
<button type="submit" class="btn btn-secondary text-sm py-1.5 px-2" title="Duplicate">📋</button>
</form>
<form method="post" asp-page-handler="Delete" class="flex-shrink-0">
<input type="hidden" name="id" value="@room.Id" />
<button type="submit" class="btn bg-red-600 hover:bg-red-700 text-sm py-1.5 px-2"
onclick="return confirm('Delete this room template?')" title="Delete">🗑️</button>
</form>
</div>
</div>
}
</div>
@if (Model.Rooms.Count == 0)
{
<div class="card p-8 md:p-12 text-center">
<p class="text-gray-400 mb-4">No room templates yet. Create rooms to use in dungeon generation.</p>
<a href="/admin/roomtemplates/edit" class="btn btn-primary">Create Your First Room</a>
</div>
}
@functions {
string GetRoomTypeColor(RoomType type)
{
return type switch
{
RoomType.Entrance => "bg-green-900 text-green-300",
RoomType.Exit => "bg-blue-900 text-blue-300",
RoomType.Boss => "bg-red-900 text-red-300",
RoomType.Treasure => "bg-yellow-900 text-yellow-300",
RoomType.Secret => "bg-purple-900 text-purple-300",
RoomType.Shop => "bg-cyan-900 text-cyan-300",
RoomType.Hallway => "bg-gray-700 text-gray-300",
_ => "bg-gray-600 text-gray-300"
};
}
int CountTiles(string? json)
{
if (string.IsNullOrEmpty(json)) return 0;
try
{
var tiles = System.Text.Json.JsonSerializer.Deserialize<List<TilePlacement>>(json);
return tiles?.Count ?? 0;
}
catch { return 0; }
}
}
@@ -0,0 +1,64 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using DataServer.Data.Entities;
namespace Server.Services.Admin.Pages.RoomTemplates;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<RoomTemplate> Rooms { get; set; } = new();
public async Task OnGetAsync()
{
Rooms = await _db.RoomTemplates
.OrderBy(r => r.Type)
.ThenBy(r => r.Name)
.ToListAsync();
}
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var room = await _db.RoomTemplates.FindAsync(id);
if (room != null)
{
_db.RoomTemplates.Remove(room);
await _db.SaveChangesAsync();
}
return RedirectToPage();
}
public async Task<IActionResult> OnPostDuplicateAsync(int id)
{
var room = await _db.RoomTemplates.FindAsync(id);
if (room != null)
{
var copy = new RoomTemplate
{
Name = room.Name + " (Copy)",
Description = room.Description,
Tags = room.Tags,
Type = room.Type,
Width = room.Width,
Height = room.Height,
MinTier = room.MinTier,
MaxTier = room.MaxTier,
Weight = room.Weight,
TileDataJson = room.TileDataJson,
SpawnPointsJson = room.SpawnPointsJson,
ConnectionPointsJson = room.ConnectionPointsJson,
IsEnabled = false
};
_db.RoomTemplates.Add(copy);
await _db.SaveChangesAsync();
}
return RedirectToPage();
}
}
@@ -159,6 +159,13 @@
TileMaps
</a>
<a href="/admin/roomtemplates" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/RoomTemplates") == true ? "active" : "")" onclick="closeMobileMenu()">
<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="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/>
</svg>
Room Templates
</a>
<a href="/admin/assets" class="sidebar-link @(ViewContext.RouteData.Values["page"]?.ToString()?.StartsWith("/Assets") == true ? "active" : "")" onclick="closeMobileMenu()">
<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="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
+1 -1
View File
@@ -353,7 +353,7 @@
@section Scripts {
<script>
const tileDefinitions = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.TileDefinitions.ToDictionary(t => t.FrameIndex)));
const tileDefinitions = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.TileDefinitions.ToDictionary(t => t.FrameIndex, t => new { t.Id, t.FrameIndex, t.Name, t.Type, t.Tags, t.IsWalkable, t.BlocksProjectiles, t.BlocksLineOfSight, t.RenderLayer })));
const sheetWidth = @Model.Sheet.SheetWidth;
const sheetHeight = @Model.Sheet.SheetHeight;
const tileWidth = @Model.Sheet.TileWidth;