Compare commits

..
2 Commits
Author SHA1 Message Date
marvin 9178202c57 added global item config 2026-10-25 22:31:22 +01:00
marvin 6184cdba0a added transformation item 2026-10-25 22:08:09 +01:00
45 changed files with 937 additions and 133 deletions
+4 -7
View File
@@ -11,10 +11,7 @@ PATH_BASE=
# Comma separated origins allowed to connect to the hub. Empty = allow any origin.
ALLOWED_ORIGINS=https://game.example.com
# Chance (0..1) that each block of a new piece carries an item. Every block rolls on its
# own, so one piece can carry several items. 0 = no items, 1 = every block has one.
ITEM_SPAWN_CHANCE=0.1
# Other optional gameplay tuning, passed to the server as Game__<Setting> (see GameSettings.cs).
# Add these under the server's "environment:" in docker-compose.yml to use them.
# Game__CountdownSeconds=3
# Gameplay tuning (item chance, how items split it up, item durations, other rules) lives in
# config/game.json, which the server container mounts. Edits apply from the next match on.
# Single values can still be overridden as Game__<Setting> env vars under the server's
# "environment:" in docker-compose.yml, e.g. Game__CountdownSeconds=3.
+4 -2
View File
@@ -53,8 +53,10 @@ The reverse proxy (attached to both networks) should route:
| `ALLOWED_ORIGINS` | server | Comma-separated CORS origins. Empty allows any origin. |
| `HUB_PATH` | server | Hub endpoint path (default `/hub`). |
| `PATH_BASE` | server | Prefix to accept when the proxy forwards a sub-path unstripped, e.g. `/server`. |
| `ITEM_SPAWN_CHANCE` | server | Chance (0..1) that each block of a new piece carries an item. Default `0.1`. Passed as `Game__ItemSpawnChance`. |
| `Game__*` | server | Overrides any `GameSettings` value, e.g. `Game__ItemSpawnChance=0.2`. |
| `GAME_CONFIG` | server | Path of the gameplay config file. Set to `/app/config/game.json` in the compose file, which mounts `./config`. |
| `Game__*` | server | Overrides any `GameSettings` value from the config file, e.g. `Game__ItemSpawnChance=0.2`. |
Gameplay tuning lives in **`config/game.json`**: the item chance per block, each item's weight (its share of that chance) and the duration of the timed items. The server picks up edits for the next match without a restart. See [Deployment](doc/deployment.md#game-config).
## Extending
@@ -3,10 +3,31 @@ namespace ActionBlocks.Game.Core;
/// <summary>
/// A piece definition as it travels through the queue: its shape plus optional items
/// hidden inside its minos. <see cref="Items"/>[i] is the item in mino i (null = none).
/// <see cref="Original"/> is set on a transformed piece and holds the piece it was before.
/// </summary>
public sealed record PieceSpec(PieceType Type, IReadOnlyList<string?>? Items = null)
public sealed record PieceSpec(PieceType Type, IReadOnlyList<string?>? Items = null, PieceSpec? Original = null)
{
public bool HasItem => Items?.Any(i => i is not null) == true;
/// <summary>The same piece as <paramref name="type"/>. Items move to the new minos in order; extras are dropped.</summary>
public PieceSpec Transform(PieceType type)
{
var original = Original ?? this;
var carried = original.Items?.Where(i => i is not null).ToList() ?? [];
string?[]? items = null;
if (carried.Count > 0)
{
items = new string?[PieceDefinitions.Minos(type, 0).Count];
for (var i = 0; i < Math.Min(items.Length, carried.Count); i++)
{
items[i] = carried[i];
}
}
return new PieceSpec(type, items, original);
}
/// <summary>Undoes <see cref="Transform"/>.</summary>
public PieceSpec Restore() => Original ?? this;
}
/// <summary>A piece placed somewhere on the board (position = top-left corner of its bounding box).</summary>
@@ -18,12 +18,23 @@ public static class PieceDefinitions
[PieceType.S] = (3, [new(1, 0), new(2, 0), new(0, 1), new(1, 1)]),
[PieceType.Z] = (3, [new(0, 0), new(1, 0), new(1, 1), new(2, 1)]),
[PieceType.T] = (3, [new(1, 0), new(0, 1), new(1, 1), new(2, 1)]),
[PieceType.Dot] = (1, [new(0, 0)]),
[PieceType.SmallL] = (2, [new(0, 0), new(0, 1), new(1, 1)]),
[PieceType.U] = (3, [new(0, 0), new(2, 0), new(0, 1), new(1, 1), new(2, 1)]),
[PieceType.Plus] = (3, [new(1, 0), new(0, 1), new(1, 1), new(2, 1), new(1, 2)]),
[PieceType.W] = (3, [new(0, 0), new(0, 1), new(1, 1), new(1, 2), new(2, 2)]),
};
private static readonly Dictionary<PieceType, Point[][]> Rotations = BuildRotations();
public static IReadOnlyList<PieceType> All { get; } = Enum.GetValues<PieceType>();
/// <summary>The seven four-cell shapes dealt by the randomizer.</summary>
public static IReadOnlyList<PieceType> Standard { get; } = All.Where(t => t <= PieceType.T).ToArray();
/// <summary>Oddball shapes that only appear while a player is transformed.</summary>
public static IReadOnlyList<PieceType> Odd { get; } = All.Where(t => t > PieceType.T).ToArray();
public static int BoxSize(PieceType type) => SpawnShapes[type].BoxSize;
/// <summary>Mino offsets of a piece in the given rotation state (0 = spawn, 1 = R, 2 = 180, 3 = L).</summary>
@@ -1,6 +1,9 @@
namespace ActionBlocks.Game.Core;
/// <summary>The seven four-cell piece shapes. Numeric values double as cell colors (1-7).</summary>
/// <summary>
/// Piece shapes. Numeric values double as cell colors: 1-7 are the seven four-cell shapes,
/// 9-13 the odd shapes dealt only during a Transformation (8 is garbage).
/// </summary>
public enum PieceType : byte
{
I = 1,
@@ -10,6 +13,11 @@ public enum PieceType : byte
S = 5,
Z = 6,
T = 7,
Dot = 9,
SmallL = 10,
U = 11,
Plus = 12,
W = 13,
}
public static class CellColor
@@ -14,7 +14,7 @@ public sealed class SevenBagRandomizer(Random random) : IRandomizer
{
if (_bag.Count == 0)
{
var pieces = PieceDefinitions.All.ToArray();
var pieces = PieceDefinitions.Standard.ToArray();
random.Shuffle(pieces);
foreach (var p in pieces)
{
@@ -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,60 +1,97 @@
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(
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);
}
/// <summary>The built-in items with their default durations and equal weights.</summary>
public static ItemRegistry Default { get; } = FromSettings(new GameSettings());
/// <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(),
]);
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;
public IReadOnlyCollection<IItem> All => _items.Values.Select(e => e.Item).ToList();
public IItem? Get(string id) => _items.GetValueOrDefault(id);
/// <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.");
}
}
/// <summary>Decides which minos of a new piece carry an item. Each mino rolls <c>chance</c> (0..1) on its own.</summary>
public sealed class ItemSpawner(ItemRegistry registry, double chance, Random random)
{
private const int MinosPerPiece = 4;
private readonly double _chance = double.IsNaN(chance) ? 0 : Math.Clamp(chance, 0, 1);
public Core.PieceSpec Decorate(Core.PieceType type)
{
if (registry.All.Count == 0)
if (!registry.CanSpawn)
{
return new Core.PieceSpec(type);
}
var items = new string?[MinosPerPiece];
var items = new string?[Core.PieceDefinitions.Minos(type, 0).Count];
var any = false;
for (var i = 0; i < MinosPerPiece; i++)
for (var i = 0; i < items.Length; i++)
{
if (random.NextDouble() < _chance)
{
@@ -39,14 +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(double durationSeconds = TransformationItem.DefaultDurationSeconds) : IItem
{
public const string ItemId = "transform";
public const double DefaultDurationSeconds = 8;
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);
}
@@ -92,6 +92,10 @@ public sealed class PlayerGame
public double InvisibleUntil { get; set; }
public bool IsInvisible => Now < InvisibleUntil;
/// <summary>Match time until which this player's upcoming pieces are odd shapes.</summary>
public double TransformedUntil { get; private set; }
public bool IsTransformed => Now < TransformedUntil;
/// <summary>The player selected as item target (own id = self).</summary>
public string TargetId { get; set; }
@@ -103,7 +107,12 @@ public sealed class PlayerGame
public void Update(double deltaSeconds, double now)
{
var wasTransformed = IsTransformed;
Now = now;
if (wasTransformed && !IsTransformed)
{
RestoreTransformedPieces();
}
if (!IsAlive || Active is null)
{
return;
@@ -280,11 +289,40 @@ public sealed class PlayerGame
public void Forfeit() => TopOut();
/// <summary>
/// Turns the queue into odd shapes for <paramref name="seconds"/> (added to any time left).
/// The falling piece stays as it is; pieces still queued or held change back when the time runs out.
/// </summary>
public void Transform(double now, double seconds)
{
TransformedUntil = Math.Max(TransformedUntil, now) + seconds;
for (var i = 0; i < _next.Count; i++)
{
if (_next[i].Original is null)
{
_next[i] = TransformRandomly(_next[i]);
}
}
}
private PieceSpec TransformRandomly(PieceSpec spec) =>
spec.Transform(PieceDefinitions.Odd[_random.Next(PieceDefinitions.Odd.Count)]);
private void RestoreTransformedPieces()
{
for (var i = 0; i < _next.Count; i++)
{
_next[i] = _next[i].Restore();
}
Hold = Hold?.Restore();
}
private void FillQueue()
{
while (_next.Count < Math.Max(1, _settings.PreviewCount))
{
_next.Add(_itemSpawner.Decorate(_randomizer.Next()));
var spec = _itemSpawner.Decorate(_randomizer.Next());
_next.Add(IsTransformed ? TransformRandomly(spec) : spec);
}
}
@@ -402,7 +440,8 @@ public sealed class PlayerGame
{
return;
}
var current = Active.Spec;
// A piece left over from an expired Transformation changes back once it is put away.
var current = IsTransformed ? Active.Spec : Active.Spec.Restore();
HoldUsed = true;
if (Hold is null)
{
@@ -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();
}
@@ -39,7 +39,8 @@ public sealed record PlayerStateDto(
int Lines,
int Level,
int PendingGarbage,
double InvisibleRemaining);
double InvisibleRemaining,
double TransformedRemaining);
/// <summary>A match event. <see cref="Type"/> is "itemUsed" or "eliminated".</summary>
public sealed record MatchEventDto(
@@ -59,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);
@@ -51,7 +51,8 @@ public static class SnapshotMapper
player.Lines,
player.Level,
player.PendingGarbage,
Math.Round(Math.Max(0, player.InvisibleUntil - match.Now), 2));
Math.Round(Math.Max(0, player.InvisibleUntil - match.Now), 2),
Math.Round(Math.Max(0, player.TransformedUntil - match.Now), 2));
}
private static ActivePieceDto ToDto(ActivePiece piece, Board board) =>
@@ -62,7 +63,7 @@ public static class SnapshotMapper
private static PieceDto ToDto(PieceSpec spec) => new((int)spec.Type, ToItems(spec));
private static string?[] ToItems(PieceSpec spec) => spec.Items?.ToArray() ?? new string?[4];
private static string?[] ToItems(PieceSpec spec) => spec.Items?.ToArray() ?? new string?[PieceDefinitions.Minos(spec.Type, 0).Count];
private static MatchEventDto ToDto(MatchEvent e) => e switch
{
@@ -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"));
}
}
@@ -28,6 +28,24 @@ public class CoreTests
}
}
[Fact]
public void Rotations_keep_the_mino_count()
{
foreach (var type in PieceDefinitions.All)
{
var count = PieceDefinitions.Minos(type, 0).Count;
Assert.All(Enumerable.Range(1, 3), r => Assert.Equal(count, PieceDefinitions.Minos(type, r).Distinct().Count()));
}
}
[Fact]
public void Seven_bag_never_deals_odd_shapes()
{
var randomizer = new SevenBagRandomizer(new Random(42));
Assert.All(Enumerable.Range(0, 70), _ => Assert.Contains(randomizer.Next(), PieceDefinitions.Standard));
}
[Fact]
public void Seven_bag_deals_every_shape_once_per_bag()
{
@@ -121,9 +121,96 @@ public class ItemTests
}
[Fact]
public void Registry_contains_five_unique_items()
public void Transformation_turns_the_queue_into_odd_shapes_but_not_the_falling_piece()
{
Assert.Equal(5, ItemRegistry.Default.All.Select(i => i.Id).Distinct().Count());
var target = CreatePlayer("b", pieces: [PieceType.T, PieceType.O, PieceType.S]);
target.Start();
new TransformationItem().Apply(Context(target, target, now: 10));
Assert.Equal(PieceType.T, target.Active!.Type);
Assert.All(target.Next, p => Assert.Contains(p.Type, PieceDefinitions.Odd));
}
[Fact]
public void Transformation_deals_odd_shapes_while_active()
{
var target = CreatePlayer("b");
target.Start();
new TransformationItem().Apply(Context(target, target));
for (var i = 0; i < 8; i++)
{
target.HandleInput(InputAction.HardDrop);
}
Assert.True(target.IsAlive);
Assert.Contains(target.Active!.Type, PieceDefinitions.Odd);
Assert.All(target.Next, p => Assert.Contains(p.Type, PieceDefinitions.Odd));
}
[Fact]
public void Transformation_expiry_restores_queue_and_hold()
{
var target = CreatePlayer("b", pieces: [PieceType.T, PieceType.O, PieceType.S]);
target.Start();
var queued = target.Next.Select(p => p.Type).ToList();
new TransformationItem().Apply(Context(target, target));
target.HandleInput(InputAction.HardDrop);
target.HandleInput(InputAction.Hold);
Assert.Contains(target.Hold!.Type, PieceDefinitions.Odd);
target.Update(0.01, 7.9);
Assert.True(target.IsTransformed);
target.Update(0.01, 8.1);
Assert.False(target.IsTransformed);
Assert.Equal(queued[0], target.Hold!.Type);
Assert.All(target.Next, p => Assert.Contains(p.Type, PieceDefinitions.Standard));
}
[Fact]
public void Transformation_durations_stack()
{
var target = CreatePlayer("b");
target.Start();
new TransformationItem().Apply(Context(target, target, now: 10));
new TransformationItem().Apply(Context(target, target, now: 12));
target.Update(0.01, 25.9);
Assert.True(target.IsTransformed);
target.Update(0.01, 26.1);
Assert.False(target.IsTransformed);
}
[Fact]
public void Transformed_piece_keeps_its_items_and_restores_them()
{
var spec = new PieceSpec(PieceType.T, [null, "nuke", null, "swap"]);
var plus = spec.Transform(PieceType.Plus);
var dot = plus.Transform(PieceType.Dot);
Assert.Equal(["nuke", "swap", null, null, null], plus.Items);
Assert.Equal(["nuke"], dot.Items);
Assert.Same(spec, dot.Restore());
}
[Fact]
public void Registry_contains_six_unique_items()
{
Assert.Equal(6, ItemRegistry.Default.All.Select(i => i.Id).Distinct().Count());
}
[Fact]
public void Spawner_sizes_items_to_the_shape()
{
var spawner = new ItemSpawner(ItemRegistry.Default, 1, new Random(1));
Assert.Equal(5, spawner.Decorate(PieceType.Plus).Items!.Count);
Assert.Single(spawner.Decorate(PieceType.Dot).Items!);
}
[Theory]
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="64" height="64" shape-rendering="crispEdges"><rect width="8" height="8" fill="#000000"/><rect x="3" y="1" width="1" height="1" fill="#ff6fd8"/><rect x="4" y="1" width="1" height="1" fill="#ff6fd8"/><rect x="3" y="2" width="1" height="1" fill="#ff6fd8"/><rect x="4" y="2" width="1" height="1" fill="#ff6fd8"/><rect x="1" y="3" width="1" height="1" fill="#ff6fd8"/><rect x="2" y="3" width="1" height="1" fill="#ff6fd8"/><rect x="3" y="3" width="1" height="1" fill="#ff6fd8"/><rect x="4" y="3" width="1" height="1" fill="#ff6fd8"/><rect x="5" y="3" width="1" height="1" fill="#ff6fd8"/><rect x="6" y="3" width="1" height="1" fill="#ff6fd8"/><rect x="1" y="4" width="1" height="1" fill="#ff6fd8"/><rect x="2" y="4" width="1" height="1" fill="#ff6fd8"/><rect x="3" y="4" width="1" height="1" fill="#ff6fd8"/><rect x="4" y="4" width="1" height="1" fill="#ff6fd8"/><rect x="5" y="4" width="1" height="1" fill="#ff6fd8"/><rect x="6" y="4" width="1" height="1" fill="#ff6fd8"/><rect x="3" y="5" width="1" height="1" fill="#ff6fd8"/><rect x="4" y="5" width="1" height="1" fill="#ff6fd8"/><rect x="3" y="6" width="1" height="1" fill="#ff6fd8"/><rect x="4" y="6" width="1" height="1" fill="#ff6fd8"/><rect x="0" y="0" width="1" height="1" fill="#ffffff"/><rect x="7" y="0" width="1" height="1" fill="#ffffff"/><rect x="0" y="7" width="1" height="1" fill="#ffffff"/><rect x="7" y="7" width="1" height="1" fill="#ffffff"/><rect x="1" y="1" width="1" height="1" fill="#ffffff"/><rect x="6" y="6" width="1" height="1" fill="#ffffff"/></svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

