Add hex grid support (sides 3–10) for boards, pathfinding, LOS, and client rendering

- New HexGrid.cs: axial coord helpers, BFS neighbors, cube-lerp LOS, jump-range
- Board: HexSides property, GetNeighbors() dispatches hex/square, IsInBounds() hex-aware
- BoardShapeGenerator: MakeHexagon() with edge-based starting zones (2–6 players);
  FromTemplate() now carries HexSides through to the Board
- Pathfinding: Walk/Flight BFS uses board.GetNeighbors() (hex+square unified)
- LineOfSight: delegates to HexGrid.HasLos when hexSides > 0
- GameRules/GameRuleSet/BoardTemplate/BoardTemplateSnapshot: GridType + HexSides fields
- GameMessages BoardDto: GridType + HexSides sent to client
- GameEngine: PlaceArchSpirit range uses HexGrid.Distance on hex boards;
  Teleport LOS passes board.HexSides; ToBoardDto emits GridType/HexSides
- EF migration 20260401000000_AddHexGridSupport: grid_type + hex_sides columns on
  game_rule_sets and board_templates; applied to pg-forge-01
- Client game_screen.gd: hex coord→world (pointy-top flat layout), CylinderMesh
  tiles (radial_segments=6), _board_distance cube metric, _bfs_reachable 6-dir,
  _client_has_los cube-lerp, highlight mesh for hex tiles; reads gridType/hexSides
  from BoardDto

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:
dingo
2026-04-01 16:44:17 -04:00
co-authored by Claude Happy
parent c756b9cffa
commit 2cfa60c7dd
16 changed files with 990 additions and 40 deletions
+109 -28
View File
@@ -1099,9 +1099,20 @@ func _touch_pair_mid() -> Vector2:
# ── Coord helpers ─────────────────────────────────────────────────────────────
## Grid spacing: 1.0 tile + 0.1 gap between tiles (visual only).
const TILE_SPACING := 1.1
const TILE_SPACING := 1.1
const HEX_TILE_RADIUS := 0.5774 # ≈ 1/√3 — flat-to-flat = TILE_SPACING
var _board_grid_type : String = "Square"
var _board_hex_sides : int = 0
func _coord_to_world(x: int, y: int) -> Vector3:
if _board_grid_type == "Hexagon":
var N : int = _board_hex_sides
var q : float = x - (N - 1)
var r : float = y - (N - 1)
var wx : float = TILE_SPACING * sqrt(3.0) * (q + r * 0.5)
var wz : float = TILE_SPACING * 1.5 * r
return Vector3(wx, 0.0, wz)
return Vector3(
x * TILE_SPACING - (Game.board_width() - 1) * TILE_SPACING * 0.5, 0.0,
y * TILE_SPACING - (Game.board_height() - 1) * TILE_SPACING * 0.5)
@@ -1164,6 +1175,8 @@ func _rebuild_ownership(state: Dictionary) -> void:
# ── Board building ────────────────────────────────────────────────────────────
func _build_board(board: Dictionary) -> void:
_board_grid_type = board.get("gridType", "Square")
_board_hex_sides = int(board.get("hexSides", 0))
for c in _tiles_root.get_children(): c.queue_free()
for c in _units_root.get_children(): c.queue_free()
for c : Node in _hi_root.get_children():
@@ -1202,16 +1215,28 @@ func _add_tile(x: int, y: int, affinity: String) -> void:
body.set_meta("tile_height", h) # used by bottom-model loader
var shape := CollisionShape3D.new()
var box := BoxShape3D.new()
box.size = Vector3(0.98, h, 0.98)
shape.shape = box
var mi := MeshInstance3D.new()
if _board_grid_type == "Hexagon":
var cyl := CylinderMesh.new()
cyl.radial_segments = 6
cyl.top_radius = HEX_TILE_RADIUS * TILE_SPACING
cyl.bottom_radius = HEX_TILE_RADIUS * TILE_SPACING
cyl.height = h
mi.mesh = cyl
var cshape := CylinderShape3D.new()
cshape.radius = HEX_TILE_RADIUS * TILE_SPACING
cshape.height = h
shape.shape = cshape
else:
var box := BoxShape3D.new()
box.size = Vector3(0.98, h, 0.98)
shape.shape = box
var bm := BoxMesh.new()
bm.size = Vector3(0.98, h, 0.98)
mi.mesh = bm
body.add_child(shape)
# Placeholder: affinity-coloured flat box, swapped out if a 3D model loads.
var mi := MeshInstance3D.new()
var bm := BoxMesh.new()
bm.size = Vector3(0.98, h, 0.98)
mi.mesh = bm
# Placeholder: affinity-coloured mesh, swapped out if a 3D model loads.
var mat := StandardMaterial3D.new()
mat.albedo_color = AFFINITY_COLORS.get(affinity, Color(0.2, 0.2, 0.2))
mat.roughness = 0.85
@@ -1231,7 +1256,10 @@ func _add_tile(x: int, y: int, affinity: String) -> void:
## PureVoid tiles never receive a stalagmite bottom model.
func _try_load_tile_model(body: StaticBody3D, affinity: String) -> void:
var want_bottom : bool = affinity != "PureVoid"
var model_url := ContentCache.get_tile_model_url(affinity, "Square")
var shape_key := "Hex" if _board_grid_type == "Hexagon" else "Square"
var model_url := ContentCache.get_tile_model_url(affinity, shape_key)
if model_url.is_empty() and _board_grid_type == "Hexagon":
model_url = ContentCache.get_tile_model_url(affinity, "Square")
if model_url.is_empty():
# No 3D model — apply a 2D texture to the placeholder box and attach
# a stalagmite bottom so undecorated tiles still look coherent.
@@ -2334,9 +2362,17 @@ func _make_highlight_quad(fallback: Color) -> MeshInstance3D:
## Falls back to HighlightConfig colours when no texture is loaded yet.
func _add_highlight(x: int, y: int, type_key: String) -> void:
var mi := MeshInstance3D.new()
var pm := PlaneMesh.new()
pm.size = Vector2(0.96, 0.96)
mi.mesh = pm
if _board_grid_type == "Hexagon":
var hm := CylinderMesh.new()
hm.radial_segments = 6
hm.top_radius = HEX_TILE_RADIUS * TILE_SPACING * 0.95
hm.bottom_radius = HEX_TILE_RADIUS * TILE_SPACING * 0.95
hm.height = 0.02
mi.mesh = hm
else:
var pm := PlaneMesh.new()
pm.size = Vector2(0.96, 0.96)
mi.mesh = pm
var mat := StandardMaterial3D.new()
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
mat.emission_enabled = true
@@ -2437,10 +2473,24 @@ func _terra_count_for_card(card: Dictionary) -> int:
## BFS reachable set — returns all coords reachable within max_mp steps,
## treating blocked_coords as impassable walls (destination included in check).
## Mirrors Pathfinding.GetReachableWithCost on the server.
func _board_distance(x1: int, y1: int, x2: int, y2: int) -> int:
if _board_grid_type == "Hexagon":
var N : int = _board_hex_sides
var dq : int = (x1 - (N - 1)) - (x2 - (N - 1))
var dr : int = (y1 - (N - 1)) - (y2 - (N - 1))
return (abs(dq) + abs(dr) + abs(dq + dr)) / 2
return abs(x1 - x2) + abs(y1 - y2)
func _bfs_reachable(fx: int, fy: int, max_mp: int, blocked_coords: Dictionary) -> Array:
var bw := Game.board_width()
var bh := Game.board_height()
var DIRS : Array[Vector2i] = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)]
var DIRS : Array[Vector2i]
if _board_grid_type == "Hexagon":
DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1),
Vector2i(1,-1), Vector2i(-1,1)]
else:
DIRS = [Vector2i(1,0), Vector2i(-1,0), Vector2i(0,1), Vector2i(0,-1)]
var cost : Dictionary = { Vector2i(fx, fy): 0 }
var queue : Array = [Vector2i(fx, fy)]
while not queue.is_empty():
@@ -2491,12 +2541,12 @@ func _valid_move_tiles(unit: Dictionary) -> Array:
blocked[Vector2i(cx, cy)] = true
return _bfs_reachable(ux, uy, mp, blocked)
# Jump / Teleport: Manhattan range, land on any unoccupied tile.
# Jump / Teleport: board-metric range, land on any unoccupied tile.
var results : Array = []
for tx in range(bw):
for ty in range(bh):
if not _tile_bodies.has("%d,%d" % [tx, ty]): continue
var dist : int = abs(tx - ux) + abs(ty - uy)
var dist : int = _board_distance(tx, ty, ux, uy)
if dist == 0 or dist > mp: continue
if Game.get_tile(tx, ty).get("occupantId"): continue
# Teleport additionally requires LOS to the destination.
@@ -2524,7 +2574,7 @@ func _valid_attack_target_coords(unit: Dictionary) -> Array:
if tp.is_empty(): continue
var tx : int = tp.get("x", 0)
var ty : int = tp.get("y", 0)
var dist : int = abs(tx - ux) + abs(ty - uy)
var dist : int = _board_distance(tx, ty, ux, uy)
if dist < min_r or dist > max_r: continue
if needs_los and not _client_has_los(ux, uy, tx, ty): continue
results.append(tp)
@@ -2548,7 +2598,7 @@ func _valid_attack_target_ids(unit: Dictionary) -> Array:
if tp.is_empty(): continue
var tx : int = tp.get("x", 0)
var ty : int = tp.get("y", 0)
var dist : int = abs(tx - ux) + abs(ty - uy)
var dist : int = _board_distance(tx, ty, ux, uy)
if dist < min_r or dist > max_r: continue
if needs_los and not _client_has_los(ux, uy, tx, ty): continue
results.append(t.get("instanceId", ""))
@@ -2572,7 +2622,7 @@ func _attack_range_tiles(unit: Dictionary) -> Array:
for tx in range(bw):
for ty in range(bh):
if not _tile_bodies.has("%d,%d" % [tx, ty]): continue
var dist : int = abs(tx - ux) + abs(ty - uy)
var dist : int = _board_distance(tx, ty, ux, uy)
if dist < min_r or dist > max_r: continue
if needs_los and not _client_has_los(ux, uy, tx, ty): continue
results.append(Vector2i(tx, ty))
@@ -2620,7 +2670,7 @@ func _valid_sacrifice_spirits() -> Array:
if up.is_empty(): continue
var ux : int = up.get("x", 0)
var uy : int = up.get("y", 0)
if abs(ux - ax) + abs(uy - ay) == 1:
if _board_distance(ux, uy, ax, ay) == 1:
results.append(unit)
return results
@@ -3364,8 +3414,9 @@ func _highlight_ability_targets(action: Dictionary) -> void:
if not _unit_passes_filters(u, filters): continue
if not _ability_range.is_empty():
if src_pos_ab.is_empty(): continue
var dist := (absi(int(pos.get("x", 0)) - int(src_pos_ab.get("x", 0))) +
absi(int(pos.get("y", 0)) - int(src_pos_ab.get("y", 0))))
var dist := _board_distance(
int(pos.get("x", 0)), int(pos.get("y", 0)),
int(src_pos_ab.get("x", 0)), int(src_pos_ab.get("y", 0)))
if dist < int(_ability_range.get("min", 0)) or dist > int(_ability_range.get("max", 999)):
continue
# Linear and LOS checks — applied independently of the distance range check.
@@ -3390,16 +3441,18 @@ func _unit_passes_filters(unit: Dictionary, filters: Array) -> bool:
if src_pos.is_empty(): return false
var tgt_pos : Dictionary = unit.get("position", {})
if tgt_pos.is_empty(): return false
var dist := (absi(int(tgt_pos.get("x", 0)) - int(src_pos.get("x", 0))) +
absi(int(tgt_pos.get("y", 0)) - int(src_pos.get("y", 0))))
var dist := _board_distance(
int(tgt_pos.get("x", 0)), int(tgt_pos.get("y", 0)),
int(src_pos.get("x", 0)), int(src_pos.get("y", 0)))
if dist < int(f.get("min", 0)) or dist > int(f.get("max", 999)):
return false
"isadjacenttosource":
if src_pos.is_empty(): return false
var tgt_pos : Dictionary = unit.get("position", {})
if tgt_pos.is_empty(): return false
var dist := (absi(int(tgt_pos.get("x", 0)) - int(src_pos.get("x", 0))) +
absi(int(tgt_pos.get("y", 0)) - int(src_pos.get("y", 0))))
var dist := _board_distance(
int(tgt_pos.get("x", 0)), int(tgt_pos.get("y", 0)),
int(src_pos.get("x", 0)), int(src_pos.get("y", 0)))
if dist != 1: return false
# Check ability-level target conditions (e.g. IsOnTileWithAffinity for card abilities).
for cond: Dictionary in _ability_target_conditions:
@@ -3422,8 +3475,7 @@ func _tile_passes_filters(tx: int, ty: int, filters: Array) -> bool:
match f.get("$type", ""):
"tilewithinrange":
if src_pos.is_empty(): return false
var dist := (absi(tx - int(src_pos.get("x", 0))) +
absi(ty - int(src_pos.get("y", 0))))
var dist := _board_distance(tx, ty, int(src_pos.get("x", 0)), int(src_pos.get("y", 0)))
if dist < int(f.get("min", 0)) or dist > int(f.get("max", 999)):
return false
return true
@@ -3440,6 +3492,35 @@ func _is_linear(sx: int, sy: int, tx: int, ty: int) -> bool:
## Any unit occupying an intermediate tile blocks LOS (source and destination excluded).
func _client_has_los(sx: int, sy: int, tx: int, ty: int) -> bool:
if sx == tx and sy == ty: return true
if _board_grid_type == "Hexagon":
var N : int = _board_hex_sides
var aq : int = sx - (N - 1); var ar : int = sy - (N - 1)
var bq : int = tx - (N - 1); var br : int = ty - (N - 1)
var as_ : int = -aq - ar; var bs : int = -bq - br
var n : int = _board_distance(sx, sy, tx, ty)
if n == 0: return true
for i in range(1, n):
var t : float = float(i) / float(n)
var fq : float = aq + (bq - aq) * t
var fr : float = ar + (br - ar) * t
var fs : float = as_ + (bs - as_) * t
var rq : int = roundi(fq)
var rr : int = roundi(fr)
var rs : int = roundi(fs)
if rq + rr + rs != 0:
var eq : float = abs(rq - fq)
var er : float = abs(rr - fr)
var es : float = abs(rs - fs)
if eq >= er and eq >= es: rq = -rr - rs
elif er >= es: rr = -rq - rs
else: rs = -rq - rr
var cx : int = rq + (N - 1)
var cy : int = rr + (N - 1)
var tile := Game.get_tile(cx, cy)
if not tile.is_empty() and str(tile.get("occupantId", "")) != "":
return false
return true
# Square: supercover DDA
var dx := tx - sx; var dy := ty - sy
var nx := absi(dx); var ny := absi(dy)
var sign_x := 1 if dx > 0 else -1
@@ -32,6 +32,9 @@ public sealed class BoardTemplate
public int MinPlayers { get; set; } = 2;
public int MaxPlayers { get; set; } = 2;
public string GridType { get; set; } = "Square";
public int HexSides { get; set; } = 0;
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset UpdatedAt { get; set; }
}
@@ -99,6 +99,9 @@ public sealed class GameRuleSet
/// <summary>When set, use this BoardTemplate for games created under this ruleset.</summary>
public Guid? BoardTemplateId { get; set; }
public string GridType { get; set; } = "Square";
public int HexSides { get; set; } = 0;
// ── Timestamps ───────────────────────────────────────────────────────────
public DateTimeOffset CreatedAt { get; set; }
@@ -0,0 +1,539 @@
// <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("20260401000000_AddHexGridSupport")]
partial class AddHexGridSupport
{
/// <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.BoardTemplate", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Height")
.HasColumnType("integer");
b.Property<string>("GridType")
.IsRequired()
.HasDefaultValue("Square")
.HasColumnType("text");
b.Property<int>("HexSides")
.HasDefaultValue(0)
.HasColumnType("integer");
b.Property<bool>("IsAvailableForCustom")
.HasColumnType("boolean");
b.Property<bool>("IsAvailableForRanked")
.HasColumnType("boolean");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<int>("MaxPlayers")
.HasColumnType("integer");
b.Property<int>("MinPlayers")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StartingZonesJson")
.IsRequired()
.HasColumnType("jsonb");
b.Property<string>("TilesJson")
.IsRequired()
.HasColumnType("jsonb");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("Width")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("IsEnabled");
b.ToTable("board_templates", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AdditionalPlayersJson")
.HasColumnType("text")
.HasColumnName("additional_players_json");
b.Property<int?>("BoardHeightOverride")
.HasColumnType("integer");
b.Property<string>("BoardShapeOverride")
.HasColumnType("text");
b.Property<Guid?>("BoardTemplateIdOverride")
.HasColumnType("uuid");
b.Property<int?>("BoardWidthOverride")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool?>("DiscardOnMaxHandOverride")
.HasColumnType("boolean");
b.Property<int?>("DrawPerTurnOverride")
.HasColumnType("integer");
b.Property<bool?>("FirstPlayerSkipsDrawOverride")
.HasColumnType("boolean");
b.Property<string>("GameMode")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("FFA")
.HasColumnName("game_mode");
b.Property<Guid?>("GameSessionId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestAccountId")
.HasColumnType("uuid");
b.Property<Guid?>("GuestDeckId")
.HasColumnType("uuid");
b.Property<string>("GuestFirstTurnPref")
.HasColumnType("text");
b.Property<bool>("GuestReady")
.HasColumnType("boolean");
b.Property<int?>("HandSizeCapOverride")
.HasColumnType("integer");
b.Property<Guid>("HostAccountId")
.HasColumnType("uuid");
b.Property<Guid>("HostDeckId")
.HasColumnType("uuid");
b.Property<string>("HostFirstTurnPref")
.HasColumnType("text");
b.Property<bool>("HostReady")
.HasColumnType("boolean");
b.Property<int?>("MaxArchTier1Override")
.HasColumnType("integer");
b.Property<int?>("MaxDeckSizeOverride")
.HasColumnType("integer");
b.Property<int>("MaxPlayers")
.HasColumnType("integer");
b.Property<int?>("MinDeckSizeOverride")
.HasColumnType("integer");
b.Property<int?>("MpBuffOverride")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("OpeningHandSizeOverride")
.HasColumnType("integer");
b.Property<string>("Password")
.HasColumnType("text");
b.Property<int?>("SpAccumulationPerTurnOverride")
.HasColumnType("integer");
b.Property<int?>("SpCapOverride")
.HasColumnType("integer");
b.Property<bool?>("SpHasCapOverride")
.HasColumnType("boolean");
b.Property<int?>("StartingRandomTilePctOverride")
.HasColumnType("integer");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<string>("TeamAssignmentsJson")
.HasColumnType("text");
b.Property<int>("TeamCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(1)
.HasColumnName("team_count");
b.Property<int?>("TimeLimitMinutesOverride")
.HasColumnType("integer");
b.Property<int?>("TurnLimitOverride")
.HasColumnType("integer");
b.Property<int?>("TurnTimerSecondsOverride")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("HostAccountId");
b.HasIndex("Status", "CreatedAt");
b.ToTable("custom_lobbies", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
{
b.Property<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<string>("ResultJson")
.HasColumnType("jsonb")
.HasColumnName("result");
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<Guid?>("BoardTemplateId")
.HasColumnType("uuid");
b.Property<int>("BoardWidth")
.HasColumnType("integer");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("DiscardOnMaxHand")
.HasColumnType("boolean");
b.Property<int>("DrawPerTurn")
.HasColumnType("integer");
b.Property<bool>("FirstPlayerSkipsDraw")
.HasColumnType("boolean");
b.Property<string>("GridType")
.IsRequired()
.HasDefaultValue("Square")
.HasColumnType("text");
b.Property<int>("HandSizeCap")
.HasColumnType("integer");
b.Property<int>("HexSides")
.HasDefaultValue(0)
.HasColumnType("integer");
b.Property<bool>("IsCustomDefault")
.HasColumnType("boolean");
b.Property<bool>("IsRankedDefault")
.HasColumnType("boolean");
b.Property<int>("LoserOpReward")
.HasColumnType("integer");
b.Property<int>("MaxArchTier1")
.HasColumnType("integer");
b.Property<int>("MaxDeckSize")
.HasColumnType("integer");
b.Property<int>("MinDeckSize")
.HasColumnType("integer");
b.Property<int>("MpBuff")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("OpeningHandSize")
.HasColumnType("integer");
b.Property<int>("RankDiffOpMultiplierPct")
.HasColumnType("integer");
b.Property<int>("SpAccumulationPerTurn")
.HasColumnType("integer");
b.Property<int>("SpCap")
.HasColumnType("integer");
b.Property<bool>("SpHasCap")
.HasColumnType("boolean");
b.Property<int>("StartingRandomTilePct")
.HasColumnType("integer");
b.Property<int>("TimeLimitMinutes")
.HasColumnType("integer");
b.Property<int>("TurnLimit")
.HasColumnType("integer");
b.Property<int>("TurnTimerSeconds")
.HasColumnType("integer");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("WinnerOpReward")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("IsCustomDefault");
b.HasIndex("IsRankedDefault");
b.ToTable("game_rule_sets", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("AdditionalPlayersJson")
.HasColumnType("text")
.HasColumnName("additional_players_json");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<DateTimeOffset?>("EndedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("GameMode")
.IsRequired()
.ValueGeneratedOnAdd()
.HasColumnType("text")
.HasDefaultValue("FFA")
.HasColumnName("game_mode");
b.Property<DateTimeOffset?>("LastActionAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("PlayerCount")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(2)
.HasColumnName("player_count");
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.LobbyPreset", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("OwnerAccountId")
.HasColumnType("uuid");
b.Property<string>("RulesJson")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("OwnerAccountId");
b.ToTable("lobby_presets", "game");
});
modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b =>
{
b.Property<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,55 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SOR.Database.Migrations.Game
{
/// <inheritdoc />
public partial class AddHexGridSupport : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "grid_type",
schema: "game",
table: "game_rule_sets",
type: "text",
nullable: false,
defaultValue: "Square");
migrationBuilder.AddColumn<int>(
name: "hex_sides",
schema: "game",
table: "game_rule_sets",
type: "integer",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<string>(
name: "grid_type",
schema: "game",
table: "board_templates",
type: "text",
nullable: false,
defaultValue: "Square");
migrationBuilder.AddColumn<int>(
name: "hex_sides",
schema: "game",
table: "board_templates",
type: "integer",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(name: "grid_type", schema: "game", table: "game_rule_sets");
migrationBuilder.DropColumn(name: "hex_sides", schema: "game", table: "game_rule_sets");
migrationBuilder.DropColumn(name: "grid_type", schema: "game", table: "board_templates");
migrationBuilder.DropColumn(name: "hex_sides", schema: "game", table: "board_templates");
}
}
}
@@ -35,6 +35,15 @@ namespace SOR.Database.Migrations.Game
b.Property<int>("Height")
.HasColumnType("integer");
b.Property<string>("GridType")
.IsRequired()
.HasDefaultValue("Square")
.HasColumnType("text");
b.Property<int>("HexSides")
.HasDefaultValue(0)
.HasColumnType("integer");
b.Property<bool>("IsAvailableForCustom")
.HasColumnType("boolean");
@@ -281,9 +290,18 @@ namespace SOR.Database.Migrations.Game
b.Property<bool>("FirstPlayerSkipsDraw")
.HasColumnType("boolean");
b.Property<string>("GridType")
.IsRequired()
.HasDefaultValue("Square")
.HasColumnType("text");
b.Property<int>("HandSizeCap")
.HasColumnType("integer");
b.Property<int>("HexSides")
.HasDefaultValue(0)
.HasColumnType("integer");
b.Property<bool>("IsCustomDefault")
.HasColumnType("boolean");
+14 -2
View File
@@ -22,10 +22,12 @@ public static class AttackSystem
Board board,
IReadOnlyDictionary<Coord, string> unitsByCoord)
{
var dist = attackerPos.ManhattanDistance(targetPos);
var dist = board.HexSides > 0
? HexGrid.Distance(attackerPos, targetPos, board.HexSides)
: attackerPos.ManhattanDistance(targetPos);
if (dist < minRange || dist > maxRange) return false;
if (requiresLos && !LineOfSight.HasLos(board, attackerPos, targetPos, unitsByCoord))
if (requiresLos && !LineOfSight.HasLos(board, attackerPos, targetPos, unitsByCoord, board.HexSides))
return false;
return true;
@@ -42,6 +44,16 @@ public static class AttackSystem
bool requiresLos,
IReadOnlyDictionary<Coord, string> unitsByCoord)
{
if (board.HexSides > 0)
{
foreach (var tile in board.Tiles.Values)
{
if (CanAttack(attackerPos, tile.Coord, minRange, maxRange, requiresLos, board, unitsByCoord))
yield return tile.Coord;
}
yield break;
}
for (int dy = -maxRange; dy <= maxRange; dy++)
for (int dx = -maxRange; dx <= maxRange; dx++)
{
+7 -3
View File
@@ -317,7 +317,9 @@ public static class GameEngine
var minRange = card.MinChannelRange ?? 1;
var maxRange = card.MaxChannelRange ?? 1;
var dist = archSpirit.Position.Value.ManhattanDistance(coord);
var dist = board.HexSides > 0
? HexGrid.Distance(archSpirit.Position.Value, coord, board.HexSides)
: archSpirit.Position.Value.ManhattanDistance(coord);
if (dist < minRange || dist > maxRange)
throw new GameException("OUT_OF_CHANNEL_RANGE");
@@ -629,7 +631,7 @@ public static class GameEngine
var occupancy = board.BuildOccupancyMap();
occupancy.Remove(from); // exclude self from LOS check
if (!LineOfSight.HasLos(board, from, targetPos, occupancy))
if (!LineOfSight.HasLos(board, from, targetPos, occupancy, board.HexSides))
throw new GameException("NO_LINE_OF_SIGHT");
unit.CurrentMp -= 1;
@@ -1500,7 +1502,9 @@ public static class GameEngine
kvp => (IEnumerable<CoordDto>)kvp.Value.Select(c => new CoordDto(c.X, c.Y)));
}
return new BoardDto(board.Width, board.Height, tiles, startingZones);
return new BoardDto(board.Width, board.Height, tiles, startingZones,
GridType: board.HexSides > 0 ? "Hexagon" : "Square",
HexSides: board.HexSides);
}
}
+3 -1
View File
@@ -649,7 +649,9 @@ public sealed record BoardDto(
int Height,
IEnumerable<TileDto> Tiles,
/// <summary>Seat index → list of valid ArchSpirit placement coords. Empty for legacy 1v1.</summary>
Dictionary<int, IEnumerable<CoordDto>>? StartingZones = null);
Dictionary<int, IEnumerable<CoordDto>>? StartingZones = null,
string GridType = "Square",
int HexSides = 0);
public sealed record TileDto(
CoordDto Coord,
+3
View File
@@ -59,6 +59,9 @@ public sealed record GameRules
/// <summary>Board shape identifier passed to BoardShapeGenerator. "Rectangle" | "Cross".</summary>
public string BoardShape { get; init; } = "Default";
public string GridType { get; init; } = "Square";
public int HexSides { get; init; } = 0;
/// <summary>Number of players in this game. 2 = standard 1v1.</summary>
public int PlayerCount { get; init; } = 2;
+18 -1
View File
@@ -21,6 +21,12 @@ public sealed class Board
/// </summary>
public Dictionary<int, HashSet<Coord>> StartingZones { get; init; } = new();
/// <summary>
/// When &gt; 0, this board uses hex grid rules with the given number of sides (N).
/// Diameter = 2N−1. 0 = square grid.
/// </summary>
public int HexSides { get; init; } = 0;
// Base1 pool: elemental basics + Aether (never Void — Base1 always carries a real affinity).
private static readonly Affinity[] _base1Pool =
[Affinity.Lake, Affinity.Hill, Affinity.Forest, Affinity.Field, Affinity.Aether];
@@ -75,7 +81,9 @@ public sealed class Board
}
public bool IsInBounds(Coord c)
=> c.X >= 0 && c.X < Width && c.Y >= 0 && c.Y < Height;
=> HexSides > 0
? HexGrid.IsInBounds(c, HexSides)
: 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;
@@ -87,6 +95,15 @@ public sealed class Board
.Where(t => t is not null)
.Select(t => t!);
/// <summary>
/// Returns all grid neighbours of <paramref name="c"/>, respecting the grid type.
/// For hex boards uses the six axial directions; for square boards uses four orthogonal directions.
/// </summary>
public IEnumerable<Coord> GetNeighbors(Coord c)
=> HexSides > 0
? HexGrid.Neighbors(c, HexSides)
: c.OrthogonalNeighbors().Where(IsInBounds);
public Coord? FindOccupant(string instanceId)
{
foreach (var tile in Tiles.Values)
@@ -43,6 +43,7 @@ public static class BoardShapeGenerator
"radialstar" => "RadialStar",
"hexring" => "HexRing",
"decagonal" => "Decagonal",
"hexagon" => "Hexagon",
_ => "Rectangle",
};
}
@@ -58,6 +59,7 @@ public static class BoardShapeGenerator
"RadialStar" => MakeRadialStar(rules),
"HexRing" => MakeHexRing(rules),
"Decagonal" => MakeDecagonal(rules, playerCount),
"Hexagon" => MakeHexagon(rules, playerCount),
_ => MakeRectangle(rules, playerCount),
};
}
@@ -345,6 +347,84 @@ public static class BoardShapeGenerator
return new Board { Width = total, Height = total, Tiles = tiles, StartingZones = zones };
}
/// <summary>
/// Regular hexagonal board. <see cref="GameRules.HexSides"/> N controls size (3–10).
/// Diameter = 2N−1. Up to 6 starting zones, one per flat-top edge, assigned in order
/// bottom → lower-right → upper-right → top → upper-left → lower-left.
/// </summary>
private static Board MakeHexagon(GameRules rules, int playerCount)
{
int N = Math.Clamp(rules.HexSides > 0 ? rules.HexSides : 5, 3, 10);
int diameter = 2 * N - 1;
var tiles = new Dictionary<string, Tile>();
for (int x = 0; x < diameter; x++)
for (int y = 0; y < diameter; y++)
{
var c = new Coord(x, y);
if (HexGrid.IsInBounds(c, N))
AddTile(tiles, x, y, rules.StartingRandomTilePct);
}
// Six edge directions in axial (dq, dr) — each edge spans N tiles.
// Axial corners (q,r): (N-1, -(N-1)), (N-1, 0), (0, N-1),
// (-(N-1), N-1), (-(N-1), 0), (0, -(N-1))
(int q, int r)[] corners =
[
( N-1, -(N-1)), // edge 0 start (bottom-right corner)
( N-1, 0), // edge 1 start (right corner)
( 0, N-1), // edge 2 start (upper-right corner)
(-(N-1), N-1), // edge 3 start (upper-left corner) — top edge start
(-(N-1), 0), // edge 4 start (left corner)
( 0, -(N-1)), // edge 5 start (lower-left corner)
];
(int dq, int dr)[] edgeDirs =
[
(-1, +1), // edge 0: bottom
(-1, 0), // edge 1: lower-right
( 0, -1), // edge 2: upper-right
(+1, -1), // edge 3: top
(+1, 0), // edge 4: upper-left
( 0, +1), // edge 5: lower-left
];
int seats = Math.Clamp(playerCount, 2, 6);
int[] edgeAssign = seats switch
{
2 => [0, 3],
3 => [0, 2, 4],
4 => [0, 1, 3, 4],
5 => [0, 1, 2, 3, 4],
_ => [0, 1, 2, 3, 4, 5],
};
var zones = new Dictionary<int, HashSet<Coord>>();
for (int seat = 0; seat < seats; seat++)
{
int ei = edgeAssign[seat];
var (sq, sr) = corners[ei];
var (dq, dr) = edgeDirs[ei];
var edge = new HashSet<Coord>(N);
for (int step = 0; step < N; step++)
{
var c = HexGrid.FromAxial(sq + dq * step, sr + dr * step, N);
if (HexGrid.IsInBounds(c, N))
edge.Add(c);
}
zones[seat] = edge;
}
return new Board
{
Width = diameter,
Height = diameter,
HexSides = N,
Tiles = tiles,
StartingZones = zones,
};
}
// ── Template-based board ──────────────────────────────────────────────────
/// <summary>
@@ -442,6 +522,7 @@ public static class BoardShapeGenerator
{
Width = snapshot.Width,
Height = snapshot.Height,
HexSides = snapshot.HexSides,
Tiles = tiles,
StartingZones = zones,
};
@@ -12,8 +12,10 @@ using SOR.Database.Enums;
/// </summary>
public sealed class BoardTemplateSnapshot
{
public int Width { get; set; }
public int Height { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string GridType { get; set; } = "Square";
public int HexSides { get; set; } = 0;
public List<SnapshotTile> Tiles { get; set; } = new();
+127
View File
@@ -0,0 +1,127 @@
namespace SOR.Game.Grid;
/// <summary>
/// Hex grid helpers using offset-mapped axial coordinates.
///
/// A hex board of <c>sides</c> N has diameter = 2N−1.
/// Coord(x,y) maps to axial (q,r) = (x − (N−1), y − (N−1)).
/// In-bounds: max(|q|, |r|, |q+r|) ≤ N−1.
///
/// Six neighbour directions in axial space:
/// (+1, 0), (−1, 0), (0, +1), (0, −1), (+1, −1), (−1, +1)
/// </summary>
public static class HexGrid
{
// The six axial direction vectors.
private static readonly (int dq, int dr)[] Directions =
[
( 1, 0), (-1, 0),
( 0, 1), ( 0, -1),
( 1, -1), (-1, 1),
];
/// <summary>Convert offset Coord → axial (q, r).</summary>
public static (int q, int r) ToAxial(Coord c, int sides)
=> (c.X - (sides - 1), c.Y - (sides - 1));
/// <summary>Convert axial (q, r) → offset Coord.</summary>
public static Coord FromAxial(int q, int r, int sides)
=> new(q + sides - 1, r + sides - 1);
/// <summary>True when Coord c lies within the hex board of the given side count.</summary>
public static bool IsInBounds(Coord c, int sides)
{
var (q, r) = ToAxial(c, sides);
return Math.Max(Math.Abs(q), Math.Max(Math.Abs(r), Math.Abs(q + r))) <= sides - 1;
}
/// <summary>Hex distance (cube metric) between two offset coords.</summary>
public static int Distance(Coord a, Coord b, int sides)
{
var (aq, ar) = ToAxial(a, sides);
var (bq, br) = ToAxial(b, sides);
int dq = aq - bq, dr = ar - br;
return (Math.Abs(dq) + Math.Abs(dr) + Math.Abs(dq + dr)) / 2;
}
/// <summary>All six in-bounds neighbours of c on a hex board of given side count.</summary>
public static IEnumerable<Coord> Neighbors(Coord c, int sides)
{
var (q, r) = ToAxial(c, sides);
foreach (var (dq, dr) in Directions)
{
var nb = FromAxial(q + dq, r + dr, sides);
if (IsInBounds(nb, sides))
yield return nb;
}
}
/// <summary>
/// Returns true if there is unobstructed LOS from <paramref name="from"/> to
/// <paramref name="to"/> on a hex board. Uses cube-coordinate linear interpolation
/// with fractional rounding — the hex analogue of supercover DDA.
/// Source and destination are excluded from the obstruction check.
/// </summary>
public static bool HasLos(
Coord from,
Coord to,
int sides,
IReadOnlyDictionary<Coord, string> unitsByCoord)
{
if (from == to) return true;
int n = Distance(from, to, sides);
if (n == 0) return true;
var (aq, ar) = ToAxial(from, sides);
var (bq, br) = ToAxial(to, sides);
int @as = -aq - ar;
int bs = -bq - br;
for (int i = 1; i < n; i++)
{
double t = (double)i / n;
double fq = aq + (bq - aq) * t;
double fr = ar + (br - ar) * t;
double fs = @as + (bs - @as) * t;
// Cube round: round all three, then fix the one with largest error
// to preserve the invariant rq + rr + rs == 0.
int rq = (int)Math.Round(fq);
int rr = (int)Math.Round(fr);
int rs = (int)Math.Round(fs);
if (rq + rr + rs != 0)
{
double eq = Math.Abs(rq - fq);
double er = Math.Abs(rr - fr);
double es = Math.Abs(rs - fs);
if (eq >= er && eq >= es) rq = -rr - rs;
else if (er >= es) rr = -rq - rs;
else rs = -rq - rr;
}
var mid = FromAxial(rq, rr, sides);
if (unitsByCoord.ContainsKey(mid))
return false;
}
return true;
}
/// <summary>
/// All in-bounds hex tiles reachable by a Jump/Teleport from <paramref name="from"/>
/// within [minRange..maxRange] hex steps.
/// </summary>
public static IEnumerable<Coord> GetJumpRange(
Board board, Coord from, int minRange, int maxRange, int sides)
{
foreach (var tile in board.Tiles.Values)
{
var c = tile.Coord;
int d = Distance(from, c, sides);
if (d >= minRange && d <= maxRange)
yield return c;
}
}
}
+5 -1
View File
@@ -20,8 +20,12 @@ public static class LineOfSight
Board board,
Coord from,
Coord to,
IReadOnlyDictionary<Coord, string> unitsByCoord)
IReadOnlyDictionary<Coord, string> unitsByCoord,
int hexSides = 0)
{
if (hexSides > 0)
return HexGrid.HasLos(from, to, hexSides, unitsByCoord);
if (from == to) return true;
int dx = to.X - from.X;
+1 -2
View File
@@ -33,9 +33,8 @@ public static class Pathfinding
var (current, cost) = queue.Dequeue();
if (cost >= maxMp) continue;
foreach (var neighbor in current.OrthogonalNeighbors())
foreach (var neighbor in board.GetNeighbors(current))
{
if (!board.IsInBounds(neighbor)) continue;
if (blocked.Contains(neighbor)) continue;
if (result.ContainsKey(neighbor)) continue;