SlimePlatformer/Levels/Maze/maze_carver.gd
tachyonwolf e7ae22b8cd Add Maze mode with one-way tubes and a soft-lock check
- Main menu "Maze" button opens a setup panel (width, height in screens;
  complexity 1-5) and generates a maze of rock chambers joined by tubes,
  with Start and End pads and a win panel.
- New one-way tube kind: orange tiles that only let the slime in at their
  entrance, with motes drifting into it (OneWayTube, TubeVacuum). The
  auto-tube trace moved to PixelStream.trace_tube so the player and the
  maze validator share it.
- Generation: chamber graph (spanning tree rooted at End, one-way tubes
  only towards End on the route, extra tubes), carved with AStarGrid2D.
  MazeValidator re-derives the chamber graph from the tiles and checks
  that End is reachable from every chamber reachable from Start.
- tests/maze_check.gd: headless batch check (360 mazes) plus a known
  soft-lock the validator must reject. See docs/MAZE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:45:46 -06:00

181 lines
7.4 KiB
GDScript

class_name MazeCarver
extends RefCounted
# Turns a MazeGraph into tiles: rock everywhere, a rectangle of air for each
# chamber, and each tube routed through the rock between its two chambers.
#
# Each screen (one RoomCamera room) is split into a grid of regions, one per
# chamber. A chamber is a random rectangle inside its region with at least a
# tile of rock all round, so chambers never touch and never cross a screen
# border. Tubes are routed with AStarGrid2D over the rock, with random weights
# so they wander; tubes never share a tile, so they can't join by accident.
const MIN_CHAMBER_SIZE = 3 # Tiles of air across and down, at least.
const MIN_ROCK = 3 # Rock left in a region beside its chamber, across and down, at least (when there's room).
const MOUTH_CHOICES = 4 # Of the spots for a mouth nearest the other chamber, how many we pick from.
const ROUTE_TRIES = 8 # Pairs of mouth spots to try before giving up on a tube.
var chamberRects: Array[Rect2i] = []
var bounds := Rect2i() # The whole maze, in tiles.
var startCell := Vector2i.ZERO # The air tile Start sits on (on a chamber's floor).
var endCell := Vector2i.ZERO
var isComplete := false # Whether every tube the maze needs got a route.
var routedTubeCount := 0
var _layer: TileMapLayer
var _tiles: MazeTiles
var _random: RandomNumberGenerator
var _pathfinder := AStarGrid2D.new()
var _winding := 0.0
func _init(graph: MazeGraph, screens: Vector2i, layer: TileMapLayer, random: RandomNumberGenerator, winding: float) -> void:
_layer = layer
_tiles = MazeTiles.new(layer.tile_set)
_random = random
_winding = winding
var screenTiles := Vector2i(RoomCamera.ROOM_SIZE) / layer.tile_set.tile_size
bounds = Rect2i(Vector2i.ZERO, screenTiles * screens)
_fill_rock()
_carve_chambers(graph, screenTiles)
_setup_pathfinder()
isComplete = true
for tube in graph.tubes:
if _carve_tube(tube):
routedTubeCount += 1
elif tube.isRequired:
isComplete = false
return
startCell = _floor_cell(chamberRects[graph.start])
endCell = _floor_cell(chamberRects[graph.end])
func _fill_rock() -> void:
_layer.clear()
for y in range(bounds.position.y, bounds.end.y):
for x in range(bounds.position.x, bounds.end.x):
_tiles.set_tile(_layer, Vector2i(x, y), 0, MazeTiles.ROCK)
func _carve_chambers(graph: MazeGraph, screenTiles: Vector2i) -> void:
var split: Vector2i = graph.gridSize / (bounds.size / screenTiles)
for chamber in graph.chamber_count():
var region := _region(graph.grid_cell(chamber), split, screenTiles)
var size := Vector2i(_random_size(region.size.x), _random_size(region.size.y))
var corner := Vector2i(_random.randi_range(region.position.x + 1, region.end.x - 1 - size.x),
_random.randi_range(region.position.y + 1, region.end.y - 1 - size.y))
var rect := Rect2i(corner, size)
chamberRects.append(rect)
for y in range(rect.position.y, rect.end.y):
for x in range(rect.position.x, rect.end.x):
_layer.erase_cell(Vector2i(x, y))
# The tiles a chamber's region covers. The last region in each screen row or
# column takes what's left over.
static func _region(gridCell: Vector2i, split: Vector2i, screenTiles: Vector2i) -> Rect2i:
var screen := gridCell / split
var inScreen := gridCell % split
var regionSize := screenTiles / split
var position := screen * screenTiles + inScreen * regionSize
var size := regionSize
if inScreen.x == split.x - 1:
size.x = screenTiles.x - inScreen.x * regionSize.x
if inScreen.y == split.y - 1:
size.y = screenTiles.y - inScreen.y * regionSize.y
return Rect2i(position, size)
# A chamber size for a region `regionSize` tiles long: room for MIN_ROCK
# beside it if possible, and always a tile of rock each side.
func _random_size(regionSize: int) -> int:
var largest := maxi(regionSize - MIN_ROCK, MIN_CHAMBER_SIZE)
return mini(_random.randi_range(MIN_CHAMBER_SIZE, largest), regionSize - 2)
# A random tile along the bottom row of a chamber.
func _floor_cell(rect: Rect2i) -> Vector2i:
return Vector2i(_random.randi_range(rect.position.x, rect.end.x - 1), rect.end.y - 1)
# ---- Tubes ----
func _setup_pathfinder() -> void:
_pathfinder.region = bounds
_pathfinder.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
_pathfinder.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
_pathfinder.update()
# Tubes go through rock only, and never through the maze's outer edge.
for y in range(bounds.position.y, bounds.end.y):
for x in range(bounds.position.x, bounds.end.x):
var cell := Vector2i(x, y)
var isEdge := x == bounds.position.x or y == bounds.position.y or x == bounds.end.x - 1 or y == bounds.end.y - 1
_pathfinder.set_point_solid(cell, isEdge or _layer.get_cell_source_id(cell) == -1)
# Routes `tube` and puts its tiles down. False if there's no way through.
func _carve_tube(tube: Dictionary) -> bool:
var fromRect := chamberRects[tube.from]
var toRect := chamberRects[tube.to]
_randomize_weights()
var fromMouths := _mouth_spots(fromRect, toRect)
var toMouths := _mouth_spots(toRect, fromRect)
for attempt in ROUTE_TRIES:
if fromMouths.is_empty() or toMouths.is_empty():
return false
var fromMouth: Vector2i = fromMouths[_random.randi_range(0, fromMouths.size() - 1)]
var toMouth: Vector2i = toMouths[_random.randi_range(0, toMouths.size() - 1)]
var path := _pathfinder.get_id_path(fromMouth, toMouth)
if path.is_empty():
continue
_put_tube_tiles(path, fromRect, toRect, tube.kind)
return true
return false
# Random extra cost on every tile, so routes wander instead of always taking
# the shortest way.
func _randomize_weights() -> void:
for y in range(bounds.position.y, bounds.end.y):
for x in range(bounds.position.x, bounds.end.x):
_pathfinder.set_point_weight_scale(Vector2i(x, y), 1.0 + _random.randf() * _winding)
# Free rock tiles touching `rect`'s sides, where a mouth into it can go: the
# MOUTH_CHOICES nearest `towards`.
func _mouth_spots(rect: Rect2i, towards: Rect2i) -> Array[Vector2i]:
var spots: Array[Vector2i] = []
for x in range(rect.position.x, rect.end.x):
spots.append(Vector2i(x, rect.position.y - 1))
spots.append(Vector2i(x, rect.end.y))
for y in range(rect.position.y, rect.end.y):
spots.append(Vector2i(rect.position.x - 1, y))
spots.append(Vector2i(rect.end.x, y))
spots = spots.filter(func(spot: Vector2i) -> bool: return not _pathfinder.is_point_solid(spot))
var target := Vector2(towards.get_center())
spots.sort_custom(func(a: Vector2i, b: Vector2i) -> bool:
return Vector2(a).distance_squared_to(target) < Vector2(b).distance_squared_to(target))
return spots.slice(0, MOUTH_CHOICES)
# Lays tube tiles along `path`, from a mouth into `fromRect` to one into `toRect`.
func _put_tube_tiles(path: Array[Vector2i], fromRect: Rect2i, toRect: Rect2i, kind: StringName) -> void:
var last := path.size() - 1
for i in path.size():
var cell := path[i]
var back := _side_towards(cell, fromRect) if i == 0 else path[i - 1] - cell
var ahead := _side_towards(cell, toRect) if i == last else path[i + 1] - cell
var openings := TubeSteer.side_bit(back) | TubeSteer.side_bit(ahead)
# A one-way tube's way in is its mouth into `fromRect`.
var entrySide := TubeSteer.side_bit(back) if kind == MazeGraph.ONE_WAY and i == 0 else 0
_tiles.set_tile(_layer, cell, openings, kind, entrySide)
_pathfinder.set_point_solid(cell)
# Which way from `cell` (just outside `rect`) the rect is.
static func _side_towards(cell: Vector2i, rect: Rect2i) -> Vector2i:
for direction in TubeSteer.DIRECTIONS:
if rect.has_point(cell + direction):
return direction
return Vector2i.ZERO