mirror of
https://github.com/Stone-Red-Code/TextLore.git
synced 2026-09-07 23:42:44 +02:00
Add basic level generation
This commit is contained in:
+1
-1
@@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
|||||||
# Visual Studio Version 17
|
# Visual Studio Version 17
|
||||||
VisualStudioVersion = 17.8.34511.84
|
VisualStudioVersion = 17.8.34511.84
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TextLore", "TextLore\TextLore.csproj", "{1F935415-BA18-42C8-B210-D6195F93A719}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TextLore", "TextLore\TextLore.csproj", "{1F935415-BA18-42C8-B210-D6195F93A719}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
@page "/"
|
@page "/"
|
||||||
|
|
||||||
|
|
||||||
<PageTitle>TextLore</PageTitle>
|
<PageTitle>TextLore</PageTitle>
|
||||||
|
|
||||||
<Console Name="Main Menu" Commands="commands" HelpCommand="helpCommand" />
|
<Console Name="Main Menu" Commands="commands" Description="@desctiption" HelpCommand="helpCommand" />
|
||||||
|
|
||||||
@code
|
@code
|
||||||
{
|
{
|
||||||
@@ -11,6 +10,8 @@
|
|||||||
|
|
||||||
HelpCommand? helpCommand;
|
HelpCommand? helpCommand;
|
||||||
|
|
||||||
|
string desctiption = "Select a game mode by using the 'play' command.";
|
||||||
|
|
||||||
protected override void OnInitialized()
|
protected override void OnInitialized()
|
||||||
{
|
{
|
||||||
helpCommand = new HelpCommand(commands);
|
helpCommand = new HelpCommand(commands);
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
@using Microsoft.AspNetCore.Components.Forms
|
@using Microsoft.AspNetCore.Components.Forms
|
||||||
@using TextLore.Models
|
|
||||||
|
|
||||||
<div id="console">
|
<div id="console">
|
||||||
<div id="header">
|
<div id="header">
|
||||||
@@ -72,11 +71,16 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Execute(EditContext context)
|
private Task Execute(EditContext context)
|
||||||
{
|
{
|
||||||
string commandName = ConsoleInput.Text.Split(' ')[0];
|
string commandName = ConsoleInput.Text.Split(' ')[0];
|
||||||
string commandArgs = new string(ConsoleInput.Text.Skip(commandName.Length).ToArray()).TrimStart(' ');
|
string commandArgs = new string(ConsoleInput.Text.Skip(commandName.Length).ToArray()).TrimStart(' ');
|
||||||
|
|
||||||
|
return Execute(commandName, commandArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Execute(string commandName, string commandArgs = "")
|
||||||
|
{
|
||||||
Command? command = Commands.FirstOrDefault(c => c.Name.Equals(commandName) || c.Aliases.Contains(commandName));
|
Command? command = Commands.FirstOrDefault(c => c.Name.Equals(commandName) || c.Aliases.Contains(commandName));
|
||||||
command ??= HelpCommand?.Name.Equals(commandName) == true || HelpCommand?.Aliases.Contains(commandName) == true ? HelpCommand : null;
|
command ??= HelpCommand?.Name.Equals(commandName) == true || HelpCommand?.Aliases.Contains(commandName) == true ? HelpCommand : null;
|
||||||
|
|
||||||
@@ -86,13 +90,20 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await Execute(command, commandArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task Execute(Command command, string commandArgs = "")
|
||||||
|
{
|
||||||
disabled = true;
|
disabled = true;
|
||||||
|
|
||||||
ConsoleWriter consoleWriter = new ConsoleWriter();
|
ConsoleWriter consoleWriter = new ConsoleWriter();
|
||||||
ConsoleOutput consoleOutput = new ConsoleOutput();
|
ConsoleOutput consoleOutput = new ConsoleOutput();
|
||||||
|
|
||||||
consoleWriter.OnOutput += (_, e) => WriteOutput(consoleOutput, e);
|
consoleWriter.OnOutput += (_, e) => WriteOutput(consoleOutput, e);
|
||||||
consoleWriter.OnClear += (_, _) => consoleOutputs.Clear();
|
consoleWriter.OnClearAll += (_, _) => consoleOutputs.Clear();
|
||||||
|
consoleWriter.OnClearLine += (_, _) => ClearLine(consoleOutput);
|
||||||
|
consoleWriter.OnClearCurrent += (_, _) => consoleOutput.Text = string.Empty;
|
||||||
consoleOutput.Command = ConsoleInput.Text;
|
consoleOutput.Command = ConsoleInput.Text;
|
||||||
currentOutput = consoleOutput;
|
currentOutput = consoleOutput;
|
||||||
|
|
||||||
@@ -119,6 +130,18 @@
|
|||||||
StateHasChanged();
|
StateHasChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ClearLine(ConsoleOutput consoleOutput)
|
||||||
|
{
|
||||||
|
consoleOutput.Text = consoleOutput.Text.TrimEnd(Environment.NewLine.ToCharArray());
|
||||||
|
|
||||||
|
if (consoleOutput.Text.Contains(Environment.NewLine))
|
||||||
|
{
|
||||||
|
consoleOutput.Text = consoleOutput.Text.Substring(0, consoleOutput.Text.LastIndexOf(Environment.NewLine));
|
||||||
|
}
|
||||||
|
|
||||||
|
consoleOutput.Text += Environment.NewLine;
|
||||||
|
}
|
||||||
|
|
||||||
private async Task CommandNotFound(string commandName)
|
private async Task CommandNotFound(string commandName)
|
||||||
{
|
{
|
||||||
currentOutput = new()
|
currentOutput = new()
|
||||||
|
|||||||
@@ -9,5 +9,5 @@
|
|||||||
@using TextLore
|
@using TextLore
|
||||||
@using TextLore.Components
|
@using TextLore.Components
|
||||||
@using TextLore.Components.Shared
|
@using TextLore.Components.Shared
|
||||||
@using TextLore.Commands
|
@using TextLore.Console
|
||||||
@using TextLore.Models
|
@using TextLore.Console.Commands
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace TextLore.Models;
|
namespace TextLore.Console;
|
||||||
|
|
||||||
public abstract class Command
|
public abstract class Command
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
namespace TextLore.Console;
|
||||||
|
|
||||||
|
public class CommandResult(string message, bool success, Command? precedingCommand = null)
|
||||||
|
{
|
||||||
|
public string Message { get; } = message;
|
||||||
|
public bool IsSuccess { get; } = success;
|
||||||
|
|
||||||
|
public Command? PrecedingCommand { get; } = precedingCommand;
|
||||||
|
|
||||||
|
public static CommandResult Success(string message = "")
|
||||||
|
{
|
||||||
|
return new(message, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandResult Success(Command precedingCommand, string message = "")
|
||||||
|
{
|
||||||
|
return new(message, true, precedingCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandResult Failure(string message = "")
|
||||||
|
{
|
||||||
|
return new(message, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CommandResult Failure(Command precedingCommand, string message = "")
|
||||||
|
{
|
||||||
|
return new(message, false, precedingCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static implicit operator CommandResult(string message)
|
||||||
|
{
|
||||||
|
return Success(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static implicit operator Task<CommandResult>(CommandResult result)
|
||||||
|
{
|
||||||
|
return Task.FromResult(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-5
@@ -1,6 +1,4 @@
|
|||||||
using TextLore.Models;
|
namespace TextLore.Console.Commands;
|
||||||
|
|
||||||
namespace TextLore.Commands;
|
|
||||||
|
|
||||||
public class ClearCommand : Command
|
public class ClearCommand : Command
|
||||||
{
|
{
|
||||||
@@ -13,7 +11,7 @@ public class ClearCommand : Command
|
|||||||
|
|
||||||
public override Task<CommandResult> Execute(ConsoleWriter consoleOutput, string args)
|
public override Task<CommandResult> Execute(ConsoleWriter consoleOutput, string args)
|
||||||
{
|
{
|
||||||
consoleOutput.Clear();
|
consoleOutput.ClearAll();
|
||||||
return Task.FromResult(CommandResult.Success("Console cleared!"));
|
return CommandResult.Success("Console cleared!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
using TextLore.Models;
|
namespace TextLore.Console.Commands;
|
||||||
|
|
||||||
namespace TextLore.Commands;
|
|
||||||
|
|
||||||
public class HelpCommand(IEnumerable<Command> commands) : Command
|
public class HelpCommand(IEnumerable<Command> commands) : Command
|
||||||
{
|
{
|
||||||
@@ -18,7 +16,7 @@ public class HelpCommand(IEnumerable<Command> commands) : Command
|
|||||||
{
|
{
|
||||||
consoleOutput.WriteLine($" {command.Name} - {command.Description}");
|
consoleOutput.WriteLine($" {command.Name} - {command.Description}");
|
||||||
}
|
}
|
||||||
return Task.FromResult(CommandResult.Success());
|
return CommandResult.Success();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -26,7 +24,7 @@ public class HelpCommand(IEnumerable<Command> commands) : Command
|
|||||||
if (command is null)
|
if (command is null)
|
||||||
{
|
{
|
||||||
consoleOutput.WriteLine($"Command \"{args[0]}\" not found.");
|
consoleOutput.WriteLine($"Command \"{args[0]}\" not found.");
|
||||||
return Task.FromResult(CommandResult.Failure());
|
return CommandResult.Failure();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -44,7 +42,7 @@ public class HelpCommand(IEnumerable<Command> commands) : Command
|
|||||||
consoleOutput.WriteLine($"Usage: {command.Usage}");
|
consoleOutput.WriteLine($"Usage: {command.Usage}");
|
||||||
}
|
}
|
||||||
|
|
||||||
return Task.FromResult(CommandResult.Success());
|
return CommandResult.Success();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
using TextLore.Models;
|
namespace TextLore.Console.Commands;
|
||||||
|
|
||||||
namespace TextLore.Commands;
|
|
||||||
|
|
||||||
public class TestCommand : Command
|
public class TestCommand : Command
|
||||||
{
|
{
|
||||||
@@ -12,6 +10,6 @@ public class TestCommand : Command
|
|||||||
public override Task<CommandResult> Execute(ConsoleWriter consoleOutput, string args)
|
public override Task<CommandResult> Execute(ConsoleWriter consoleOutput, string args)
|
||||||
{
|
{
|
||||||
consoleOutput.WriteLine("This is a test command.");
|
consoleOutput.WriteLine("This is a test command.");
|
||||||
return Task.FromResult(CommandResult.Success("test"));
|
return CommandResult.Success("test");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace TextLore.Models;
|
namespace TextLore.Console;
|
||||||
|
|
||||||
public class ConsoleInput
|
public class ConsoleInput
|
||||||
{
|
{
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace TextLore.Models;
|
namespace TextLore.Console;
|
||||||
|
|
||||||
public enum ConsoleMessageType
|
public enum ConsoleMessageType
|
||||||
{
|
{
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace TextLore.Models;
|
namespace TextLore.Console;
|
||||||
|
|
||||||
public class ConsoleOutput
|
public class ConsoleOutput
|
||||||
{
|
{
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace TextLore.Models;
|
namespace TextLore.Console;
|
||||||
|
|
||||||
public class ConsoleOutputEventArgs(string message, ConsoleMessageType messageType) : EventArgs
|
public class ConsoleOutputEventArgs(string message, ConsoleMessageType messageType) : EventArgs
|
||||||
{
|
{
|
||||||
@@ -1,10 +1,15 @@
|
|||||||
namespace TextLore.Models;
|
namespace TextLore.Console;
|
||||||
|
|
||||||
public class ConsoleWriter
|
public class ConsoleWriter
|
||||||
{
|
{
|
||||||
public event EventHandler<ConsoleOutputEventArgs>? OnOutput;
|
public event EventHandler<ConsoleOutputEventArgs>? OnOutput;
|
||||||
|
|
||||||
public event EventHandler<EventArgs>? OnClear;
|
public event EventHandler<EventArgs>? OnClearAll;
|
||||||
|
|
||||||
|
public event EventHandler<EventArgs>? OnClearLine;
|
||||||
|
|
||||||
|
public event EventHandler<EventArgs>? OnClearCurrent;
|
||||||
|
|
||||||
public void Write(string message, ConsoleMessageType consoleMessageType = ConsoleMessageType.Default)
|
public void Write(string message, ConsoleMessageType consoleMessageType = ConsoleMessageType.Default)
|
||||||
{
|
{
|
||||||
OnOutput?.Invoke(this, new(message, consoleMessageType));
|
OnOutput?.Invoke(this, new(message, consoleMessageType));
|
||||||
@@ -45,8 +50,18 @@ public class ConsoleWriter
|
|||||||
WriteInfo(message + Environment.NewLine);
|
WriteInfo(message + Environment.NewLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Clear()
|
public void ClearLine()
|
||||||
{
|
{
|
||||||
OnClear?.Invoke(this, EventArgs.Empty);
|
OnClearLine?.Invoke(this, EventArgs.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ClearAll()
|
||||||
|
{
|
||||||
|
OnClearAll?.Invoke(this, EventArgs.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ClearCurrent()
|
||||||
|
{
|
||||||
|
OnClearCurrent?.Invoke(this, EventArgs.Empty);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace TextLore.Database;
|
||||||
|
|
||||||
|
public class GamesDatabaseContext(DbContextOptions<GamesDatabaseContext> options) : DbContext(options)
|
||||||
|
{
|
||||||
|
public DbSet<Games.Roguelike.Models.RoomDefinition> RoguelikeRooms { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
using TextLore.Console;
|
||||||
|
using TextLore.Games.Roguelike.Logic;
|
||||||
|
using TextLore.Games.Roguelike.Models;
|
||||||
|
using TextLore.Utilities.Logic;
|
||||||
|
using TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
namespace TextLore.Games.Roguelike.Commands;
|
||||||
|
|
||||||
|
public class GenerateLevelCommand(IQueryable<RoomDefinition> roomDefinitions, NavigationManager navigationManager, Action<Level> levelGeneratedCallback) : Command
|
||||||
|
{
|
||||||
|
private bool isGenerated = false;
|
||||||
|
public override string Name => "generatelevel";
|
||||||
|
public override string Description => "Generates a new level.";
|
||||||
|
|
||||||
|
public override string[] Aliases => ["genlevel"];
|
||||||
|
|
||||||
|
public override bool NoHistoryIfNoOutput => true;
|
||||||
|
|
||||||
|
public override async Task<CommandResult> Execute(ConsoleWriter consoleOutput, string args)
|
||||||
|
{
|
||||||
|
if (!DeterministicRandom.TryParse(args, out DeterministicRandom? seed))
|
||||||
|
{
|
||||||
|
consoleOutput.WriteLine("Invalid seed. Generating a new one...");
|
||||||
|
seed = await GenerateSeed();
|
||||||
|
|
||||||
|
navigationManager.NavigateTo($"/roguelike/{seed.ToBase64()}");
|
||||||
|
}
|
||||||
|
|
||||||
|
consoleOutput.WriteLine("Generating level...");
|
||||||
|
|
||||||
|
LevelGenerator levelGenerator = new LevelGenerator(seed, roomDefinitions);
|
||||||
|
|
||||||
|
IProgress<PercentageProgress> progress = new Progress<PercentageProgress>(p => ReportProgress(p, consoleOutput));
|
||||||
|
|
||||||
|
Level level;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
level = await levelGenerator.GenerateLevel(progress);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return CommandResult.Failure(ex.Message);
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
return CommandResult.Failure(ex.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
isGenerated = true;
|
||||||
|
|
||||||
|
consoleOutput.WriteLine($"Level size: {level.Size.Width}x{level.Size.Height}");
|
||||||
|
consoleOutput.WriteLine($"Room count: {level.RoomCount}");
|
||||||
|
consoleOutput.WriteLine($"Filled space: {(double)level.RoomCount / (level.Size.Width * level.Size.Height):F0}%");
|
||||||
|
consoleOutput.WriteLine($"Seed: {seed.ToBase64()}");
|
||||||
|
|
||||||
|
consoleOutput.WriteLine("Level generation complete!");
|
||||||
|
|
||||||
|
levelGeneratedCallback?.Invoke(level);
|
||||||
|
|
||||||
|
return CommandResult.Success("Level generated!");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReportProgress(PercentageProgress progress, ConsoleWriter consoleOutput)
|
||||||
|
{
|
||||||
|
if (isGenerated)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
char spinner = (DateTime.UtcNow.Second % 4) switch
|
||||||
|
{
|
||||||
|
0 => '|',
|
||||||
|
1 => '/',
|
||||||
|
2 => '-',
|
||||||
|
3 => '\\',
|
||||||
|
_ => '|'
|
||||||
|
};
|
||||||
|
|
||||||
|
consoleOutput.ClearLine();
|
||||||
|
|
||||||
|
consoleOutput.WriteLine($"{spinner} Generating level... {progress.Percentage}%");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<DeterministicRandom> GenerateSeed()
|
||||||
|
{
|
||||||
|
int baseSeed = Guid.NewGuid().GetHashCode();
|
||||||
|
int min = await roomDefinitions.MinAsync(r => r.Id);
|
||||||
|
int max = await roomDefinitions.MaxAsync(r => r.Id);
|
||||||
|
|
||||||
|
return new DeterministicRandom(baseSeed, min, max);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
using TextLore.Games.Roguelike.Models;
|
||||||
|
using TextLore.Utilities.Logic;
|
||||||
|
using TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
namespace TextLore.Games.Roguelike.Logic;
|
||||||
|
|
||||||
|
public class LevelGenerator(DeterministicRandom seed, IQueryable<RoomDefinition> rooms)
|
||||||
|
{
|
||||||
|
public async Task<Level> GenerateLevel(IProgress<PercentageProgress> progress)
|
||||||
|
{
|
||||||
|
// Random size between 10x10 and 100x100.
|
||||||
|
Size size = new Size(seed.Next(10, 100), seed.Next(10, 100));
|
||||||
|
|
||||||
|
// Fill 20-60% of the level with rooms.
|
||||||
|
int roomCount = size.Width * size.Height / 100 * seed.Next(20, 60);
|
||||||
|
|
||||||
|
Level level = new Level(size, seed);
|
||||||
|
Queue<Room> generationQueue = new Queue<Room>();
|
||||||
|
|
||||||
|
RoomDefinition startRoomDefinition = await GetRandomRoomDefinition() ?? throw new InvalidOperationException("No rooms found in the database.");
|
||||||
|
Position startRoomPosition = new Position(seed.Next(0, size.Width), seed.Next(0, size.Height));
|
||||||
|
|
||||||
|
Room startRoom = new Room(startRoomPosition, startRoomDefinition);
|
||||||
|
|
||||||
|
level.AddRoom(startRoom);
|
||||||
|
generationQueue.Enqueue(startRoom);
|
||||||
|
|
||||||
|
while (generationQueue.Count > 0)
|
||||||
|
{
|
||||||
|
Room currentRoom = generationQueue.Dequeue();
|
||||||
|
|
||||||
|
foreach (Direction direction in currentRoom.DoorDirections.ToArray())
|
||||||
|
{
|
||||||
|
Position newPosition = currentRoom.Position + direction;
|
||||||
|
|
||||||
|
// Randomly skip a direction to create a maze-like structure.
|
||||||
|
if (seed.Next(0, 100) < 50)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (level.IsPositionInBounds(newPosition) && level.GetRoom(newPosition) is null)
|
||||||
|
{
|
||||||
|
RoomDefinition? newRoomDefinition = await GetRandomRoomDefinition();
|
||||||
|
|
||||||
|
Room newRoom = new Room(newPosition, newRoomDefinition ?? throw new InvalidOperationException("No rooms found in the database."));
|
||||||
|
|
||||||
|
level.AddRoom(newRoom);
|
||||||
|
generationQueue.Enqueue(newRoom);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(1);
|
||||||
|
progress.Report(new(level.RoomCount, roomCount));
|
||||||
|
|
||||||
|
if (level.RoomCount >= roomCount)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (generationQueue.Count == 0)
|
||||||
|
{
|
||||||
|
Room? nextRoom = level.GetRooms().Values.ElementAt(seed.Next(0, level.RoomCount));
|
||||||
|
|
||||||
|
if (nextRoom is not null)
|
||||||
|
{
|
||||||
|
generationQueue.Enqueue(nextRoom);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return level;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<RoomDefinition?> GetRandomRoomDefinition()
|
||||||
|
{
|
||||||
|
RoomDefinition? room = null;
|
||||||
|
int randomRoomIndex = seed.Next();
|
||||||
|
|
||||||
|
// This is a fallback in case the room doesn't exist in the database to keep the order of the future rooms the same.
|
||||||
|
DeterministicRandom fallbackRandom = new DeterministicRandom(randomRoomIndex, seed.Min, seed.Max);
|
||||||
|
|
||||||
|
// Try to find a room 100 times, if it doesn't exist, then return null.
|
||||||
|
for (int i = 0; i < 100; i++)
|
||||||
|
{
|
||||||
|
room = await rooms.FirstOrDefaultAsync(x => x.Id == randomRoomIndex);
|
||||||
|
|
||||||
|
if (room is not null)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
randomRoomIndex = fallbackRandom.Next();
|
||||||
|
}
|
||||||
|
|
||||||
|
return room;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using TextLore.Utilities.Logic;
|
||||||
|
using TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
namespace TextLore.Games.Roguelike.Models;
|
||||||
|
|
||||||
|
public class Level(Size size, DeterministicRandom seed)
|
||||||
|
{
|
||||||
|
private readonly Dictionary<Position, Room> rooms = [];
|
||||||
|
|
||||||
|
public Size Size => size;
|
||||||
|
public int RoomCount => rooms.Count;
|
||||||
|
|
||||||
|
public DeterministicRandom Seed => seed;
|
||||||
|
|
||||||
|
public Room? GetRoom(Position point)
|
||||||
|
{
|
||||||
|
return rooms.GetValueOrDefault(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<Position, Room> GetRooms()
|
||||||
|
{
|
||||||
|
return rooms;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddRoom(Room room)
|
||||||
|
{
|
||||||
|
if (!IsRoomInBounds(room))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Room is out of bounds.");
|
||||||
|
}
|
||||||
|
|
||||||
|
rooms[room.Position] = room;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsPositionInBounds(Position point)
|
||||||
|
{
|
||||||
|
return point.X >= 0 && point.X < size.Width && point.Y >= 0 && point.Y < size.Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsRoomInBounds(Room room)
|
||||||
|
{
|
||||||
|
return IsPositionInBounds(room.Position);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool RoomExists(Position point)
|
||||||
|
{
|
||||||
|
return rooms.ContainsKey(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ClearRoom(Position point)
|
||||||
|
{
|
||||||
|
_ = rooms.Remove(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ClearRooms()
|
||||||
|
{
|
||||||
|
rooms.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
namespace TextLore.Games.Roguelike.Models;
|
||||||
|
|
||||||
|
public class Room(Position position, RoomDefinition roomDefinition)
|
||||||
|
{
|
||||||
|
public Position Position => position;
|
||||||
|
public List<Direction> DoorDirections { get; init; } = [Direction.Up, Direction.Down, Direction.Right, Direction.Left];
|
||||||
|
public RoomDefinition Definition => roomDefinition;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
|
|
||||||
|
namespace TextLore.Games.Roguelike.Models;
|
||||||
|
|
||||||
|
public class RoomDefinition(string name)
|
||||||
|
{
|
||||||
|
[Key]
|
||||||
|
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||||
|
public int Id { get; private set; }
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
public string Name { get; set; } = name;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
@page "/roguelike/{Seed?}"
|
||||||
|
|
||||||
|
@inject GamesDatabaseContext DatabaseContext
|
||||||
|
@inject NavigationManager NavigationManager
|
||||||
|
|
||||||
|
<Console @ref="console" Name="Roguelike" Commands="commands" Description="@desctiption" HelpCommand="helpCommand" />
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using Microsoft.AspNetCore.Components;
|
||||||
|
|
||||||
|
using TextLore.Console;
|
||||||
|
using TextLore.Console.Commands;
|
||||||
|
using TextLore.Games.Roguelike.Commands;
|
||||||
|
using TextLore.Games.Roguelike.Models;
|
||||||
|
|
||||||
|
namespace TextLore.Games.Roguelike;
|
||||||
|
|
||||||
|
public partial class RoguelikePage
|
||||||
|
{
|
||||||
|
private readonly List<Command> commands = [new TestCommand(), new ClearCommand()];
|
||||||
|
|
||||||
|
// Short description how to play the game
|
||||||
|
private readonly string desctiption = "This is a roguelike game. Use commands to play the game.";
|
||||||
|
|
||||||
|
private Components.Shared.Console console = null!;
|
||||||
|
private HelpCommand? helpCommand;
|
||||||
|
|
||||||
|
private Level? level;
|
||||||
|
|
||||||
|
[Parameter]
|
||||||
|
public string Seed { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public void OnLevelGenerated(Level level)
|
||||||
|
{
|
||||||
|
this.level = level;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnInitialized()
|
||||||
|
{
|
||||||
|
helpCommand = new HelpCommand(commands);
|
||||||
|
commands.Add(helpCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
|
{
|
||||||
|
if (firstRender)
|
||||||
|
{
|
||||||
|
await console.Execute(new GenerateLevelCommand(DatabaseContext.RoguelikeRooms, NavigationManager, OnLevelGenerated), Seed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
@using System.Net.Http
|
||||||
|
@using System.Net.Http.Json
|
||||||
|
@using Microsoft.AspNetCore.Components.Forms
|
||||||
|
@using Microsoft.AspNetCore.Components.Routing
|
||||||
|
@using Microsoft.AspNetCore.Components.Web
|
||||||
|
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||||
|
@using Microsoft.AspNetCore.Components.Web.Virtualization
|
||||||
|
@using Microsoft.JSInterop
|
||||||
|
@using TextLore
|
||||||
|
@using TextLore.Database
|
||||||
|
@using TextLore.Components
|
||||||
|
@using TextLore.Components.Shared
|
||||||
|
@using TextLore.Console
|
||||||
|
@using TextLore.Console.Commands
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
namespace TextLore.Models;
|
|
||||||
|
|
||||||
public class CommandResult(string message, bool success)
|
|
||||||
{
|
|
||||||
public string Message { get; } = message;
|
|
||||||
public bool IsSuccess { get; } = success;
|
|
||||||
|
|
||||||
public static CommandResult Success(string message = "")
|
|
||||||
{
|
|
||||||
return new(message, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static CommandResult Failure(string message = "")
|
|
||||||
{
|
|
||||||
return new(message, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static implicit operator CommandResult(string message)
|
|
||||||
{
|
|
||||||
return Success(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+34
-6
@@ -1,19 +1,47 @@
|
|||||||
using TextLore.Components;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
using TextLore.Components;
|
||||||
|
using TextLore.Database;
|
||||||
|
|
||||||
|
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
builder.Services.AddRazorComponents()
|
builder.Services.AddRazorComponents()
|
||||||
.AddInteractiveServerComponents();
|
.AddInteractiveServerComponents();
|
||||||
|
|
||||||
var app = builder.Build();
|
builder.Services.AddDbContext<GamesDatabaseContext>(options =>
|
||||||
|
options.UseSqlite(builder.Configuration.GetConnectionString("GamesDatabase")));
|
||||||
|
|
||||||
|
WebApplication app = builder.Build();
|
||||||
|
|
||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
if (!app.Environment.IsDevelopment())
|
if (!app.Environment.IsDevelopment())
|
||||||
{
|
{
|
||||||
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
_ = app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
||||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||||
app.UseHsts();
|
_ = app.UseHsts();
|
||||||
|
}
|
||||||
|
|
||||||
|
using AsyncServiceScope serviceScope = app.Services.CreateAsyncScope();
|
||||||
|
|
||||||
|
GamesDatabaseContext databaseContext = serviceScope.ServiceProvider.GetRequiredService<GamesDatabaseContext>();
|
||||||
|
|
||||||
|
if (await databaseContext.Database.EnsureCreatedAsync())
|
||||||
|
{
|
||||||
|
databaseContext.RoguelikeRooms.AddRange(
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 1"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 2"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 3"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 4"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 5"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 6"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 7"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 8"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 9"),
|
||||||
|
new TextLore.Games.Roguelike.Models.RoomDefinition("Room 10")
|
||||||
|
);
|
||||||
|
|
||||||
|
_ = await databaseContext.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
@@ -24,4 +52,4 @@ app.UseAntiforgery();
|
|||||||
app.MapRazorComponents<App>()
|
app.MapRazorComponents<App>()
|
||||||
.AddInteractiveServerRenderMode();
|
.AddInteractiveServerRenderMode();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
@@ -6,4 +6,9 @@
|
|||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.1" />
|
||||||
|
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.3.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
|
||||||
|
namespace TextLore.Utilities.Logic;
|
||||||
|
|
||||||
|
public class DeterministicRandom(int seed, int min, int max) : IParsable<DeterministicRandom>
|
||||||
|
{
|
||||||
|
private readonly Random random = new Random(seed);
|
||||||
|
public int Seed => seed;
|
||||||
|
public int Min => min;
|
||||||
|
public int Max => max;
|
||||||
|
|
||||||
|
public DeterministicRandom(int min, int max) : this(Guid.NewGuid().GetHashCode(), min, max)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DeterministicRandom Parse(string s, IFormatProvider? provider)
|
||||||
|
{
|
||||||
|
byte[] bytes = Base64UrlEncoder.DecodeBytes(s);
|
||||||
|
|
||||||
|
int lseed = BitConverter.ToInt32(bytes.Take(4).ToArray(), 0);
|
||||||
|
int lmin = BitConverter.ToInt32(bytes.Skip(4).Take(4).ToArray(), 0);
|
||||||
|
int lmax = BitConverter.ToInt32(bytes.Skip(8).Take(4).ToArray(), 0);
|
||||||
|
|
||||||
|
return new DeterministicRandom(lseed, lmin, lmax);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DeterministicRandom Parse(string s)
|
||||||
|
{
|
||||||
|
return Parse(s, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [NotNullWhen(true)] out DeterministicRandom? result)
|
||||||
|
{
|
||||||
|
if (s is null)
|
||||||
|
{
|
||||||
|
result = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int lseed;
|
||||||
|
int lmin;
|
||||||
|
int lmax;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] bytes = Base64UrlEncoder.DecodeBytes(s);
|
||||||
|
|
||||||
|
lseed = BitConverter.ToInt32(bytes.Take(4).ToArray(), 0);
|
||||||
|
lmin = BitConverter.ToInt32(bytes.Skip(4).Take(4).ToArray(), 0);
|
||||||
|
lmax = BitConverter.ToInt32(bytes.Skip(8).Take(4).ToArray(), 0);
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
result = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lmin > lmax)
|
||||||
|
{
|
||||||
|
result = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
result = new DeterministicRandom(lseed, lmin, lmax);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryParse([NotNullWhen(true)] string? s, [NotNullWhen(true)] out DeterministicRandom? result)
|
||||||
|
{
|
||||||
|
return TryParse(s, null, out result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Next()
|
||||||
|
{
|
||||||
|
return random.Next(min, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Next(int min, int max)
|
||||||
|
{
|
||||||
|
return random.Next(min, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string ToBase64()
|
||||||
|
{
|
||||||
|
byte[] bytes = new byte[12];
|
||||||
|
|
||||||
|
Array.Copy(BitConverter.GetBytes(seed), 0, bytes, 0, 4);
|
||||||
|
Array.Copy(BitConverter.GetBytes(min), 0, bytes, 4, 4);
|
||||||
|
Array.Copy(BitConverter.GetBytes(max), 0, bytes, 8, 4);
|
||||||
|
|
||||||
|
return Base64UrlEncoder.Encode(bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
public readonly struct Direction(int x, int y)
|
||||||
|
{
|
||||||
|
public static Direction Up => new Direction(0, -1);
|
||||||
|
public static Direction Down => new Direction(0, 1);
|
||||||
|
public static Direction Left => new Direction(-1, 0);
|
||||||
|
public static Direction Right => new Direction(1, 0);
|
||||||
|
public static Direction UpLeft => new Direction(-1, -1);
|
||||||
|
public static Direction UpRight => new Direction(1, -1);
|
||||||
|
public static Direction DownLeft => new Direction(-1, 1);
|
||||||
|
public static Direction DownRight => new Direction(1, 1);
|
||||||
|
public int X { get; } = x;
|
||||||
|
public int Y { get; } = y;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
public class PercentageProgress(int current, int total)
|
||||||
|
{
|
||||||
|
public int Current { get; set; } = current;
|
||||||
|
public int Total { get; set; } = total;
|
||||||
|
public int Percentage => (int)((double)Current / Total * 100);
|
||||||
|
public bool IsComplete => Current >= Total;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
namespace TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
public struct Position(int x, int y)
|
||||||
|
{
|
||||||
|
public int X { get; set; } = x;
|
||||||
|
public int Y { get; set; } = y;
|
||||||
|
|
||||||
|
public static Position operator +(Position a, Position b)
|
||||||
|
{
|
||||||
|
return new Position(a.X + b.X, a.Y + b.Y);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Position operator -(Position a, Position b)
|
||||||
|
{
|
||||||
|
return new Position(a.X - b.X, a.Y - b.Y);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Position operator +(Position a, Direction b)
|
||||||
|
{
|
||||||
|
return new Position(a.X + b.X, a.Y + b.Y);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Position operator -(Position a, Direction b)
|
||||||
|
{
|
||||||
|
return new Position(a.X - b.X, a.Y - b.Y);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace TextLore.Utilities.Models;
|
||||||
|
|
||||||
|
public readonly struct Size(int width, int height)
|
||||||
|
{
|
||||||
|
public int Width { get; } = width;
|
||||||
|
public int Height { get; } = height;
|
||||||
|
}
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
{
|
{
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Information",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"GamesDatabase": "Data Source=games.sqlite"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
Binary file not shown.
Binary file not shown.
@@ -29,14 +29,8 @@ app {
|
|||||||
overflow-y: hidden;
|
overflow-y: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
#console::before {
|
h1:focus {
|
||||||
position: absolute;
|
outline: none;
|
||||||
content: "";
|
|
||||||
height: 10%;
|
|
||||||
width: 100%;
|
|
||||||
bottom: 3rem;
|
|
||||||
left: 0;
|
|
||||||
background: linear-gradient(transparent 0%, black 100%);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.sidebar {
|
.sidebar {
|
||||||
@@ -139,5 +133,5 @@ app {
|
|||||||
}
|
}
|
||||||
|
|
||||||
::selection {
|
::selection {
|
||||||
background: #FF5E99;
|
background: #0dcaf0;
|
||||||
}
|
}
|
||||||
@@ -111,6 +111,16 @@
|
|||||||
color: inherit;
|
color: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#console::before {
|
||||||
|
position: absolute;
|
||||||
|
content: "";
|
||||||
|
height: 10%;
|
||||||
|
width: 100%;
|
||||||
|
bottom: 3rem;
|
||||||
|
left: 0;
|
||||||
|
background: linear-gradient(transparent 0%, black 100%);
|
||||||
|
}
|
||||||
|
|
||||||
.valid {
|
.valid {
|
||||||
outline-color: black !important;
|
outline-color: black !important;
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user