@@ -1,18 +0,0 @@
import { itemVisual } from '../theme/assets';
import styles from './BlackoutTimer.module.css';
/** Seconds left on a player's blackout, in the corner of their board. */
export function BlackoutTimer({ remaining, small = false }: { remaining: number; small?: boolean }) {
if (remaining <= 0) return null;
const visual = itemVisual('blind');
return (
<div
className={[styles.timer, small ? styles.small : '', remaining < 1 ? styles.ending : ''].join(' ')}
style={{ color: visual.color, borderColor: visual.color }}
title={visual.name}
>
<img className={styles.icon} src={visual.icon} alt="" />
{remaining.toFixed(1)}s
</div>
);
}
@@ -1,7 +1,16 @@
.timer {
.timers {
position: absolute;
top: 4px;
right: 4px;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
pointer-events: none;
z-index: 2;
}
.timer {
display: flex;
align-items: center;
gap: 6px;
@@ -10,8 +19,6 @@
background: #000;
font-size: 12px;
line-height: 1;
pointer-events: none;
z-index: 2;
}
.icon {
@@ -23,6 +30,10 @@
.small {
top: 2px;
right: 2px;
gap: 2px;
}
.small .timer {
gap: 3px;
padding: 2px 3px;
border-width: 2px;
@@ -34,7 +45,7 @@
height: 8px;
}
/* Blink during the last second so the return of the board isn't a surprise. */
/* Blink during the last second so the end of the effect isn't a surprise. */
.ending {
animation: blink 0.25s steps(2) infinite;
}
@@ -0,0 +1,29 @@
import { itemVisual } from '../theme/assets';
import styles from './EffectTimers.module.css';
/** A timed item effect on a player: the item id and the seconds it has left. */
export type Effect = [itemId: string, remaining: number];
/** Seconds left on a player's timed item effects (Blackout, Transformation), in the corner of their board. */
export function EffectTimers({ effects, small = false }: { effects: Effect[]; small?: boolean }) {
const active = effects.filter(([, remaining]) => remaining > 0);
if (active.length === 0) return null;
return (
<div className={[styles.timers, small ? styles.small : ''].join(' ')}>
{active.map(([itemId, remaining]) => {
const visual = itemVisual(itemId);
return (
<div
key={itemId}
className={[styles.timer, remaining < 1 ? styles.ending : ''].join(' ')}
style={{ color: visual.color, borderColor: visual.color }}
title={visual.name}
>
<img className={styles.icon} src={visual.icon} alt="" />
{remaining.toFixed(1)}s
</div>
);
})}
</div>
);
}
@@ -1,7 +1,7 @@
import { memo } from 'react';
import type { PlayerState } from '../net/types';
import type { ItemFlash } from '../net/useGameConnection';
import { BlackoutTimer } from './BlackoutTimer';
import { EffectTimers } from './EffectTimers';
import { BoardCanvas } from './BoardCanvas';
import { ItemBar } from './ItemBar';
import { ItemFlashOverlay } from './ItemFlashOverlay';
@@ -30,7 +30,15 @@ export const MiniBoard = memo(function MiniBoard({ state, width, height, slot, s
</div>
<BoardCanvas state={state} width={width} height={height} cell={cell} highlighted={selected}>
<ItemFlashOverlay flashes={flashes} small />
<BlackoutTimer remaining={state.alive ? state.invisibleRemaining : 0} small />
{state.alive && (
<EffectTimers
effects={[
['blind', state.invisibleRemaining],
['transform', state.transformedRemaining],
]}
small
/>
)}
</BoardCanvas>
<div className={styles.items} style={{ width: width * cell + 6 }}>
<ItemBar items={state.inventory} size={Math.max(10, cell)} />
+6 -1
View File
@@ -1,6 +1,6 @@
import * as signalR from '@microsoft/signalr';
import { getServerUrl } from '../config/runtimeConfig';
import type { InputAction, JoinResult, Lobby, MatchState } from './types';
import type { InputAction, ItemInfo, JoinResult, Lobby, MatchState } from './types';
export interface HubHandlers {
onLobbyUpdated: (lobby: Lobby) => void;
@@ -64,6 +64,11 @@ export class HubClient {
return this.invoke<void>('StartGame');
}
/** Items with their spawn share and duration from the server config. */
getItems() {
return this.invoke<ItemInfo[]>('GetItems');
}
/** Fire-and-forget input; ordering is preserved by the connection. */
input(action: InputAction) {
if (this.connection.state === signalR.HubConnectionState.Connected) {
+13 -1
View File
@@ -23,6 +23,16 @@ export interface Lobby {
lastResults: MatchResult[] | null;
}
/** An item of the server's current config (config/game.json). */
export interface ItemInfo {
id: string;
name: string;
/** Fraction (0..1) of spawned items that are this item; 0 = disabled. */
share: number;
/** Effect length for timed items, null for instant ones. */
durationSeconds: number | null;
}
export interface JoinResult {
playerId: string;
lobby: Lobby;
@@ -52,7 +62,8 @@ export interface PlayerState {
name: string;
alive: boolean;
place: number | null;
/** One character per visible cell, row by row: '0' empty, '1'-'7' piece colors, '8' garbage. */
/** One character per visible cell, row by row: '0' empty, '1'-'7' piece colors, '8' garbage,
* '9'-'=' (values 9-13) odd shapes from Transformation. Decode with charCodeAt - 48. */
board: string;
items: ItemCell[];
active: ActivePieceState | null;
@@ -66,6 +77,7 @@ export interface PlayerState {
level: number;
pendingGarbage: number;
invisibleRemaining: number;
transformedRemaining: number;
}
export interface MatchEvent {
@@ -79,12 +79,13 @@ export function useGameConnection() {
}, []);
const startGame = useCallback(() => clientRef.current!.startGame(), []);
const getItems = useCallback(() => clientRef.current!.getItems(), []);
const sendInput = useCallback((action: InputAction) => clientRef.current?.input(action), []);
const selectTarget = useCallback((targetId: string) => clientRef.current?.selectTarget(targetId), []);
const actions = useMemo(
() => ({ createLobby, joinLobby, leaveLobby, startGame, sendInput, selectTarget }),
[createLobby, joinLobby, leaveLobby, startGame, sendInput, selectTarget],
() => ({ createLobby, joinLobby, leaveLobby, startGame, getItems, sendInput, selectTarget }),
[createLobby, joinLobby, leaveLobby, startGame, getItems, sendInput, selectTarget],
);
return { status, playerId, lobby, match, flashes, actions };
+7 -2
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCurrentTrack, useSound } from '../audio/SoundContext';
import { useGameSounds } from '../audio/useGameSounds';
import { BlackoutTimer } from '../components/BlackoutTimer';
import { EffectTimers } from '../components/EffectTimers';
import { BoardCanvas } from '../components/BoardCanvas';
import { ItemBar } from '../components/ItemBar';
import { ItemFlashOverlay } from '../components/ItemFlashOverlay';
@@ -130,7 +130,12 @@ export function GamePage({ match, lobby, playerId, flashes, actions }: Props) {
highlighted={targetId === playerId}
>
<ItemFlashOverlay flashes={flashesFor(me.id)} />
<BlackoutTimer remaining={me.invisibleRemaining} />
<EffectTimers
effects={[
['blind', me.invisibleRemaining],
['transform', me.transformedRemaining],
]}
/>
{match.phase === 'countdown' && (
<div className={styles.overlay}>
<span className={styles.countdown}>{Math.ceil(match.countdown)}</span>
@@ -127,6 +127,20 @@
image-rendering: pixelated;
}
.itemText {
flex: 1;
}
.itemName {
display: flex;
justify-content: space-between;
gap: 8px;
}
.itemShare {
color: var(--color-muted);
}
.itemDescription {
color: var(--color-muted);
font-size: 8px;
+36 -8
View File
@@ -1,13 +1,13 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { Logo } from '../components/Logo';
import { MusicTracks } from '../components/MusicTracks';
import { CornerControls } from '../components/CornerControls';
import { Button } from '../components/ui/Button';
import { Panel } from '../components/ui/Panel';
import { controlsHelp } from '../config/keybindings';
import type { Lobby } from '../net/types';
import type { ItemInfo, Lobby } from '../net/types';
import type { GameActions } from '../net/useGameConnection';
import { itemVisuals } from '../theme/assets';
import { itemDescription, itemVisual, itemVisuals } from '../theme/assets';
import styles from './LobbyPage.module.css';
interface Props {
@@ -20,6 +20,23 @@ export function LobbyPage({ lobby, playerId, actions }: Props) {
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const isHost = lobby.hostId === playerId;
// Items as configured on the server; null until loaded (or if the call fails) = built-in list.
const [items, setItems] = useState<ItemInfo[] | null>(null);
useEffect(() => {
let cancelled = false;
actions
.getItems()
.then((list) => !cancelled && setItems(list))
.catch(() => {});
return () => {
cancelled = true;
};
}, [actions]);
const shownItems = items
? items.filter((i) => i.share > 0).map((i) => ({ id: i.id, share: i.share, duration: i.durationSeconds }))
: Object.keys(itemVisuals).map((id) => ({ id, share: null, duration: null }));
const copyLink = async () => {
const url = `${window.location.origin}${window.location.pathname}?code=${lobby.code}`;
@@ -107,15 +124,21 @@ export function LobbyPage({ lobby, playerId, actions }: Props) {
<Panel title="Items">
<p className={styles.hint}>Items hide inside blocks. Clear their line to collect them.</p>
<ul className={styles.items}>
{Object.entries(itemVisuals).map(([id, v]) => (
{shownItems.map(({ id, share, duration }) => {
const v = itemVisual(id);
return (
<li key={id}>
<img src={v.icon} alt="" width={20} height={20} />
<div>
<div style={{ color: v.color }}>{v.name}</div>
<div className={styles.itemDescription}>{v.description}</div>
<div className={styles.itemText}>
<div className={styles.itemName}>
<span style={{ color: v.color }}>{v.name}</span>
{share !== null && <span className={styles.itemShare}>{formatShare(share)}</span>}
</div>
<div className={styles.itemDescription}>{itemDescription(v, duration)}</div>
</div>
</li>
))}
);
})}
</ul>
</Panel>
@@ -126,3 +149,8 @@ export function LobbyPage({ lobby, playerId, actions }: Props) {
</main>
);
}
/** Share of spawned items as a percentage, e.g. "17%". */
function formatShare(share: number): string {
return share < 0.01 ? '<1%' : `${Math.round(share * 100)}%`;
}
+2
View File
@@ -135,6 +135,8 @@ export function drawPreviewPiece(
if (!shape) return;
const w = Math.max(...shape.map(([x]) => x)) + 1;
const h = Math.max(...shape.map(([, y]) => y)) + 1;
// Three-row shapes (Transformation) are shrunk to fit the preview box.
cell = Math.min(cell, Math.floor(boxHeight / (h + 0.5)));
const ox = offsetX + (boxWidth - w * cell) / 2;
const oy = offsetY + (boxHeight - h * cell) / 2;
const color = dimmed ? '#555555' : (blockColors[piece.type] ?? '#fff');
@@ -7,4 +7,10 @@ export const pieceShapes: Record<number, [number, number][]> = {
5: [[1, 0], [2, 0], [0, 1], [1, 1]],
6: [[0, 0], [1, 0], [1, 1], [2, 1]],
7: [[1, 0], [0, 1], [1, 1], [2, 1]],
// Odd shapes, only dealt during a Transformation.
9: [[0, 0]],
10: [[0, 0], [0, 1], [1, 1]],
11: [[0, 0], [2, 0], [0, 1], [1, 1], [2, 1]],
12: [[1, 0], [0, 1], [1, 1], [2, 1], [1, 2]],
13: [[0, 0], [0, 1], [1, 1], [1, 2], [2, 2]],
};
+18 -2
View File
@@ -16,8 +16,10 @@ export interface ItemVisual {
name: string;
/** Accent color used for flashes and as icon fallback. */
color: string;
/** Short explanation for the lobby help panel. */
/** Short explanation for the lobby help panel. "{duration}" is replaced with the configured seconds. */
description: string;
/** Built-in duration of timed items, shown when the server config can't be read. */
defaultDurationSeconds?: number;
}
/** Keyed by the server item id (IItem.Id). Add an entry here when adding an item on the server. */
@@ -50,7 +52,15 @@ export const itemVisuals: Record<string, ItemVisual> = {
icon: asset('assets/items/blind.svg'),
name: 'Blackout',
color: '#c452ff',
description: 'Hides placed blocks and the drop shadow for 4 seconds. Stacks.',
description: 'Hides placed blocks and the drop shadow for {duration} seconds. Stacks.',
defaultDurationSeconds: 4,
},
transform: {
icon: asset('assets/items/transform.svg'),
name: 'Transformation',
color: '#ff6fd8',
description: "Turns the target's next pieces into odd shapes for {duration} seconds. Stacks.",
defaultDurationSeconds: 8,
},
};
@@ -89,6 +99,12 @@ export function itemVisual(id: string): ItemVisual {
return itemVisuals[id] ?? unknownItem;
}
/** The lobby description of an item, with its duration filled in. */
export function itemDescription(visual: ItemVisual, durationSeconds?: number | null): string {
const seconds = durationSeconds ?? visual.defaultDurationSeconds;
return seconds === undefined ? visual.description : visual.description.replace('{duration}', String(seconds));
}
const imageCache = new Map<string, HTMLImageElement>();
/** Returns a (possibly still loading) image for canvas rendering. */
+6 -1
View File
@@ -1,6 +1,6 @@
/**
* Block colors by cell value (see PlayerState.board). Swap these to restyle the blocks.
* Index 0 is the empty cell, 8 is garbage.
* Index 0 is the empty cell, 1-7 the standard pieces, 8 garbage, 9-13 the Transformation shapes.
*/
export const blockColors: Record<number, string> = {
1: '#3fe3f2',
@@ -11,6 +11,11 @@ export const blockColors: Record<number, string> = {
6: '#ff4256',
7: '#c452ff',
8: '#8c8c8c',
9: '#ff6fd8',
10: '#2fd6a3',
11: '#b8ff3f',
12: '#f2f2f2',
13: '#ff7a3a',
};
export const boardColors = {
+23
View File
@@ -0,0 +1,23 @@
// Gameplay tuning for the Action Blocks server.
// Changes are picked up automatically and used from the next match on (running matches keep their values).
// An invalid edit is logged by the server and ignored; an invalid file at startup stops the server.
// Any value can also be overridden with an env var, e.g. Game__Items__blind__DurationSeconds=6.
// Other rules (CountdownSeconds, LockDelaySeconds, ...) can be added to "Game" too, see GameSettings.cs.
{
"Game": {
// Chance (0..1) that each block of a new piece carries an item. Every block rolls on its own,
// so one piece can carry several items. 0 = no items, 1 = every block has one.
"ItemSpawnChance": 0.05,
// Which item a block gets: Weight / sum of all weights. Example: weights 2, 1, 1 = 50%, 25%, 25%.
// Weight 0 disables an item. DurationSeconds only exists for the timed items (blind, transform).
"Items": {
"add_line": { "Weight": 1 },
"clear_line": { "Weight": 1 },
"nuke": { "Weight": 1 },
"swap": { "Weight": 1 },
"blind": { "Weight": 1, "DurationSeconds": 4 },
"transform": { "Weight": 1, "DurationSeconds": 8 }
}
}
}
+27 -2
View File
@@ -59,8 +59,33 @@ cp .env.example .env
| `ALLOWED_ORIGINS` | server | empty → any origin | Comma-separated list of origins allowed to connect, e.g. `https://game.example.com` |
| `PATH_BASE` | server | empty | Prefix to accept if the proxy forwards a sub-path **without stripping it**, e.g. `/server` |
| `HUB_PATH` | server | `/hub` | Hub endpoint path. It is fixed to `/hub` in the compose file |
| `ITEM_SPAWN_CHANCE` | server | `0.1` | Chance (0..1) that each block of a new piece carries an item. Passed to the server as `Game__ItemSpawnChance` |
| `Game__<Setting>` | server | see `GameSettings.cs` | Overrides other gameplay values, e.g. `Game__CountdownSeconds=5`. Add these under the server's `environment:` in the compose file |
| `GAME_CONFIG` | server | `/app/config/game.json` (compose) | Path of the gameplay config file, see [below](#game-config) |
| `Game__<Setting>` | server | see `GameSettings.cs` | Overrides a value from the config file, e.g. `Game__CountdownSeconds=5` or `Game__Items__blind__DurationSeconds=6`. Add these under the server's `environment:` in the compose file |
### Game config
`config/game.json` (next to `docker-compose.yml`) holds the gameplay tuning. The compose file mounts the `config` folder read-only into the server container.
```jsonc
{
"Game": {
"ItemSpawnChance": 0.1, // chance (0..1) per block of a new piece to carry an item
"Items": {
"nuke": { "Weight": 1 }, // share = weight / sum of all weights; 0 = disabled
"blind": { "Weight": 2, "DurationSeconds": 4 },
...
}
}
}
```
- **Effective chance** of an item per block = `ItemSpawnChance × weight / sum of weights`. With the defaults (all weights 1), each of the six items gets 1/6 of the 10%.
- `DurationSeconds` exists only for the timed items `blind` and `transform`. The other items act instantly.
- Items left out of the file keep weight 1 and their built-in duration. Item ids are case-insensitive. Any other `GameSettings` value (e.g. `CountdownSeconds`) may be added to `"Game"` too.
- **Changes apply from the next match on**, without a restart. Running matches keep the values they started with. The server logs `Game config reloaded` with the new shares.
- **Invalid values** (chance outside 0..1, negative weight, duration ≤ 0, unknown item, duration on an instant item, broken JSON) are reported in the server log:
- at startup, the server refuses to start;
- on a later edit, the change is ignored and the last good config stays active.
Start or update:
+3 -3
View File
@@ -29,14 +29,14 @@ To play against yourself, open the site in two browser windows. Create a lobby i
### Handy server settings for testing
Any `GameSettings` value can be overridden with an environment variable:
`dotnet run` finds `config/game.json` in the repo root automatically. Edit it (changes apply from the next match), point `GAME_CONFIG` to a separate test file, or override single values with environment variables:
```bash
Game__ItemSpawnChance=0.9 Game__CountdownSeconds=1 \
dotnet run --project src/ActionBlocks.Server --urls http://localhost:5080
```
That gives items on almost every piece and a near-instant start, which is useful for testing items.
That gives items on almost every piece and a near-instant start, which is useful for testing items. To test one item, set the weight of all others to 0 in a test config.
## Commands
@@ -73,7 +73,7 @@ That gives items on almost every piece and a near-instant start, which is useful
**Server**
- File-scoped namespaces, nullable reference types enabled, one main type per file. Small closely related types may share a file, e.g. all five items in `Items.cs`.
- File-scoped namespaces, nullable reference types enabled, one main type per file. Small closely related types may share a file, e.g. all items in `Items.cs`.
- `ActionBlocks.Game` must stay free of ASP.NET or serialization dependencies. Mapping to the wire format happens in `ActionBlocks.Server/Dtos`.
- Game objects are not thread-safe. Only touch them inside `lock (lobby.Sync)`.
- Prefer adding a value to `GameSettings`, or an implementation of an existing interface, over hard-coding numbers in logic.
+21 -12
View File
@@ -27,18 +27,20 @@ public sealed class SpeedUpItem : IItem
{
public string Id => "speed"; // stable id, also used by the frontend
public string DisplayName => "Speed Up";
public int SpawnWeight => 1; // optional, default 1 (higher = more common)
public double? DurationSeconds => 5; // optional: only for timed items, shown in the lobby
public void Apply(ItemContext context) =>
context.Target.FastUntil = Math.Max(context.Target.FastUntil, context.Now + 5);
}
```
To make the duration configurable, take it as a constructor parameter like `InvisibilityItem` does.
`ItemContext` gives you the `User`, the `Target`, a shared `Random` and the match time `Now`. Use `context.IsSelfTarget` to special-case self-use.
### 2. Server: add any new state the item needs
If existing `PlayerGame` methods (`InsertGarbageNow`, `RemoveBottomLine`, `ClearBoard`, `SwapBoards`, `InvisibleUntil`) aren't enough, add a property or method to `PlayerGame`. For the example:
If existing `PlayerGame` methods (`InsertGarbageNow`, `RemoveBottomLine`, `ClearBoard`, `SwapBoards`, `InvisibleUntil`, `Transform`) aren't enough, add a property or method to `PlayerGame`. For the example:
```csharp
public double FastUntil { get; set; }
@@ -49,31 +51,38 @@ If the board changes under the active piece, call `ResolveActiveOverlap()` after
### 3. Server: register it
In `Items/ItemRegistry.cs`:
In `Items/ItemRegistry.cs`, add it to `FromSettings`:
```csharp
public static ItemRegistry Default { get; } = new(
IItem[] items =
[
new AddGarbageLineItem(),
...
new SpeedUpItem(),
]);
new SpeedUpItem(), // or new SpeedUpItem(Duration("speed", 5)) for a configurable duration
];
```
Then add it to `config/game.json` so its weight (and duration) can be tuned:
```jsonc
"speed": { "Weight": 1, "DurationSeconds": 5 }
```
### 4. Server: test it
Add a test to `tests/ActionBlocks.Game.Tests/ItemAndMatchTests.cs`, and update `Registry_contains_five_unique_items` to the new count.
Add a test to `tests/ActionBlocks.Game.Tests/ItemAndMatchTests.cs`, and update `Registry_contains_six_unique_items` to the new count.
### 5. Website: add the visuals
Add an icon at `actionBlocks_website/public/assets/items/speed.svg`. Any image format works; the existing icons are 8×8 pixel-art SVGs. Then add an entry to `itemVisuals` in `src/theme/assets.ts`:
Add an icon at `actionBlocks_website/public/assets/items/speed.svg`. Any image format works; the existing icons are 8×8 pixel-art SVGs. Then add an entry to `itemVisuals` in `src/theme/assets.ts`. In `description`, write `{duration}` where the configured duration should appear:
```ts
speed: {
icon: asset('assets/items/speed.svg'),
name: 'Speed Up',
color: '#ff9b26',
description: 'Target pieces fall very fast for 5 seconds.',
description: 'Target pieces fall very fast for {duration} seconds.',
defaultDurationSeconds: 5,
},
```
@@ -81,7 +90,7 @@ The id key must match `IItem.Id`. Unknown ids still work but show `unknown.svg`.
### 6. Website: show the effect (only if needed)
If the item needs a visual effect, as Blackout does, expose the state in the snapshot (see [below](#add-new-state-to-the-snapshot)) and use it in `GamePage` / `draw.ts`.
If the item needs a visual effect, as Blackout does, expose the state in the snapshot (see [below](#add-new-state-to-the-snapshot)) and use it in `GamePage` / `draw.ts`. For a timed effect, add an entry to the `effects` list of `EffectTimers` in `GamePage` and `MiniBoard` to show a countdown.
---
@@ -99,7 +108,7 @@ All numbers are in `ActionBlocks.Game/GameSettings.cs`. There are two ways to ch
Game__LockDelaySeconds: "0.6"
```
The item chance already has its own variable: set `ITEM_SPAWN_CHANCE` in `.env` (the compose file passes it as `Game__ItemSpawnChance`).
- **Put it in `config/game.json`** (same `"Game"` section). That needs no rebuild and applies from the next match. The item chance, item weights and durations already live there; see [Deployment → Game config](deployment.md#game-config).
To add a **new** setting, add an `init` property with a default to `GameSettings` and read it where needed. Configuration binding picks it up automatically.
@@ -161,7 +170,7 @@ Keep snapshots small. They are sent ~30 times per second for every player to eve
|---|---|
| Item icon | Replace the file in `public/assets/items/`, or point `itemVisuals[id].icon` elsewhere |
| Logo | Put an image in `public/assets/`, set `uiAssets.logo: asset('assets/logo.png')` |
| Block colors | `src/theme/colors.ts` (`blockColors[1..7]` pieces, `[8]` garbage) |
| Block colors | `src/theme/colors.ts` (`blockColors[1..7]` pieces, `[8]` garbage, `[9..13]` Transformation shapes) |
| Block style (bevel, texture, …) | `drawBlock` in `src/render/draw.ts` |
| Ghost look | `drawGhostCell` in `draw.ts`, `boardColors.ghostAlpha` |
| UI colors, borders, font | CSS variables in `src/theme/global.css` |
+1 -1
View File
@@ -93,7 +93,7 @@ Layout: **hold + stats + "1 YOU"**, then the **own board** with the garbage mete
- If the target dies, an effect resets it to yourself, which mirrors the server rule. The selected board gets a cyan frame, and its slot number is filled cyan.
- **Leave.** The Leave button in the corner calls `leaveLobby`. While you are still alive in a match, leaving gives up that match, so the first click only turns the button into a red `SURE?` for 3 s and a second click leaves. After you are out, or once the match has finished, one click is enough. No browser dialog is used, because dialogs block the page.
- **Overlays on the own board:** `ItemFlashOverlay` (flashes whose `targetId` is you), the countdown number, and "YOU WIN!" or "<name> WINS".
- **Blackout.** `hideStack={me.invisibleRemaining > 0}` makes `drawBoard` skip locked cells, item icons and the ghost.
- **Blackout.** `hideStack={me.invisibleRemaining > 0}` makes `drawBoard` skip locked cells, item icons and the ghost. `EffectTimers` shows the seconds left on Blackout and Transformation in the board corner.
- **Garbage meter.** A red bar whose height is `pendingGarbage × cell`.
- **Inventory bar.** 10 slots, with the oldest item outlined, plus the hint line `F: <next item> > <target>`.
- **Mini boards.** `MiniBoard` is memoized. It shows the slot number, the name, the board, a flash overlay and the opponent's **item bar beneath the board**.
+5 -4
View File
@@ -28,7 +28,7 @@ Pieces spawn in the two buffer rows directly above the visible field. They are h
## Pieces and randomizer
- There are 7 shapes. Each has 4 rotation states (0 = spawn, 1 = right, 2 = 180°, 3 = left). States are derived by rotating the spawn shape inside its bounding box (`Core/PieceDefinitions.cs`).
- The **bag randomizer** shuffles all 7 shapes into a bag and deals them one by one, then refills (`Core/Randomizer.cs`). This guarantees every shape appears exactly once in every 7 pieces.
- The **bag randomizer** shuffles all 7 shapes into a bag and deals them one by one, then refills (`Core/Randomizer.cs`). This guarantees every shape appears exactly once in every 7 pieces. The odd Transformation shapes are never in the bag.
## Rotation (SRS)
@@ -114,7 +114,7 @@ A player is eliminated when any of these happens:
### Spawning and collecting
- Each of the four minos of a **newly generated** piece has its own 10% chance (`GameSettings.ItemSpawnChance`, env `ITEM_SPAWN_CHANCE`) to carry an item, so one piece can carry several items (up to four). Each item is picked separately. The roll happens when the piece enters the queue, so items are already visible in the preview and in hold (`Items/ItemRegistry.cs`, `ItemSpawner`).
- Each mino of a **newly generated** piece has its own 10% chance (`ItemSpawnChance` in `config/game.json`) to carry an item, so one piece can carry several items. Which item it is depends on the item **weights** in the same file: share = weight / sum of weights (default: all equal). Each item is picked separately. The roll happens when the piece enters the queue, so items are already visible in the preview and in hold (`Items/ItemRegistry.cs`, `ItemSpawner`).
- When the piece locks, the item stays in that cell of the board. Item cells move with the board: they drop when lines below them clear, rise with garbage, and travel along when boards are swapped.
- **Clearing the row that contains the item cell** moves the item into the player's inventory.
- If the cell is destroyed another way (for example by *Clear Line* or *Wipe Out*), the item is lost.
@@ -133,7 +133,7 @@ A player is eliminated when any of these happens:
- Everyone sees every opponent's inventory in the item bar beneath their mini board.
- Every client is told when an item hits someone (`ItemUsedEvent`): which player was hit and which item, but not who used it. The item name flashes on top of the hit player's board. That is the big board for yourself, or the mini board for an opponent.
### The five items
### The six items
| Id | Name | Effect | Class |
|---|---|---|---|
@@ -141,7 +141,8 @@ A player is eliminated when any of these happens:
| `clear_line` | Clear Line | Removes the bottom row of the target. Items in it are lost. | `ClearBottomLineItem` |
| `nuke` | Wipe Out | Removes **all** locked blocks of the target. The active piece is unaffected. | `ClearBoardItem` |
| `swap` | Switch | The user and the target exchange all locked blocks. Active pieces, hold, queues, inventories and pending garbage stay with their owners. If an active piece now overlaps, it is pushed up. Does nothing when used on yourself. | `SwapBoardItem` |
| `blind` | Blackout | For 4 seconds, the target cannot see their locked blocks or their ghost piece. Only the falling piece stays visible. Durations stack: each further Blackout adds 4 s to the time that is left. | `InvisibilityItem` |
| `blind` | Blackout | For 4 seconds (`DurationSeconds` in `config/game.json`), the target cannot see their locked blocks or their ghost piece. Only the falling piece stays visible. Durations stack: each further Blackout adds 4 s to the time that is left. | `InvisibilityItem` |
| `transform` | Transformation | For 8 seconds (configurable like Blackout), the target's upcoming pieces become odd shapes: Dot, small L, U, Plus or W (random). The whole next queue changes at once; the falling piece does not. Items inside a piece move to the new shape. When the time runs out, pieces still in the queue or hold change back to what they were. Durations stack like Blackout. | `TransformationItem` |
Every item can also be used on yourself: target `1`. *Wipe Out* and *Clear Line* are useful defensively.
+4 -3
View File
@@ -20,7 +20,7 @@ Communication uses **ASP.NET Core SignalR** over WebSockets. SignalR falls back
| `StartGame` | – | – | Host only; fails while a match is running |
| `Input` | `action: InputAction` | – | Sent with `send` (fire-and-forget) |
| `SelectTarget` | `targetId: string` | – | Player id of the item target, or your own id |
| `GetItems` | – | `ItemInfo[]` | Lists all server items (id + name). Currently unused by the website |
| `GetItems` | – | `ItemInfo[]` | Items of the current config: `{ id, name, share, durationSeconds }`. `share` is 0..1 (0 = disabled), `durationSeconds` is null for instant items. The lobby help panel uses it |
`InputAction` is one of `MoveLeft`, `MoveRight`, `RotateCw`, `RotateCcw`, `SoftDropStart`, `SoftDropStop`, `HardDrop`, `Hold`, `UseItem`.
@@ -143,11 +143,12 @@ sequenceDiagram
"lines": 12,
"level": 2,
"pendingGarbage": 3, // incoming lines waiting to rise
"invisibleRemaining": 0 // seconds of Blackout left (> 0 = hide stack + ghost)
"invisibleRemaining": 0, // seconds of Blackout left (> 0 = hide stack + ghost)
"transformedRemaining": 0 // seconds of Transformation left (queue shows odd shapes)
}
```
**Board encoding.** One character per cell: `'0'` is empty, `'1'`–`'7'` are piece colors (I, J, L, O, S, Z, T), `'8'` is garbage. Index = `y * width + x`, where y = 0 is the **top visible row**.
**Board encoding.** One character per cell: `'0'` is empty, `'1'`–`'7'` are piece colors (I, J, L, O, S, Z, T), `'8'` is garbage, and `'9'`, `':'`, `';'`, `'<'`, `'='` (values 9–13) are the Transformation shapes (Dot, SmallL, U, Plus, W). Decode with `charCode - 48`. Index = `y * width + x`, where y = 0 is the **top visible row**.
**Coordinates.** All `x, y` values are in visible coordinates. Active-piece cells can have **negative y** while the piece is still above the visible area. Clients skip those cells when drawing.
+5 -3
View File
@@ -108,20 +108,22 @@ public interface IItem
{
string Id { get; } // stable id shared with the frontend ("add_line", ...)
string DisplayName { get; } // shown in the flash
int SpawnWeight => 1; // relative spawn probability
double? DurationSeconds => null; // effect length of timed items, null = instant
void Apply(ItemContext context);
}
public sealed record ItemContext(PlayerGame User, PlayerGame Target, Random Random, double Now);
```
- `ItemRegistry.Default` lists all active items. `ItemRegistry.PickRandom` chooses an item weighted by `SpawnWeight`.
- `ItemRegistry.FromSettings(settings)` builds the items with the weights and durations from `GameSettings.Items` (from `config/game.json`). `ItemRegistry.Default` is the same with built-in values. `PickRandom` chooses an item by weight; weight-0 items never spawn. `Share(id)` is weight / sum of weights.
- `ItemSpawner.Decorate(type)` turns a raw piece type into a `PieceSpec`. Each mino rolls `ItemSpawnChance` on its own, so a piece can carry 0–4 items.
See [Extending → Add an item](extending.md#add-a-new-item).
### `GameSettings`
`GameSettings` is an immutable record with `init` properties, one per tunable number. See [Game rules](game-rules.md) for what each one does. The host binds it from the configuration section `Game`, so you can override any property with an environment variable named `Game__<PropertyName>`, e.g. `Game__ItemSpawnChance=0.25`.
`GameSettings` is an immutable record with `init` properties, one per tunable number, plus `Items` (per-item `Weight` and `DurationSeconds`). See [Game rules](game-rules.md) for what each one does. `Validate()` lists invalid values.
The host binds it from the configuration section `Game`. Its main source is `config/game.json` (`Config/GameConfigFile.cs`, path from `GAME_CONFIG`, otherwise searched upwards from the content root). Environment variables named `Game__<PropertyName>` override the file, e.g. `Game__ItemSpawnChance=0.25`. `Config/GameConfigProvider.cs` validates the config and follows changes to the file. A valid edit replaces `Current`, which the next `StartGame` hands to the new match. An invalid one is logged and ignored. At startup, an invalid config stops the server.
---
+7 -1
View File
@@ -30,7 +30,13 @@ services:
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-}
HUB_PATH: /hub
PATH_BASE: ${PATH_BASE:-}
Game__ItemSpawnChance: ${ITEM_SPAWN_CHANCE:-0.1}
# Gameplay tuning (item chance, weights, durations). Edits apply from the next match on.
GAME_CONFIG: /app/config/game.json
# File change events don't always cross bind mounts; polling makes the reload reliable.
DOTNET_USE_POLLING_FILE_WATCHER: "true"
volumes:
# The folder, not the single file: editors that save by replacing the file would break a file mount.
- ./config:/app/config:ro
networks:
- actionBlocks_server