Add square grid system, positional combat, sacrifice, and Placement phase
Grid infrastructure (SOR.Game/Grid/): - Coord — immutable (X,Y) struct with Manhattan distance, adjacency, BFS helpers - Tile — mutable affinity slots (Base1/Base2) + occupancy tracking - Board — 8×8 (configurable) grid, PlaceUnit/RemoveUnit/MoveUnit/BuildOccupancyMap - Pathfinding — Walk/Flight BFS (GetReachableWithCost), Jump/Teleport range (GetJumpRange) - LineOfSight — supercover DDA; occupied intermediate tiles block LOS - AffinitySystem — full Resolve table for all 20+ affinities per affinity.md, PushAffinity, ApplyPlacementAffinity, IsAffinityValid (basic vs non-basic rules) Combat (SOR.Game/Combat/): - AttackSystem — Manhattan range + optional LOS validation (§6.10) - SacrificeSystem — exact ST return formula from gameplay.md §6.15 Abilities (SOR.Game/Abilities/): - AbilitySystem stub — future pass per abilities.md Game engine / state changes: - GamePhase: added Placement phase (before Draw) - GameRuleSet + GameRules: added BoardWidth/BoardHeight (default 8×8) - GameState: added Board, PlayerOneAccountId; CardInstance gains MovementType, MaxMp, MinAttackRange, MaxAttackRange, RequiresLos, MinChannelRange, MaxChannelRange, IsLeader (moved from FieldCard); FieldCard adds Position + CurrentMp - [JsonPolymorphic] on CardInstance so FieldCard survives JSONB round-trip - JsonStringEnumConverter added to GameEngine serializer options - GameEngine.Initialize: creates Board + sets Placement phase; no opening draw yet - GameEngine.PlaceArchSpirit: validates row, pushes affinity, triggers opening draw and SP gain when both players placed - GameEngine.ChannelCard (was PlayCard): validates channeling range + affinity for Spirits - GameEngine.MoveUnit: Walk/Flight BFS, Jump (1 MP/landing), Teleport (LOS + 1 MP) - GameEngine.Attack: adds range+LOS validation via AttackSystem - GameEngine.Sacrifice: adjacency + SacrificeSystem ST formula - GameEngine.EndTurn: now also restores MP (§6.0 step 1) for next player - ToDto: includes Board tiles with resolved affinities; CardInstanceDto gets Position, CurrentMp, MaxMp, MovementType New handlers: game.place_arch_spirit, game.move_unit, game.sacrifice Updated handlers: game.play_card (target tile), GameReadyHandler (new Initialize sig) Migration: AddBoardDimensions (board_width/board_height on game_rule_sets) Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -43,6 +43,12 @@ public sealed class GameRuleSet
|
||||
/// <summary>Maximum SP balance. Ignored if SpHasCap is false.</summary>
|
||||
public int SpCap { get; set; }
|
||||
|
||||
/// <summary>Battlefield width (columns). Default: 8.</summary>
|
||||
public int BoardWidth { get; set; } = 8;
|
||||
|
||||
/// <summary>Battlefield height (rows). Default: 8.</summary>
|
||||
public int BoardHeight { get; set; } = 8;
|
||||
|
||||
// ── Timestamps ───────────────────────────────────────────────────────────
|
||||
|
||||
public DateTimeOffset CreatedAt { get; set; }
|
||||
|
||||
@@ -33,11 +33,13 @@ public enum GameSessionStatus
|
||||
/// </summary>
|
||||
public enum GamePhase
|
||||
{
|
||||
/// <summary>Game just started — both players draw their opening hands.</summary>
|
||||
/// <summary>Game just started — both players place their ArchSpirits and draw opening hands.</summary>
|
||||
Setup,
|
||||
/// <summary>Both players are placing their ArchSpirits on their starting rows.</summary>
|
||||
Placement,
|
||||
/// <summary>Active player draws a card.</summary>
|
||||
Draw,
|
||||
/// <summary>Active player may play cards, activate abilities, and attack.</summary>
|
||||
/// <summary>Active player may play cards, activate abilities, attack, and move.</summary>
|
||||
Main,
|
||||
/// <summary>Active player has declared end of turn; cleanup runs.</summary>
|
||||
End,
|
||||
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
// <auto-generated />
|
||||
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
|
||||
{
|
||||
/// <inheritdoc />
|
||||
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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("DrawPerTurnOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid?>("GameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("GuestAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("GuestDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("HostAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("HostDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int?>("OpeningHandSizeOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int?>("SpAccumulationPerTurnOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int?>("SpCapOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("SpHasCapOverride")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("ActionType")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid>("ActorAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("GameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("OccurredAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("PayloadJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("payload");
|
||||
|
||||
b.Property<int>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("BoardHeight")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("BoardWidth")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("DrawPerTurn")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("FirstPlayerSkipsDraw")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsCustomDefault")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsRankedDefault")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OpeningHandSize")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("SpAccumulationPerTurn")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("SpCap")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("SpHasCap")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<DateTimeOffset?>("EndedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid>("PlayerOneAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("PlayerOneDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("PlayerOneReady")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid>("PlayerTwoAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("PlayerTwoDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<bool>("PlayerTwoReady")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RuleSnapshotJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("rule_snapshot");
|
||||
|
||||
b.Property<DateTimeOffset?>("StartedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("StateJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("state");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("WinCondition")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<Guid?>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("AccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("DeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("JoinedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<Guid?>("MatchedGameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("RankScore")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset?>("ResolvedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SOR.Database.Migrations.Game
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddBoardDimensions : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
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<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
Status = table.Column<string>(type: "text", nullable: false),
|
||||
HostAccountId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
HostDeckId = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
GuestAccountId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
GuestDeckId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
GameSessionId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
OpeningHandSizeOverride = table.Column<int>(type: "integer", nullable: true),
|
||||
FirstPlayerSkipsDrawOverride = table.Column<bool>(type: "boolean", nullable: true),
|
||||
SpAccumulationPerTurnOverride = table.Column<int>(type: "integer", nullable: true),
|
||||
DrawPerTurnOverride = table.Column<int>(type: "integer", nullable: true),
|
||||
SpHasCapOverride = table.Column<bool>(type: "boolean", nullable: true),
|
||||
SpCapOverride = table.Column<int>(type: "integer", nullable: true),
|
||||
CreatedAt = table.Column<DateTimeOffset>(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<Guid>(type: "uuid", nullable: false),
|
||||
Name = table.Column<string>(type: "text", nullable: false),
|
||||
IsRankedDefault = table.Column<bool>(type: "boolean", nullable: false),
|
||||
IsCustomDefault = table.Column<bool>(type: "boolean", nullable: false),
|
||||
OpeningHandSize = table.Column<int>(type: "integer", nullable: false),
|
||||
FirstPlayerSkipsDraw = table.Column<bool>(type: "boolean", nullable: false),
|
||||
SpAccumulationPerTurn = table.Column<int>(type: "integer", nullable: false),
|
||||
DrawPerTurn = table.Column<int>(type: "integer", nullable: false),
|
||||
SpHasCap = table.Column<bool>(type: "boolean", nullable: false),
|
||||
SpCap = table.Column<int>(type: "integer", nullable: false),
|
||||
BoardWidth = table.Column<int>(type: "integer", nullable: false),
|
||||
BoardHeight = table.Column<int>(type: "integer", nullable: false),
|
||||
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
UpdatedAt = table.Column<DateTimeOffset>(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");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,65 @@ namespace SOR.Database.Migrations.Game
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int?>("DrawPerTurnOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid?>("GameSessionId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("GuestAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("GuestDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("HostAccountId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("HostDeckId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int?>("OpeningHandSizeOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int?>("SpAccumulationPerTurnOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int?>("SpCapOverride")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool?>("SpHasCapOverride")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("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<Guid>("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<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("BoardHeight")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("BoardWidth")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("DrawPerTurn")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("FirstPlayerSkipsDraw")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsCustomDefault")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("IsRankedDefault")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<int>("OpeningHandSize")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("SpAccumulationPerTurn")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("SpCap")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("SpHasCap")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<DateTimeOffset>("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<Guid>("Id")
|
||||
@@ -89,6 +203,10 @@ namespace SOR.Database.Migrations.Game
|
||||
b.Property<bool>("PlayerTwoReady")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("RuleSnapshotJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("rule_snapshot");
|
||||
|
||||
b.Property<DateTimeOffset?>("StartedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace SOR.Game.Abilities;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class AbilitySystem
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
namespace SOR.Game.Combat;
|
||||
|
||||
using SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class AttackSystem
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if the attacker can legally target the given position.
|
||||
/// </summary>
|
||||
public static bool CanAttack(
|
||||
Coord attackerPos,
|
||||
Coord targetPos,
|
||||
int minRange,
|
||||
int maxRange,
|
||||
bool requiresLos,
|
||||
Board board,
|
||||
IReadOnlyDictionary<Coord, string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enumerate all in-bounds tiles the attacker can target from its current position.
|
||||
/// </summary>
|
||||
public static IEnumerable<Coord> GetAttackableCoords(
|
||||
Board board,
|
||||
Coord attackerPos,
|
||||
int minRange,
|
||||
int maxRange,
|
||||
bool requiresLos,
|
||||
IReadOnlyDictionary<Coord, string> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
namespace SOR.Game.Combat;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class SacrificeSystem
|
||||
{
|
||||
/// <summary>
|
||||
/// Compute SpiritSacValue for a Spirit with the given costs.
|
||||
/// SpiritSacValue = (CardSTCost * 3) + CardSPCost
|
||||
/// </summary>
|
||||
public static int GetSacrificeValue(int stCost, int spCost)
|
||||
=> (stCost * 3) + spCost;
|
||||
|
||||
/// <summary>
|
||||
/// Compute the ST earned from a sacrifice, given current ST and the Spirit's SpiritSacValue.
|
||||
/// Exact formula from gameplay.md §6.15.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<GameState>(json, _json)
|
||||
@@ -36,23 +47,21 @@ public static class GameEngine
|
||||
=> JsonSerializer.Deserialize<GameRules>(json, _json)
|
||||
?? GameRules.Default;
|
||||
|
||||
// ── Initialization ────────────────────────────────────────────────────────
|
||||
// ── Initialization ─────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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 ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<Affinity>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static (GameState state, CardInstance? drawn) Draw(GameState state, string actorId)
|
||||
{
|
||||
@@ -105,11 +170,16 @@ public static class GameEngine
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<Affinity>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<FieldCard>()
|
||||
.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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<FieldCard>())
|
||||
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<FieldCard>())
|
||||
{
|
||||
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 ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Compute ELO rank score deltas after a game.
|
||||
/// Returns (winnerDelta, loserDelta) — both are positive values indicating change magnitude.
|
||||
/// </summary>
|
||||
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<CardInstance>();
|
||||
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<Coord> BuildBlockedSet(
|
||||
GameState state, string movingUnitId, MovementType? movType)
|
||||
{
|
||||
var blocked = new HashSet<Coord>();
|
||||
foreach (var player in state.Players.Values)
|
||||
{
|
||||
foreach (var card in player.Field.OfType<FieldCard>())
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game-rule violation — maps to a client error code.</summary>
|
||||
|
||||
@@ -11,8 +11,20 @@ public sealed record GameGetStateRequest(Guid SessionId);
|
||||
/// <summary>Draw a card from the player's deck.</summary>
|
||||
public sealed record GameDrawRequest(Guid SessionId);
|
||||
|
||||
/// <summary>Play a card from hand onto the field.</summary>
|
||||
public sealed record GamePlayCardRequest(Guid SessionId, string CardInstanceId);
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed record GamePlaceArchSpiritRequest(Guid SessionId, CoordDto Position);
|
||||
|
||||
/// <summary>
|
||||
/// Channel (play) a card from hand. Spirit cards require a TargetTile within
|
||||
/// the ArchSpirit's channeling range; other card types may omit it.
|
||||
/// </summary>
|
||||
public sealed record GamePlayCardRequest(Guid SessionId, string CardInstanceId, CoordDto? TargetTile = null);
|
||||
|
||||
/// <summary>Move a unit on the board to a new tile.</summary>
|
||||
public sealed record GameMoveUnitRequest(Guid SessionId, string UnitInstanceId, CoordDto TargetPosition);
|
||||
|
||||
/// <summary>Attack an opponent card (or their ArchSpirit) with one of your field cards.</summary>
|
||||
public sealed record GameAttackRequest(
|
||||
@@ -20,6 +32,12 @@ public sealed record GameAttackRequest(
|
||||
string AttackerInstanceId,
|
||||
string TargetInstanceId);
|
||||
|
||||
/// <summary>
|
||||
/// Sacrifice one of your Spirits adjacent to your ArchSpirit (§6.15).
|
||||
/// Sacrifice is a free action — does not consume an attack or ability use.
|
||||
/// </summary>
|
||||
public sealed record GameSacrificeRequest(Guid SessionId, string UnitInstanceId);
|
||||
|
||||
/// <summary>End the active player's turn.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Join an open custom lobby with the specified deck.</summary>
|
||||
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(
|
||||
/// </summary>
|
||||
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<PlayerStateDto> Players);
|
||||
IEnumerable<PlayerStateDto> 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<TileDto> Tiles);
|
||||
|
||||
public sealed record TileDto(
|
||||
CoordDto Coord,
|
||||
string Base1,
|
||||
string Base2,
|
||||
string ResolvedAffinity,
|
||||
string? OccupantId,
|
||||
string? OccupantOwner);
|
||||
|
||||
/// <summary>Client-facing 2D coordinate.</summary>
|
||||
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);
|
||||
|
||||
@@ -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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
namespace SOR.Game;
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// Full live game state — serialized as JSONB in GameSession.StateJson.
|
||||
@@ -15,14 +17,23 @@ public sealed class GameState
|
||||
/// <summary>AccountId (as string) of the player whose turn it currently is.</summary>
|
||||
public string ActivePlayerAccountId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>AccountId (as string) of the first player (P1). Determines placement row.</summary>
|
||||
public string PlayerOneAccountId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Per-player state, keyed by AccountId.ToString().</summary>
|
||||
public Dictionary<string, PlayerState> Players { get; set; } = new();
|
||||
|
||||
/// <summary>Running sequence number for action log entries.</summary>
|
||||
/// <summary>Running sequence number for action log / StateVersion.</summary>
|
||||
public int NextActionSequence { get; set; } = 1;
|
||||
|
||||
/// <summary>Rules snapshot applied to this game session.</summary>
|
||||
public GameRules Rules { get; set; } = GameRules.Default;
|
||||
|
||||
/// <summary>
|
||||
/// The battlefield grid. Null only before the game session is initialized.
|
||||
/// Created during GameEngine.Initialize and populated during the Placement phase.
|
||||
/// </summary>
|
||||
public Board? Board { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PlayerState
|
||||
@@ -45,29 +56,35 @@ public sealed class PlayerState
|
||||
public int CurrentSp { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int CurrentSt { get; set; }
|
||||
|
||||
// ── Leader ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public FieldCard? ArchSpirit { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$t")]
|
||||
[JsonDerivedType(typeof(CardInstance), "c")]
|
||||
[JsonDerivedType(typeof(FieldCard), "f")]
|
||||
public class CardInstance
|
||||
{
|
||||
/// <summary>Unique instance ID within the game session (not a DB id).</summary>
|
||||
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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>True if the card has already attacked or used an ability this turn.</summary>
|
||||
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 ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>True if this unit has already attacked or used an ability this turn.</summary>
|
||||
public bool IsExhausted { get; set; }
|
||||
|
||||
// ── Field flags ──────────────────────────────────────────────────────────
|
||||
/// <summary>True for the player's ArchSpirit (the win-condition target).</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class FieldCard : CardInstance
|
||||
{
|
||||
/// <summary>True for the player's starting ArchSpirit (the win-condition target).</summary>
|
||||
public bool IsLeader { get; set; }
|
||||
/// <summary>Current tile position on the board. Null until placed.</summary>
|
||||
public Coord? Position { get; set; }
|
||||
|
||||
/// <summary>Remaining movement points this turn.</summary>
|
||||
public int CurrentMp { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class AffinitySystem
|
||||
{
|
||||
private static readonly HashSet<Affinity> BasicAffinities =
|
||||
[
|
||||
Affinity.Void, Affinity.Aether,
|
||||
Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field,
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Resolve the effective affinity of a tile from its two base slots.
|
||||
/// Base1 = older slot, Base2 = newer slot.
|
||||
/// </summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Push a new basic affinity onto a tile: Base1 = old Base2, Base2 = newAffinity.
|
||||
/// </summary>
|
||||
public static void PushAffinity(Tile tile, Affinity newAffinity)
|
||||
{
|
||||
tile.Base1 = tile.Base2;
|
||||
tile.Base2 = newAffinity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Apply ArchSpirit placement affinity push (§3):
|
||||
/// pushes the affinity to the placement tile AND all in-bounds orthogonal neighbors.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class Board
|
||||
{
|
||||
public int Width { get; init; }
|
||||
public int Height { get; init; }
|
||||
|
||||
public Dictionary<string, Tile> Tiles { get; init; } = new();
|
||||
|
||||
/// <summary>Create an empty board with all tiles initialized to Void/Void affinities.</summary>
|
||||
public static Board Create(int width, int height)
|
||||
{
|
||||
var tiles = new Dictionary<string, Tile>(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<Tile> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build a coord→instanceId lookup for all occupied tiles.
|
||||
/// Used by pathfinding and LOS checks.
|
||||
/// </summary>
|
||||
public Dictionary<Coord, string> BuildOccupancyMap()
|
||||
=> Tiles.Values
|
||||
.Where(t => !t.IsEmpty)
|
||||
.ToDictionary(t => t.Coord, t => t.OccupantId!);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public readonly record struct Coord(int X, int Y)
|
||||
{
|
||||
/// <summary>Manhattan distance — no diagonals on square grid.</summary>
|
||||
public int ManhattanDistance(Coord other) => Math.Abs(X - other.X) + Math.Abs(Y - other.Y);
|
||||
|
||||
/// <summary>True when the two coords share an edge (not diagonal).</summary>
|
||||
public bool IsOrthogonallyAdjacentTo(Coord other) => ManhattanDistance(other) == 1;
|
||||
|
||||
/// <summary>All four orthogonal neighbors (may be out of bounds).</summary>
|
||||
public IEnumerable<Coord> 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);
|
||||
}
|
||||
|
||||
/// <summary>Stable dictionary key for the Tiles dictionary.</summary>
|
||||
public string ToKey() => $"{X},{Y}";
|
||||
|
||||
public override string ToString() => $"({X},{Y})";
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// Line-of-sight checks on a square grid using supercover DDA.
|
||||
///
|
||||
/// A ray is traced from the center of <c>from</c> to the center of <c>to</c>.
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class LineOfSight
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if there is an unobstructed line of sight from <paramref name="from"/>
|
||||
/// to <paramref name="to"/>.
|
||||
///
|
||||
/// <paramref name="unitsByCoord"/>: occupied tile map (from Board.BuildOccupancyMap()).
|
||||
/// Source and destination tiles are excluded from the obstruction check.
|
||||
/// </summary>
|
||||
public static bool HasLos(
|
||||
Board board,
|
||||
Coord from,
|
||||
Coord to,
|
||||
IReadOnlyDictionary<Coord, string> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class Pathfinding
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static Dictionary<Coord, int> GetReachableWithCost(
|
||||
Board board, Coord from, int maxMp, IReadOnlySet<Coord> blocked)
|
||||
{
|
||||
var result = new Dictionary<Coord, int>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static IEnumerable<Coord> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace SOR.Game.Grid;
|
||||
|
||||
using SOR.Database.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class Tile
|
||||
{
|
||||
public Coord Coord { get; init; }
|
||||
|
||||
// ── Affinity slots ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Older slot. Default: Void.</summary>
|
||||
public Affinity Base1 { get; set; } = Affinity.Void;
|
||||
|
||||
/// <summary>Newer slot. Default: Void (→ resolved = PureVoid).</summary>
|
||||
public Affinity Base2 { get; set; } = Affinity.Void;
|
||||
|
||||
// ── Occupancy ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>InstanceId of the unit on this tile, or null if empty.</summary>
|
||||
public string? OccupantId { get; set; }
|
||||
|
||||
/// <summary>AccountId (string) of the occupying unit's owner, or null if empty.</summary>
|
||||
public string? OccupantOwner { get; set; }
|
||||
|
||||
public bool IsEmpty => OccupantId is null;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameMoveUnitRequest>(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)));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GamePlaceArchSpiritRequest>(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)));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler
|
||||
{
|
||||
@@ -33,9 +38,14 @@ internal sealed class GamePlayCardHandler : GameHandlerBase, IMessageHandler
|
||||
var req = _serializer.DeserializePayload<GamePlayCardRequest>(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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var req = _serializer.DeserializePayload<GameSacrificeRequest>(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)));
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,11 @@ public static class ServiceRegistration
|
||||
services.AddTransient<IMessageHandler, GameReadyHandler>();
|
||||
services.AddTransient<IMessageHandler, GameGetStateHandler>();
|
||||
services.AddTransient<IMessageHandler, GameDrawHandler>();
|
||||
services.AddTransient<IMessageHandler, GamePlaceArchSpiritHandler>();
|
||||
services.AddTransient<IMessageHandler, GamePlayCardHandler>();
|
||||
services.AddTransient<IMessageHandler, GameMoveUnitHandler>();
|
||||
services.AddTransient<IMessageHandler, GameAttackHandler>();
|
||||
services.AddTransient<IMessageHandler, GameSacrificeHandler>();
|
||||
services.AddTransient<IMessageHandler, GameEndTurnHandler>();
|
||||
services.AddTransient<IMessageHandler, GameConcedeHandler>();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user