Files
systemrevivalserver/Game/Dungeon/DungeonGenerator.cs
T
2025-12-06 11:20:32 -05:00

438 lines
12 KiB
C#

using System.Text.Json;
namespace DungeonCrawler.Game.Dungeon;
/// <summary>
/// Procedural dungeon generator using BSP (Binary Space Partition) + room placement
/// </summary>
public class DungeonGenerator
{
private readonly Random _rng;
private readonly int _seed;
// Generation parameters
private readonly int _tier;
private readonly int _tileSize = 32;
// Tier-based scaling
private int MinRooms => 5 + (_tier * 2);
private int MaxRooms => 8 + (_tier * 3);
private int MinRoomSize => 5; // In tiles
private int MaxRoomSize => 12;
private int MapWidth => 50 + (_tier * 10); // In tiles
private int MapHeight => 50 + (_tier * 10);
public DungeonGenerator(int seed, int tier)
{
_seed = seed;
_tier = Math.Max(1, tier);
_rng = new Random(seed);
}
public DungeonLayout Generate()
{
var layout = new DungeonLayout
{
Seed = _seed,
Tier = _tier,
Width = MapWidth,
Height = MapHeight,
TileSize = _tileSize
};
// Initialize tile map (0 = wall, 1 = floor)
layout.Tiles = new int[MapWidth, MapHeight];
// Generate rooms
int roomCount = _rng.Next(MinRooms, MaxRooms + 1);
var rooms = new List<Room>();
int attempts = 0;
int maxAttempts = roomCount * 20;
while (rooms.Count < roomCount && attempts < maxAttempts)
{
attempts++;
int w = _rng.Next(MinRoomSize, MaxRoomSize + 1);
int h = _rng.Next(MinRoomSize, MaxRoomSize + 1);
int x = _rng.Next(2, MapWidth - w - 2);
int y = _rng.Next(2, MapHeight - h - 2);
var newRoom = new Room(x, y, w, h);
// Check for overlap with existing rooms (with padding)
bool overlaps = rooms.Any(r => newRoom.Intersects(r, padding: 2));
if (!overlaps)
{
rooms.Add(newRoom);
CarveRoom(layout.Tiles, newRoom);
}
}
// Sort rooms by distance from top-left for corridor generation
rooms = rooms.OrderBy(r => r.CenterX + r.CenterY).ToList();
// Connect rooms with corridors
for (int i = 0; i < rooms.Count - 1; i++)
{
ConnectRooms(layout.Tiles, rooms[i], rooms[i + 1]);
}
// Optionally add some extra connections for loops
for (int i = 0; i < rooms.Count / 3; i++)
{
int a = _rng.Next(rooms.Count);
int b = _rng.Next(rooms.Count);
if (a != b)
{
ConnectRooms(layout.Tiles, rooms[a], rooms[b]);
}
}
// Assign room types
AssignRoomTypes(rooms, layout);
// Place spawn point (first room)
layout.SpawnPoint = new Point(rooms[0].CenterX, rooms[0].CenterY);
rooms[0].Type = RoomType.Entrance;
// Generate mob spawns
GenerateMobSpawns(rooms, layout);
// Generate chest spawns
GenerateChestSpawns(rooms, layout);
// Store rooms
layout.Rooms = rooms;
return layout;
}
private void CarveRoom(int[,] tiles, Room room)
{
for (int x = room.X; x < room.X + room.Width; x++)
{
for (int y = room.Y; y < room.Y + room.Height; y++)
{
tiles[x, y] = 1; // Floor
}
}
}
private void ConnectRooms(int[,] tiles, Room a, Room b)
{
int x = a.CenterX;
int y = a.CenterY;
int targetX = b.CenterX;
int targetY = b.CenterY;
// L-shaped corridor (horizontal then vertical, or vice versa)
if (_rng.Next(2) == 0)
{
// Horizontal first
CarveHorizontalTunnel(tiles, x, targetX, y);
CarveVerticalTunnel(tiles, y, targetY, targetX);
}
else
{
// Vertical first
CarveVerticalTunnel(tiles, y, targetY, x);
CarveHorizontalTunnel(tiles, x, targetX, targetY);
}
}
private void CarveHorizontalTunnel(int[,] tiles, int x1, int x2, int y)
{
int minX = Math.Min(x1, x2);
int maxX = Math.Max(x1, x2);
for (int x = minX; x <= maxX; x++)
{
if (x >= 0 && x < tiles.GetLength(0) && y >= 0 && y < tiles.GetLength(1))
{
tiles[x, y] = 1;
// Make corridor 2 tiles wide
if (y + 1 < tiles.GetLength(1)) tiles[x, y + 1] = 1;
}
}
}
private void CarveVerticalTunnel(int[,] tiles, int y1, int y2, int x)
{
int minY = Math.Min(y1, y2);
int maxY = Math.Max(y1, y2);
for (int y = minY; y <= maxY; y++)
{
if (x >= 0 && x < tiles.GetLength(0) && y >= 0 && y < tiles.GetLength(1))
{
tiles[x, y] = 1;
// Make corridor 2 tiles wide
if (x + 1 < tiles.GetLength(0)) tiles[x + 1, y] = 1;
}
}
}
private void AssignRoomTypes(List<Room> rooms, DungeonLayout layout)
{
if (rooms.Count == 0) return;
// First room is entrance (already set)
// Last room is boss room
if (rooms.Count > 1)
{
rooms[^1].Type = RoomType.Boss;
}
// Assign some treasure rooms (10-20% of rooms)
int treasureCount = Math.Max(1, rooms.Count / 6);
var availableRooms = rooms.Skip(1).Take(rooms.Count - 2).ToList();
for (int i = 0; i < treasureCount && availableRooms.Count > 0; i++)
{
int idx = _rng.Next(availableRooms.Count);
availableRooms[idx].Type = RoomType.Treasure;
availableRooms.RemoveAt(idx);
}
// Rest are combat rooms
foreach (var room in rooms.Where(r => r.Type == RoomType.Combat))
{
// Already default
}
}
private void GenerateMobSpawns(List<Room> rooms, DungeonLayout layout)
{
foreach (var room in rooms)
{
if (room.Type == RoomType.Entrance) continue;
int mobCount = room.Type switch
{
RoomType.Boss => 1, // Just the boss
RoomType.Treasure => _rng.Next(1, 3), // Light guard
RoomType.Combat => _rng.Next(2, 5 + _tier),
_ => _rng.Next(1, 3)
};
for (int i = 0; i < mobCount; i++)
{
// Random position within room (with margin)
int x = room.X + 1 + _rng.Next(room.Width - 2);
int y = room.Y + 1 + _rng.Next(room.Height - 2);
var spawn = new MobSpawn
{
Id = layout.MobSpawns.Count + 1,
X = x,
Y = y,
MobType = room.Type == RoomType.Boss ? MobSpawnType.Boss : MobSpawnType.Normal,
RoomIndex = rooms.IndexOf(room)
};
layout.MobSpawns.Add(spawn);
}
}
layout.TotalMobs = layout.MobSpawns.Count;
}
private void GenerateChestSpawns(List<Room> rooms, DungeonLayout layout)
{
foreach (var room in rooms)
{
int chestCount = room.Type switch
{
RoomType.Treasure => _rng.Next(2, 4),
RoomType.Boss => 1, // Guaranteed chest after boss
RoomType.Combat => _rng.NextDouble() < 0.3 ? 1 : 0, // 30% chance
_ => 0
};
for (int i = 0; i < chestCount; i++)
{
int x = room.X + 1 + _rng.Next(room.Width - 2);
int y = room.Y + 1 + _rng.Next(room.Height - 2);
var chest = new ChestSpawn
{
Id = layout.ChestSpawns.Count + 1,
X = x,
Y = y,
ChestType = room.Type == RoomType.Boss ? ChestType.Boss : ChestType.Normal,
RoomIndex = rooms.IndexOf(room)
};
layout.ChestSpawns.Add(chest);
}
}
layout.TotalChests = layout.ChestSpawns.Count;
}
}
// Data structures
public class DungeonLayout
{
public int Seed { get; set; }
public int Tier { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int TileSize { get; set; }
public int[,] Tiles { get; set; } = new int[0, 0];
public List<Room> Rooms { get; set; } = new();
public Point SpawnPoint { get; set; }
public Point? ExitPosition { get; set; } // Set when dungeon is cleared
public List<MobSpawn> MobSpawns { get; set; } = new();
public List<ChestSpawn> ChestSpawns { get; set; } = new();
public int TotalMobs { get; set; }
public int TotalChests { get; set; }
// Serialize tiles to string for DB storage
public string SerializeTiles()
{
var rows = new List<string>();
for (int y = 0; y < Height; y++)
{
var row = new char[Width];
for (int x = 0; x < Width; x++)
{
row[x] = Tiles[x, y] == 1 ? '.' : '#';
}
rows.Add(new string(row));
}
return string.Join("\n", rows);
}
public void DeserializeTiles(string data)
{
var rows = data.Split('\n');
Height = rows.Length;
Width = rows.Length > 0 ? rows[0].Length : 0;
Tiles = new int[Width, Height];
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width && x < rows[y].Length; x++)
{
Tiles[x, y] = rows[y][x] == '.' ? 1 : 0;
}
}
}
public string ToJson()
{
return JsonSerializer.Serialize(new
{
seed = Seed,
tier = Tier,
width = Width,
height = Height,
tileSize = TileSize,
tiles = SerializeTiles(),
spawn = new { x = SpawnPoint.X, y = SpawnPoint.Y },
rooms = Rooms.Select(r => new
{
x = r.X, y = r.Y, w = r.Width, h = r.Height,
type = r.Type.ToString()
}),
mobs = MobSpawns.Select(m => new
{
id = m.Id, x = m.X, y = m.Y,
type = m.MobType.ToString(),
roomIndex = m.RoomIndex
}),
chests = ChestSpawns.Select(c => new
{
id = c.Id, x = c.X, y = c.Y,
type = c.ChestType.ToString(),
roomIndex = c.RoomIndex
})
});
}
}
public class Room
{
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public RoomType Type { get; set; } = RoomType.Combat;
public int CenterX => X + Width / 2;
public int CenterY => Y + Height / 2;
public Room() { }
public Room(int x, int y, int width, int height)
{
X = x; Y = y; Width = width; Height = height;
}
public bool Intersects(Room other, int padding = 0)
{
return X - padding < other.X + other.Width + padding &&
X + Width + padding > other.X - padding &&
Y - padding < other.Y + other.Height + padding &&
Y + Height + padding > other.Y - padding;
}
}
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y) { X = x; Y = y; }
}
public class MobSpawn
{
public int Id { get; set; }
public int X { get; set; }
public int Y { get; set; }
public MobSpawnType MobType { get; set; }
public int RoomIndex { get; set; }
public bool IsAlive { get; set; } = true;
}
public class ChestSpawn
{
public int Id { get; set; }
public int X { get; set; }
public int Y { get; set; }
public ChestType ChestType { get; set; }
public int RoomIndex { get; set; }
public bool IsOpened { get; set; } = false;
}
public enum RoomType
{
Entrance,
Combat,
Treasure,
Boss,
Empty
}
public enum MobSpawnType
{
Normal,
Elite,
Boss
}
public enum ChestType
{
Normal,
Rare,
Boss
}