From 71947f785e226be810e8ee57bf4e8e35ad2c7980 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 18 Mar 2026 22:42:59 -0400 Subject: [PATCH] =?UTF-8?q?Phase=201:=20Custom=20game=20system=20=E2=80=94?= =?UTF-8?q?=20DB=20schema=20extensions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extend CustomLobby with 12 new rule override columns (Password, HandSizeCap, DiscardOnMaxHand, MaxDeckSize, MinDeckSize, MaxArchTier1, TurnTimerSeconds, TimeLimitMinutes, TurnLimit, MpBuff, BoardWidth/Height) - Extend GameRuleSet with matching non-nullable rule fields (same set) - Extend GameRules record with 9 new rule fields (all default to 0/false) - Add LobbyPreset entity (owner-scoped named rule presets) - Register LobbyPreset in GameDbContext with index on OwnerAccountId - Migration: AddCustomGameExtensions (applied to pg-forge-01) - Add custom-game-system-plan.md with full 8-phase architecture plan and deferred features tracking list - Also includes: AbilityBuilder ValueExpr dropdowns + help panel, Affinity enum/system fixes (from prior sessions) Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../Pages/Cards/AbilityBuilder.razor | 239 +++++++++-- .../SOR.Database/Contexts/GameDbContext.cs | 8 + .../SOR.Database/Entities/Game/CustomLobby.cs | 38 ++ .../SOR.Database/Entities/Game/GameRuleSet.cs | 27 ++ .../SOR.Database/Entities/Game/LobbyPreset.cs | 20 + Server/src/SOR.Database/Enums/Affinity.cs | 4 +- ...024116_AddCustomGameExtensions.Designer.cs | 402 ++++++++++++++++++ .../20260319024116_AddCustomGameExtensions.cs | 306 +++++++++++++ .../Game/GameDbContextModelSnapshot.cs | 90 ++++ Server/src/SOR.Game/GameRules.cs | 27 ++ Server/src/SOR.Game/Grid/AffinitySystem.cs | 4 +- custom-game-system-plan.md | 373 ++++++++++++++++ 12 files changed, 1508 insertions(+), 30 deletions(-) create mode 100644 Server/src/SOR.Database/Entities/Game/LobbyPreset.cs create mode 100644 Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.Designer.cs create mode 100644 Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.cs create mode 100644 custom-game-system-plan.md diff --git a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor index 485436c..9abd4dd 100644 --- a/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor +++ b/Server/src/SOR.Admin/Components/Pages/Cards/AbilityBuilder.razor @@ -323,7 +323,7 @@
- @RenderEffectFields(effect) + @RenderEffectFields(effect, actionIdx, ab.TypeStr == "Triggered")
@@ -466,9 +466,14 @@ } } - +
+ + +
@@ -497,6 +502,141 @@
+@if (_showHelp) +{ +
+
+
Ability Builder Reference
+ +
+
+ +
Ability Types
+ + + + + + + + +
TypeWhen it firesKey fields
ActivePlayer explicitly activates on their turnRange, Cost, UsesPerTurn
PassiveAlways in effect while unit is on battlefieldActions (target=Self)
AuraContinuously affects all units in rangeAuraRange, Actions
TriggeredFires automatically when a specific game event occursTriggerEvent, Actions
+ +
Targeting — Scope
+

Scope defines the zone searched for targets.

+ + + + + + + + + + +
ScopeZone searched
BattlefieldUnits currently on the board
HandCards in a player's hand
DeckCards in a player's deck
DiscardCards in a player's discard pile
PlayerA player entity (for player-targeting effects like ModifySP)
AnyZoneAll zones simultaneously
+ +
Targeting — Ownership
+

Ownership narrows the candidate pool and determines whether the player is prompted to pick.

+ + + + + + + + + + + + +
OwnershipMeaningPlayer prompted?
SelfAny unit owned by the same controller as the ability sourceNo (auto)
ExactSelfThe exact unit instance that owns this abilityNo (auto)
OwnerEntities belonging to the ability ownerYes (if Count>1 or All)
AllyFriendly units other than selfYes
EnemyOpponent's unitsYes
AnyAny entity in the zone regardless of controllerYes
RandomEngine picks a random valid target; player is not promptedNo (auto)
TargetRe-uses the resolved target from the previous actionNo (chained)
+ +
Targeting — Target Filters
+ + + + + + + +
FilterMeaning
IsSelfTarget shares the same card definition as the source (matches all copies of this card type on the board)
IsExactSelfTarget is the exact unit instance that owns this ability (use when only this specific unit should be affected)
IsAdjacentToSourceTarget must be orthogonally adjacent to the ability's source unit
+ +
ValueExpr References
+

In any Amt field you can choose a dynamic reference instead of a fixed number. The engine resolves the reference at the moment the effect fires.

+ + + + + + + + + + + + + + + + + + + +
ReferenceResolves toWhen available
EventData.AmountNumeric payload from the trigger event (e.g. damage dealt)Triggered abilities only
Target.DamageCurrent damage stat of this action's first resolved targetAlways
Target.DefenseCurrent defense stat of the targetAlways
Target.HealthCurrent HP of the targetAlways
Target.MPCurrent MP of the targetAlways
Target.SpCostSP channel cost of the target cardAlways
Target.StCostST channel cost of the target cardAlways
Self.DamageDamage stat of the ability's source unitAlways
Self.DefenseDefense stat of the source unitAlways
Self.HealthCurrent HP of the source unitAlways
Self.MPCurrent MP of the source unitAlways
Self.SpCostSP cost of the source cardAlways
Self.StCostST cost of the source cardAlways
Action0.Target.*Stat of the first target resolved in Action 1Actions 2+ only
Action1.Target.*Stat of the first target resolved in Action 2Actions 3+ only
+ +
Multi-Action Cross-Reference Example
+

"Return a target Spirit to its owner's hand and refund its SP cost."

+
    +
  • Action 1 — Scope: Hand or Battlefield, Type: Spirit, Ownership: Any, Count: 1 → Effect: ReturnToHand
  • +
  • Action 2 — Scope: Player, Type: Player, Ownership: Target, Count: 1 → Effect: ModifySP, Amt: Action0.Target.SpCost
  • +
+

Action 2 uses Ownership: Target to re-target the owner of the card selected in Action 1. The Amt dropdown will show Action0.Target.* options once Action 2 exists.

+ +
Duration Types
+ + + + + + + + + + + +
DurationWhen the effect expires
InstantApplied once, never removed (stat changes etc.)
UntilEndOfTurnExpires at end of the active player's turn
UntilStartOfOwnerTurnExpires at start of the ability owner's next turn
UntilStartOfSourceOwnerTurnExpires at start of the source unit owner's next turn
ForNTurnsExpires after N complete turns have elapsed
WhileSourceOnBattlefieldExpires when the source unit leaves the battlefield
PermanentInMatchNever expires for the rest of this game
+ +
Conditions
+

Conditions can be added to Ability-level (ActivationConditions) or Action-level. All must pass for the ability/action to fire. The Subject dropdown selects whose state is checked: Self = ability source, Target = the resolved target.

+ + + + + + + + + + + + + + +
ConditionPasses when…
IsOwnTurn / IsOpponentTurnIt is (or isn't) the owner's turn
HealthBelow / HealthAbove NSubject's current HP < N or > N
DefenseIs / SPAtLeast / STAtLeastStat comparisons
HasGenus / HasAbilitySubject has a genus tag / named ability
IsOnTileWithAffinitySubject's tile matches the specified affinity
IsAdjacentToSubject is adjacent to a unit matching Ownership
WithinRangeOfSubject is within N tiles of a unit matching Ownership
UnitCountOnBattlefieldTotal matching units on board satisfies comparator
CardInZoneA matching card exists in the specified zone
AND / OR / XORComposite — combines nested conditions
+ +
Trigger Events
+

Available for Triggered abilities. The engine fires the ability whenever the event occurs and all ActivationConditions pass.

+
    + @foreach (var t in TriggerTypesList) + {
  • @t
  • } +
+ +
+
+
+} + @code { [Parameter] public string AbilitiesJson { get; set; } = "[]"; [Parameter] public EventCallback AbilitiesJsonChanged { get; set; } @@ -505,6 +645,7 @@ private string _compiledJson = "[]"; private string _lastJson = ""; private bool _showRaw; + private bool _showHelp; // ── Static enum options ────────────────────────────────────────────────────── @@ -807,9 +948,12 @@ var typeKey = eff["$type"]?.GetValue() ?? "DealDamage"; var d = new EffectDraft { TypeKey = typeKey }; - // ValueExpr helper: reads {"Fixed": N} + // ValueExpr helpers int ReadFixed(string key, int def = 1) => eff[key]?["Fixed"]?.GetValue() ?? eff[key]?.GetValue() ?? def; + string ReadRef(string key) => + eff[key]?["Ref"]?.GetValue() ?? ""; + void ReadValueExpr(string key) { d.Amount = ReadFixed(key); d.AmountRef = ReadRef(key); } string ReadStr(string key, string def = "") => eff[key]?.GetValue() ?? def; @@ -828,24 +972,24 @@ if (_amountBypassTypes.Contains(typeKey)) { - d.Amount = ReadFixed("Amount"); d.BypassDefense = ReadBool("BypassDefense"); + ReadValueExpr("Amount"); d.BypassDefense = ReadBool("BypassDefense"); } else if (typeKey == "DOT") { - d.Amount = ReadFixed("Amount"); d.BypassDefense = ReadBool("BypassDefense"); + ReadValueExpr("Amount"); d.BypassDefense = ReadBool("BypassDefense"); d.DurationType = ReadDurType(); d.DurationN = ReadDurN(); } else if (typeKey == "HOT") { - d.Amount = ReadFixed("Amount"); d.DurationType = ReadDurType(); d.DurationN = ReadDurN(); + ReadValueExpr("Amount"); d.DurationType = ReadDurType(); d.DurationN = ReadDurN(); } else if (_amountStatTypes.Contains(typeKey)) { - d.Amount = ReadFixed("Amount"); d.StatTarget = ReadStr("StatTarget", "Current"); + ReadValueExpr("Amount"); d.StatTarget = ReadStr("StatTarget", "Current"); } else if (_amountOnlyTypes.Contains(typeKey)) { - d.Amount = ReadFixed("Amount"); + ReadValueExpr("Amount"); } else if (typeKey is "DrawCards" or "DiscardCards") { @@ -1216,31 +1360,33 @@ { var node = new JsonObject { ["$type"] = d.TypeKey }; - JsonObject Fixed(int v) => new() { ["Fixed"] = v }; + JsonObject ValueExpr() => string.IsNullOrEmpty(d.AmountRef) + ? new JsonObject { ["Fixed"] = d.Amount } + : new JsonObject { ["Ref"] = d.AmountRef }; JsonObject Duration() => d.DurationType == "ForNTurns" ? new JsonObject { ["Type"] = d.DurationType, ["N"] = d.DurationN } : new JsonObject { ["Type"] = d.DurationType }; if (_amountBypassTypes.Contains(d.TypeKey)) { - node["Amount"] = Fixed(d.Amount); node["BypassDefense"] = d.BypassDefense; + node["Amount"] = ValueExpr(); node["BypassDefense"] = d.BypassDefense; } else if (d.TypeKey == "DOT") { - node["Amount"] = Fixed(d.Amount); node["BypassDefense"] = d.BypassDefense; + node["Amount"] = ValueExpr(); node["BypassDefense"] = d.BypassDefense; node["Duration"] = Duration(); } else if (d.TypeKey == "HOT") { - node["Amount"] = Fixed(d.Amount); node["Duration"] = Duration(); + node["Amount"] = ValueExpr(); node["Duration"] = Duration(); } else if (_amountStatTypes.Contains(d.TypeKey)) { - node["Amount"] = Fixed(d.Amount); node["StatTarget"] = d.StatTarget; + node["Amount"] = ValueExpr(); node["StatTarget"] = d.StatTarget; } else if (_amountOnlyTypes.Contains(d.TypeKey)) { - node["Amount"] = Fixed(d.Amount); + node["Amount"] = ValueExpr(); } else if (d.TypeKey is "DrawCards" or "DiscardCards") { @@ -1427,34 +1573,34 @@ // AND/OR/XOR + no-field types: no extra inputs }; - private RenderFragment RenderEffectFields(EffectDraft d) => __builder => + private RenderFragment RenderEffectFields(EffectDraft d, int actionIdx = 0, bool isTriggered = false) => __builder => { var t = d.TypeKey; if (_amountBypassTypes.Contains(t)) { - BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildValueExprInput(__builder, d, actionIdx, isTriggered); BuildCheckbox(__builder, "BypassDefense", d.BypassDefense, v => { d.BypassDefense = v; Compile(); }); } else if (t == "DOT") { - BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildValueExprInput(__builder, d, actionIdx, isTriggered); BuildCheckbox(__builder, "BypassDefense", d.BypassDefense, v => { d.BypassDefense = v; Compile(); }); BuildDuration(__builder, d); } else if (t == "HOT") { - BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildValueExprInput(__builder, d, actionIdx, isTriggered); BuildDuration(__builder, d); } else if (_amountStatTypes.Contains(t)) { - BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildValueExprInput(__builder, d, actionIdx, isTriggered); BuildSelect(__builder, StatTargetValues, d.StatTarget, v => { d.StatTarget = v; Compile(); }, 100); } else if (_amountOnlyTypes.Contains(t)) { - BuildFixedAmountInput(__builder, d.Amount, v => { d.Amount = v; Compile(); }); + BuildValueExprInput(__builder, d, actionIdx, isTriggered); } else if (t is "DrawCards" or "DiscardCards") { @@ -1789,16 +1935,56 @@ b.CloseElement(); } - private void BuildFixedAmountInput(RenderTreeBuilder b, int value, Action onChange) + private void BuildValueExprInput(RenderTreeBuilder b, EffectDraft d, int actionIdx, bool isTriggered) { + var refs = BuildValueRefs(actionIdx, isTriggered); b.OpenElement(0, "div"); - b.AddAttribute(1, "class", "d-flex align-items-center gap-1"); + b.AddAttribute(1, "class", "d-flex align-items-center gap-1 flex-wrap"); + // "Amt" label b.OpenElement(2, "label"); b.AddAttribute(3, "class", "form-label small mb-0 text-nowrap"); b.AddContent(4, "Amt"); b.CloseElement(); - BuildIntInput(b, value, onChange, 70, "Fixed value"); + // Ref dropdown + b.OpenElement(5, "select"); + b.AddAttribute(6, "class", "form-select form-select-sm"); + b.AddAttribute(7, "style", "width:185px"); + b.AddAttribute(8, "value", d.AmountRef); + b.AddAttribute(9, "onchange", EventCallback.Factory.Create( + this, e => { d.AmountRef = e.Value?.ToString() ?? ""; Compile(); })); + // Fixed option + b.OpenElement(10, "option"); + b.AddAttribute(11, "value", ""); + if (string.IsNullOrEmpty(d.AmountRef)) b.AddAttribute(12, "selected", true); + b.AddContent(13, "— fixed value —"); b.CloseElement(); + // Dynamic ref options + foreach (var r in refs) + { + b.OpenElement(10, "option"); + b.AddAttribute(11, "value", r); + if (r == d.AmountRef) b.AddAttribute(12, "selected", true); + b.AddContent(13, r); + b.CloseElement(); + } + b.CloseElement(); // select + // Number input — only shown when fixed mode + if (string.IsNullOrEmpty(d.AmountRef)) + BuildIntInput(b, d.Amount, v => { d.Amount = v; Compile(); }, 70, "Fixed value"); + b.CloseElement(); // outer div + } + + private static string[] BuildValueRefs(int actionIdx, bool isTriggered) + { + var refs = new List(); + if (isTriggered) refs.Add("EventData.Amount"); + refs.AddRange(["Target.Damage", "Target.Defense", "Target.Health", "Target.MP", "Target.SpCost", "Target.StCost"]); + refs.AddRange(["Self.Damage", "Self.Defense", "Self.Health", "Self.MP", "Self.SpCost", "Self.StCost"]); + for (int i = 0; i < actionIdx; i++) + refs.AddRange([$"Action{i}.Target.Damage", $"Action{i}.Target.Defense", + $"Action{i}.Target.Health", $"Action{i}.Target.MP", + $"Action{i}.Target.SpCost", $"Action{i}.Target.StCost"]); + return [.. refs]; } private void BuildCheckbox(RenderTreeBuilder b, string label, bool value, Action onChange) @@ -1904,7 +2090,7 @@ { // Reset all typed fields so we start fresh for the new type effect.TypeKey = typeKey; - effect.Amount = 1; effect.N = 1; effect.Tiles = 1; effect.BlockedDamage = 0; + effect.Amount = 1; effect.AmountRef = ""; effect.N = 1; effect.Tiles = 1; effect.BlockedDamage = 0; effect.BypassDefense = false; effect.Value = true; effect.PayCost = true; effect.Min = 1; effect.Max = 2; effect.StAmount = 1; effect.Player = "Owner"; effect.Controller = "Owner"; effect.StatTarget = "Current"; @@ -2008,6 +2194,7 @@ { public string TypeKey { get; set; } = "DealDamage"; public int Amount { get; set; } = 1; + public string AmountRef { get; set; } = ""; // "" = use Fixed; non-empty = ValueExpr Ref path public int N { get; set; } = 1; public bool BypassDefense{ get; set; } = false; public bool Value { get; set; } = true; diff --git a/Server/src/SOR.Database/Contexts/GameDbContext.cs b/Server/src/SOR.Database/Contexts/GameDbContext.cs index cd5a57d..d606f96 100644 --- a/Server/src/SOR.Database/Contexts/GameDbContext.cs +++ b/Server/src/SOR.Database/Contexts/GameDbContext.cs @@ -28,6 +28,7 @@ public sealed class GameDbContext : DbContext public DbSet ActionLogs => Set(); public DbSet GameRuleSets => Set(); public DbSet CustomLobbies => Set(); + public DbSet LobbyPresets => Set(); protected override void OnModelCreating(ModelBuilder builder) { @@ -86,5 +87,12 @@ public sealed class GameDbContext : DbContext e.HasIndex(l => new { l.Status, l.CreatedAt }); e.HasIndex(l => l.HostAccountId); }); + + builder.Entity(e => + { + e.ToTable("lobby_presets"); + e.HasKey(p => p.Id); + e.HasIndex(p => p.OwnerAccountId); + }); } } diff --git a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs index 4382edf..d865e81 100644 --- a/Server/src/SOR.Database/Entities/Game/CustomLobby.cs +++ b/Server/src/SOR.Database/Entities/Game/CustomLobby.cs @@ -42,6 +42,44 @@ public sealed class CustomLobby public bool? SpHasCapOverride { get; set; } public int? SpCapOverride { get; set; } + // ── Extended rule overrides ─────────────────────────────────────────────── + + /// Optional password to join this lobby. Null = no password required. + public string? Password { get; set; } + + /// Max cards in hand. 0 = no cap. + public int? HandSizeCapOverride { get; set; } + + /// If true, excess cards are auto-discarded when hand is at cap. If false, draw is blocked. + public bool? DiscardOnMaxHandOverride { get; set; } + + /// Maximum deck size. 0 = no limit. + public int? MaxDeckSizeOverride { get; set; } + + /// Minimum deck size. 0 = no limit. + public int? MinDeckSizeOverride { get; set; } + + /// Max copies of a Tier-1 Arch card allowed per deck. 0 = no limit. + public int? MaxArchTier1Override { get; set; } + + /// Seconds per turn before auto-end. 0 = no timer. + public int? TurnTimerSecondsOverride { get; set; } + + /// Total game time limit in minutes. 0 = no limit. + public int? TimeLimitMinutesOverride { get; set; } + + /// Maximum number of turns before game ends. 0 = no limit. + public int? TurnLimitOverride { get; set; } + + /// Flat MP bonus added to each unit at the start of its owner's turn. 0 = no buff. + public int? MpBuffOverride { get; set; } + + /// Board width override in columns. + public int? BoardWidthOverride { get; set; } + + /// Board height override in rows. + public int? BoardHeightOverride { get; set; } + // ── Timestamps ─────────────────────────────────────────────────────────── public DateTimeOffset CreatedAt { get; set; } diff --git a/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs b/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs index cfa63ce..2160e5b 100644 --- a/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs +++ b/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs @@ -49,6 +49,33 @@ public sealed class GameRuleSet /// Battlefield height (rows). Default: 8. public int BoardHeight { get; set; } = 8; + /// Max cards in hand. 0 = no cap. + public int HandSizeCap { get; set; } = 0; + + /// If true, excess cards are auto-discarded when hand is at cap. If false, draw is blocked. + public bool DiscardOnMaxHand { get; set; } = false; + + /// Maximum deck size. 0 = no limit. + public int MaxDeckSize { get; set; } = 0; + + /// Minimum deck size. 0 = no limit. + public int MinDeckSize { get; set; } = 0; + + /// Max copies of a Tier-1 Arch card allowed per deck. 0 = no limit. + public int MaxArchTier1 { get; set; } = 0; + + /// Seconds per turn before auto-end. 0 = no timer. + public int TurnTimerSeconds { get; set; } = 0; + + /// Total game time limit in minutes. 0 = no limit. + public int TimeLimitMinutes { get; set; } = 0; + + /// Maximum number of turns before game ends. 0 = no limit. + public int TurnLimit { get; set; } = 0; + + /// Flat MP bonus added to each unit at the start of its owner's turn. 0 = no buff. + public int MpBuff { get; set; } = 0; + // ── Origin Points Rewards ───────────────────────────────────────────────── /// OP awarded to the winner of a ranked game. diff --git a/Server/src/SOR.Database/Entities/Game/LobbyPreset.cs b/Server/src/SOR.Database/Entities/Game/LobbyPreset.cs new file mode 100644 index 0000000..0e8b57b --- /dev/null +++ b/Server/src/SOR.Database/Entities/Game/LobbyPreset.cs @@ -0,0 +1,20 @@ +namespace SOR.Database.Entities.Game; + +/// +/// A named lobby rule preset saved by a player for quick re-use. +/// +/// Rules are stored as serialized JSON (CustomRulesOverride shape). +/// Personal only — presets are scoped to the owner's account. +/// Cross-schema: OwnerAccountId is a bare Guid — no EF foreign key. +/// +public sealed class LobbyPreset +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid OwnerAccountId { get; set; } + public string Name { get; set; } = string.Empty; + + /// Serialized CustomRulesOverride JSON (nullable fields = inherit default). + public string RulesJson { get; set; } = "{}"; + + public DateTimeOffset CreatedAt { get; set; } +} diff --git a/Server/src/SOR.Database/Enums/Affinity.cs b/Server/src/SOR.Database/Enums/Affinity.cs index 8778bd5..990454c 100644 --- a/Server/src/SOR.Database/Enums/Affinity.cs +++ b/Server/src/SOR.Database/Enums/Affinity.cs @@ -26,10 +26,10 @@ public enum Affinity Marsh, // Lake + Field Swamp, // Lake + Forest Mountain, // Hill + Hill - Steppe, // Field + Forest + Steppe, // Field + Hill Fort, // Hill + forest Plains, // Field + Field - Grove, // Field + Hill + Grove, // Field + Forest Jungle, // Forest + Forest // ── Aether combinations ─────────────────────────────────────────────── diff --git a/Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.Designer.cs new file mode 100644 index 0000000..023663b --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.Designer.cs @@ -0,0 +1,402 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SOR.Database.Contexts; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + [DbContext(typeof(GameDbContext))] + [Migration("20260319024116_AddCustomGameExtensions")] + partial class AddCustomGameExtensions + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("game") + .HasAnnotation("ProductVersion", "8.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardHeightOverride") + .HasColumnType("integer"); + + b.Property("BoardWidthOverride") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHandOverride") + .HasColumnType("boolean"); + + b.Property("DrawPerTurnOverride") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDrawOverride") + .HasColumnType("boolean"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("GuestAccountId") + .HasColumnType("uuid"); + + b.Property("GuestDeckId") + .HasColumnType("uuid"); + + b.Property("HandSizeCapOverride") + .HasColumnType("integer"); + + b.Property("HostAccountId") + .HasColumnType("uuid"); + + b.Property("HostDeckId") + .HasColumnType("uuid"); + + b.Property("MaxArchTier1Override") + .HasColumnType("integer"); + + b.Property("MaxDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MinDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MpBuffOverride") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSizeOverride") + .HasColumnType("integer"); + + b.Property("Password") + .HasColumnType("text"); + + b.Property("SpAccumulationPerTurnOverride") + .HasColumnType("integer"); + + b.Property("SpCapOverride") + .HasColumnType("integer"); + + b.Property("SpHasCapOverride") + .HasColumnType("boolean"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TimeLimitMinutesOverride") + .HasColumnType("integer"); + + b.Property("TurnLimitOverride") + .HasColumnType("integer"); + + b.Property("TurnTimerSecondsOverride") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HostAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("custom_lobbies", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ActionType") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorAccountId") + .HasColumnType("uuid"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PayloadJson") + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("ResultJson") + .HasColumnType("jsonb") + .HasColumnName("result"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ActorAccountId"); + + b.HasIndex("GameSessionId", "SequenceNumber") + .IsUnique(); + + b.ToTable("action_logs", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardHeight") + .HasColumnType("integer"); + + b.Property("BoardWidth") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHand") + .HasColumnType("boolean"); + + b.Property("DrawPerTurn") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDraw") + .HasColumnType("boolean"); + + b.Property("HandSizeCap") + .HasColumnType("integer"); + + b.Property("IsCustomDefault") + .HasColumnType("boolean"); + + b.Property("IsRankedDefault") + .HasColumnType("boolean"); + + b.Property("LoserOpReward") + .HasColumnType("integer"); + + b.Property("MaxArchTier1") + .HasColumnType("integer"); + + b.Property("MaxDeckSize") + .HasColumnType("integer"); + + b.Property("MinDeckSize") + .HasColumnType("integer"); + + b.Property("MpBuff") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSize") + .HasColumnType("integer"); + + b.Property("RankDiffOpMultiplierPct") + .HasColumnType("integer"); + + b.Property("SpAccumulationPerTurn") + .HasColumnType("integer"); + + b.Property("SpCap") + .HasColumnType("integer"); + + b.Property("SpHasCap") + .HasColumnType("boolean"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TurnLimit") + .HasColumnType("integer"); + + b.Property("TurnTimerSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("WinnerOpReward") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsCustomDefault"); + + b.HasIndex("IsRankedDefault"); + + b.ToTable("game_rule_sets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("LastActionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PlayerOneAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerOneDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerOneReady") + .HasColumnType("boolean"); + + b.Property("PlayerTwoAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoReady") + .HasColumnType("boolean"); + + b.Property("RuleSnapshotJson") + .HasColumnType("jsonb") + .HasColumnName("rule_snapshot"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("StateJson") + .HasColumnType("jsonb") + .HasColumnName("state"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("WinCondition") + .HasColumnType("text"); + + b.Property("WinnerAccountId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PlayerOneAccountId"); + + b.HasIndex("PlayerTwoAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("game_sessions", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.LobbyPreset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerAccountId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerAccountId"); + + b.ToTable("lobby_presets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("DeckId") + .HasColumnType("uuid"); + + b.Property("JoinedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("MatchedGameSessionId") + .HasColumnType("uuid"); + + b.Property("RankScore") + .HasColumnType("integer"); + + b.Property("ResolvedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AccountId", "Status"); + + b.HasIndex("Status", "RankScore"); + + b.ToTable("matchmaking_entries", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.HasOne("SOR.Database.Entities.Game.GameSession", "Session") + .WithMany("ActionLog") + .HasForeignKey("GameSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Session"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Navigation("ActionLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.cs b/Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.cs new file mode 100644 index 0000000..8f1cc5a --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260319024116_AddCustomGameExtensions.cs @@ -0,0 +1,306 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + /// + public partial class AddCustomGameExtensions : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "DiscardOnMaxHand", + schema: "game", + table: "game_rule_sets", + type: "boolean", + nullable: false, + defaultValue: false); + + migrationBuilder.AddColumn( + name: "HandSizeCap", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "MaxArchTier1", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "MaxDeckSize", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "MinDeckSize", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "MpBuff", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "TimeLimitMinutes", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "TurnLimit", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "TurnTimerSeconds", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "BoardHeightOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "BoardWidthOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "DiscardOnMaxHandOverride", + schema: "game", + table: "custom_lobbies", + type: "boolean", + nullable: true); + + migrationBuilder.AddColumn( + name: "HandSizeCapOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "MaxArchTier1Override", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "MaxDeckSizeOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "MinDeckSizeOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "MpBuffOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "Password", + schema: "game", + table: "custom_lobbies", + type: "text", + nullable: true); + + migrationBuilder.AddColumn( + name: "TimeLimitMinutesOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "TurnLimitOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.AddColumn( + name: "TurnTimerSecondsOverride", + schema: "game", + table: "custom_lobbies", + type: "integer", + nullable: true); + + migrationBuilder.CreateTable( + name: "lobby_presets", + schema: "game", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + OwnerAccountId = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "text", nullable: false), + RulesJson = table.Column(type: "text", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_lobby_presets", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_lobby_presets_OwnerAccountId", + schema: "game", + table: "lobby_presets", + column: "OwnerAccountId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "lobby_presets", + schema: "game"); + + migrationBuilder.DropColumn( + name: "DiscardOnMaxHand", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "HandSizeCap", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "MaxArchTier1", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "MaxDeckSize", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "MinDeckSize", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "MpBuff", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "TimeLimitMinutes", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "TurnLimit", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "TurnTimerSeconds", + schema: "game", + table: "game_rule_sets"); + + migrationBuilder.DropColumn( + name: "BoardHeightOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "BoardWidthOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "DiscardOnMaxHandOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "HandSizeCapOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "MaxArchTier1Override", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "MaxDeckSizeOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "MinDeckSizeOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "MpBuffOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "Password", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "TimeLimitMinutesOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "TurnLimitOverride", + schema: "game", + table: "custom_lobbies"); + + migrationBuilder.DropColumn( + name: "TurnTimerSecondsOverride", + schema: "game", + table: "custom_lobbies"); + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs index 19c966e..e440e11 100644 --- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs @@ -29,9 +29,18 @@ namespace SOR.Database.Migrations.Game .ValueGeneratedOnAdd() .HasColumnType("uuid"); + b.Property("BoardHeightOverride") + .HasColumnType("integer"); + + b.Property("BoardWidthOverride") + .HasColumnType("integer"); + b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); + b.Property("DiscardOnMaxHandOverride") + .HasColumnType("boolean"); + b.Property("DrawPerTurnOverride") .HasColumnType("integer"); @@ -47,12 +56,27 @@ namespace SOR.Database.Migrations.Game b.Property("GuestDeckId") .HasColumnType("uuid"); + b.Property("HandSizeCapOverride") + .HasColumnType("integer"); + b.Property("HostAccountId") .HasColumnType("uuid"); b.Property("HostDeckId") .HasColumnType("uuid"); + b.Property("MaxArchTier1Override") + .HasColumnType("integer"); + + b.Property("MaxDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MinDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MpBuffOverride") + .HasColumnType("integer"); + b.Property("Name") .IsRequired() .HasColumnType("text"); @@ -60,6 +84,9 @@ namespace SOR.Database.Migrations.Game b.Property("OpeningHandSizeOverride") .HasColumnType("integer"); + b.Property("Password") + .HasColumnType("text"); + b.Property("SpAccumulationPerTurnOverride") .HasColumnType("integer"); @@ -73,6 +100,15 @@ namespace SOR.Database.Migrations.Game .IsRequired() .HasColumnType("text"); + b.Property("TimeLimitMinutesOverride") + .HasColumnType("integer"); + + b.Property("TurnLimitOverride") + .HasColumnType("integer"); + + b.Property("TurnTimerSecondsOverride") + .HasColumnType("integer"); + b.HasKey("Id"); b.HasIndex("HostAccountId"); @@ -137,12 +173,18 @@ namespace SOR.Database.Migrations.Game b.Property("CreatedAt") .HasColumnType("timestamp with time zone"); + b.Property("DiscardOnMaxHand") + .HasColumnType("boolean"); + b.Property("DrawPerTurn") .HasColumnType("integer"); b.Property("FirstPlayerSkipsDraw") .HasColumnType("boolean"); + b.Property("HandSizeCap") + .HasColumnType("integer"); + b.Property("IsCustomDefault") .HasColumnType("boolean"); @@ -152,6 +194,18 @@ namespace SOR.Database.Migrations.Game b.Property("LoserOpReward") .HasColumnType("integer"); + b.Property("MaxArchTier1") + .HasColumnType("integer"); + + b.Property("MaxDeckSize") + .HasColumnType("integer"); + + b.Property("MinDeckSize") + .HasColumnType("integer"); + + b.Property("MpBuff") + .HasColumnType("integer"); + b.Property("Name") .IsRequired() .HasColumnType("text"); @@ -171,6 +225,15 @@ namespace SOR.Database.Migrations.Game b.Property("SpHasCap") .HasColumnType("boolean"); + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TurnLimit") + .HasColumnType("integer"); + + b.Property("TurnTimerSeconds") + .HasColumnType("integer"); + b.Property("UpdatedAt") .HasColumnType("timestamp with time zone"); @@ -251,6 +314,33 @@ namespace SOR.Database.Migrations.Game b.ToTable("game_sessions", "game"); }); + modelBuilder.Entity("SOR.Database.Entities.Game.LobbyPreset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerAccountId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerAccountId"); + + b.ToTable("lobby_presets", "game"); + }); + modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b => { b.Property("Id") diff --git a/Server/src/SOR.Game/GameRules.cs b/Server/src/SOR.Game/GameRules.cs index 3cd4635..4314b90 100644 --- a/Server/src/SOR.Game/GameRules.cs +++ b/Server/src/SOR.Game/GameRules.cs @@ -23,5 +23,32 @@ public sealed record GameRules public int BoardWidth { get; init; } = 9; public int BoardHeight { get; init; } = 9; + /// Max cards in hand. 0 = no cap. + public int HandSizeCap { get; init; } = 0; + + /// If true, excess cards are discarded when hand is at cap. If false, draw is blocked. + public bool DiscardOnMaxHand { get; init; } = false; + + /// Maximum deck size. 0 = no limit. + public int MaxDeckSize { get; init; } = 0; + + /// Minimum deck size. 0 = no limit. + public int MinDeckSize { get; init; } = 0; + + /// Max copies of a Tier-1 Arch card allowed per deck. 0 = no limit. + public int MaxArchTier1 { get; init; } = 0; + + /// Seconds per turn before auto-end. 0 = no timer. + public int TurnTimerSeconds { get; init; } = 0; + + /// Total game time limit in minutes. 0 = no limit. + public int TimeLimitMinutes { get; init; } = 0; + + /// Maximum number of turns before game ends. 0 = no limit. + public int TurnLimit { get; init; } = 0; + + /// Flat MP bonus added to each unit at the start of its owner's turn. 0 = no buff. + public int MpBuff { get; init; } = 0; + public static readonly GameRules Default = new(); } diff --git a/Server/src/SOR.Game/Grid/AffinitySystem.cs b/Server/src/SOR.Game/Grid/AffinitySystem.cs index a58505b..111852e 100644 --- a/Server/src/SOR.Game/Grid/AffinitySystem.cs +++ b/Server/src/SOR.Game/Grid/AffinitySystem.cs @@ -55,12 +55,12 @@ public static class AffinitySystem // ── Hill pairings ───────────────────────────────────────────────── (Affinity.Hill, Affinity.Hill) => Affinity.Mountain, - (Affinity.Hill, Affinity.Field) or (Affinity.Field, Affinity.Hill) => Affinity.Grove, + (Affinity.Hill, Affinity.Field) or (Affinity.Field, Affinity.Hill) => Affinity.Steppe, (Affinity.Hill, Affinity.Forest) or (Affinity.Forest, Affinity.Hill) => Affinity.Fort, // ── Field pairings ──────────────────────────────────────────────── (Affinity.Field, Affinity.Field) => Affinity.Plains, - (Affinity.Field, Affinity.Forest) or (Affinity.Forest, Affinity.Field) => Affinity.Steppe, + (Affinity.Field, Affinity.Forest) or (Affinity.Forest, Affinity.Field) => Affinity.Grove, // ── Forest pairings ─────────────────────────────────────────────── (Affinity.Forest, Affinity.Forest) => Affinity.Jungle, diff --git a/custom-game-system-plan.md b/custom-game-system-plan.md new file mode 100644 index 0000000..b39edb0 --- /dev/null +++ b/custom-game-system-plan.md @@ -0,0 +1,373 @@ +# Plan: Extended Custom Game System + +## Context +The game already has a minimal 2-player custom lobby (create/join/list), but it is missing most of the requested features: the full rule set, spectating, board templates, preset save/reload with voting, and all client-side UI. This plan extends the existing foundation into a complete custom game system. + +**Scope decisions:** +- **2-player only** for now (engine is strictly 2-player; MaxPlayers is a UI-only stub) +- **Hex tile** is a stub (field stored, option shown as disabled in client) +- **Save/reload** = named lobby-config presets (NOT mid-match state resume) +- **Turn timer** = auto-end turn when expired (not auto-concede) +- **Lobby privacy** = public + optional password + +--- + +## Deferred / Out of Scope + +The following features are intentionally excluded from this implementation pass. Track these for future work: + +| Feature | Notes | +|---|---| +| **Board templates** | `BoardTemplateIdOverride` column added to schema as a nullable `Guid`, but no `BoardTemplate` entity, no admin page to create/edit templates, and no engine logic to apply a template. Wire-up deferred until template format is designed. | +| **Admin: BoardTemplate editor** | Full CRUD page for named board templates (tile layout, size, special tiles). Requires defining what a template actually stores (JSON layout? preset size only?). | +| **Admin: Custom lobby oversight** | Admin page listing all active/recent custom lobbies, with ability to cancel a lobby or kick a player. | +| **Hex tile shape** | `TileShape` field can be stored as an enum stub (Square / Hex), but the engine, client renderer, and pathfinding are square-only. Hex is UI-disabled. | +| **3+ player support** | `MinPlayers` / `MaxPlayers` are UI-only stubs. Engine is strictly 2-player. Multi-player requires engine rewrite. | +| **Lobby chat** | In-lobby text chat between host and guest before the game starts. | +| **Friend invite / direct invite** | Invite a specific player by name/ID to your lobby, bypassing the browser. | +| **Spectate from browser** | Browsing and joining in-progress games as a spectator. Current plan only covers `game.spectate` by known `SessionId`. Requires a `game.custom.list_active` endpoint and browser UI flow. | +| **Public preset sharing** | Presets are personal (owner-scoped) only. Public presets browsable by all players are deferred. | +| **Replay system** | Recording and replaying completed games. Related to spectating infrastructure. | +| **OP/ELO rewards for custom games** | Custom games give 0 OP and no ELO change. A configurable rewards toggle is deferred. | +| **Vote "concede" option** | The preset-load vote only supports yes/no. A third "concede the lobby" option (host or guest exits if vote drags on) is deferred. | +| **Lobby update while waiting** | Host changing rules after the guest has joined (without a preset vote) — rules are currently only editable while lobby is `Open`. Real-time rule editing in `Full` state requires a push + guest acknowledgement flow. | + +--- + +## Phase 1 — DB Schema Extensions + +### New fields on `CustomLobby` +**File:** `Server/src/SOR.Database/Entities/Game/CustomLobby.cs` + +Add nullable override columns (parallel to existing pattern): +```csharp +public string? Password { get; set; } // null = no password +public int? HandSizeCapOverride { get; set; } // 0 = no cap +public bool? DiscardOnMaxHandOverride { get; set; } +public int? MaxDeckSizeOverride { get; set; } // 0 = no limit +public int? MinDeckSizeOverride { get; set; } +public int? MaxArchTier1Override { get; set; } // 0 = no limit +public int? TurnTimerSecondsOverride { get; set; } // 0 = no timer +public int? TimeLimitMinutesOverride { get; set; } // 0 = no limit +public int? TurnLimitOverride { get; set; } // 0 = no limit +public int? MpBuffOverride { get; set; } // flat bonus to unit MP per turn +public int? BoardWidthOverride { get; set; } +public int? BoardHeightOverride { get; set; } +``` + +### New fields on `GameRuleSet` +**File:** `Server/src/SOR.Database/Entities/Game/GameRuleSet.cs` + +Same set of non-nullable fields with sensible defaults (0 = disabled for caps/limits). + +### Extend `GameRules` record +**File:** `Server/src/SOR.Game/GameRules.cs` + +```csharp +public int HandSizeCap { get; init; } = 0; // 0 = no cap +public bool DiscardOnMaxHand { get; init; } = false; +public int MaxDeckSize { get; init; } = 0; +public int MinDeckSize { get; init; } = 0; +public int MaxArchTier1 { get; init; } = 0; // 0 = no limit +public int TurnTimerSeconds { get; init; } = 0; // 0 = no timer +public int TimeLimitMinutes { get; init; } = 0; +public int TurnLimit { get; init; } = 0; +public int MpBuff { get; init; } = 0; // added to each unit's MP at turn start +``` + +### New entity: `LobbyPreset` +**File (new):** `Server/src/SOR.Database/Entities/Game/LobbyPreset.cs` + +```csharp +public sealed class LobbyPreset +{ + public Guid Id { get; set; } = Guid.NewGuid(); + public Guid OwnerAccountId { get; set; } + public string Name { get; set; } = string.Empty; + public string RulesJson { get; set; } = "{}"; // serialized CustomRulesOverride + public DateTimeOffset CreatedAt { get; set; } +} +``` +- Add `DbSet LobbyPresets` to `GameDbContext`. +- EF config: `ToTable("lobby_presets", "game")`, index on `OwnerAccountId`. + +### Migration +**Dir:** `Server/src/SOR.Database/Migrations/Game/` + +One migration (`AddCustomGameExtensions`) adding: +- All new columns to `game.custom_lobbies` +- All new columns to `game.game_rule_sets` +- New table `game.lobby_presets` +- Update `GameDbContextModelSnapshot.cs` + +--- + +## Phase 2 — GameRules Application in GameEngine + +**File:** `Server/src/SOR.Game/GameEngine.cs` (and related engine files) + +Fixes and new rule enforcement: +1. **`DrawPerTurn`** — currently ignored in the Draw phase; find the draw logic and apply `state.Rules.DrawPerTurn` instead of hardcoded 1. +2. **`HandSizeCap` / `DiscardOnMaxHand`** — after drawing: if `HandSizeCap > 0 && hand.Count > HandSizeCap`, discard excess from top (or block draw if `!DiscardOnMaxHand`). +3. **`MpBuff`** — at start of each player's turn, add `Rules.MpBuff` to all friendly unit MP values (clamped to max MP). +4. **`TurnLimit`** — at the start of a turn, if `Rules.TurnLimit > 0 && state.TurnNumber > Rules.TurnLimit`, trigger game over with win condition `"turn_limit"` (winner = player with most ArchSpirit HP; tie = draw, loser = P2). +5. **`TimeLimitMinutes`** — stored in rules; enforced in `GameTurnTimerService` (Phase 3) by checking `session.CreatedAt`. +6. **Deck validation** (`MaxDeckSize`, `MinDeckSize`, `MaxArchTier1`) — add a `GameEngine.ValidateDeck(deck, rules)` method returning validation errors. Called in `GameJoinCustomLobbyHandler` before creating the session (only when custom rules have non-zero limits). + +--- + +## Phase 3 — Turn Timer Service + +**File (new):** `Server/src/SOR.Game/GameTurnTimerService.cs` + +A `BackgroundService` singleton managing per-session turn timers: + +```csharp +internal sealed class GameTurnTimerService : BackgroundService +{ + // sessionId → CancellationTokenSource for the current turn timer + private readonly ConcurrentDictionary _timers = new(); + + public void ResetTimer(Guid sessionId, int turnTimerSeconds, int timeLimitMinutes, + DateTimeOffset sessionCreatedAt, Func onExpired) { ... } + public void CancelTimer(Guid sessionId) { ... } +} +``` + +**Integration:** +- `SaveStateAsync` in `GameHandlerBase` calls `GameTurnTimerService.ResetTimer(...)` after committing, passing the `state.Rules.TurnTimerSeconds` and an `onExpired` callback. +- On expiry: the service calls `EndTurnAsync(sessionId)` — a helper that loads the session and injects a synthetic `game.end_turn` action (reusing `GameEndTurnHandler` logic via a shared static method extracted from the handler). +- Register as singleton + hosted service in `ServiceRegistration.cs`. + +--- + +## Phase 4 — Spectator Support + +### `SpectatorRegistryService` (singleton) +**File (new):** `Server/src/SOR.Game/SpectatorRegistryService.cs` + +```csharp +internal sealed class SpectatorRegistryService +{ + private readonly ConcurrentDictionary> _map = new(); + + public void Register(Guid sessionId, Guid accountId) { ... } + public void Unregister(Guid sessionId, Guid accountId) { ... } + public void RemoveSession(Guid sessionId) { ... } + public IReadOnlySet GetSpectators(Guid sessionId) { ... } +} +``` + +### New handler: `GameSpectateHandler` +**File (new):** `Server/src/SOR.Game/Handlers/GameSpectateHandler.cs` + +- Message: `game.spectate` +- Request: `SpectateRequest(Guid SessionId)` +- Loads session (must be Active), registers caller in `SpectatorRegistryService`. +- Returns current state filtered for spectator (both hands as count-only). +- Ack: `game.spectate.ack` with `GameStateDtoSpectator`. + +### `GameStateDto` spectator variant +**File:** `Server/src/SOR.Game/GameMessages.cs` or engine DTO file + +Add `GameEngine.ToDtoSpectator(state)` — same as `ToDto` but both `MyHand` and `OpponentHand` contain only the card count (no `CardId`, no `InstanceId`). Alternatively, pass a new `viewerAccountId = null` sentinel to `ToDto` that triggers the spectator path. + +### Push to spectators +**File:** `Server/src/SOR.Game/Handlers/GameHandlerBase.cs` + +Extend `PushStateToPlayersAsync` to also push to spectators: +```csharp +foreach (var specId in spectatorRegistry.GetSpectators(session.Id)) + await clientPush.PushAsync(specId.ToString(), + ServerMessage.Push("game.state_update", + new GameStateUpdatePush(GameEngine.ToDtoSpectator(state))), ct); +``` +Also call `spectatorRegistry.RemoveSession` in `FinalizeGameAsync` after pushing `game.over` to spectators. + +--- + +## Phase 5 — Preset Save / Propose / Vote + +### `VoteSessionService` (singleton) +**File (new):** `Server/src/SOR.Game/VoteSessionService.cs` + +```csharp +internal sealed record ActiveVote(Guid LobbyId, Guid PresetId, CustomRulesOverride Rules, + Dictionary Votes); + +internal sealed class VoteSessionService +{ + private readonly ConcurrentDictionary _votes = new(); // lobbyId → vote + + public void Start(Guid lobbyId, Guid presetId, CustomRulesOverride rules, IEnumerable voters); + public VoteOutcome Cast(Guid lobbyId, Guid accountId, bool vote); // Pending/Approved/Rejected + public ActiveVote? Get(Guid lobbyId); + public void Cancel(Guid lobbyId); +} +``` + +### New handlers (in `Server/src/SOR.Game/Handlers/`) + +| Handler | Message | Description | +|---|---|---| +| `GameSavePresetHandler` | `game.custom.preset.save` | Save lobby's current rules as a named `LobbyPreset` (only participants). | +| `GameListPresetsHandler` | `game.custom.preset.list` | Return caller's saved presets. | +| `GameDeletePresetHandler` | `game.custom.preset.delete` | Delete a preset owned by the caller. | +| `GameProposePresetHandler` | `game.custom.preset.propose` | Host proposes loading a preset; starts `VoteSession`; pushes `game.custom.preset.vote_requested` to other player. | +| `GameVotePresetHandler` | `game.custom.preset.vote` | Cast yes/no. If approved: update lobby rule overrides + push `game.custom.lobby_updated` to both. If rejected: push `game.custom.preset.vote_rejected`. | + +### New message types (in `GameMessages.cs`) +```csharp +record SavePresetRequest(Guid LobbyId, string PresetName); +record ListPresetsRequest; +record DeletePresetRequest(Guid PresetId); +record ProposePresetRequest(Guid LobbyId, Guid PresetId); +record VotePresetRequest(Guid LobbyId, bool Accept); +record LobbyPresetDto(Guid PresetId, string Name, CustomRulesOverride Rules, DateTimeOffset CreatedAt); +record PresetVoteRequestedPush(Guid LobbyId, Guid PresetId, string PresetName, CustomRulesOverride Rules); +record LobbyUpdatedPush(Guid LobbyId, CustomRulesDto NewRules); +``` + +--- + +## Phase 6 — Lobby Enhancements + +### Password protection +- `CreateCustomLobbyRequest`: add `string? Password = null`. +- `CustomLobby`: store `Password` (hashed? plain text is fine for game lobbies). +- `JoinCustomLobbyRequest`: add `string? Password = null`. +- `GameJoinCustomLobbyHandler`: if `lobby.Password != null && lobby.Password != req.Password` → throw `GameException("WRONG_PASSWORD")`. + +### Host notification on guest join +**File:** `Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs` +- After guest joins (lobby now Full), push `game.custom.guest_joined` to host with `GuestAccountId`. + +### Lobby browser filters +**File:** `Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs` +- `ListCustomLobbiesRequest`: add `string? NameSearch = null`, `bool ShowPasswordProtected = true`. +- Apply `.Where(l => NameSearch == null || l.Name.Contains(NameSearch))` etc. + +### Get single lobby +**File (new):** `Server/src/SOR.Game/Handlers/GameGetLobbyHandler.cs` +- `game.custom.get` — returns full `CustomLobbyDetailDto` (all rules, host/guest presence) for a specific lobby ID. + +--- + +## Phase 7 — Update Existing Handlers for New Rules + +### `GameCreateCustomLobbyHandler` +**File:** `Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs` + +- Extend `effective` `GameRules` construction + `CustomLobby` override storage to cover all new rule fields. +- Pass `Password` from request to entity. + +### `GameJoinCustomLobbyHandler` +**File:** `Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs` + +- Extend `GameRules` construction to include all new fields. +- Call `GameEngine.ValidateDeck(hostDeck, rules)` and `GameEngine.ValidateDeck(guestDeck, rules)` before creating the session (requires loading decks — use `CatalogDbContext`). + +### `GameListCustomLobbiesHandler` +- Extend `CustomRulesDto` mapping to include new rule fields. +- Apply new filters. + +### `CustomRulesDto` and `CustomRulesOverride` records +**File:** `Server/src/SOR.Game/GameMessages.cs` +- Add all new fields with defaults to both records. + +--- + +## Phase 8 — Client Scenes + +### New: `CustomLobbyBrowser.tscn` + `custom_lobby_browser.gd` +**Dir:** `Client/origin-client/scenes/lobby/` + +- Full-screen scene with filter bar + lobby list. +- Filter: name search input, refresh button. +- Each row: lobby name, host username, player count (1/2), key rules summary, Join button. +- "Create Lobby" button → opens `CustomRulesEditor` panel → sends `game.custom.create` → navigates to `CustomLobbyRoom`. +- On Join: sends `game.custom.join` (with optional password prompt) → navigates to `CustomLobbyRoom`. + +### New: `CustomLobbyRoom.tscn` + `custom_lobby_room.gd` +**Dir:** `Client/origin-client/scenes/lobby/` + +- Shows both player slots (host / guest or "Waiting..."). +- Rules panel (read-only for guest, editable for host). +- Preset buttons: Save, Load (host only) — opens preset list dialog. +- Start is automatic when guest joins (game.custom.started push). +- Leave button → `game.custom.leave`. +- On receiving `game.custom.started` push: navigate to `GameScreen` with session ID. + +### New: `CustomRulesEditor.tscn` + `custom_rules_editor.gd` +- Panel component embedded in both browser (create flow) and lobby room (host editing). +- One control per rule (sliders/spinboxes for ints, checkboxes for bools). +- "Save as Preset" button (in room only). + +### `game_screen.gd` — spectator mode +**File:** `Client/origin-client/scenes/game/game_screen.gd` + +- On `game.spectate.ack`: set `_is_spectator = true`. +- When `_is_spectator`: hide hand panel and action buttons; show "SPECTATING" label. +- Hand display for both players shows count label only. + +--- + +## Implementation Order + +1. **Phase 1** — DB schema + migration (new columns + LobbyPreset table) +2. **Phase 2** — GameRules record extension + GameEngine fixes (DrawPerTurn, HandSizeCap, MpBuff, TurnLimit, ValidateDeck) +3. **Phase 7** — Extend existing create/join/list handlers + DTOs for all new rule fields +4. **Phase 3** — GameTurnTimerService +5. **Phase 4** — SpectatorRegistryService + GameSpectateHandler + PushStateToPlayersAsync changes +6. **Phase 5** — VoteSessionService + all preset handlers +7. **Phase 6** — Password, host-join push, lobby filters, GameGetLobbyHandler +8. **Phase 8** — Client scenes (CustomLobbyBrowser, CustomLobbyRoom, CustomRulesEditor, spectator mode) + +--- + +## Key Files Summary + +| File | Change | +|---|---| +| `SOR.Database/Entities/Game/CustomLobby.cs` | +12 new override columns | +| `SOR.Database/Entities/Game/GameRuleSet.cs` | +9 new rule fields | +| `SOR.Database/Entities/Game/LobbyPreset.cs` | **NEW** entity | +| `SOR.Database/Migrations/Game/` | **NEW** migration `AddCustomGameExtensions` | +| `SOR.Game/GameRules.cs` | +9 new rule fields | +| `SOR.Game/GameEngine.cs` | Fix DrawPerTurn; add HandSizeCap, MpBuff, TurnLimit, ValidateDeck | +| `SOR.Game/GameMessages.cs` | Extend DTOs + add preset/spectate/vote message types | +| `SOR.Game/GameTurnTimerService.cs` | **NEW** BackgroundService | +| `SOR.Game/SpectatorRegistryService.cs` | **NEW** singleton | +| `SOR.Game/VoteSessionService.cs` | **NEW** singleton | +| `SOR.Game/Handlers/GameHandlerBase.cs` | Extend PushStateToPlayersAsync for spectators | +| `SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs` | Extend for all new rules + password | +| `SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs` | Extend rules + deck validation + password check | +| `SOR.Game/Handlers/GameListCustomLobbiesHandler.cs` | Extend DTO + filters | +| `SOR.Game/Handlers/GameSpectateHandler.cs` | **NEW** | +| `SOR.Game/Handlers/GameSavePresetHandler.cs` | **NEW** | +| `SOR.Game/Handlers/GameListPresetsHandler.cs` | **NEW** | +| `SOR.Game/Handlers/GameDeletePresetHandler.cs` | **NEW** | +| `SOR.Game/Handlers/GameProposePresetHandler.cs` | **NEW** | +| `SOR.Game/Handlers/GameVotePresetHandler.cs` | **NEW** | +| `SOR.Game/Handlers/GameGetLobbyHandler.cs` | **NEW** | +| `SOR.Game/ServiceRegistration.cs` | Register all new services + handlers | +| `SOR.Host/Program.cs` | *(No changes — wiring stays in ServiceRegistration)* | +| `Client/origin-client/scenes/lobby/CustomLobbyBrowser.tscn` | **NEW** | +| `Client/origin-client/scenes/lobby/custom_lobby_browser.gd` | **NEW** | +| `Client/origin-client/scenes/lobby/CustomLobbyRoom.tscn` | **NEW** | +| `Client/origin-client/scenes/lobby/custom_lobby_room.gd` | **NEW** | +| `Client/origin-client/scenes/lobby/CustomRulesEditor.tscn` | **NEW** | +| `Client/origin-client/scenes/lobby/custom_rules_editor.gd` | **NEW** | +| `Client/origin-client/scenes/game/game_screen.gd` | +spectator mode | + +--- + +## Verification + +1. **Full lobby flow**: Create lobby → second client joins → both navigate to game screen → game starts normally. +2. **New rules applied**: Set `DrawPerTurn = 2`, play to Draw phase → confirm 2 cards drawn. Set `HandSizeCap = 5` → confirm hand is trimmed. +3. **Turn timer**: Set `TurnTimerSeconds = 30` → leave a turn idle for 30s → confirm turn auto-ends. +4. **Spectator**: Third client sends `game.spectate` → receives state with hand counts only → receives state updates as game progresses. +5. **Preset save/load**: Host saves preset → Guest proposes loading it → Host votes yes → lobby rules update → both clients see new rules. +6. **Password**: Create lobby with password → join without password → error. Join with correct password → succeeds. +7. **Deck validation**: Set `MinDeckSize = 40` → try to join with 30-card deck → error.