diff --git a/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs b/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs
index c76b76a..995ceab 100644
--- a/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs
+++ b/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs
@@ -43,6 +43,12 @@ public sealed class GameRuleSet
/// Maximum SP balance. Ignored if SpHasCap is false.
public int SpCap { get; set; }
+ /// Battlefield width (columns). Default: 8.
+ public int BoardWidth { get; set; } = 8;
+
+ /// Battlefield height (rows). Default: 8.
+ public int BoardHeight { get; set; } = 8;
+
// ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; }
diff --git a/Server/src/SOR.Database/Enums/GameEnums.cs b/Server/src/SOR.Database/Enums/GameEnums.cs
index 1c55958..329890d 100644
--- a/Server/src/SOR.Database/Enums/GameEnums.cs
+++ b/Server/src/SOR.Database/Enums/GameEnums.cs
@@ -33,11 +33,13 @@ public enum GameSessionStatus
///
public enum GamePhase
{
- /// Game just started — both players draw their opening hands.
+ /// Game just started — both players place their ArchSpirits and draw opening hands.
Setup,
+ /// Both players are placing their ArchSpirits on their starting rows.
+ Placement,
/// Active player draws a card.
Draw,
- /// Active player may play cards, activate abilities, and attack.
+ /// Active player may play cards, activate abilities, attack, and move.
Main,
/// Active player has declared end of turn; cleanup runs.
End,
diff --git a/Server/src/SOR.Database/Migrations/Game/20260226162145_AddBoardDimensions.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260226162145_AddBoardDimensions.Designer.cs
new file mode 100644
index 0000000..4db97a2
--- /dev/null
+++ b/Server/src/SOR.Database/Migrations/Game/20260226162145_AddBoardDimensions.Designer.cs
@@ -0,0 +1,296 @@
+//
+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("20260226162145_AddBoardDimensions")]
+ partial class AddBoardDimensions
+ {
+ ///
+ 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("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ 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("HostAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("HostDeckId")
+ .HasColumnType("uuid");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OpeningHandSizeOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpAccumulationPerTurnOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpCapOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpHasCapOverride")
+ .HasColumnType("boolean");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasColumnType("text");
+
+ 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("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("DrawPerTurn")
+ .HasColumnType("integer");
+
+ b.Property("FirstPlayerSkipsDraw")
+ .HasColumnType("boolean");
+
+ b.Property("IsCustomDefault")
+ .HasColumnType("boolean");
+
+ b.Property("IsRankedDefault")
+ .HasColumnType("boolean");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OpeningHandSize")
+ .HasColumnType("integer");
+
+ b.Property("SpAccumulationPerTurn")
+ .HasColumnType("integer");
+
+ b.Property("SpCap")
+ .HasColumnType("integer");
+
+ b.Property("SpHasCap")
+ .HasColumnType("boolean");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ 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("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.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/20260226162145_AddBoardDimensions.cs b/Server/src/SOR.Database/Migrations/Game/20260226162145_AddBoardDimensions.cs
new file mode 100644
index 0000000..a821a06
--- /dev/null
+++ b/Server/src/SOR.Database/Migrations/Game/20260226162145_AddBoardDimensions.cs
@@ -0,0 +1,114 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace SOR.Database.Migrations.Game
+{
+ ///
+ public partial class AddBoardDimensions : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "rule_snapshot",
+ schema: "game",
+ table: "game_sessions",
+ type: "jsonb",
+ nullable: true);
+
+ migrationBuilder.CreateTable(
+ name: "custom_lobbies",
+ schema: "game",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ Name = table.Column(type: "text", nullable: false),
+ Status = table.Column(type: "text", nullable: false),
+ HostAccountId = table.Column(type: "uuid", nullable: false),
+ HostDeckId = table.Column(type: "uuid", nullable: false),
+ GuestAccountId = table.Column(type: "uuid", nullable: true),
+ GuestDeckId = table.Column(type: "uuid", nullable: true),
+ GameSessionId = table.Column(type: "uuid", nullable: true),
+ OpeningHandSizeOverride = table.Column(type: "integer", nullable: true),
+ FirstPlayerSkipsDrawOverride = table.Column(type: "boolean", nullable: true),
+ SpAccumulationPerTurnOverride = table.Column(type: "integer", nullable: true),
+ DrawPerTurnOverride = table.Column(type: "integer", nullable: true),
+ SpHasCapOverride = table.Column(type: "boolean", nullable: true),
+ SpCapOverride = table.Column(type: "integer", nullable: true),
+ CreatedAt = table.Column(type: "timestamp with time zone", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_custom_lobbies", x => x.Id);
+ });
+
+ migrationBuilder.CreateTable(
+ name: "game_rule_sets",
+ schema: "game",
+ columns: table => new
+ {
+ Id = table.Column(type: "uuid", nullable: false),
+ Name = table.Column(type: "text", nullable: false),
+ IsRankedDefault = table.Column(type: "boolean", nullable: false),
+ IsCustomDefault = table.Column(type: "boolean", nullable: false),
+ OpeningHandSize = table.Column(type: "integer", nullable: false),
+ FirstPlayerSkipsDraw = table.Column(type: "boolean", nullable: false),
+ SpAccumulationPerTurn = table.Column(type: "integer", nullable: false),
+ DrawPerTurn = table.Column(type: "integer", nullable: false),
+ SpHasCap = table.Column(type: "boolean", nullable: false),
+ SpCap = table.Column(type: "integer", nullable: false),
+ BoardWidth = table.Column(type: "integer", nullable: false),
+ BoardHeight = table.Column(type: "integer", nullable: false),
+ CreatedAt = table.Column(type: "timestamp with time zone", nullable: false),
+ UpdatedAt = table.Column(type: "timestamp with time zone", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_game_rule_sets", x => x.Id);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_custom_lobbies_HostAccountId",
+ schema: "game",
+ table: "custom_lobbies",
+ column: "HostAccountId");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_custom_lobbies_Status_CreatedAt",
+ schema: "game",
+ table: "custom_lobbies",
+ columns: new[] { "Status", "CreatedAt" });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_game_rule_sets_IsCustomDefault",
+ schema: "game",
+ table: "game_rule_sets",
+ column: "IsCustomDefault");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_game_rule_sets_IsRankedDefault",
+ schema: "game",
+ table: "game_rule_sets",
+ column: "IsRankedDefault");
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "custom_lobbies",
+ schema: "game");
+
+ migrationBuilder.DropTable(
+ name: "game_rule_sets",
+ schema: "game");
+
+ migrationBuilder.DropColumn(
+ name: "rule_snapshot",
+ schema: "game",
+ table: "game_sessions");
+ }
+ }
+}
diff --git a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs
index 9d86efd..e7b56fa 100644
--- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs
+++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs
@@ -23,6 +23,65 @@ namespace SOR.Database.Migrations.Game
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+ modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ 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("HostAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("HostDeckId")
+ .HasColumnType("uuid");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OpeningHandSizeOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpAccumulationPerTurnOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpCapOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpHasCapOverride")
+ .HasColumnType("boolean");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasColumnType("text");
+
+ 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")
@@ -59,6 +118,61 @@ namespace SOR.Database.Migrations.Game
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("DrawPerTurn")
+ .HasColumnType("integer");
+
+ b.Property("FirstPlayerSkipsDraw")
+ .HasColumnType("boolean");
+
+ b.Property("IsCustomDefault")
+ .HasColumnType("boolean");
+
+ b.Property("IsRankedDefault")
+ .HasColumnType("boolean");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OpeningHandSize")
+ .HasColumnType("integer");
+
+ b.Property("SpAccumulationPerTurn")
+ .HasColumnType("integer");
+
+ b.Property("SpCap")
+ .HasColumnType("integer");
+
+ b.Property("SpHasCap")
+ .HasColumnType("boolean");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ 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")
@@ -89,6 +203,10 @@ namespace SOR.Database.Migrations.Game
b.Property("PlayerTwoReady")
.HasColumnType("boolean");
+ b.Property("RuleSnapshotJson")
+ .HasColumnType("jsonb")
+ .HasColumnName("rule_snapshot");
+
b.Property("StartedAt")
.HasColumnType("timestamp with time zone");
diff --git a/Server/src/SOR.Game/Abilities/AbilitySystem.cs b/Server/src/SOR.Game/Abilities/AbilitySystem.cs
new file mode 100644
index 0000000..f63b3ee
--- /dev/null
+++ b/Server/src/SOR.Game/Abilities/AbilitySystem.cs
@@ -0,0 +1,16 @@
+namespace SOR.Game.Abilities;
+
+///
+/// Ability activation and resolution stub.
+///
+/// Full ability model is defined in Shared/context-files/abilities.md.
+/// Types: Activated, Triggered, Static, Instinct.
+/// Costs: SP, ST, discard, mill, self-damage, etc.
+/// Targets: units, tiles, players, zones.
+/// Durations: UntilEndOfTurn, UntilStartOfOwnerTurn, ForNTurns, WhileCondition, PermanentInMatch.
+///
+/// TODO: Implement full ability model in a future pass.
+///
+public static class AbilitySystem
+{
+}
diff --git a/Server/src/SOR.Game/Combat/AttackSystem.cs b/Server/src/SOR.Game/Combat/AttackSystem.cs
new file mode 100644
index 0000000..d065fd9
--- /dev/null
+++ b/Server/src/SOR.Game/Combat/AttackSystem.cs
@@ -0,0 +1,54 @@
+namespace SOR.Game.Combat;
+
+using SOR.Game.Grid;
+
+///
+/// Attack range and line-of-sight validation for Spirit/ArchSpirit attacks (§6.10).
+///
+/// Range uses Manhattan distance on the square grid.
+/// LOS is required only when the attacker's RequiresLos flag is set.
+///
+public static class AttackSystem
+{
+ ///
+ /// Returns true if the attacker can legally target the given position.
+ ///
+ public static bool CanAttack(
+ Coord attackerPos,
+ Coord targetPos,
+ int minRange,
+ int maxRange,
+ bool requiresLos,
+ Board board,
+ IReadOnlyDictionary unitsByCoord)
+ {
+ var dist = attackerPos.ManhattanDistance(targetPos);
+ if (dist < minRange || dist > maxRange) return false;
+
+ if (requiresLos && !LineOfSight.HasLos(board, attackerPos, targetPos, unitsByCoord))
+ return false;
+
+ return true;
+ }
+
+ ///
+ /// Enumerate all in-bounds tiles the attacker can target from its current position.
+ ///
+ public static IEnumerable GetAttackableCoords(
+ Board board,
+ Coord attackerPos,
+ int minRange,
+ int maxRange,
+ bool requiresLos,
+ IReadOnlyDictionary unitsByCoord)
+ {
+ for (int dy = -maxRange; dy <= maxRange; dy++)
+ for (int dx = -maxRange; dx <= maxRange; dx++)
+ {
+ var target = new Coord(attackerPos.X + dx, attackerPos.Y + dy);
+ if (!board.IsInBounds(target)) continue;
+ if (CanAttack(attackerPos, target, minRange, maxRange, requiresLos, board, unitsByCoord))
+ yield return target;
+ }
+ }
+}
diff --git a/Server/src/SOR.Game/Combat/SacrificeSystem.cs b/Server/src/SOR.Game/Combat/SacrificeSystem.cs
new file mode 100644
index 0000000..af6aba6
--- /dev/null
+++ b/Server/src/SOR.Game/Combat/SacrificeSystem.cs
@@ -0,0 +1,55 @@
+namespace SOR.Game.Combat;
+
+///
+/// Sacrifice action computations (§6.15).
+///
+/// Sacrifice is a free action (no attack/ability use expended).
+/// The sacrificed Spirit must be orthogonally adjacent to the player's ArchSpirit.
+/// ST earned is a function of the current ST total and the Spirit's SpiritSacValue.
+///
+public static class SacrificeSystem
+{
+ ///
+ /// Compute SpiritSacValue for a Spirit with the given costs.
+ /// SpiritSacValue = (CardSTCost * 3) + CardSPCost
+ ///
+ public static int GetSacrificeValue(int stCost, int spCost)
+ => (stCost * 3) + spCost;
+
+ ///
+ /// Compute the ST earned from a sacrifice, given current ST and the Spirit's SpiritSacValue.
+ /// Exact formula from gameplay.md §6.15.
+ ///
+ public static int GetSTReturn(int currentST, int spiritSacValue)
+ {
+ if (currentST == 0)
+ {
+ if (spiritSacValue <= 15) return 1;
+ if (spiritSacValue >= 16) return 2;
+ }
+ else if (currentST == 1)
+ {
+ if (spiritSacValue <= 2) return 0;
+ if (spiritSacValue >= 3 && spiritSacValue <= 15) return 1;
+ if (spiritSacValue >= 16) return 2;
+ }
+ else if (currentST == 2)
+ {
+ if (spiritSacValue <= 6) return 0;
+ if (spiritSacValue >= 7 && spiritSacValue <= 15) return 1;
+ if (spiritSacValue >= 16) return 2;
+ }
+ else if (currentST == 3)
+ {
+ if (spiritSacValue <= 9) return 0;
+ if (spiritSacValue >= 10 && spiritSacValue <= 15) return 1;
+ if (spiritSacValue >= 16) return 2;
+ }
+ else if (currentST >= 4)
+ {
+ return 0;
+ }
+
+ return 0;
+ }
+}
diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs
index ed721c4..fed3ed7 100644
--- a/Server/src/SOR.Game/GameEngine.cs
+++ b/Server/src/SOR.Game/GameEngine.cs
@@ -1,29 +1,40 @@
namespace SOR.Game;
using System.Text.Json;
+using System.Text.Json.Serialization;
using SOR.Database.Entities.Catalog;
using SOR.Database.Enums;
+using SOR.Game.Combat;
+using SOR.Game.Grid;
///
/// Pure game logic — no database access, no DI. Takes a GameState, mutates it,
/// returns the updated state. Handlers are responsible for loading and saving.
///
+/// Turn flow:
+/// 1. game.ready (both players) → Placement phase, board created.
+/// 2. game.place_arch_spirit (both players) → affinities pushed, opening draw, turn 1 begins.
+/// 3. Draw → Main → EndTurn → (repeat).
+///
/// Rules applied (per gameplay.md + user spec):
-/// - Opening hand: all players draw OpeningHandSize cards at game start.
+/// - Opening hand: both players draw OpeningHandSize cards after placement.
/// - P1 skips the Draw phase on turn 1 (FirstPlayerSkipsDraw).
-/// P2 draws 1 at the start of their turn → 7 cards total by their first turn.
/// - SP: starts at 0, accumulates SpAccumulationPerTurn per turn. Never resets.
/// - ST: starts at 0, earned only through sacrifice — never granted per turn.
-/// - No entry sickness: units can attack/move/ability the turn they are summoned.
-/// - Defense restores to MaxDefense at the start of each turn (§6.9.3).
+/// - No entry sickness: units can attack/move/sacrifice the turn they are channeled.
+/// - Defense restores to MaxDefense at the start of each player's turn (§6.9.3).
+/// - MP restores to MaxMp at the start of each player's turn (§6.0).
/// - Win condition: ArchSpirit destruction.
///
public static class GameEngine
{
- private static readonly JsonSerializerOptions _json =
- new(JsonSerializerDefaults.Web) { WriteIndented = false };
+ private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web)
+ {
+ WriteIndented = false,
+ Converters = { new JsonStringEnumConverter() },
+ };
- // ── Serialization ─────────────────────────────────────────────────────────
+ // ── Serialization ──────────────────────────────────────────────────────────
public static GameState Deserialize(string json)
=> JsonSerializer.Deserialize(json, _json)
@@ -36,23 +47,21 @@ public static class GameEngine
=> JsonSerializer.Deserialize(json, _json)
?? GameRules.Default;
- // ── Initialization ────────────────────────────────────────────────────────
+ // ── Initialization ─────────────────────────────────────────────────────────
///
/// Build the initial GameState from card definition data for both players.
///
- /// Both players draw OpeningHandSize cards into their opening hand.
- /// ArchSpirit cards are placed on the field as leaders (not in the deck pile).
- /// SP and ST start at 0 for all players.
+ /// The game starts in the Placement phase — both players must call PlaceArchSpirit
+ /// before the opening draw happens and turn 1 begins.
///
- /// If FirstPlayerSkipsDraw is true (the default), P1's first turn begins at
- /// Main phase — they already drew their opening hand. P2 gets a Draw phase at
- /// the start of their first turn, giving them one additional card (7 total).
+ /// Decks are shuffled. ArchSpirits are created but NOT yet placed on the board
+ /// (Position = null until PlaceArchSpirit is called).
///
public static GameState Initialize(
Guid sessionId,
- Guid p1AccountId, IEnumerable<(CardDefinition def, int qty)> p1Deck, Guid p1ArchSpiritDefId, CardDefinition p1ArchSpirit,
- Guid p2AccountId, IEnumerable<(CardDefinition def, int qty)> p2Deck, Guid p2ArchSpiritDefId, CardDefinition p2ArchSpirit,
+ Guid p1AccountId, IEnumerable<(CardDefinition def, int qty)> p1Deck, CardDefinition p1ArchSpirit,
+ Guid p2AccountId, IEnumerable<(CardDefinition def, int qty)> p2Deck, CardDefinition p2ArchSpirit,
GameRules? rules = null)
{
rules ??= GameRules.Default;
@@ -62,28 +71,84 @@ public static class GameEngine
SessionId = sessionId,
TurnNumber = 1,
ActivePlayerAccountId = p1AccountId.ToString(),
+ PlayerOneAccountId = p1AccountId.ToString(),
Rules = rules,
+ Phase = GamePhase.Placement,
+ Board = Board.Create(rules.BoardWidth, rules.BoardHeight),
};
state.Players[p1AccountId.ToString()] = BuildPlayerState(p1AccountId, p1Deck, p1ArchSpirit);
state.Players[p2AccountId.ToString()] = BuildPlayerState(p2AccountId, p2Deck, p2ArchSpirit);
- // Both players draw their opening hand.
- DrawCards(state.Players[p1AccountId.ToString()], rules.OpeningHandSize);
- DrawCards(state.Players[p2AccountId.ToString()], rules.OpeningHandSize);
-
- // P1's first turn: skip Draw phase (they drew their opening hand already).
- // P2's first turn will begin at Draw phase — they draw 1 more card there.
- state.Phase = rules.FirstPlayerSkipsDraw ? GamePhase.Main : GamePhase.Draw;
-
return state;
}
- // ── Actions ───────────────────────────────────────────────────────────────
+ // ── Actions ────────────────────────────────────────────────────────────────
+
+ ///
+ /// Place the player's ArchSpirit on their starting row (Placement phase).
+ ///
+ /// P1 must place in row y=0; P2 must place in row y=Height-1.
+ /// Affinity is pushed to the placement tile and all in-bounds orthogonal neighbors.
+ ///
+ /// When both players have placed, the opening draw is performed and turn 1 begins.
+ /// Returns whether both players are now placed (game can advance).
+ ///
+ public static (GameState state, bool bothPlaced) PlaceArchSpirit(
+ GameState state, string actorId, Coord coord)
+ {
+ ValidatePhase(state, GamePhase.Placement);
+
+ var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
+ var player = state.Players[actorId];
+
+ var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
+ if (archSpirit.Position.HasValue) throw new GameException("ARCH_SPIRIT_ALREADY_PLACED");
+
+ // Validate placement row.
+ bool isP1 = actorId == state.PlayerOneAccountId;
+ int expectedRow = isP1 ? 0 : board.Height - 1;
+ if (coord.Y != expectedRow) throw new GameException("INVALID_PLACEMENT_ROW");
+
+ // Validate tile.
+ var tile = board.GetTile(coord) ?? throw new GameException("TILE_OUT_OF_BOUNDS");
+ if (!tile.IsEmpty) throw new GameException("TILE_OCCUPIED");
+
+ // Place ArchSpirit.
+ archSpirit.Position = coord;
+ archSpirit.CurrentMp = archSpirit.MaxMp ?? 0;
+ board.PlaceUnit(coord, archSpirit.InstanceId, actorId);
+
+ // Push placement affinity.
+ if (Enum.TryParse(archSpirit.Affinity, out var affinity))
+ AffinitySystem.ApplyPlacementAffinity(board, coord, affinity);
+
+ // Check if both players have placed.
+ bool bothPlaced = state.Players.Values.All(p => p.ArchSpirit?.Position.HasValue == true);
+
+ if (bothPlaced)
+ {
+ var rules = state.Rules;
+ // Opening draw for both players.
+ foreach (var p in state.Players.Values)
+ DrawCards(p, rules.OpeningHandSize);
+
+ // P1 gets first-turn SP accumulation.
+ var p1 = state.Players[state.PlayerOneAccountId];
+ p1.CurrentSp += rules.SpAccumulationPerTurn;
+ if (rules.SpHasCap && p1.CurrentSp > rules.SpCap)
+ p1.CurrentSp = rules.SpCap;
+
+ // Advance to first turn phase.
+ state.Phase = rules.FirstPlayerSkipsDraw ? GamePhase.Main : GamePhase.Draw;
+ }
+
+ return (state, bothPlaced);
+ }
///
/// Draw the top card from the active player's deck into hand.
- /// Returns null if the deck is empty (no mill — just no draw).
+ /// Returns null if the deck is empty (no mill).
///
public static (GameState state, CardInstance? drawn) Draw(GameState state, string actorId)
{
@@ -105,11 +170,16 @@ public static class GameEngine
}
///
- /// Play a card from hand onto the field (non-ArchSpirit cards only).
- /// Deducts SP/ST cost. Units can attack, move, and use abilities immediately
- /// (no entry sickness).
+ /// Channel (play) a card from hand.
+ ///
+ /// Spirit cards require a TargetTile within the ArchSpirit's channeling range
+ /// and valid affinity on the target tile. They are placed on the board at that tile.
+ ///
+ /// Other card types (Repentance, Instinct, Ruin, Terramorpha) do not require a tile
+ /// in this initial implementation — effect resolution is handled by AbilitySystem (future).
///
- public static GameState PlayCard(GameState state, string actorId, string cardInstanceId)
+ public static GameState ChannelCard(
+ GameState state, string actorId, string cardInstanceId, Coord? targetTile)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
@@ -118,10 +188,36 @@ public static class GameEngine
var card = player.Hand.FirstOrDefault(c => c.InstanceId == cardInstanceId)
?? throw new GameException("CARD_NOT_IN_HAND");
- if (player.CurrentSp < card.SpCost)
- throw new GameException("INSUFFICIENT_SP");
- if (player.CurrentSt < card.StCost)
- throw new GameException("INSUFFICIENT_ST");
+ if (player.CurrentSp < card.SpCost) throw new GameException("INSUFFICIENT_SP");
+ if (player.CurrentSt < card.StCost) throw new GameException("INSUFFICIENT_ST");
+
+ var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
+
+ if (card.CardType == "Spirit")
+ {
+ if (!targetTile.HasValue) throw new GameException("TARGET_TILE_REQUIRED");
+
+ var tile = board.GetTile(targetTile.Value)
+ ?? throw new GameException("TILE_OUT_OF_BOUNDS");
+ if (!tile.IsEmpty) throw new GameException("TILE_OCCUPIED");
+
+ // Validate channeling range from ArchSpirit.
+ var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
+ if (archSpirit.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED");
+
+ var minRange = card.MinChannelRange ?? 1;
+ var maxRange = card.MaxChannelRange ?? 1;
+ var dist = archSpirit.Position.Value.ManhattanDistance(targetTile.Value);
+ if (dist < minRange || dist > maxRange)
+ throw new GameException("OUT_OF_CHANNEL_RANGE");
+
+ // Validate affinity.
+ if (Enum.TryParse(card.Affinity, out var cardAffinity))
+ {
+ if (!AffinitySystem.IsAffinityValid(tile, cardAffinity))
+ throw new GameException("INVALID_AFFINITY");
+ }
+ }
player.Hand.Remove(card);
player.CurrentSp -= card.SpCost;
@@ -144,12 +240,90 @@ public static class GameEngine
Damage = card.Damage,
CanAttack = card.CanAttack,
CanDefend = card.CanDefend,
- IsExhausted = false,
+ CanMove = card.CanMove,
+ MovementType = card.MovementType,
+ MaxMp = card.MaxMp,
+ CurrentMp = card.MaxMp ?? 0,
+ MinAttackRange = card.MinAttackRange,
+ MaxAttackRange = card.MaxAttackRange,
+ RequiresLos = card.RequiresLos,
+ MinChannelRange = card.MinChannelRange,
+ MaxChannelRange = card.MaxChannelRange,
IsLeader = false,
+ IsExhausted = false,
+ Position = targetTile,
};
player.Field.Add(field);
+ if (targetTile.HasValue)
+ board.PlaceUnit(targetTile.Value, field.InstanceId, actorId);
+
+ return state;
+ }
+
+ ///
+ /// Move a unit on the board.
+ ///
+ /// Walk/Flight: BFS pathfinding within the unit's remaining MP.
+ /// Walk: all occupied tiles block pathing.
+ /// Flight: only tiles occupied by other Flight units block pathing.
+ ///
+ /// Jump: can land on any empty in-bounds tile; costs 1 MP per landing.
+ /// Teleport: same as Jump but requires line-of-sight to the destination; costs 1 MP.
+ ///
+ public static GameState MoveUnit(
+ GameState state, string actorId, string unitInstanceId, Coord targetPos)
+ {
+ ValidateActivePlayer(state, actorId);
+ ValidatePhase(state, GamePhase.Main);
+
+ var board = state.Board ?? throw new GameException("BOARD_NOT_INITIALIZED");
+ var player = state.Players[actorId];
+ var unit = GetFieldCard(player, unitInstanceId);
+
+ if (unit.Position is null) throw new GameException("UNIT_NOT_ON_BOARD");
+ if (unit.CurrentMp <= 0) throw new GameException("NO_MP");
+
+ var from = unit.Position.Value;
+ var targetTile = board.GetTile(targetPos) ?? throw new GameException("TILE_OUT_OF_BOUNDS");
+ if (!targetTile.IsEmpty) throw new GameException("TILE_OCCUPIED");
+ if (from == targetPos) throw new GameException("ALREADY_AT_TARGET");
+
+ var movType = unit.MovementType;
+
+ if (movType == MovementType.Walk || movType == MovementType.Flight)
+ {
+ var blocked = BuildBlockedSet(state, unitInstanceId, movType);
+ var reachable = Pathfinding.GetReachableWithCost(board, from, unit.CurrentMp, blocked);
+
+ if (!reachable.TryGetValue(targetPos, out var cost))
+ throw new GameException("TILE_UNREACHABLE");
+
+ unit.CurrentMp -= cost;
+ }
+ else if (movType == MovementType.Jump)
+ {
+ unit.CurrentMp -= 1;
+ }
+ else if (movType == MovementType.Teleport)
+ {
+ var occupancy = board.BuildOccupancyMap();
+ occupancy.Remove(from); // exclude self from LOS check
+
+ if (!LineOfSight.HasLos(board, from, targetPos, occupancy))
+ throw new GameException("NO_LINE_OF_SIGHT");
+
+ unit.CurrentMp -= 1;
+ }
+ else
+ {
+ throw new GameException("UNIT_CANNOT_MOVE");
+ }
+
+ unit.Position = targetPos;
+ board.MoveUnit(unitInstanceId, targetPos);
+
return state;
}
@@ -157,9 +331,9 @@ public static class GameEngine
/// Declare an attack from one of the active player's field cards against an
/// opponent's field card (or their ArchSpirit).
///
+ /// Range and LOS are validated against the board when present.
/// Combat: attacker damage hits defender's defense first; overflow hits health.
/// Defender counter-attacks (damage hits attacker's health directly if no defense).
- /// Destroyed units move to the Discard pile.
/// If the defending ArchSpirit is destroyed the game ends.
///
public static (GameState state, bool gameOver) Attack(
@@ -172,39 +346,55 @@ public static class GameEngine
ValidatePhase(state, GamePhase.Main);
var opponentId = GetOpponentId(state, actorId);
- var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
- var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
+ var attacker = GetFieldCard(state.Players[actorId], attackerInstanceId);
+ var target = GetFieldCard(state.Players[opponentId], targetInstanceId);
- if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
- if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK");
+ if (attacker.IsExhausted) throw new GameException("CARD_EXHAUSTED");
+ if (!attacker.CanAttack) throw new GameException("CARD_CANNOT_ATTACK");
+
+ // Range + LOS validation when board is active.
+ if (state.Board is not null && attacker.Position.HasValue && target.Position.HasValue)
+ {
+ var occupancy = state.Board.BuildOccupancyMap();
+ var minRange = attacker.MinAttackRange ?? 1;
+ var maxRange = attacker.MaxAttackRange ?? 1;
+
+ if (!AttackSystem.CanAttack(
+ attacker.Position.Value, target.Position.Value,
+ minRange, maxRange, attacker.RequiresLos,
+ state.Board, occupancy))
+ throw new GameException("TARGET_OUT_OF_RANGE");
+ }
// Attacker hits target.
ApplyDamage(target, attacker.Damage ?? 0);
- // Target counter-attacks if able (and still alive).
+ // Target counter-attacks if able and still alive.
if (target.CurrentHealth > 0 && target.CanAttack && !target.IsExhausted)
ApplyDamage(attacker, target.Damage ?? 0);
attacker.IsExhausted = true;
- // Clean up destroyed cards.
bool gameOver = false;
var activePlayer = state.Players[actorId];
var opponentPlayer = state.Players[opponentId];
if (attacker.CurrentHealth <= 0)
+ {
+ if (state.Board is not null) state.Board.RemoveUnit(attacker.InstanceId);
MoveToDiscard(activePlayer, attacker);
+ }
if (target.CurrentHealth <= 0)
{
if (target.IsLeader)
{
- // ArchSpirit destroyed — game over.
state.Phase = GamePhase.GameOver;
gameOver = true;
}
else
{
+ if (state.Board is not null) state.Board.RemoveUnit(target.InstanceId);
MoveToDiscard(opponentPlayer, target);
}
}
@@ -212,52 +402,84 @@ public static class GameEngine
return (state, gameOver);
}
+ ///
+ /// Sacrifice a Spirit adjacent to the player's ArchSpirit (§6.15).
+ /// Sacrifice is a free action — does not exhaust the Spirit and does not consume
+ /// attack or ability uses.
+ ///
+ public static GameState Sacrifice(GameState state, string actorId, string unitInstanceId)
+ {
+ ValidateActivePlayer(state, actorId);
+ ValidatePhase(state, GamePhase.Main);
+
+ var player = state.Players[actorId];
+ var unit = player.Field.OfType()
+ .FirstOrDefault(c => c.InstanceId == unitInstanceId)
+ ?? throw new GameException("UNIT_NOT_ON_FIELD");
+
+ if (unit.IsLeader) throw new GameException("CANNOT_SACRIFICE_ARCH_SPIRIT");
+
+ var archSpirit = player.ArchSpirit ?? throw new GameException("NO_ARCH_SPIRIT");
+ if (archSpirit.Position is null) throw new GameException("ARCH_SPIRIT_NOT_PLACED");
+ if (unit.Position is null) throw new GameException("UNIT_NOT_ON_BOARD");
+
+ if (!unit.Position.Value.IsOrthogonallyAdjacentTo(archSpirit.Position.Value))
+ throw new GameException("UNIT_NOT_ADJACENT_TO_ARCH_SPIRIT");
+
+ var sacValue = SacrificeSystem.GetSacrificeValue(unit.StCost, unit.SpCost);
+ var stReturn = SacrificeSystem.GetSTReturn(player.CurrentSt, sacValue);
+ player.CurrentSt += stReturn;
+
+ if (state.Board is not null) state.Board.RemoveUnit(unitInstanceId);
+ player.Field.Remove(unit);
+ player.Discard.Add(unit);
+
+ return state;
+ }
+
///
/// End the active player's turn.
///
- /// Per §6.0 (start-of-turn order):
- /// 1. MP restore (not yet implemented — no positional grid in v1)
- /// 2. Defense restoration for the NEXT player's units (§6.9.3)
- /// 3. SP gain for the next player
- /// 4. Draw phase
+ /// Per §6.0 (applied at start of next player's turn):
+ /// 1. MP restoration for all friendly units.
+ /// 2. Defense restoration for all friendly units.
+ /// 3. SP accumulation.
+ /// 4. Advance to Draw phase.
///
- /// Note: IsExhausted resets for the ENDING player's units (they finished acting).
- /// Defense restores for the STARTING player's units (at the top of their turn).
- /// These apply to different players — restoring defense for the wrong player
- /// would let the opponent attack into fully-restored defense every single turn.
+ /// IsExhausted resets for the ENDING player's units (they finished acting).
+ /// MP + Defense restore for the STARTING player (at the top of their turn).
///
public static GameState EndTurn(GameState state, string actorId)
{
ValidateActivePlayer(state, actorId);
ValidatePhase(state, GamePhase.Main);
- // End of active player's turn: reset exhausted status only.
- // Defense does NOT restore here — it restores at start of that player's NEXT turn.
+ // Reset exhausted for the player ending their turn.
var active = state.Players[actorId];
- foreach (var card in active.Field)
+ foreach (var card in active.Field.OfType())
card.IsExhausted = false;
if (active.ArchSpirit is not null)
active.ArchSpirit.IsExhausted = false;
// Switch active player.
state.ActivePlayerAccountId = GetOpponentId(state, actorId);
+ state.TurnNumber++;
- // Start of next player's turn: restore their defense (§6.9.3), accumulate SP.
+ // Start of next player's turn: restore MP, defense, accumulate SP.
var next = state.Players[state.ActivePlayerAccountId];
var rules = state.Rules;
- state.TurnNumber++;
-
- // Defense restores for the player whose turn is starting.
- foreach (var card in next.Field)
+ foreach (var card in next.Field.OfType())
{
- if (card.MaxDefense.HasValue)
- card.CurrentDefense = card.MaxDefense;
+ if (card.MaxMp.HasValue) card.CurrentMp = card.MaxMp.Value;
+ if (card.MaxDefense.HasValue) card.CurrentDefense = card.MaxDefense;
+ }
+ if (next.ArchSpirit is not null)
+ {
+ if (next.ArchSpirit.MaxMp.HasValue) next.ArchSpirit.CurrentMp = next.ArchSpirit.MaxMp.Value;
+ if (next.ArchSpirit.MaxDefense.HasValue) next.ArchSpirit.CurrentDefense = next.ArchSpirit.MaxDefense;
}
- if (next.ArchSpirit is not null && next.ArchSpirit.MaxDefense.HasValue)
- next.ArchSpirit.CurrentDefense = next.ArchSpirit.MaxDefense;
- // SP accumulates — never resets between turns.
next.CurrentSp += rules.SpAccumulationPerTurn;
if (rules.SpHasCap && next.CurrentSp > rules.SpCap)
next.CurrentSp = rules.SpCap;
@@ -298,21 +520,20 @@ public static class GameEngine
CurrentSt : p.CurrentSt);
});
+ var boardDto = state.Board is not null ? ToBoardDto(state.Board) : null;
+
return new GameStateDto(
SessionId : state.SessionId,
Phase : state.Phase.ToString(),
ActivePlayerAccountId : state.ActivePlayerAccountId,
TurnNumber : state.TurnNumber,
StateVersion : state.NextActionSequence,
- Players : players);
+ Players : players,
+ Board : boardDto);
}
- // ── ELO ──────────────────────────────────────────────────────────────────
+ // ── ELO ───────────────────────────────────────────────────────────────────
- ///
- /// Compute ELO rank score deltas after a game.
- /// Returns (winnerDelta, loserDelta) — both are positive values indicating change magnitude.
- ///
public static (int winnerDelta, int loserDelta) ComputeEloDelta(int winnerScore, int loserScore)
{
const double K = 32.0;
@@ -331,7 +552,6 @@ public static class GameEngine
{
var ps = new PlayerState { AccountId = accountId.ToString() };
- // Build deck pile (expand by quantity).
var pile = new List();
foreach (var (def, qty) in deckCards)
{
@@ -348,7 +568,7 @@ public static class GameEngine
}
ps.Deck = pile;
- // ArchSpirit starts on the field as the leader.
+ // ArchSpirit: created but not yet placed (Position = null, CurrentMp = 0 until placed).
ps.ArchSpirit = new FieldCard
{
InstanceId = $"arch_{accountId:N}"[..8],
@@ -362,12 +582,22 @@ public static class GameEngine
MaxDefense = archSpiritDef.MaxDefense,
CurrentDefense = archSpiritDef.MaxDefense,
Damage = archSpiritDef.Damage,
- CanAttack = archSpiritDef.CanAttack ?? false,
- CanDefend = archSpiritDef.CanDefend ?? false,
+ CanAttack = archSpiritDef.CanAttack ?? false,
+ CanDefend = archSpiritDef.CanDefend ?? false,
+ CanMove = archSpiritDef.CanMove ?? false,
+ MovementType = archSpiritDef.MovementType,
+ MaxMp = archSpiritDef.MovementPoints,
+ CurrentMp = 0, // set when placed during Placement phase
+ MinAttackRange = archSpiritDef.MinAttackRange,
+ MaxAttackRange = archSpiritDef.MaxAttackRange,
+ RequiresLos = archSpiritDef.RequiresLos ?? false,
+ MinChannelRange = archSpiritDef.MinChannelRange,
+ MaxChannelRange = archSpiritDef.MaxChannelRange,
IsLeader = true,
+ IsExhausted = false,
+ Position = null,
};
- // SP and ST start at 0 for all players.
ps.CurrentSp = 0;
ps.CurrentSt = 0;
@@ -390,8 +620,16 @@ public static class GameEngine
MaxDefense = def.MaxDefense,
CurrentDefense = def.MaxDefense,
Damage = def.Damage,
- CanAttack = def.CanAttack ?? false,
- CanDefend = def.CanDefend ?? false,
+ CanAttack = def.CanAttack ?? false,
+ CanDefend = def.CanDefend ?? false,
+ CanMove = def.CanMove ?? false,
+ MovementType = def.MovementType,
+ MaxMp = def.MovementPoints,
+ MinAttackRange = def.MinAttackRange,
+ MaxAttackRange = def.MaxAttackRange,
+ RequiresLos = def.RequiresLos ?? false,
+ MinChannelRange = def.MinChannelRange,
+ MaxChannelRange = def.MaxChannelRange,
};
private static void DrawCards(PlayerState player, int count)
@@ -440,6 +678,30 @@ public static class GameEngine
private static string GetOpponentId(GameState state, string actorId)
=> state.Players.Keys.First(k => k != actorId);
+ private static HashSet BuildBlockedSet(
+ GameState state, string movingUnitId, MovementType? movType)
+ {
+ var blocked = new HashSet();
+ foreach (var player in state.Players.Values)
+ {
+ foreach (var card in player.Field.OfType())
+ {
+ if (card.InstanceId == movingUnitId) continue;
+ if (!card.Position.HasValue) continue;
+ // Flight is blocked only by other Flight units; Walk is blocked by all.
+ if (movType == MovementType.Flight && card.MovementType != MovementType.Flight) continue;
+ blocked.Add(card.Position.Value);
+ }
+ var arch = player.ArchSpirit;
+ if (arch is not null && arch.InstanceId != movingUnitId && arch.Position.HasValue)
+ {
+ if (movType != MovementType.Flight || arch.MovementType == MovementType.Flight)
+ blocked.Add(arch.Position.Value);
+ }
+ }
+ return blocked;
+ }
+
private static void ValidateActivePlayer(GameState state, string actorId)
{
if (state.ActivePlayerAccountId != actorId)
@@ -453,7 +715,9 @@ public static class GameEngine
}
private static CardInstanceDto ToCardDto(CardInstance c)
- => new(
+ {
+ var fc = c as FieldCard;
+ return new(
InstanceId : c.InstanceId,
CardDefinitionId : c.CardDefinitionId,
Name : c.Name,
@@ -466,7 +730,26 @@ public static class GameEngine
MaxDefense : c.MaxDefense,
Damage : c.Damage,
IsExhausted : c.IsExhausted,
- IsLeader : c is FieldCard fc && fc.IsLeader);
+ IsLeader : c.IsLeader,
+ Position : fc?.Position.HasValue == true
+ ? new CoordDto(fc.Position.Value.X, fc.Position.Value.Y) : null,
+ CurrentMp : fc?.CurrentMp,
+ MaxMp : c.MaxMp,
+ MovementType : c.MovementType?.ToString());
+ }
+
+ private static BoardDto ToBoardDto(Board board)
+ {
+ var tiles = board.Tiles.Values.Select(t => new TileDto(
+ Coord : new CoordDto(t.Coord.X, t.Coord.Y),
+ Base1 : t.Base1.ToString(),
+ Base2 : t.Base2.ToString(),
+ ResolvedAffinity : AffinitySystem.Resolve(t.Base1, t.Base2).ToString(),
+ OccupantId : t.OccupantId,
+ OccupantOwner : t.OccupantOwner));
+
+ return new BoardDto(board.Width, board.Height, tiles);
+ }
}
/// Game-rule violation — maps to a client error code.
diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs
index 16d467f..ef13753 100644
--- a/Server/src/SOR.Game/GameMessages.cs
+++ b/Server/src/SOR.Game/GameMessages.cs
@@ -11,8 +11,20 @@ public sealed record GameGetStateRequest(Guid SessionId);
/// Draw a card from the player's deck.
public sealed record GameDrawRequest(Guid SessionId);
-/// Play a card from hand onto the field.
-public sealed record GamePlayCardRequest(Guid SessionId, string CardInstanceId);
+///
+/// Place the player's ArchSpirit on their starting row (Placement phase only).
+/// P1 must place in row y=0; P2 must place in row y=Height-1.
+///
+public sealed record GamePlaceArchSpiritRequest(Guid SessionId, CoordDto Position);
+
+///
+/// Channel (play) a card from hand. Spirit cards require a TargetTile within
+/// the ArchSpirit's channeling range; other card types may omit it.
+///
+public sealed record GamePlayCardRequest(Guid SessionId, string CardInstanceId, CoordDto? TargetTile = null);
+
+/// Move a unit on the board to a new tile.
+public sealed record GameMoveUnitRequest(Guid SessionId, string UnitInstanceId, CoordDto TargetPosition);
/// Attack an opponent card (or their ArchSpirit) with one of your field cards.
public sealed record GameAttackRequest(
@@ -20,6 +32,12 @@ public sealed record GameAttackRequest(
string AttackerInstanceId,
string TargetInstanceId);
+///
+/// Sacrifice one of your Spirits adjacent to your ArchSpirit (§6.15).
+/// Sacrifice is a free action — does not consume an attack or ability use.
+///
+public sealed record GameSacrificeRequest(Guid SessionId, string UnitInstanceId);
+
/// End the active player's turn.
public sealed record GameEndTurnRequest(Guid SessionId);
@@ -44,7 +62,9 @@ public sealed record CustomRulesOverride(
int? SpAccumulationPerTurn = null,
int? DrawPerTurn = null,
bool? SpHasCap = null,
- int? SpCap = null);
+ int? SpCap = null,
+ int? BoardWidth = null,
+ int? BoardHeight = null);
/// Join an open custom lobby with the specified deck.
public sealed record JoinCustomLobbyRequest(Guid LobbyId, Guid DeckId);
@@ -64,10 +84,16 @@ public sealed record GameGetStateResponse(GameStateDto State);
public sealed record GameDrawResponse(GameStateDto State);
+public sealed record GamePlaceArchSpiritResponse(GameStateDto State);
+
public sealed record GamePlayCardResponse(GameStateDto State);
+public sealed record GameMoveUnitResponse(GameStateDto State);
+
public sealed record GameAttackResponse(GameStateDto State);
+public sealed record GameSacrificeResponse(GameStateDto State);
+
public sealed record GameEndTurnResponse(GameStateDto State);
public sealed record GameConcedeResponse(GameStateDto State);
@@ -130,11 +156,12 @@ public sealed record CustomLobbyGameStartedPush(
///
public sealed record GameStateDto(
Guid SessionId,
- string Phase, // Draw | Main | End | GameOver
+ string Phase, // Placement | Draw | Main | End | GameOver
string ActivePlayerAccountId,
int TurnNumber,
int StateVersion, // monotonic; use for client mismatch detection
- IEnumerable Players);
+ IEnumerable Players,
+ BoardDto? Board); // full board state including tile affinities
public sealed record PlayerStateDto(
Guid AccountId,
@@ -148,19 +175,39 @@ public sealed record PlayerStateDto(
int CurrentSt);
public sealed record CardInstanceDto(
- string InstanceId,
- Guid CardDefinitionId,
- string Name,
- string CardType,
- string Affinity,
- string Rarity,
- int? CurrentHealth,
- int? MaxHealth,
- int? CurrentDefense,
- int? MaxDefense,
- int? Damage,
- bool IsExhausted,
- bool IsLeader); // true for the ArchSpirit
+ string InstanceId,
+ Guid CardDefinitionId,
+ string Name,
+ string CardType,
+ string Affinity,
+ string Rarity,
+ int? CurrentHealth,
+ int? MaxHealth,
+ int? CurrentDefense,
+ int? MaxDefense,
+ int? Damage,
+ bool IsExhausted,
+ bool IsLeader,
+ CoordDto? Position, // null when not on field or not yet placed
+ int? CurrentMp,
+ int? MaxMp,
+ string? MovementType); // enum as string, null for non-unit cards
+
+public sealed record BoardDto(
+ int Width,
+ int Height,
+ IEnumerable Tiles);
+
+public sealed record TileDto(
+ CoordDto Coord,
+ string Base1,
+ string Base2,
+ string ResolvedAffinity,
+ string? OccupantId,
+ string? OccupantOwner);
+
+/// Client-facing 2D coordinate.
+public sealed record CoordDto(int X, int Y);
public sealed record CustomLobbyDto(
Guid LobbyId,
@@ -176,4 +223,6 @@ public sealed record CustomRulesDto(
int SpAccumulationPerTurn,
int DrawPerTurn,
bool SpHasCap,
- int SpCap);
+ int SpCap,
+ int BoardWidth,
+ int BoardHeight);
diff --git a/Server/src/SOR.Game/GameRules.cs b/Server/src/SOR.Game/GameRules.cs
index 7333644..07e9740 100644
--- a/Server/src/SOR.Game/GameRules.cs
+++ b/Server/src/SOR.Game/GameRules.cs
@@ -5,11 +5,12 @@ namespace SOR.Game;
/// GameSession.RuleSnapshotJson when a game is initialized.
///
/// Defaults reflect the standard ruleset:
-/// - Both players draw 6 cards at game start.
-/// - P1 skips the Draw phase on turn 1 (they already drew their opening hand).
-/// P2 still draws once at the start of their first turn → 7 cards total.
+/// - Both players draw OpeningHandSize cards during opening placement draw.
+/// - P1 skips the Draw phase on turn 1 (FirstPlayerSkipsDraw).
+/// P2 still draws once at the start of their first turn.
/// - SP starts at 0, gains +3 per turn, never resets, no cap.
/// - Draw 1 card per turn during the Draw phase.
+/// - 8×8 battlefield.
///
public sealed record GameRules
{
@@ -19,6 +20,8 @@ public sealed record GameRules
public int DrawPerTurn { get; init; } = 1;
public bool SpHasCap { get; init; } = false;
public int SpCap { get; init; } = 0;
+ public int BoardWidth { get; init; } = 8;
+ public int BoardHeight { get; init; } = 8;
public static readonly GameRules Default = new();
}
diff --git a/Server/src/SOR.Game/GameState.cs b/Server/src/SOR.Game/GameState.cs
index b7877db..02a1739 100644
--- a/Server/src/SOR.Game/GameState.cs
+++ b/Server/src/SOR.Game/GameState.cs
@@ -1,6 +1,8 @@
namespace SOR.Game;
+using System.Text.Json.Serialization;
using SOR.Database.Enums;
+using SOR.Game.Grid;
///
/// Full live game state — serialized as JSONB in GameSession.StateJson.
@@ -15,14 +17,23 @@ public sealed class GameState
/// AccountId (as string) of the player whose turn it currently is.
public string ActivePlayerAccountId { get; set; } = string.Empty;
+ /// AccountId (as string) of the first player (P1). Determines placement row.
+ public string PlayerOneAccountId { get; set; } = string.Empty;
+
/// Per-player state, keyed by AccountId.ToString().
public Dictionary Players { get; set; } = new();
- /// Running sequence number for action log entries.
+ /// Running sequence number for action log / StateVersion.
public int NextActionSequence { get; set; } = 1;
/// Rules snapshot applied to this game session.
public GameRules Rules { get; set; } = GameRules.Default;
+
+ ///
+ /// The battlefield grid. Null only before the game session is initialized.
+ /// Created during GameEngine.Initialize and populated during the Placement phase.
+ ///
+ public Board? Board { get; set; }
}
public sealed class PlayerState
@@ -45,29 +56,35 @@ public sealed class PlayerState
public int CurrentSp { get; set; }
///
- /// Sacrifice Tokens — earned only by sacrificing Spirits (never granted per-turn).
- /// Starts at 0.
+ /// Sacrifice Tokens — earned by sacrificing Spirits (§6.15).
+ /// Starts at 0; never granted per turn.
///
public int CurrentSt { get; set; }
// ── Leader ───────────────────────────────────────────────────────────────
///
- /// The player's ArchSpirit — starts on the field at game start.
+ /// The player's ArchSpirit — placed during the Placement phase.
/// If destroyed the game ends (this player loses).
///
public FieldCard? ArchSpirit { get; set; }
}
///
-/// A card instance in play. Carries mutable combat state.
+/// A card instance in any zone. Carries mutable combat and positional state.
+///
+/// [JsonPolymorphic] is required so that FieldCard sub-type properties
+/// survive the GameState JSONB serialize/deserialize round-trip.
///
+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$t")]
+[JsonDerivedType(typeof(CardInstance), "c")]
+[JsonDerivedType(typeof(FieldCard), "f")]
public class CardInstance
{
/// Unique instance ID within the game session (not a DB id).
public string InstanceId { get; set; } = Guid.NewGuid().ToString("N")[..8];
- // ── Definition mirror (denormalized for performance) ─────────────────────
+ // ── Definition mirror ─────────────────────────────────────────────────────
public Guid CardDefinitionId { get; set; }
public string Name { get; set; } = string.Empty;
@@ -77,7 +94,7 @@ public class CardInstance
public int SpCost { get; set; }
public int StCost { get; set; }
- // ── Combat stats ─────────────────────────────────────────────────────────
+ // ── Combat stats ──────────────────────────────────────────────────────────
public int? MaxHealth { get; set; }
public int? CurrentHealth { get; set; }
@@ -85,22 +102,44 @@ public class CardInstance
public int? CurrentDefense { get; set; }
public int? Damage { get; set; }
- // ── State flags ──────────────────────────────────────────────────────────
+ // ── Movement ──────────────────────────────────────────────────────────────
- /// True if the card has already attacked or used an ability this turn.
+ public MovementType? MovementType { get; set; }
+ public int? MaxMp { get; set; }
+ public bool CanMove { get; set; }
+
+ // ── Attack ────────────────────────────────────────────────────────────────
+
+ public int? MinAttackRange { get; set; }
+ public int? MaxAttackRange { get; set; }
+ public bool RequiresLos { get; set; }
+
+ // ── Channeling ────────────────────────────────────────────────────────────
+
+ public int? MinChannelRange { get; set; }
+ public int? MaxChannelRange { get; set; }
+
+ // ── State flags ───────────────────────────────────────────────────────────
+
+ /// True if this unit has already attacked or used an ability this turn.
public bool IsExhausted { get; set; }
- // ── Field flags ──────────────────────────────────────────────────────────
+ /// True for the player's ArchSpirit (the win-condition target).
+ public bool IsLeader { get; set; }
- public bool CanAttack { get; set; }
- public bool CanDefend { get; set; }
+ public bool CanAttack { get; set; }
+ public bool CanDefend { get; set; }
}
///
-/// A CardInstance that is on the field (includes the ArchSpirit leader).
+/// A CardInstance that is on the field (placed by ChannelCard or PlaceArchSpirit).
+/// Carries positional state (tile coordinate) and remaining movement points.
///
public sealed class FieldCard : CardInstance
{
- /// True for the player's starting ArchSpirit (the win-condition target).
- public bool IsLeader { get; set; }
+ /// Current tile position on the board. Null until placed.
+ public Coord? Position { get; set; }
+
+ /// Remaining movement points this turn.
+ public int CurrentMp { get; set; }
}
diff --git a/Server/src/SOR.Game/Grid/AffinitySystem.cs b/Server/src/SOR.Game/Grid/AffinitySystem.cs
new file mode 100644
index 0000000..111852e
--- /dev/null
+++ b/Server/src/SOR.Game/Grid/AffinitySystem.cs
@@ -0,0 +1,107 @@
+namespace SOR.Game.Grid;
+
+using SOR.Database.Enums;
+
+///
+/// Affinity resolution, push operations, and channeling validity.
+///
+/// Combination rules (see affinity.md §4):
+/// Basic affinities: Void, Aether, Lake, Hill, Forest, Field.
+/// Non-basic affinities: determined by (Base1, Base2) pair.
+/// Gateway affinities are directional — require Base2 == Void.
+/// Gateway/UnstableAether are tile-only and cannot appear on cards.
+///
+public static class AffinitySystem
+{
+ private static readonly HashSet BasicAffinities =
+ [
+ Affinity.Void, Affinity.Aether,
+ Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field,
+ ];
+
+ ///
+ /// Resolve the effective affinity of a tile from its two base slots.
+ /// Base1 = older slot, Base2 = newer slot.
+ ///
+ public static Affinity Resolve(Affinity base1, Affinity base2)
+ => (base1, base2) switch
+ {
+ // ── Void + Void ───────────────────────────────────────────────────
+ (Affinity.Void, Affinity.Void) => Affinity.PureVoid,
+
+ // ── Void + basic → tile reads as that basic affinity (§8) ─────────
+ (Affinity.Void, Affinity.Lake) => Affinity.Lake,
+ (Affinity.Void, Affinity.Hill) => Affinity.Hill,
+ (Affinity.Void, Affinity.Forest) => Affinity.Forest,
+ (Affinity.Void, Affinity.Field) => Affinity.Field,
+ (Affinity.Void, Affinity.Aether) => Affinity.UnstableAether,
+
+ // ── Gateway: basic + Void (directional, Base2 must be Void) ──────
+ (Affinity.Lake, Affinity.Void) => Affinity.GatewayLake,
+ (Affinity.Hill, Affinity.Void) => Affinity.GatewayHill,
+ (Affinity.Forest, Affinity.Void) => Affinity.GatewayForest,
+ (Affinity.Field, Affinity.Void) => Affinity.GatewayField,
+
+ // ── Aether combinations ──────────────────────────────────────────
+ (Affinity.Aether, Affinity.Aether) => Affinity.PerfectAether,
+ (Affinity.Aether, _) => Affinity.UnstableAether,
+ (_, Affinity.Aether) => Affinity.UnstableAether,
+
+ // ── Lake pairings ─────────────────────────────────────────────────
+ (Affinity.Lake, Affinity.Lake) => Affinity.Ocean,
+ (Affinity.Lake, Affinity.Hill) or (Affinity.Hill, Affinity.Lake) => Affinity.Island,
+ (Affinity.Lake, Affinity.Field) or (Affinity.Field, Affinity.Lake) => Affinity.Marsh,
+ (Affinity.Lake, Affinity.Forest) or (Affinity.Forest, Affinity.Lake) => Affinity.Swamp,
+
+ // ── Hill pairings ─────────────────────────────────────────────────
+ (Affinity.Hill, Affinity.Hill) => Affinity.Mountain,
+ (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.Grove,
+
+ // ── Forest pairings ───────────────────────────────────────────────
+ (Affinity.Forest, Affinity.Forest) => Affinity.Jungle,
+
+ // ── Fallback (should not occur in a valid game state) ─────────────
+ _ => Affinity.PureVoid,
+ };
+
+ ///
+ /// Push a new basic affinity onto a tile: Base1 = old Base2, Base2 = newAffinity.
+ ///
+ public static void PushAffinity(Tile tile, Affinity newAffinity)
+ {
+ tile.Base1 = tile.Base2;
+ tile.Base2 = newAffinity;
+ }
+
+ ///
+ /// Apply ArchSpirit placement affinity push (§3):
+ /// pushes the affinity to the placement tile AND all in-bounds orthogonal neighbors.
+ ///
+ public static void ApplyPlacementAffinity(Board board, Coord placementCoord, Affinity affinity)
+ {
+ var tile = board.GetTile(placementCoord);
+ if (tile is not null) PushAffinity(tile, affinity);
+
+ foreach (var adjacent in board.GetAdjacentTiles(placementCoord))
+ PushAffinity(adjacent, affinity);
+ }
+
+ ///
+ /// Validate whether a card with the given affinity may be channeled to a tile (§6.3).
+ ///
+ /// Basic affinity card: tile.Base1 or tile.Base2 must match the card's affinity.
+ /// Non-basic affinity card: the resolved tile affinity must match exactly.
+ ///
+ public static bool IsAffinityValid(Tile tile, Affinity cardAffinity)
+ {
+ if (BasicAffinities.Contains(cardAffinity))
+ return tile.Base1 == cardAffinity || tile.Base2 == cardAffinity;
+
+ return Resolve(tile.Base1, tile.Base2) == cardAffinity;
+ }
+}
diff --git a/Server/src/SOR.Game/Grid/Board.cs b/Server/src/SOR.Game/Grid/Board.cs
new file mode 100644
index 0000000..0255c91
--- /dev/null
+++ b/Server/src/SOR.Game/Grid/Board.cs
@@ -0,0 +1,86 @@
+namespace SOR.Game.Grid;
+
+///
+/// Rectangular game board — a dictionary of Tiles keyed by "x,y".
+///
+/// X increases right (column index), Y increases up (row index).
+/// P1's starting row is y=0; P2's starting row is y=Height-1.
+///
+public sealed class Board
+{
+ public int Width { get; init; }
+ public int Height { get; init; }
+
+ public Dictionary Tiles { get; init; } = new();
+
+ /// Create an empty board with all tiles initialized to Void/Void affinities.
+ public static Board Create(int width, int height)
+ {
+ var tiles = new Dictionary(width * height);
+ for (int y = 0; y < height; y++)
+ for (int x = 0; x < width; x++)
+ {
+ var c = new Coord(x, y);
+ tiles[c.ToKey()] = new Tile { Coord = c };
+ }
+ return new Board { Width = width, Height = height, Tiles = tiles };
+ }
+
+ public bool IsInBounds(Coord c)
+ => c.X >= 0 && c.X < Width && c.Y >= 0 && c.Y < Height;
+
+ public Tile? GetTile(Coord c)
+ => Tiles.TryGetValue(c.ToKey(), out var t) ? t : null;
+
+ public IEnumerable GetAdjacentTiles(Coord c)
+ => c.OrthogonalNeighbors()
+ .Where(IsInBounds)
+ .Select(n => Tiles[n.ToKey()]);
+
+ public Coord? FindOccupant(string instanceId)
+ {
+ foreach (var tile in Tiles.Values)
+ if (tile.OccupantId == instanceId) return tile.Coord;
+ return null;
+ }
+
+ public void PlaceUnit(Coord c, string instanceId, string ownerAccountId)
+ {
+ var tile = GetTile(c) ?? throw new GameException($"TILE_OUT_OF_BOUNDS:{c}");
+ if (!tile.IsEmpty) throw new GameException($"TILE_OCCUPIED");
+ tile.OccupantId = instanceId;
+ tile.OccupantOwner = ownerAccountId;
+ }
+
+ public void RemoveUnit(string instanceId)
+ {
+ var tile = Tiles.Values.FirstOrDefault(t => t.OccupantId == instanceId);
+ if (tile is null) return;
+ tile.OccupantId = null;
+ tile.OccupantOwner = null;
+ }
+
+ public void MoveUnit(string instanceId, Coord dest)
+ {
+ var src = Tiles.Values.FirstOrDefault(t => t.OccupantId == instanceId)
+ ?? throw new GameException($"UNIT_NOT_ON_BOARD");
+ var destTile = GetTile(dest)
+ ?? throw new GameException($"TILE_OUT_OF_BOUNDS:{dest}");
+ if (!destTile.IsEmpty)
+ throw new GameException($"TILE_OCCUPIED");
+
+ destTile.OccupantId = src.OccupantId;
+ destTile.OccupantOwner = src.OccupantOwner;
+ src.OccupantId = null;
+ src.OccupantOwner = null;
+ }
+
+ ///
+ /// Build a coord→instanceId lookup for all occupied tiles.
+ /// Used by pathfinding and LOS checks.
+ ///
+ public Dictionary BuildOccupancyMap()
+ => Tiles.Values
+ .Where(t => !t.IsEmpty)
+ .ToDictionary(t => t.Coord, t => t.OccupantId!);
+}
diff --git a/Server/src/SOR.Game/Grid/Coord.cs b/Server/src/SOR.Game/Grid/Coord.cs
new file mode 100644
index 0000000..8f793f6
--- /dev/null
+++ b/Server/src/SOR.Game/Grid/Coord.cs
@@ -0,0 +1,28 @@
+namespace SOR.Game.Grid;
+
+///
+/// Immutable (X, Y) coordinate on a square grid.
+/// X increases right; Y increases up. P1 starts at row y=0, P2 at row y=Height-1.
+///
+public readonly record struct Coord(int X, int Y)
+{
+ /// Manhattan distance — no diagonals on square grid.
+ public int ManhattanDistance(Coord other) => Math.Abs(X - other.X) + Math.Abs(Y - other.Y);
+
+ /// True when the two coords share an edge (not diagonal).
+ public bool IsOrthogonallyAdjacentTo(Coord other) => ManhattanDistance(other) == 1;
+
+ /// All four orthogonal neighbors (may be out of bounds).
+ public IEnumerable OrthogonalNeighbors()
+ {
+ yield return new Coord(X, Y + 1);
+ yield return new Coord(X, Y - 1);
+ yield return new Coord(X + 1, Y);
+ yield return new Coord(X - 1, Y);
+ }
+
+ /// Stable dictionary key for the Tiles dictionary.
+ public string ToKey() => $"{X},{Y}";
+
+ public override string ToString() => $"({X},{Y})";
+}
diff --git a/Server/src/SOR.Game/Grid/LineOfSight.cs b/Server/src/SOR.Game/Grid/LineOfSight.cs
new file mode 100644
index 0000000..7a31c04
--- /dev/null
+++ b/Server/src/SOR.Game/Grid/LineOfSight.cs
@@ -0,0 +1,63 @@
+namespace SOR.Game.Grid;
+
+///
+/// Line-of-sight checks on a square grid using supercover DDA.
+///
+/// A ray is traced from the center of from to the center of to.
+/// Every tile whose cell boundary the ray crosses is checked for occupancy.
+/// If any intermediate tile (excluding source and destination) is occupied, LOS is blocked.
+///
+public static class LineOfSight
+{
+ ///
+ /// Returns true if there is an unobstructed line of sight from
+ /// to .
+ ///
+ /// : occupied tile map (from Board.BuildOccupancyMap()).
+ /// Source and destination tiles are excluded from the obstruction check.
+ ///
+ public static bool HasLos(
+ Board board,
+ Coord from,
+ Coord to,
+ IReadOnlyDictionary unitsByCoord)
+ {
+ if (from == to) return true;
+
+ int dx = to.X - from.X;
+ int dy = to.Y - from.Y;
+ int nx = Math.Abs(dx);
+ int ny = Math.Abs(dy);
+ int signX = dx > 0 ? 1 : -1;
+ int signY = dy > 0 ? 1 : -1;
+
+ int ix = 0, iy = 0;
+ int cx = from.X, cy = from.Y;
+
+ while (ix < nx || iy < ny)
+ {
+ // Pick horizontal or vertical step based on which grid line is closer.
+ double tx = nx > 0 ? (ix + 0.5) / nx : double.MaxValue;
+ double ty = ny > 0 ? (iy + 0.5) / ny : double.MaxValue;
+
+ if (tx < ty)
+ {
+ cx += signX;
+ ix++;
+ }
+ else
+ {
+ cy += signY;
+ iy++;
+ }
+
+ var current = new Coord(cx, cy);
+ if (current == to) break; // reached destination, stop
+
+ if (unitsByCoord.ContainsKey(current))
+ return false; // occupied intermediate tile blocks LOS
+ }
+
+ return true;
+ }
+}
diff --git a/Server/src/SOR.Game/Grid/Pathfinding.cs b/Server/src/SOR.Game/Grid/Pathfinding.cs
new file mode 100644
index 0000000..54bcbae
--- /dev/null
+++ b/Server/src/SOR.Game/Grid/Pathfinding.cs
@@ -0,0 +1,70 @@
+namespace SOR.Game.Grid;
+
+///
+/// Pathfinding algorithms for all four movement types on a square grid.
+///
+/// Walk / Flight — BFS returning tiles reachable within a given MP budget.
+/// Walk: blocked by any occupied tile.
+/// Flight: blocked only by tiles occupied by other Flight units.
+/// Callers are responsible for building the appropriate blocked set.
+///
+/// Jump / Teleport — range set: all in-bounds tiles within Manhattan [1..maxMp].
+/// Each landing costs exactly 1 MP regardless of distance.
+/// Teleport additionally requires LOS — callers filter with LineOfSight.HasLos.
+///
+public static class Pathfinding
+{
+ ///
+ /// BFS for Walk/Flight movement.
+ /// Returns all reachable non-blocked tiles mapped to their step cost.
+ /// The starting tile is excluded from results (can't "move" to current position).
+ ///
+ public static Dictionary GetReachableWithCost(
+ Board board, Coord from, int maxMp, IReadOnlySet blocked)
+ {
+ var result = new Dictionary();
+ var queue = new Queue<(Coord coord, int cost)>();
+
+ result[from] = 0;
+ queue.Enqueue((from, 0));
+
+ while (queue.Count > 0)
+ {
+ var (current, cost) = queue.Dequeue();
+ if (cost >= maxMp) continue;
+
+ foreach (var neighbor in current.OrthogonalNeighbors())
+ {
+ if (!board.IsInBounds(neighbor)) continue;
+ if (blocked.Contains(neighbor)) continue;
+ if (result.ContainsKey(neighbor)) continue;
+
+ result[neighbor] = cost + 1;
+ queue.Enqueue((neighbor, cost + 1));
+ }
+ }
+
+ result.Remove(from);
+ return result;
+ }
+
+ ///
+ /// Jump/Teleport range: all in-bounds tiles within Manhattan distance [minRange..maxMp]
+ /// from the starting position.
+ ///
+ /// For Teleport, callers should additionally filter by LineOfSight.HasLos.
+ ///
+ public static IEnumerable GetJumpRange(
+ Board board, Coord from, int minRange, int maxRange)
+ {
+ for (int dy = -maxRange; dy <= maxRange; dy++)
+ for (int dx = -maxRange; dx <= maxRange; dx++)
+ {
+ var target = new Coord(from.X + dx, from.Y + dy);
+ if (!board.IsInBounds(target)) continue;
+ var dist = from.ManhattanDistance(target);
+ if (dist < minRange || dist > maxRange) continue;
+ yield return target;
+ }
+ }
+}
diff --git a/Server/src/SOR.Game/Grid/Tile.cs b/Server/src/SOR.Game/Grid/Tile.cs
new file mode 100644
index 0000000..32fc7a7
--- /dev/null
+++ b/Server/src/SOR.Game/Grid/Tile.cs
@@ -0,0 +1,33 @@
+namespace SOR.Game.Grid;
+
+using SOR.Database.Enums;
+
+///
+/// Mutable state of a single tile on the game board.
+///
+/// Two affinity slots (Base1 = older, Base2 = newer) evolve as affinities are pushed.
+/// Resolved affinity = AffinitySystem.Resolve(Base1, Base2).
+/// Occupancy tracks which unit instance (if any) is standing on the tile.
+///
+public sealed class Tile
+{
+ public Coord Coord { get; init; }
+
+ // ── Affinity slots ────────────────────────────────────────────────────────
+
+ /// Older slot. Default: Void.
+ public Affinity Base1 { get; set; } = Affinity.Void;
+
+ /// Newer slot. Default: Void (→ resolved = PureVoid).
+ public Affinity Base2 { get; set; } = Affinity.Void;
+
+ // ── Occupancy ─────────────────────────────────────────────────────────────
+
+ /// InstanceId of the unit on this tile, or null if empty.
+ public string? OccupantId { get; set; }
+
+ /// AccountId (string) of the occupying unit's owner, or null if empty.
+ public string? OccupantOwner { get; set; }
+
+ public bool IsEmpty => OccupantId is null;
+}
diff --git a/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs
index afdaf10..22d7c5b 100644
--- a/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs
+++ b/Server/src/SOR.Game/Handlers/GameCreateCustomLobbyHandler.cs
@@ -85,5 +85,7 @@ internal sealed class GameCreateCustomLobbyHandler : GameHandlerBase, IMessageHa
SpAccumulationPerTurn : r.SpAccumulationPerTurn,
DrawPerTurn : r.DrawPerTurn,
SpHasCap : r.SpHasCap,
- SpCap : r.SpCap);
+ SpCap : r.SpCap,
+ BoardWidth : r.BoardWidth,
+ BoardHeight : r.BoardHeight);
}
diff --git a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs
index a9b5fef..823194e 100644
--- a/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs
+++ b/Server/src/SOR.Game/Handlers/GameJoinCustomLobbyHandler.cs
@@ -65,6 +65,8 @@ internal sealed class GameJoinCustomLobbyHandler : GameHandlerBase, IMessageHand
DrawPerTurn = lobby.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn,
SpHasCap = lobby.SpHasCapOverride ?? GameRules.Default.SpHasCap,
SpCap = lobby.SpCapOverride ?? GameRules.Default.SpCap,
+ BoardWidth = GameRules.Default.BoardWidth,
+ BoardHeight = GameRules.Default.BoardHeight,
};
// Create the game session with the rule snapshot.
diff --git a/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs b/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs
index 9958830..b4b2203 100644
--- a/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs
+++ b/Server/src/SOR.Game/Handlers/GameListCustomLobbiesHandler.cs
@@ -55,7 +55,9 @@ internal sealed class GameListCustomLobbiesHandler : GameHandlerBase, IMessageHa
SpAccumulationPerTurn : l.SpAccumulationPerTurnOverride ?? GameRules.Default.SpAccumulationPerTurn,
DrawPerTurn : l.DrawPerTurnOverride ?? GameRules.Default.DrawPerTurn,
SpHasCap : l.SpHasCapOverride ?? GameRules.Default.SpHasCap,
- SpCap : l.SpCapOverride ?? GameRules.Default.SpCap),
+ SpCap : l.SpCapOverride ?? GameRules.Default.SpCap,
+ BoardWidth : GameRules.Default.BoardWidth,
+ BoardHeight : GameRules.Default.BoardHeight),
CreatedAt : l.CreatedAt));
return ServerMessage.Reply("game.custom.list.ack", message.Seq,
diff --git a/Server/src/SOR.Game/Handlers/GameMoveUnitHandler.cs b/Server/src/SOR.Game/Handlers/GameMoveUnitHandler.cs
new file mode 100644
index 0000000..b2b1c10
--- /dev/null
+++ b/Server/src/SOR.Game/Handlers/GameMoveUnitHandler.cs
@@ -0,0 +1,56 @@
+namespace SOR.Game.Handlers;
+
+using System.Text.Json;
+using SOR.Database.Contexts;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Push;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Game.Grid;
+using SOR.Shared.Networking;
+
+///
+/// game.move_unit — active player moves a Spirit or ArchSpirit to a target tile.
+///
+/// Walk/Flight: BFS pathfinding; MP deducted = path cost.
+/// Jump/Teleport: any reachable empty tile; MP deducted = 1 per landing.
+///
+internal sealed class GameMoveUnitHandler : GameHandlerBase, IMessageHandler
+{
+ private readonly IMessageSerializer _serializer;
+ private readonly GameDbContext _gameDb;
+ private readonly IClientPush _clientPush;
+
+ public GameMoveUnitHandler(
+ IMessageSerializer serializer,
+ GameDbContext gameDb,
+ IClientPush clientPush)
+ {
+ _serializer = serializer;
+ _gameDb = gameDb;
+ _clientPush = clientPush;
+ }
+
+ public string MessageType => "game.move_unit";
+
+ public async Task HandleAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken ct)
+ {
+ var req = _serializer.DeserializePayload(message.Payload);
+ var actorId = connection.UserId;
+
+ var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
+ var state = GameEngine.Deserialize(session.StateJson!);
+ var target = new Coord(req.TargetPosition.X, req.TargetPosition.Y);
+ var newState = GameEngine.MoveUnit(state, actorId, req.UnitInstanceId, target);
+
+ await SaveStateAsync(_gameDb, session, newState, actorId, "game.move_unit",
+ JsonSerializer.Serialize(req), ct);
+
+ await PushStateToPlayersAsync(_clientPush, session, newState, ct);
+
+ return ServerMessage.Reply("game.move_unit.ack", message.Seq,
+ new GameMoveUnitResponse(GameEngine.ToDto(newState, actorId)));
+ }
+}
diff --git a/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs b/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs
new file mode 100644
index 0000000..7361760
--- /dev/null
+++ b/Server/src/SOR.Game/Handlers/GamePlaceArchSpiritHandler.cs
@@ -0,0 +1,60 @@
+namespace SOR.Game.Handlers;
+
+using System.Text.Json;
+using SOR.Database.Contexts;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Push;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Game.Grid;
+using SOR.Shared.Networking;
+
+///
+/// game.place_arch_spirit — player places their ArchSpirit during the Placement phase.
+///
+/// P1 must place in row y=0; P2 must place in row y=Height-1.
+/// Affinity is pushed to the placement tile and all in-bounds orthogonal neighbors.
+///
+/// When both players have placed, the opening draw is performed and turn 1 begins.
+/// A GameStateUpdatePush is sent to both players after each placement.
+///
+internal sealed class GamePlaceArchSpiritHandler : GameHandlerBase, IMessageHandler
+{
+ private readonly IMessageSerializer _serializer;
+ private readonly GameDbContext _gameDb;
+ private readonly IClientPush _clientPush;
+
+ public GamePlaceArchSpiritHandler(
+ IMessageSerializer serializer,
+ GameDbContext gameDb,
+ IClientPush clientPush)
+ {
+ _serializer = serializer;
+ _gameDb = gameDb;
+ _clientPush = clientPush;
+ }
+
+ public string MessageType => "game.place_arch_spirit";
+
+ public async Task HandleAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken ct)
+ {
+ var req = _serializer.DeserializePayload(message.Payload);
+ var actorId = connection.UserId;
+
+ var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
+ var state = GameEngine.Deserialize(session.StateJson!);
+
+ var coord = new Coord(req.Position.X, req.Position.Y);
+ var (newState, _) = GameEngine.PlaceArchSpirit(state, actorId, coord);
+
+ await SaveStateAsync(_gameDb, session, newState, actorId, "game.place_arch_spirit",
+ JsonSerializer.Serialize(req), ct);
+
+ await PushStateToPlayersAsync(_clientPush, session, newState, ct);
+
+ return ServerMessage.Reply("game.place_arch_spirit.ack", message.Seq,
+ new GamePlaceArchSpiritResponse(GameEngine.ToDto(newState, actorId)));
+ }
+}
diff --git a/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs b/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs
index cd65248..f000c2f 100644
--- a/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs
+++ b/Server/src/SOR.Game/Handlers/GamePlayCardHandler.cs
@@ -2,13 +2,18 @@ namespace SOR.Game.Handlers;
using System.Text.Json;
using SOR.Database.Contexts;
+using SOR.Game.Grid;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
///
-/// game.play_card — active player plays a card from their hand onto the field.
+/// game.play_card — active player channels a card from their hand.
+///
+/// Spirit cards require a TargetTile within the ArchSpirit's channeling range with
+/// valid affinity. Other card types (Repentance, Instinct, Ruin, Terramorpha) may
+/// omit TargetTile — full effect resolution is handled by AbilitySystem (future).
///
internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler
{
@@ -33,9 +38,14 @@ internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler
var req = _serializer.DeserializePayload(message.Payload);
var actorId = connection.UserId;
- var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
- var state = GameEngine.Deserialize(session.StateJson!);
- var newState = GameEngine.PlayCard(state, actorId, req.CardInstanceId);
+ var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
+ var state = GameEngine.Deserialize(session.StateJson!);
+
+ Coord? target = req.TargetTile is not null
+ ? new Coord(req.TargetTile.X, req.TargetTile.Y)
+ : null;
+
+ var newState = GameEngine.ChannelCard(state, actorId, req.CardInstanceId, target);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.play_card",
JsonSerializer.Serialize(req), ct);
diff --git a/Server/src/SOR.Game/Handlers/GameReadyHandler.cs b/Server/src/SOR.Game/Handlers/GameReadyHandler.cs
index 79d574c..72a274f 100644
--- a/Server/src/SOR.Game/Handlers/GameReadyHandler.cs
+++ b/Server/src/SOR.Game/Handlers/GameReadyHandler.cs
@@ -86,8 +86,8 @@ internal sealed class GameReadyHandler : GameHandlerBase, IMessageHandler
var state = GameEngine.Initialize(
session.Id,
- session.PlayerOneAccountId, p1DeckCards, session.PlayerOneDeckId, p1ArchSpirit,
- session.PlayerTwoAccountId, p2DeckCards, session.PlayerTwoDeckId, p2ArchSpirit,
+ session.PlayerOneAccountId, p1DeckCards, p1ArchSpirit,
+ session.PlayerTwoAccountId, p2DeckCards, p2ArchSpirit,
rules);
session.StateJson = GameEngine.Serialize(state);
diff --git a/Server/src/SOR.Game/Handlers/GameSacrificeHandler.cs b/Server/src/SOR.Game/Handlers/GameSacrificeHandler.cs
new file mode 100644
index 0000000..6fad96b
--- /dev/null
+++ b/Server/src/SOR.Game/Handlers/GameSacrificeHandler.cs
@@ -0,0 +1,55 @@
+namespace SOR.Game.Handlers;
+
+using System.Text.Json;
+using SOR.Database.Contexts;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Push;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Shared.Networking;
+
+///
+/// game.sacrifice — active player sacrifices one of their Spirits adjacent to their ArchSpirit.
+///
+/// Sacrifice is a free action (§6.15): it does not consume an attack or ability use.
+/// The Spirit must be orthogonally adjacent to the player's ArchSpirit.
+/// ST earned = SacrificeSystem.GetSTReturn(currentST, spiritSacValue).
+///
+internal sealed class GameSacrificeHandler : GameHandlerBase, IMessageHandler
+{
+ private readonly IMessageSerializer _serializer;
+ private readonly GameDbContext _gameDb;
+ private readonly IClientPush _clientPush;
+
+ public GameSacrificeHandler(
+ IMessageSerializer serializer,
+ GameDbContext gameDb,
+ IClientPush clientPush)
+ {
+ _serializer = serializer;
+ _gameDb = gameDb;
+ _clientPush = clientPush;
+ }
+
+ public string MessageType => "game.sacrifice";
+
+ public async Task HandleAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken ct)
+ {
+ var req = _serializer.DeserializePayload(message.Payload);
+ var actorId = connection.UserId;
+
+ var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
+ var state = GameEngine.Deserialize(session.StateJson!);
+ var newState = GameEngine.Sacrifice(state, actorId, req.UnitInstanceId);
+
+ await SaveStateAsync(_gameDb, session, newState, actorId, "game.sacrifice",
+ JsonSerializer.Serialize(req), ct);
+
+ await PushStateToPlayersAsync(_clientPush, session, newState, ct);
+
+ return ServerMessage.Reply("game.sacrifice.ack", message.Seq,
+ new GameSacrificeResponse(GameEngine.ToDto(newState, actorId)));
+ }
+}
diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs
index ffb287f..61a2411 100644
--- a/Server/src/SOR.Game/ServiceRegistration.cs
+++ b/Server/src/SOR.Game/ServiceRegistration.cs
@@ -24,8 +24,11 @@ public static class ServiceRegistration
services.AddTransient();
services.AddTransient();
services.AddTransient();
+ services.AddTransient();
services.AddTransient();
+ services.AddTransient();
services.AddTransient();
+ services.AddTransient();
services.AddTransient();
services.AddTransient();