added global item config
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
using ActionBlocks.Game.Items;
|
||||
|
||||
namespace ActionBlocks.Game;
|
||||
|
||||
/// <summary>Tunable rules for a match. Change values here (or pass a custom instance) to alter gameplay.</summary>
|
||||
@@ -22,6 +24,12 @@ public sealed record GameSettings
|
||||
public double ItemSpawnChance { get; init; } = 0.1;
|
||||
public int MaxInventory { get; init; } = 10;
|
||||
|
||||
/// <summary>
|
||||
/// Per-item tuning by item id (e.g. "blind"). Items missing here keep weight 1 and their default duration.
|
||||
/// Usually filled from config/game.json; see <see cref="ItemRegistry.FromSettings"/>. Ids are case-insensitive.
|
||||
/// </summary>
|
||||
public Dictionary<string, ItemSettings> Items { get; init; } = new();
|
||||
|
||||
public double CountdownSeconds { get; init; } = 3;
|
||||
|
||||
/// <summary>Seconds per row for a level (marathon speed curve).</summary>
|
||||
@@ -30,4 +38,50 @@ public sealed record GameSettings
|
||||
var l = Math.Clamp(level, 1, MaxLevel);
|
||||
return Math.Pow(0.8 - (l - 1) * 0.007, l - 1);
|
||||
}
|
||||
|
||||
/// <summary>Problems with the item settings, as readable messages. Empty = valid.</summary>
|
||||
public IReadOnlyList<string> Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (double.IsNaN(ItemSpawnChance) || ItemSpawnChance is < 0 or > 1)
|
||||
{
|
||||
errors.Add($"ItemSpawnChance must be between 0 and 1 (is {ItemSpawnChance}).");
|
||||
}
|
||||
foreach (var (id, item) in Items)
|
||||
{
|
||||
var known = ItemRegistry.Default.Get(id);
|
||||
if (known is null)
|
||||
{
|
||||
var ids = string.Join(", ", ItemRegistry.Default.All.Select(i => i.Id));
|
||||
errors.Add($"Items.{id}: unknown item. Known items: {ids}.");
|
||||
continue;
|
||||
}
|
||||
if (item.Weight is { } weight && (double.IsNaN(weight) || weight < 0))
|
||||
{
|
||||
errors.Add($"Items.{id}.Weight must be 0 or more (is {weight}).");
|
||||
}
|
||||
if (item.DurationSeconds is { } duration)
|
||||
{
|
||||
if (known.DurationSeconds is null)
|
||||
{
|
||||
errors.Add($"Items.{id}: this item acts instantly and has no DurationSeconds.");
|
||||
}
|
||||
else if (double.IsNaN(duration) || duration <= 0)
|
||||
{
|
||||
errors.Add($"Items.{id}.DurationSeconds must be more than 0 (is {duration}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tuning for one item. Null = keep the default.</summary>
|
||||
public sealed record ItemSettings
|
||||
{
|
||||
/// <summary>Relative spawn weight: the item's share is weight / sum of all weights. 0 = never spawns.</summary>
|
||||
public double? Weight { get; init; }
|
||||
|
||||
/// <summary>Effect length for timed items (Blackout, Transformation).</summary>
|
||||
public double? DurationSeconds { get; init; }
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ namespace ActionBlocks.Game.Items;
|
||||
|
||||
/// <summary>
|
||||
/// An item that can be found inside pieces and used on a player.
|
||||
/// To add a new item: implement this interface and register it in <see cref="ItemRegistry"/>.
|
||||
/// To add a new item: implement this interface and add it to <see cref="ItemRegistry.FromSettings"/>.
|
||||
/// The frontend needs a matching icon entry for <see cref="Id"/>.
|
||||
/// </summary>
|
||||
public interface IItem
|
||||
@@ -13,8 +13,8 @@ public interface IItem
|
||||
/// <summary>Name shown when the item is used.</summary>
|
||||
string DisplayName { get; }
|
||||
|
||||
/// <summary>Relative chance of this item being picked when an item spawns.</summary>
|
||||
int SpawnWeight => 1;
|
||||
/// <summary>How long the effect lasts, or null for items that act instantly.</summary>
|
||||
double? DurationSeconds => null;
|
||||
|
||||
void Apply(ItemContext context);
|
||||
}
|
||||
|
||||
@@ -1,42 +1,80 @@
|
||||
namespace ActionBlocks.Game.Items;
|
||||
|
||||
/// <summary>All items that exist in the game. Register new items here.</summary>
|
||||
/// <summary>All items that exist in the game, each with its spawn weight. Register new items in <see cref="FromSettings"/>.</summary>
|
||||
public sealed class ItemRegistry
|
||||
{
|
||||
private readonly Dictionary<string, IItem> _items;
|
||||
private readonly Dictionary<string, (IItem Item, double Weight)> _items;
|
||||
private readonly double _totalWeight;
|
||||
|
||||
public ItemRegistry(IEnumerable<IItem> items)
|
||||
: this(items.Select(i => (i, 1.0)))
|
||||
{
|
||||
_items = items.ToDictionary(i => i.Id);
|
||||
}
|
||||
|
||||
public static ItemRegistry Default { get; } = new(
|
||||
[
|
||||
new AddGarbageLineItem(),
|
||||
new ClearBottomLineItem(),
|
||||
new ClearBoardItem(),
|
||||
new SwapBoardItem(),
|
||||
new InvisibilityItem(),
|
||||
new TransformationItem(),
|
||||
]);
|
||||
public ItemRegistry(IEnumerable<(IItem Item, double Weight)> items)
|
||||
{
|
||||
_items = items.ToDictionary(e => e.Item.Id, e => (e.Item, Math.Max(0, e.Weight)), StringComparer.OrdinalIgnoreCase);
|
||||
_totalWeight = _items.Values.Sum(e => e.Weight);
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<IItem> All => _items.Values;
|
||||
/// <summary>The built-in items with their default durations and equal weights.</summary>
|
||||
public static ItemRegistry Default { get; } = FromSettings(new GameSettings());
|
||||
|
||||
public IItem? Get(string id) => _items.GetValueOrDefault(id);
|
||||
/// <summary>
|
||||
/// The built-in items with durations and weights from <see cref="GameSettings.Items"/>.
|
||||
/// Items missing there keep weight 1 and their default duration.
|
||||
/// </summary>
|
||||
public static ItemRegistry FromSettings(GameSettings settings)
|
||||
{
|
||||
// Item ids in the config are case-insensitive, like all configuration keys.
|
||||
var config = new Dictionary<string, ItemSettings>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (id, item) in settings.Items)
|
||||
{
|
||||
config[id] = item;
|
||||
}
|
||||
double Duration(string id, double fallback) => config.GetValueOrDefault(id)?.DurationSeconds ?? fallback;
|
||||
|
||||
IItem[] items =
|
||||
[
|
||||
new AddGarbageLineItem(),
|
||||
new ClearBottomLineItem(),
|
||||
new ClearBoardItem(),
|
||||
new SwapBoardItem(),
|
||||
new InvisibilityItem(Duration(InvisibilityItem.ItemId, InvisibilityItem.DefaultDurationSeconds)),
|
||||
new TransformationItem(Duration(TransformationItem.ItemId, TransformationItem.DefaultDurationSeconds)),
|
||||
];
|
||||
return new(items.Select(i => (i, config.GetValueOrDefault(i.Id)?.Weight ?? 1)));
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<IItem> All => _items.Values.Select(e => e.Item).ToList();
|
||||
|
||||
/// <summary>False when every weight is 0, i.e. no item can spawn.</summary>
|
||||
public bool CanSpawn => _totalWeight > 0;
|
||||
|
||||
public IItem? Get(string id) => _items.TryGetValue(id, out var e) ? e.Item : null;
|
||||
|
||||
/// <summary>Fraction (0..1) of spawned items that are <paramref name="id"/>.</summary>
|
||||
public double Share(string id) =>
|
||||
_totalWeight > 0 && _items.TryGetValue(id, out var e) ? e.Weight / _totalWeight : 0;
|
||||
|
||||
public IItem PickRandom(Random random)
|
||||
{
|
||||
var total = _items.Values.Sum(i => i.SpawnWeight);
|
||||
var roll = random.Next(total);
|
||||
foreach (var item in _items.Values)
|
||||
var roll = random.NextDouble() * _totalWeight;
|
||||
IItem? last = null;
|
||||
foreach (var (item, weight) in _items.Values)
|
||||
{
|
||||
roll -= item.SpawnWeight;
|
||||
if (weight <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
last = item;
|
||||
roll -= weight;
|
||||
if (roll < 0)
|
||||
{
|
||||
return item;
|
||||
}
|
||||
}
|
||||
return _items.Values.First();
|
||||
return last ?? throw new InvalidOperationException("No item has a spawn weight above 0.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +85,7 @@ public sealed class ItemSpawner(ItemRegistry registry, double chance, Random ran
|
||||
|
||||
public Core.PieceSpec Decorate(Core.PieceType type)
|
||||
{
|
||||
if (registry.All.Count == 0)
|
||||
if (!registry.CanSpawn)
|
||||
{
|
||||
return new Core.PieceSpec(type);
|
||||
}
|
||||
|
||||
@@ -39,25 +39,29 @@ public sealed class SwapBoardItem : IItem
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class InvisibilityItem : IItem
|
||||
public sealed class InvisibilityItem(double durationSeconds = InvisibilityItem.DefaultDurationSeconds) : IItem
|
||||
{
|
||||
public const double DurationSeconds = 4;
|
||||
public const string ItemId = "blind";
|
||||
public const double DefaultDurationSeconds = 4;
|
||||
|
||||
public string Id => "blind";
|
||||
public string Id => ItemId;
|
||||
public string DisplayName => "Blackout";
|
||||
public double? DurationSeconds => durationSeconds;
|
||||
|
||||
// Stacks: a second Blackout adds its full duration to whatever is left.
|
||||
public void Apply(ItemContext context) =>
|
||||
context.Target.InvisibleUntil = Math.Max(context.Target.InvisibleUntil, context.Now) + DurationSeconds;
|
||||
context.Target.InvisibleUntil = Math.Max(context.Target.InvisibleUntil, context.Now) + durationSeconds;
|
||||
}
|
||||
|
||||
public sealed class TransformationItem : IItem
|
||||
public sealed class TransformationItem(double durationSeconds = TransformationItem.DefaultDurationSeconds) : IItem
|
||||
{
|
||||
public const double DurationSeconds = 8;
|
||||
public const string ItemId = "transform";
|
||||
public const double DefaultDurationSeconds = 8;
|
||||
|
||||
public string Id => "transform";
|
||||
public string Id => ItemId;
|
||||
public string DisplayName => "Transformation";
|
||||
public double? DurationSeconds => durationSeconds;
|
||||
|
||||
// Stacks like Blackout.
|
||||
public void Apply(ItemContext context) => context.Target.Transform(context.Now, DurationSeconds);
|
||||
public void Apply(ItemContext context) => context.Target.Transform(context.Now, durationSeconds);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using Microsoft.Extensions.Configuration.EnvironmentVariables;
|
||||
using Microsoft.Extensions.Configuration.Json;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
|
||||
namespace ActionBlocks.Server.Config;
|
||||
|
||||
/// <summary>
|
||||
/// Location of the game config file (config/game.json) and the last error from reading it.
|
||||
/// The file is added as a configuration source, so its "Game" section binds to <see cref="Game.GameSettings"/>.
|
||||
/// </summary>
|
||||
public sealed class GameConfigFile
|
||||
{
|
||||
private const string RelativePath = "config/game.json";
|
||||
|
||||
/// <summary>Full path of the file, or null when none was configured or found.</summary>
|
||||
public string? Path { get; private init; }
|
||||
|
||||
public bool Exists => Path is not null && File.Exists(Path);
|
||||
|
||||
/// <summary>Why the last read failed (e.g. a JSON syntax error), or null. Cleared by <see cref="TakeLoadError"/>.</summary>
|
||||
private string? _loadError;
|
||||
|
||||
public string? TakeLoadError() => Interlocked.Exchange(ref _loadError, null);
|
||||
|
||||
/// <summary>
|
||||
/// Adds the file as a reloading configuration source. <paramref name="configuredPath"/> comes from GAME_CONFIG;
|
||||
/// when empty, config/game.json is searched upwards from <paramref name="contentRoot"/> (finds the repo root in dev).
|
||||
/// </summary>
|
||||
public static GameConfigFile AddTo(IConfigurationBuilder configuration, string? configuredPath, string contentRoot)
|
||||
{
|
||||
var file = new GameConfigFile
|
||||
{
|
||||
Path = string.IsNullOrWhiteSpace(configuredPath)
|
||||
? FindUpwards(contentRoot)
|
||||
: System.IO.Path.GetFullPath(configuredPath, contentRoot),
|
||||
};
|
||||
if (file.Path is null)
|
||||
{
|
||||
return file;
|
||||
}
|
||||
var source = new JsonConfigurationSource
|
||||
{
|
||||
FileProvider = new PhysicalFileProvider(System.IO.Path.GetDirectoryName(file.Path)!),
|
||||
Path = System.IO.Path.GetFileName(file.Path),
|
||||
Optional = true,
|
||||
ReloadOnChange = true,
|
||||
// Don't crash on a broken edit; GameConfigProvider reports it and keeps the last good values.
|
||||
OnLoadException = context =>
|
||||
{
|
||||
file._loadError = context.Exception.InnerException?.Message ?? context.Exception.Message;
|
||||
context.Ignore = true;
|
||||
},
|
||||
};
|
||||
// Later sources win: insert before the environment variables so Game__* env vars still override the file.
|
||||
var envIndex = configuration.Sources.ToList().FindIndex(s => s is EnvironmentVariablesConfigurationSource);
|
||||
if (envIndex < 0)
|
||||
{
|
||||
configuration.Sources.Add(source);
|
||||
}
|
||||
else
|
||||
{
|
||||
configuration.Sources.Insert(envIndex, source);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static string? FindUpwards(string start)
|
||||
{
|
||||
for (var dir = new DirectoryInfo(start); dir is not null; dir = dir.Parent)
|
||||
{
|
||||
var candidate = System.IO.Path.Combine(dir.FullName, RelativePath);
|
||||
if (File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using ActionBlocks.Game;
|
||||
using ActionBlocks.Game.Items;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
|
||||
namespace ActionBlocks.Server.Config;
|
||||
|
||||
/// <summary>Settings and items for new matches. A match keeps the instance it started with.</summary>
|
||||
public sealed record GameConfig(GameSettings Settings, ItemRegistry Items);
|
||||
|
||||
/// <summary>
|
||||
/// Binds the "Game" configuration section and follows changes to config/game.json.
|
||||
/// An invalid config at startup stops the server; an invalid edit later is logged and the last good config stays.
|
||||
/// </summary>
|
||||
public sealed class GameConfigProvider : IDisposable
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly GameConfigFile _file;
|
||||
private readonly ILogger<GameConfigProvider> _logger;
|
||||
private readonly IDisposable _subscription;
|
||||
private volatile GameConfig _current;
|
||||
|
||||
public GameConfigProvider(IConfiguration configuration, GameConfigFile file, ILogger<GameConfigProvider> logger)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_file = file;
|
||||
_logger = logger;
|
||||
|
||||
var (config, errors) = Load();
|
||||
if (config is null)
|
||||
{
|
||||
throw new InvalidOperationException($"Invalid game config ({file.Path ?? "no file"}):\n {string.Join("\n ", errors)}");
|
||||
}
|
||||
_current = config;
|
||||
if (file.Path is null)
|
||||
{
|
||||
_logger.LogInformation("No {File} found, using built-in game settings", "config/game.json");
|
||||
}
|
||||
LogValues("Game config loaded", config);
|
||||
_subscription = ChangeToken.OnChange(configuration.GetReloadToken, Reload);
|
||||
}
|
||||
|
||||
public GameConfig Current => _current;
|
||||
|
||||
private void Reload()
|
||||
{
|
||||
if (_file.Path is not null && !_file.Exists)
|
||||
{
|
||||
_logger.LogWarning("Game config {Path} is missing, keeping the previous values", _file.Path);
|
||||
return;
|
||||
}
|
||||
var (config, errors) = Load();
|
||||
if (config is null)
|
||||
{
|
||||
_logger.LogError(
|
||||
"Game config change ignored, keeping the previous values:\n {Errors}", string.Join("\n ", errors));
|
||||
return;
|
||||
}
|
||||
_current = config;
|
||||
LogValues("Game config reloaded, used from the next match", config);
|
||||
}
|
||||
|
||||
private (GameConfig? Config, IReadOnlyList<string> Errors) Load()
|
||||
{
|
||||
if (_file.TakeLoadError() is { } loadError)
|
||||
{
|
||||
return (null, [loadError]);
|
||||
}
|
||||
GameSettings settings;
|
||||
try
|
||||
{
|
||||
settings = _configuration.GetSection("Game").Get<GameSettings>() ?? new GameSettings();
|
||||
}
|
||||
catch (InvalidOperationException e)
|
||||
{
|
||||
// A value of the wrong type, e.g. "Weight": "high".
|
||||
return (null, [e.InnerException?.Message ?? e.Message]);
|
||||
}
|
||||
var errors = settings.Validate();
|
||||
return errors.Count > 0 ? (null, errors) : (new GameConfig(settings, ItemRegistry.FromSettings(settings)), errors);
|
||||
}
|
||||
|
||||
private void LogValues(string message, GameConfig config)
|
||||
{
|
||||
var items = config.Items.All.Select(i =>
|
||||
$"{i.Id} {config.Items.Share(i.Id):P0}" + (i.DurationSeconds is { } d ? $" {d}s" : ""));
|
||||
_logger.LogInformation(
|
||||
"{Message}: item chance {Chance} per block; {Items}",
|
||||
message,
|
||||
config.Settings.ItemSpawnChance,
|
||||
string.Join(", ", items));
|
||||
}
|
||||
|
||||
public void Dispose() => _subscription.Dispose();
|
||||
}
|
||||
@@ -60,4 +60,6 @@ public sealed record MatchStateDto(
|
||||
IReadOnlyList<PlayerStateDto> Players,
|
||||
IReadOnlyList<MatchEventDto> Events);
|
||||
|
||||
public sealed record ItemInfoDto(string Id, string Name);
|
||||
/// <param name="Share">Fraction (0..1) of spawned items that are this item; 0 = disabled.</param>
|
||||
/// <param name="DurationSeconds">Effect length for timed items, null for instant ones.</param>
|
||||
public sealed record ItemInfoDto(string Id, string Name, double Share, double? DurationSeconds);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using ActionBlocks.Game;
|
||||
using ActionBlocks.Server.Config;
|
||||
using ActionBlocks.Server.Dtos;
|
||||
using ActionBlocks.Server.Lobbies;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
@@ -8,7 +9,7 @@ namespace ActionBlocks.Server.Hubs;
|
||||
/// <summary>
|
||||
/// Client-facing API. Server-to-client messages: "LobbyUpdated" (LobbyDto) and "MatchState" (MatchStateDto).
|
||||
/// </summary>
|
||||
public sealed class GameHub(LobbyManager lobbies, GameSettings settings) : Hub
|
||||
public sealed class GameHub(LobbyManager lobbies, GameConfigProvider config) : Hub
|
||||
{
|
||||
public const string LobbyUpdated = "LobbyUpdated";
|
||||
public const string MatchState = "MatchState";
|
||||
@@ -51,7 +52,7 @@ public sealed class GameHub(LobbyManager lobbies, GameSettings settings) : Hub
|
||||
{
|
||||
throw new HubException("A game is already running.");
|
||||
}
|
||||
lobby.StartMatch(settings);
|
||||
lobby.StartMatch(config.Current.Settings, config.Current.Items);
|
||||
dto = lobby.ToDto();
|
||||
}
|
||||
await Clients.Group(lobby.Code).SendAsync(LobbyUpdated, dto);
|
||||
@@ -67,8 +68,12 @@ public sealed class GameHub(LobbyManager lobbies, GameSettings settings) : Hub
|
||||
public void SelectTarget(string targetId) =>
|
||||
WithPlayer((lobby, player) => lobby.Match?.SelectTarget(player.Id, targetId));
|
||||
|
||||
public IReadOnlyList<ItemInfoDto> GetItems() =>
|
||||
Game.Items.ItemRegistry.Default.All.Select(i => new ItemInfoDto(i.Id, i.DisplayName)).ToList();
|
||||
/// <summary>Items of the current config with their spawn share and duration (used by the lobby help panel).</summary>
|
||||
public IReadOnlyList<ItemInfoDto> GetItems()
|
||||
{
|
||||
var items = config.Current.Items;
|
||||
return items.All.Select(i => new ItemInfoDto(i.Id, i.DisplayName, items.Share(i.Id), i.DurationSeconds)).ToList();
|
||||
}
|
||||
|
||||
public override async Task OnDisconnectedAsync(Exception? exception)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using ActionBlocks.Game;
|
||||
using ActionBlocks.Game.Items;
|
||||
using ActionBlocks.Server.Dtos;
|
||||
|
||||
namespace ActionBlocks.Server.Lobbies;
|
||||
@@ -48,9 +49,9 @@ public sealed class Lobby(string code)
|
||||
}
|
||||
}
|
||||
|
||||
public void StartMatch(GameSettings settings)
|
||||
public void StartMatch(GameSettings settings, ItemRegistry items)
|
||||
{
|
||||
Match = new Match(_players.Select(p => new MatchPlayer(p.Id, p.Name)), settings);
|
||||
Match = new Match(_players.Select(p => new MatchPlayer(p.Id, p.Name)), settings, items);
|
||||
MatchFinishedAt = null;
|
||||
Dirty = true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using ActionBlocks.Game;
|
||||
using ActionBlocks.Server.Config;
|
||||
using ActionBlocks.Server.Hubs;
|
||||
using ActionBlocks.Server.Lobbies;
|
||||
|
||||
@@ -31,13 +31,19 @@ builder.Services
|
||||
.AddSignalR()
|
||||
.AddJsonProtocol(o => o.PayloadSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
|
||||
|
||||
// Rules can be tuned via configuration, e.g. env Game__ItemSpawnChance=0.2
|
||||
builder.Services.AddSingleton(builder.Configuration.GetSection("Game").Get<GameSettings>() ?? new GameSettings());
|
||||
// Rules come from the "Game" section: config/game.json (path in GAME_CONFIG, reloaded for each new match),
|
||||
// overridable by env vars such as Game__ItemSpawnChance=0.2.
|
||||
builder.Services.AddSingleton(
|
||||
GameConfigFile.AddTo(builder.Configuration, builder.Configuration["GAME_CONFIG"], builder.Environment.ContentRootPath));
|
||||
builder.Services.AddSingleton<GameConfigProvider>();
|
||||
builder.Services.AddSingleton<LobbyManager>();
|
||||
builder.Services.AddHostedService<MatchRunner>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Read the game config now, so an invalid file stops the server at startup instead of at the first match.
|
||||
app.Services.GetRequiredService<GameConfigProvider>();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(pathBase))
|
||||
{
|
||||
app.UsePathBase(pathBase);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
using ActionBlocks.Game.Core;
|
||||
using ActionBlocks.Game.Items;
|
||||
using static ActionBlocks.Game.Tests.TestHelpers;
|
||||
|
||||
namespace ActionBlocks.Game.Tests;
|
||||
|
||||
public class ConfigTests
|
||||
{
|
||||
private static GameSettings WithItems(params (string Id, ItemSettings Item)[] items) =>
|
||||
new() { Items = items.ToDictionary(i => i.Id, i => i.Item, StringComparer.OrdinalIgnoreCase) };
|
||||
|
||||
private static ItemContext Context(PlayerGame target, double now) => new(target, target, new Random(3), now);
|
||||
|
||||
[Fact]
|
||||
public void Empty_settings_keep_the_built_in_defaults()
|
||||
{
|
||||
var registry = ItemRegistry.FromSettings(new GameSettings());
|
||||
|
||||
Assert.Equal(6, registry.All.Count);
|
||||
Assert.All(registry.All, i => Assert.Equal(1.0 / 6, registry.Share(i.Id), 6));
|
||||
Assert.Equal(4, registry.Get("blind")!.DurationSeconds);
|
||||
Assert.Equal(8, registry.Get("transform")!.DurationSeconds);
|
||||
Assert.Null(registry.Get("nuke")!.DurationSeconds);
|
||||
Assert.Empty(new GameSettings().Validate());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configured_durations_change_the_effect_length()
|
||||
{
|
||||
var registry = ItemRegistry.FromSettings(WithItems(
|
||||
("blind", new ItemSettings { DurationSeconds = 2 }),
|
||||
("transform", new ItemSettings { DurationSeconds = 3 })));
|
||||
var target = CreatePlayer("b");
|
||||
target.Start();
|
||||
|
||||
registry.Get("blind")!.Apply(Context(target, 10));
|
||||
registry.Get("transform")!.Apply(Context(target, 10));
|
||||
|
||||
target.Update(0.01, 11.9);
|
||||
Assert.True(target.IsInvisible);
|
||||
target.Update(0.01, 12.1);
|
||||
Assert.False(target.IsInvisible);
|
||||
Assert.True(target.IsTransformed);
|
||||
target.Update(0.01, 13.1);
|
||||
Assert.False(target.IsTransformed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_items_with_weight_spawn()
|
||||
{
|
||||
var settings = WithItems(
|
||||
("add_line", new ItemSettings { Weight = 0 }),
|
||||
("clear_line", new ItemSettings { Weight = 0 }),
|
||||
("nuke", new ItemSettings { Weight = 0 }),
|
||||
("swap", new ItemSettings { Weight = 0 }),
|
||||
("transform", new ItemSettings { Weight = 0 }));
|
||||
var spawner = new ItemSpawner(ItemRegistry.FromSettings(settings), 1, new Random(1));
|
||||
|
||||
var items = Enumerable.Range(0, 50).SelectMany(_ => spawner.Decorate(PieceType.T).Items!).ToHashSet();
|
||||
|
||||
Assert.Equal(["blind"], items);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Weights_split_the_item_chance()
|
||||
{
|
||||
var settings = WithItems(
|
||||
("add_line", new ItemSettings { Weight = 3 }),
|
||||
("nuke", new ItemSettings { Weight = 1 }),
|
||||
("clear_line", new ItemSettings { Weight = 0 }),
|
||||
("swap", new ItemSettings { Weight = 0 }),
|
||||
("blind", new ItemSettings { Weight = 0 }),
|
||||
("transform", new ItemSettings { Weight = 0 }));
|
||||
var registry = ItemRegistry.FromSettings(settings);
|
||||
var random = new Random(7);
|
||||
|
||||
var picks = Enumerable.Range(0, 4000).Select(_ => registry.PickRandom(random).Id).ToList();
|
||||
|
||||
Assert.Equal(0.75, registry.Share("add_line"));
|
||||
Assert.Equal(0.25, registry.Share("nuke"));
|
||||
Assert.InRange(picks.Count(p => p == "add_line") / 4000.0, 0.72, 0.78);
|
||||
Assert.Equal(4000, picks.Count(p => p is "add_line" or "nuke"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void All_weights_zero_means_no_items()
|
||||
{
|
||||
var settings = new GameSettings
|
||||
{
|
||||
Items = ItemRegistry.Default.All.ToDictionary(i => i.Id, _ => new ItemSettings { Weight = 0 }),
|
||||
};
|
||||
var spawner = new ItemSpawner(ItemRegistry.FromSettings(settings), 1, new Random(1));
|
||||
|
||||
Assert.Empty(settings.Validate());
|
||||
Assert.False(spawner.Decorate(PieceType.T).HasItem);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Item_ids_are_case_insensitive()
|
||||
{
|
||||
var settings = new GameSettings { Items = new() { ["Blind"] = new ItemSettings { DurationSeconds = 2 } } };
|
||||
|
||||
Assert.Empty(settings.Validate());
|
||||
Assert.Equal(2, ItemRegistry.FromSettings(settings).Get("blind")!.DurationSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_items_keep_weight_one()
|
||||
{
|
||||
var registry = ItemRegistry.FromSettings(WithItems(("nuke", new ItemSettings { Weight = 5 })));
|
||||
|
||||
Assert.Equal(0.5, registry.Share("nuke"));
|
||||
Assert.Equal(0.1, registry.Share("blind"), 6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_reports_every_problem()
|
||||
{
|
||||
var settings = WithItems(
|
||||
("add_line", new ItemSettings { Weight = -1 }),
|
||||
("blind", new ItemSettings { DurationSeconds = 0 }),
|
||||
("nuke", new ItemSettings { DurationSeconds = 5 }),
|
||||
("laser", new ItemSettings { Weight = 1 })) with { ItemSpawnChance = 1.5 };
|
||||
|
||||
var errors = settings.Validate();
|
||||
|
||||
Assert.Equal(5, errors.Count);
|
||||
Assert.Contains(errors, e => e.StartsWith("ItemSpawnChance"));
|
||||
Assert.Contains(errors, e => e.StartsWith("Items.add_line.Weight"));
|
||||
Assert.Contains(errors, e => e.StartsWith("Items.blind.DurationSeconds"));
|
||||
Assert.Contains(errors, e => e.StartsWith("Items.nuke: this item acts instantly"));
|
||||
Assert.Contains(errors, e => e.StartsWith("Items.laser: unknown item"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user