From 2cfa60c7ddc526a4f8fc7261c30250d596bdd32c Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 1 Apr 2026 16:44:17 -0400 Subject: [PATCH] =?UTF-8?q?Add=20hex=20grid=20support=20(sides=203?= =?UTF-8?q?=E2=80=9310)=20for=20boards,=20pathfinding,=20LOS,=20and=20clie?= =?UTF-8?q?nt=20rendering?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 Co-Authored-By: Happy --- .../origin-client/scenes/game/game_screen.gd | 137 ++++- .../Entities/Game/BoardTemplate.cs | 3 + .../SOR.Database/Entities/Game/GameRuleSet.cs | 3 + ...260401000000_AddHexGridSupport.Designer.cs | 539 ++++++++++++++++++ .../Game/20260401000000_AddHexGridSupport.cs | 55 ++ .../Game/GameDbContextModelSnapshot.cs | 18 + Server/src/SOR.Game/Combat/AttackSystem.cs | 16 +- Server/src/SOR.Game/GameEngine.cs | 10 +- Server/src/SOR.Game/GameMessages.cs | 4 +- Server/src/SOR.Game/GameRules.cs | 3 + Server/src/SOR.Game/Grid/Board.cs | 19 +- .../src/SOR.Game/Grid/BoardShapeGenerator.cs | 81 +++ .../SOR.Game/Grid/BoardTemplateSnapshot.cs | 6 +- Server/src/SOR.Game/Grid/HexGrid.cs | 127 +++++ Server/src/SOR.Game/Grid/LineOfSight.cs | 6 +- Server/src/SOR.Game/Grid/Pathfinding.cs | 3 +- 16 files changed, 990 insertions(+), 40 deletions(-) create mode 100644 Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.Designer.cs create mode 100644 Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.cs create mode 100644 Server/src/SOR.Game/Grid/HexGrid.cs diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd index 2ec8fa4..6f51109 100644 --- a/Client/origin-client/scenes/game/game_screen.gd +++ b/Client/origin-client/scenes/game/game_screen.gd @@ -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 diff --git a/Server/src/SOR.Database/Entities/Game/BoardTemplate.cs b/Server/src/SOR.Database/Entities/Game/BoardTemplate.cs index 147c649..4dbc996 100644 --- a/Server/src/SOR.Database/Entities/Game/BoardTemplate.cs +++ b/Server/src/SOR.Database/Entities/Game/BoardTemplate.cs @@ -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; } } diff --git a/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs b/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs index 9af6102..3ba70d5 100644 --- a/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs +++ b/Server/src/SOR.Database/Entities/Game/GameRuleSet.cs @@ -99,6 +99,9 @@ public sealed class GameRuleSet /// When set, use this BoardTemplate for games created under this ruleset. public Guid? BoardTemplateId { get; set; } + public string GridType { get; set; } = "Square"; + public int HexSides { get; set; } = 0; + // ── Timestamps ─────────────────────────────────────────────────────────── public DateTimeOffset CreatedAt { get; set; } diff --git a/Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.Designer.cs new file mode 100644 index 0000000..872a908 --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.Designer.cs @@ -0,0 +1,539 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("GridType") + .IsRequired() + .HasDefaultValue("Square") + .HasColumnType("text"); + + b.Property("HexSides") + .HasDefaultValue(0) + .HasColumnType("integer"); + + b.Property("IsAvailableForCustom") + .HasColumnType("boolean"); + + b.Property("IsAvailableForRanked") + .HasColumnType("boolean"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("MaxPlayers") + .HasColumnType("integer"); + + b.Property("MinPlayers") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartingZonesJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("TilesJson") + .IsRequired() + .HasColumnType("jsonb"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsEnabled"); + + b.ToTable("board_templates", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + + b.Property("BoardHeightOverride") + .HasColumnType("integer"); + + b.Property("BoardShapeOverride") + .HasColumnType("text"); + + b.Property("BoardTemplateIdOverride") + .HasColumnType("uuid"); + + b.Property("BoardWidthOverride") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHandOverride") + .HasColumnType("boolean"); + + b.Property("DrawPerTurnOverride") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDrawOverride") + .HasColumnType("boolean"); + + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("GuestAccountId") + .HasColumnType("uuid"); + + b.Property("GuestDeckId") + .HasColumnType("uuid"); + + b.Property("GuestFirstTurnPref") + .HasColumnType("text"); + + b.Property("GuestReady") + .HasColumnType("boolean"); + + b.Property("HandSizeCapOverride") + .HasColumnType("integer"); + + b.Property("HostAccountId") + .HasColumnType("uuid"); + + b.Property("HostDeckId") + .HasColumnType("uuid"); + + b.Property("HostFirstTurnPref") + .HasColumnType("text"); + + b.Property("HostReady") + .HasColumnType("boolean"); + + b.Property("MaxArchTier1Override") + .HasColumnType("integer"); + + b.Property("MaxDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MaxPlayers") + .HasColumnType("integer"); + + b.Property("MinDeckSizeOverride") + .HasColumnType("integer"); + + b.Property("MpBuffOverride") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSizeOverride") + .HasColumnType("integer"); + + b.Property("Password") + .HasColumnType("text"); + + b.Property("SpAccumulationPerTurnOverride") + .HasColumnType("integer"); + + b.Property("SpCapOverride") + .HasColumnType("integer"); + + b.Property("SpHasCapOverride") + .HasColumnType("boolean"); + + b.Property("StartingRandomTilePctOverride") + .HasColumnType("integer"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("TeamAssignmentsJson") + .HasColumnType("text"); + + b.Property("TeamCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("team_count"); + + b.Property("TimeLimitMinutesOverride") + .HasColumnType("integer"); + + b.Property("TurnLimitOverride") + .HasColumnType("integer"); + + b.Property("TurnTimerSecondsOverride") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("HostAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("custom_lobbies", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ActionType") + .IsRequired() + .HasColumnType("text"); + + b.Property("ActorAccountId") + .HasColumnType("uuid"); + + b.Property("GameSessionId") + .HasColumnType("uuid"); + + b.Property("OccurredAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PayloadJson") + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("ResultJson") + .HasColumnType("jsonb") + .HasColumnName("result"); + + b.Property("SequenceNumber") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ActorAccountId"); + + b.HasIndex("GameSessionId", "SequenceNumber") + .IsUnique(); + + b.ToTable("action_logs", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BoardHeight") + .HasColumnType("integer"); + + b.Property("BoardTemplateId") + .HasColumnType("uuid"); + + b.Property("BoardWidth") + .HasColumnType("integer"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DiscardOnMaxHand") + .HasColumnType("boolean"); + + b.Property("DrawPerTurn") + .HasColumnType("integer"); + + b.Property("FirstPlayerSkipsDraw") + .HasColumnType("boolean"); + + b.Property("GridType") + .IsRequired() + .HasDefaultValue("Square") + .HasColumnType("text"); + + b.Property("HandSizeCap") + .HasColumnType("integer"); + + b.Property("HexSides") + .HasDefaultValue(0) + .HasColumnType("integer"); + + b.Property("IsCustomDefault") + .HasColumnType("boolean"); + + b.Property("IsRankedDefault") + .HasColumnType("boolean"); + + b.Property("LoserOpReward") + .HasColumnType("integer"); + + b.Property("MaxArchTier1") + .HasColumnType("integer"); + + b.Property("MaxDeckSize") + .HasColumnType("integer"); + + b.Property("MinDeckSize") + .HasColumnType("integer"); + + b.Property("MpBuff") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OpeningHandSize") + .HasColumnType("integer"); + + b.Property("RankDiffOpMultiplierPct") + .HasColumnType("integer"); + + b.Property("SpAccumulationPerTurn") + .HasColumnType("integer"); + + b.Property("SpCap") + .HasColumnType("integer"); + + b.Property("SpHasCap") + .HasColumnType("boolean"); + + b.Property("StartingRandomTilePct") + .HasColumnType("integer"); + + b.Property("TimeLimitMinutes") + .HasColumnType("integer"); + + b.Property("TurnLimit") + .HasColumnType("integer"); + + b.Property("TurnTimerSeconds") + .HasColumnType("integer"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("WinnerOpReward") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("IsCustomDefault"); + + b.HasIndex("IsRankedDefault"); + + b.ToTable("game_rule_sets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalPlayersJson") + .HasColumnType("text") + .HasColumnName("additional_players_json"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EndedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("GameMode") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("FFA") + .HasColumnName("game_mode"); + + b.Property("LastActionAt") + .HasColumnType("timestamp with time zone"); + + b.Property("PlayerCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(2) + .HasColumnName("player_count"); + + b.Property("PlayerOneAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerOneDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerOneReady") + .HasColumnType("boolean"); + + b.Property("PlayerTwoAccountId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoDeckId") + .HasColumnType("uuid"); + + b.Property("PlayerTwoReady") + .HasColumnType("boolean"); + + b.Property("RuleSnapshotJson") + .HasColumnType("jsonb") + .HasColumnName("rule_snapshot"); + + b.Property("StartedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("StateJson") + .HasColumnType("jsonb") + .HasColumnName("state"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.Property("WinCondition") + .HasColumnType("text"); + + b.Property("WinnerAccountId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("PlayerOneAccountId"); + + b.HasIndex("PlayerTwoAccountId"); + + b.HasIndex("Status", "CreatedAt"); + + b.ToTable("game_sessions", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.LobbyPreset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("OwnerAccountId") + .HasColumnType("uuid"); + + b.Property("RulesJson") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("OwnerAccountId"); + + b.ToTable("lobby_presets", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountId") + .HasColumnType("uuid"); + + b.Property("DeckId") + .HasColumnType("uuid"); + + b.Property("JoinedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("MatchedGameSessionId") + .HasColumnType("uuid"); + + b.Property("RankScore") + .HasColumnType("integer"); + + b.Property("ResolvedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("AccountId", "Status"); + + b.HasIndex("Status", "RankScore"); + + b.ToTable("matchmaking_entries", "game"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b => + { + b.HasOne("SOR.Database.Entities.Game.GameSession", "Session") + .WithMany("ActionLog") + .HasForeignKey("GameSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Session"); + }); + + modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b => + { + b.Navigation("ActionLog"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.cs b/Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.cs new file mode 100644 index 0000000..2f61cac --- /dev/null +++ b/Server/src/SOR.Database/Migrations/Game/20260401000000_AddHexGridSupport.cs @@ -0,0 +1,55 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SOR.Database.Migrations.Game +{ + /// + public partial class AddHexGridSupport : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "grid_type", + schema: "game", + table: "game_rule_sets", + type: "text", + nullable: false, + defaultValue: "Square"); + + migrationBuilder.AddColumn( + name: "hex_sides", + schema: "game", + table: "game_rule_sets", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "grid_type", + schema: "game", + table: "board_templates", + type: "text", + nullable: false, + defaultValue: "Square"); + + migrationBuilder.AddColumn( + name: "hex_sides", + schema: "game", + table: "board_templates", + type: "integer", + nullable: false, + defaultValue: 0); + } + + /// + 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"); + } + } +} diff --git a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs index e3701a8..ff39f48 100644 --- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs +++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs @@ -35,6 +35,15 @@ namespace SOR.Database.Migrations.Game b.Property("Height") .HasColumnType("integer"); + b.Property("GridType") + .IsRequired() + .HasDefaultValue("Square") + .HasColumnType("text"); + + b.Property("HexSides") + .HasDefaultValue(0) + .HasColumnType("integer"); + b.Property("IsAvailableForCustom") .HasColumnType("boolean"); @@ -281,9 +290,18 @@ namespace SOR.Database.Migrations.Game b.Property("FirstPlayerSkipsDraw") .HasColumnType("boolean"); + b.Property("GridType") + .IsRequired() + .HasDefaultValue("Square") + .HasColumnType("text"); + b.Property("HandSizeCap") .HasColumnType("integer"); + b.Property("HexSides") + .HasDefaultValue(0) + .HasColumnType("integer"); + b.Property("IsCustomDefault") .HasColumnType("boolean"); diff --git a/Server/src/SOR.Game/Combat/AttackSystem.cs b/Server/src/SOR.Game/Combat/AttackSystem.cs index d065fd9..f8ea9bf 100644 --- a/Server/src/SOR.Game/Combat/AttackSystem.cs +++ b/Server/src/SOR.Game/Combat/AttackSystem.cs @@ -22,10 +22,12 @@ public static class AttackSystem Board board, IReadOnlyDictionary 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 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++) { diff --git a/Server/src/SOR.Game/GameEngine.cs b/Server/src/SOR.Game/GameEngine.cs index c30b498..8576f50 100644 --- a/Server/src/SOR.Game/GameEngine.cs +++ b/Server/src/SOR.Game/GameEngine.cs @@ -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)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); } } diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs index bf872a1..5cbace3 100644 --- a/Server/src/SOR.Game/GameMessages.cs +++ b/Server/src/SOR.Game/GameMessages.cs @@ -649,7 +649,9 @@ public sealed record BoardDto( int Height, IEnumerable Tiles, /// Seat index → list of valid ArchSpirit placement coords. Empty for legacy 1v1. - Dictionary>? StartingZones = null); + Dictionary>? StartingZones = null, + string GridType = "Square", + int HexSides = 0); public sealed record TileDto( CoordDto Coord, diff --git a/Server/src/SOR.Game/GameRules.cs b/Server/src/SOR.Game/GameRules.cs index 14c2084..39fac19 100644 --- a/Server/src/SOR.Game/GameRules.cs +++ b/Server/src/SOR.Game/GameRules.cs @@ -59,6 +59,9 @@ public sealed record GameRules /// Board shape identifier passed to BoardShapeGenerator. "Rectangle" | "Cross". public string BoardShape { get; init; } = "Default"; + public string GridType { get; init; } = "Square"; + public int HexSides { get; init; } = 0; + /// Number of players in this game. 2 = standard 1v1. public int PlayerCount { get; init; } = 2; diff --git a/Server/src/SOR.Game/Grid/Board.cs b/Server/src/SOR.Game/Grid/Board.cs index 17e1659..cdcd716 100644 --- a/Server/src/SOR.Game/Grid/Board.cs +++ b/Server/src/SOR.Game/Grid/Board.cs @@ -21,6 +21,12 @@ public sealed class Board /// public Dictionary> StartingZones { get; init; } = new(); + /// + /// When > 0, this board uses hex grid rules with the given number of sides (N). + /// Diameter = 2N−1. 0 = square grid. + /// + 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!); + /// + /// Returns all grid neighbours of , respecting the grid type. + /// For hex boards uses the six axial directions; for square boards uses four orthogonal directions. + /// + public IEnumerable GetNeighbors(Coord c) + => HexSides > 0 + ? HexGrid.Neighbors(c, HexSides) + : c.OrthogonalNeighbors().Where(IsInBounds); + public Coord? FindOccupant(string instanceId) { foreach (var tile in Tiles.Values) diff --git a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs index 968f961..e4c737d 100644 --- a/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs +++ b/Server/src/SOR.Game/Grid/BoardShapeGenerator.cs @@ -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 }; } + /// + /// Regular hexagonal board. 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. + /// + 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(); + + 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>(); + 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(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 ────────────────────────────────────────────────── /// @@ -442,6 +522,7 @@ public static class BoardShapeGenerator { Width = snapshot.Width, Height = snapshot.Height, + HexSides = snapshot.HexSides, Tiles = tiles, StartingZones = zones, }; diff --git a/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs b/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs index df0ee7f..977fde4 100644 --- a/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs +++ b/Server/src/SOR.Game/Grid/BoardTemplateSnapshot.cs @@ -12,8 +12,10 @@ using SOR.Database.Enums; /// 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 Tiles { get; set; } = new(); diff --git a/Server/src/SOR.Game/Grid/HexGrid.cs b/Server/src/SOR.Game/Grid/HexGrid.cs new file mode 100644 index 0000000..30edf0b --- /dev/null +++ b/Server/src/SOR.Game/Grid/HexGrid.cs @@ -0,0 +1,127 @@ +namespace SOR.Game.Grid; + +/// +/// Hex grid helpers using offset-mapped axial coordinates. +/// +/// A hex board of sides 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) +/// +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), + ]; + + /// Convert offset Coord → axial (q, r). + public static (int q, int r) ToAxial(Coord c, int sides) + => (c.X - (sides - 1), c.Y - (sides - 1)); + + /// Convert axial (q, r) → offset Coord. + public static Coord FromAxial(int q, int r, int sides) + => new(q + sides - 1, r + sides - 1); + + /// True when Coord c lies within the hex board of the given side count. + 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; + } + + /// Hex distance (cube metric) between two offset coords. + 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; + } + + /// All six in-bounds neighbours of c on a hex board of given side count. + public static IEnumerable 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; + } + } + + /// + /// Returns true if there is unobstructed LOS from 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. + /// + public static bool HasLos( + Coord from, + Coord to, + int sides, + IReadOnlyDictionary 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; + } + + /// + /// All in-bounds hex tiles reachable by a Jump/Teleport from + /// within [minRange..maxRange] hex steps. + /// + public static IEnumerable 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; + } + } +} diff --git a/Server/src/SOR.Game/Grid/LineOfSight.cs b/Server/src/SOR.Game/Grid/LineOfSight.cs index 7a31c04..4d01101 100644 --- a/Server/src/SOR.Game/Grid/LineOfSight.cs +++ b/Server/src/SOR.Game/Grid/LineOfSight.cs @@ -20,8 +20,12 @@ public static class LineOfSight Board board, Coord from, Coord to, - IReadOnlyDictionary unitsByCoord) + IReadOnlyDictionary 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; diff --git a/Server/src/SOR.Game/Grid/Pathfinding.cs b/Server/src/SOR.Game/Grid/Pathfinding.cs index 54bcbae..ef084fa 100644 --- a/Server/src/SOR.Game/Grid/Pathfinding.cs +++ b/Server/src/SOR.Game/Grid/Pathfinding.cs @@ -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;