Maze-book labyrinths, sucking one-way entrances, slime movement model

- Regions are now dense labyrinths (recursive backtracker on a coarse grid,
  1-3 tile corridors, braided loops by complexity); tubes run in the rock
  between regions, wall pipes give shortcuts inside a region.
- One-way entrances suck the slime in (player.pull_into_tube); blow zone
  is now 1 tile; blown motes are white. TubeBlower -> TubeAirCurrents.
- Validator: generous "might get to" areas vs strict SlimeMoves model
  (surface slides, corners, wraps, 1-tile gaps, ceiling falls, tubes,
  forced suction/blow tiles as all-outcomes states).
- maze_check: new hand-made blow-zone and suction traps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tachyonwolf 2026-11-16 16:15:23 -06:00
parent 88c4920fde
commit df89fa4ac7
22 changed files with 1164 additions and 683 deletions

View file

@ -51,7 +51,8 @@ const LAND_PITCH_MAX = 1.15
# through it, round corners and either way at crossings (TubeSteer). A goo one
# ("tube_goo" tiles) is the same, but the goo has no head or tail (TubeGoo).
# A one-way one ("tube_one_way" tiles) is an ordinary tube we can only go into
# at its entrance (OneWayTube).
# at its entrance, and whose air pulls us in there and blows us away from its
# exit (OneWayTube, TubeAirCurrents).
const TUBE_DATA_LAYER = "tube_openings"
const TUBE_OPEN_UP = 1
const TUBE_OPEN_RIGHT = 2
@ -1168,7 +1169,19 @@ func get_camera_focus() -> Vector2:
return global_position
# Air blowing out of a one-way tube's exit (TubeBlower) knocks us off whatever
# Air rushing into a one-way tube's entrance (TubeAirCurrents) pulls us into
# the tube at `cell` heading `direction`, without pressing anything, if it
# leads somewhere we fit.
func pull_into_tube(layer: TileMapLayer, cell: Vector2i, direction: Vector2) -> void:
if isInTube or isWrapping or isBridging or tubeReentryCooldown > 0.0:
return
var path := PixelStream.trace_tube(layer, cell, Vector2i(direction))
if path.is_empty() or _tube_exit_pose_for(path).is_empty():
return
_enter_tube({layer = layer, cell = cell, direction = direction, path = path})
# Air blowing out of a one-way tube's exit (TubeAirCurrents) knocks us off whatever
# we're stuck to and pushes us at `push` (px/s, at least: we keep any speed we
# already have that way). Called every physics frame we're in the air stream.
func blow_away(push: Vector2) -> void:

View file

@ -5,12 +5,13 @@ extends RefCounted
# that only let it in at one end. Their tiles are tagged "tube_one_way", and
# the tile at the entrance also says which of its sides is the way in
# ("tube_one_way_entry": a TUBE_OPEN_... bit, see player.gd). Every other mouth
# is an exit only, and air blows out of it, knocking the slime away (TubeBlower).
# is an exit only, and air blows out of it, knocking the slime away (TubeAirCurrents). Air also
# rushes into the entrance and pulls the slime in.
# TubeAirflow shows both: motes drawn into entrances and blown out of exits.
const ONE_WAY_LAYER = "tube_one_way"
const ENTRY_LAYER = "tube_one_way_entry"
const BLOW_RANGE = 2 # How many tiles out of an exit mouth the air blows.
const BLOW_RANGE = 1 # How many tiles out of an exit mouth the air blows.
# Whether the tile at `cell` is part of a one-way tube.
@ -43,7 +44,7 @@ static func find_entrances(layer: TileMapLayer) -> Array[Dictionary]:
# Every exit mouth in the layer that opens onto an empty tile (see _find_mouths).
# Air blows out of these: see blow_zone() and TubeBlower.
# Air blows out of these: see blow_zone() and TubeAirCurrents.
static func find_exits(layer: TileMapLayer) -> Array[Dictionary]:
return _find_mouths(layer, false)

View file

@ -0,0 +1,67 @@
class_name TubeAirCurrents
extends Node2D
# The air through every one-way tube (OneWayTube) in `layer`, acting on
# `target` (the player):
# - Sucking: while its middle is on the tile in front of an entrance, it's
# pulled into the tube without pressing anything (the target's
# pull_into_tube(), see player.gd).
# - Blowing: while its middle is in an exit's blow zone (OneWayTube.blow_zone),
# it's knocked away from the mouth: off a wall or ceiling it's stuck to, or
# lifted off the floor (the target's blow_away()). Sideways blowers also lift
# a little, so they knock the slime off the floor too, not just slide it.
# Outside the zone there's no push, so the slime can always get away.
# TubeAirflow draws the motes. Call refresh() after changing the layer's tiles.
const BLOW_SPEED = 240.0 # px/s, away from the mouth.
const SIDEWAYS_LIFT = 120.0 # px/s up, for mouths blowing sideways.
@export var layer: TileMapLayer
@export var target: Node2D
var _zones: Array[Dictionary] = [] # {rect: global Rect2, push: Vector2 px/s}.
var _intakes: Array[Dictionary] = [] # {rect: global Rect2, cell: the entrance tube tile, direction: into it}.
func _ready() -> void:
process_physics_priority = -1 # Before the player moves this frame.
refresh()
func refresh() -> void:
_zones.clear()
_intakes.clear()
if layer == null:
return
for exit in OneWayTube.find_exits(layer):
var zone := OneWayTube.blow_zone(layer, exit.cell, exit.outward)
if zone.is_empty():
continue
var push := Vector2(exit.outward) * BLOW_SPEED
if exit.outward.y == 0:
push.y = -SIDEWAYS_LIFT
var rect := _tile_rect(zone[0])
for zoneCell in zone:
rect = rect.merge(_tile_rect(zoneCell))
_zones.append({rect = rect, push = push})
for entrance in OneWayTube.find_entrances(layer):
_intakes.append({rect = _tile_rect(entrance.cell + entrance.outward), cell = entrance.cell,
direction = Vector2(-entrance.outward)})
func _physics_process(_delta: float) -> void:
if target == null or not target.has_method(&"blow_away"):
return
for intake in _intakes:
if intake.rect.has_point(target.global_position):
target.pull_into_tube(layer, intake.cell, intake.direction)
return
for zone in _zones:
if zone.rect.has_point(target.global_position):
target.blow_away(zone.push)
return
func _tile_rect(cell: Vector2i) -> Rect2:
var tileSize := Vector2(layer.tile_set.tile_size)
return Rect2(layer.to_global(layer.map_to_local(cell)) - tileSize / 2.0, tileSize)

View file

@ -1,11 +1,11 @@
class_name TubeAirflow
extends Node2D
# Orange motes showing the air through every one-way tube (OneWayTube) in
# `layer`. At an entrance they drift in like dust sucked into a vacuum: they
# Motes showing the air through every one-way tube (OneWayTube) in `layer`.
# At an entrance, orange motes drift in like dust sucked into a vacuum: they
# start spread in a fan in front of the mouth, speed up and funnel into it. At
# an exit they're blown out: fast at first, slowing and spreading as they go,
# fading out at the end of the blow zone (where TubeBlower stops pushing).
# an exit, white motes are blown out: fast at first, slowing and spreading as
# they go, fading out at the end of the blow zone (where TubeAirCurrents stops pushing).
# Call refresh() after changing the layer's tiles.
const MOTES_PER_MOUTH = 18
@ -15,7 +15,8 @@ const BLOW_SPREAD = 14.0 # How far to the side blown motes drift by the end, in
const TRIP_TIME = 1.1 # Seconds per mote trip.
const BLOW_TRIP_TIME = 0.6 # Blown motes are quicker.
const FADE = 0.2 # The share of a trip spent fading in (intake) or out (blown).
const MOTE_COLOR = Color(1.0, 0.6, 0.2)
const MOTE_COLOR = Color(1.0, 0.6, 0.2) # Drawn in.
const BLOW_COLOR = Color(0.85, 0.85, 0.85) # Blown out (lightened up to white).
const MOTE_LIGHTEN = 0.5 # Motes are up to this much lighter than MOTE_COLOR.
const BIG_MOTE_SHARE = 0.3 # This share of motes are 2x2 pixels; the rest are single pixels.
@ -73,7 +74,7 @@ func _draw() -> void:
# Drawn in: slow at first, then faster. Blown out: fast, then slower.
var out := 1.0 - progress * progress if mouth.isIntake else 1.0 - (1.0 - progress) * (1.0 - progress)
var at: Vector2 = mouth.mouth + mouth.outward * (mouth.reach * out) + across * (side * out)
var color := MOTE_COLOR.lightened(lighten)
var color := (MOTE_COLOR if mouth.isIntake else BLOW_COLOR).lightened(lighten)
var fade := progress if mouth.isIntake else 1.0 - progress
color.a = clampf(fade / FADE, 0.0, 1.0)
draw_rect(Rect2(at.floor(), moteSize), color)

View file

@ -1,51 +0,0 @@
class_name TubeBlower
extends Node2D
# Air blowing out of every one-way tube's exit (OneWayTube.blow_zone) in
# `layer`. While `target`'s middle is in a blow zone, it's knocked away from
# the mouth: off a wall or ceiling it's stuck to, or lifted off the floor
# (the target's blow_away(), see player.gd). Sideways blowers also lift a
# little, so they knock the slime off the floor too, not just slide it.
# Outside the zone there's no push, so the slime can always get away (it can
# steer in the air, and the zone is never as wide as the chamber).
# Call refresh() after changing the layer's tiles.
const BLOW_SPEED = 240.0 # px/s, away from the mouth.
const SIDEWAYS_LIFT = 120.0 # px/s up, for mouths blowing sideways.
@export var layer: TileMapLayer
@export var target: Node2D
var _zones: Array[Dictionary] = [] # {rect: global Rect2, push: Vector2 px/s}.
func _ready() -> void:
process_physics_priority = -1 # Before the player moves this frame.
refresh()
func refresh() -> void:
_zones.clear()
if layer == null:
return
var tileSize := Vector2(layer.tile_set.tile_size)
for exit in OneWayTube.find_exits(layer):
var zone := OneWayTube.blow_zone(layer, exit.cell, exit.outward)
if zone.is_empty():
continue
var push := Vector2(exit.outward) * BLOW_SPEED
if exit.outward.y == 0:
push.y = -SIDEWAYS_LIFT
var rect := Rect2(layer.to_global(layer.map_to_local(zone[0])) - tileSize / 2.0, tileSize)
for zoneCell in zone:
rect = rect.merge(Rect2(layer.to_global(layer.map_to_local(zoneCell)) - tileSize / 2.0, tileSize))
_zones.append({rect = rect, push = push})
func _physics_process(_delta: float) -> void:
if target == null or not target.has_method(&"blow_away"):
return
for zone in _zones:
if zone.rect.has_point(target.global_position):
target.blow_away(zone.push)
return

View file

@ -24,7 +24,7 @@ func _init(layer: TileMapLayer, screens: Vector2i, complexity: int, firstSeed: i
var random := RandomNumberGenerator.new()
random.seed = usedSeed
var graph := MazeGraph.new(screens, level, random)
carver = MazeCarver.new(graph, screens, layer, random, level.winding)
carver = MazeCarver.new(graph, screens, layer, random, level)
if not carver.isComplete:
problems.append("seed %d: a tube couldn't be routed" % usedSeed)
continue

View file

@ -1,28 +1,21 @@
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.
# Turns a MazeGraph into tiles: rock everywhere, a labyrinth of corridors in
# each region (MazeCorridors), tubes between regions and through walls
# (MazeTubeRouter), then Start and End on corridor floors.
#
# 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.
#
# Air blows out of one-way tubes' exits (OneWayTube.blow_zone). No other mouth
# opens into a blow zone, and Start and End aren't in one, so the slime is never
# blown away from something it needs. (MazeGraph keeps it to one blower per
# chamber; MazeValidator checks all of this again.)
# graph region. A region keeps REGION_BORDER tiles of rock round its edge, so
# neighbouring regions are 4 tiles apart; tubes run there and only they join
# regions.
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.
const REGION_BORDER = 2 # Rock tiles round the inside of each region: room for tubes between regions.
var chamberRects: Array[Rect2i] = []
var regionRects: Array[Rect2i] = []
var regionAir: Array[Dictionary] = [] # Per region: its air tiles (tile -> true).
var bounds := Rect2i() # The whole maze, in tiles.
var startCell := Vector2i.ZERO # The air tile Start sits on (on a chamber's floor).
var startCell := Vector2i.ZERO # The air tile Start sits on (on a corridor floor).
var endCell := Vector2i.ZERO
var isComplete := false # Whether every tube the maze needs got a route.
var routedTubeCount := 0
@ -30,32 +23,34 @@ var routedTubeCount := 0
var _layer: TileMapLayer
var _tiles: MazeTiles
var _random: RandomNumberGenerator
var _pathfinder := AStarGrid2D.new()
var _winding := 0.0
var _mouthFronts := {} # Air tile in front of a mouth -> true.
var _blowCells := {} # Air tile in a blow zone -> true.
var _router: MazeTubeRouter
func _init(graph: MazeGraph, screens: Vector2i, layer: TileMapLayer, random: RandomNumberGenerator, winding: float) -> void:
func _init(graph: MazeGraph, screens: Vector2i, layer: TileMapLayer, random: RandomNumberGenerator, level: Dictionary) -> 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()
_carve_regions(graph, screenTiles, level)
var interiors: Array[Rect2i] = []
for rect in regionRects:
interiors.append(rect.grow(-REGION_BORDER))
_router = MazeTubeRouter.new(layer, _tiles, random, bounds, level.winding, interiors)
isComplete = true
for tube in graph.tubes:
if _carve_tube(tube):
var fallback := MazeGraph.pick_two_way_kind(random, level.steeredShare)
if _router.route(regionAir[tube.from], regionAir[tube.to], tube.kind, fallback):
routedTubeCount += 1
elif tube.isRequired:
isComplete = false
return
startCell = _floor_cell(chamberRects[graph.start])
endCell = _floor_cell(chamberRects[graph.end])
_add_wall_pipes(roundi(level.wallPipesPerScreen * screens.x * screens.y), level.steeredShare)
startCell = _random_floor(regionAir[graph.start])
var endFrom := startCell if graph.start == graph.end else _random_floor(regionAir[graph.end])
endCell = _furthest_floor(regionAir[graph.end], endFrom)
func _fill_rock() -> void:
@ -65,22 +60,19 @@ func _fill_rock() -> void:
_tiles.set_tile(_layer, Vector2i(x, y), 0, MazeTiles.ROCK)
func _carve_chambers(graph: MazeGraph, screenTiles: Vector2i) -> void:
func _carve_regions(graph: MazeGraph, screenTiles: Vector2i, level: Dictionary) -> 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))
for region in graph.region_count():
var rect := _region(graph.grid_cell(region), split, screenTiles)
regionRects.append(rect)
var air := {}
for tile in MazeCorridors.carve(_layer, rect.grow(-REGION_BORDER), level.corridorWidth, level.braid, _random):
air[tile] = true
regionAir.append(air)
# The tiles a chamber's region covers. The last region in each screen row or
# column takes what's left over.
# The tiles a 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
@ -94,119 +86,45 @@ static func _region(gridCell: Vector2i, split: Vector2i, screenTiles: Vector2i)
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, out of any blow zone (one
# blower can't cover a whole row: chambers are wider than its reach).
func _floor_cell(rect: Rect2i) -> Vector2i:
var cells: Array[Vector2i] = []
for x in range(rect.position.x, rect.end.x):
if not _blowCells.has(Vector2i(x, rect.end.y - 1)):
cells.append(Vector2i(x, rect.end.y - 1))
return cells[_random.randi_range(0, cells.size() - 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, false)
var toMouths := _mouth_spots(toRect, fromRect, tube.kind == MazeGraph.ONE_WAY)
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():
# Short tubes through single walls, in random regions: shortcuts, and one-way
# ones where that's safe.
func _add_wall_pipes(count: int, steeredShare: float) -> void:
for i in count:
var air: Dictionary = regionAir[_random.randi_range(0, regionAir.size() - 1)]
if air.is_empty():
continue
_put_tube_tiles(path, fromRect, toRect, tube.kind)
_mouthFronts[fromMouth + _side_towards(fromMouth, fromRect)] = true
_mouthFronts[toMouth + _side_towards(toMouth, toRect)] = true
if tube.kind == MazeGraph.ONE_WAY:
for zoneCell in OneWayTube.blow_zone(_layer, toMouth, _side_towards(toMouth, toRect)):
_blowCells[zoneCell] = true
return true
return false
var twoWay := MazeGraph.pick_two_way_kind(_random, steeredShare)
var kind := MazeGraph.ONE_WAY if _random.randf() < 0.4 else twoWay
_router.add_wall_pipe(air, kind, twoWay)
# 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)
# Air tiles with solid ground below, not ones the air moves the slime off.
func _floors(air: Dictionary) -> Array[Vector2i]:
var floors: Array[Vector2i] = []
for tile: Vector2i in air:
if not air.has(tile + Vector2i.DOWN) and not _router.forcedCells.has(tile):
floors.append(tile)
floors.sort() # Same seed, same maze.
return floors
# Free rock tiles touching `rect`'s sides, where a mouth into it can go: the
# MOUTH_CHOICES nearest `towards`. None open into a blow zone, and if the mouth
# `isBlowing` (a one-way exit), its blow zone has no other mouth in it.
func _mouth_spots(rect: Rect2i, towards: Rect2i, isBlowing: bool) -> 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 _is_mouth_spot_free(spot, rect, isBlowing))
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)
func _random_floor(air: Dictionary) -> Vector2i:
var floors := _floors(air)
return floors[_random.randi_range(0, floors.size() - 1)]
func _is_mouth_spot_free(spot: Vector2i, rect: Rect2i, isBlowing: bool) -> bool:
if _pathfinder.is_point_solid(spot):
return false
var outward := _side_towards(spot, rect)
if _blowCells.has(spot + outward):
return false
if isBlowing:
for zoneCell in OneWayTube.blow_zone(_layer, spot, outward):
if _mouthFronts.has(zoneCell):
return false
return true
# 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
# The floor tile of a region furthest along the corridors from `from`.
func _furthest_floor(air: Dictionary, from: Vector2i) -> Vector2i:
var distances := {from: 0}
var queue: Array[Vector2i] = [from]
var furthest := from
while not queue.is_empty():
var tile: Vector2i = queue.pop_front()
if distances[tile] > distances[furthest] and not air.has(tile + Vector2i.DOWN):
furthest = tile
for step in MazeCorridors.STEPS:
var next := tile + step
if air.has(next) and not distances.has(next) and not _router.forcedCells.has(next):
distances[next] = distances[tile] + 1
queue.append(next)
return furthest

View file

@ -0,0 +1,99 @@
class_name MazeCorridors
extends RefCounted
# Carves a puzzle-book labyrinth into solid rock: a grid of corridor cells
# `width` tiles wide with 1-tile walls between them, joined by a recursive
# backtracker (long winding corridors, branches, dead ends). Then `braid` of the
# dead ends are opened into a neighbour, making loops.
# Every corridor tile ends up connected to every other one.
const STEPS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
# Carves into `area` (tiles) and returns the air tiles it made.
static func carve(layer: TileMapLayer, area: Rect2i, width: int, braid: float,
random: RandomNumberGenerator) -> Array[Vector2i]:
var pitch := width + 1
var gridSize := Vector2i((area.size.x + 1) / pitch, (area.size.y + 1) / pitch)
var air: Array[Vector2i] = []
if gridSize.x < 1 or gridSize.y < 1:
return air
# Centred in the area; any spare tiles stay rock.
var used := gridSize * pitch - Vector2i.ONE
var origin := area.position + (area.size - used) / 2
var openings := _backtrack(gridSize, random)
_braid(openings, gridSize, braid, random)
for y in gridSize.y:
for x in gridSize.x:
var cell := Vector2i(x, y)
var corner := origin + cell * pitch
_carve_rect(layer, Rect2i(corner, Vector2i(width, width)), air)
var bits: int = openings[_index(cell, gridSize)]
if bits & TubeSteer.side_bit(Vector2i.RIGHT):
_carve_rect(layer, Rect2i(corner + Vector2i(width, 0), Vector2i(1, width)), air)
if bits & TubeSteer.side_bit(Vector2i.DOWN):
_carve_rect(layer, Rect2i(corner + Vector2i(0, width), Vector2i(width, 1)), air)
return air
# Per grid cell: which sides are open (TubeSteer.side_bit bits).
static func _backtrack(gridSize: Vector2i, random: RandomNumberGenerator) -> PackedInt32Array:
var openings := PackedInt32Array()
openings.resize(gridSize.x * gridSize.y)
var visited := {}
var first := Vector2i(random.randi_range(0, gridSize.x - 1), random.randi_range(0, gridSize.y - 1))
var stack: Array[Vector2i] = [first]
visited[first] = true
while not stack.is_empty():
var cell: Vector2i = stack.back()
var unvisited: Array[Vector2i] = []
for step in STEPS:
var next := cell + step
if _is_inside(next, gridSize) and not visited.has(next):
unvisited.append(next)
if unvisited.is_empty():
stack.pop_back()
continue
var chosen: Vector2i = unvisited[random.randi_range(0, unvisited.size() - 1)]
_open(openings, gridSize, cell, chosen - cell)
visited[chosen] = true
stack.append(chosen)
return openings
# Opens `share` of the dead ends into a neighbour they aren't joined to yet.
static func _braid(openings: PackedInt32Array, gridSize: Vector2i, share: float, random: RandomNumberGenerator) -> void:
for y in gridSize.y:
for x in gridSize.x:
var cell := Vector2i(x, y)
var bits: int = openings[_index(cell, gridSize)]
var isDeadEnd := bits in [1, 2, 4, 8]
if not isDeadEnd or random.randf() >= share:
continue
var closed: Array[Vector2i] = []
for step in STEPS:
if _is_inside(cell + step, gridSize) and bits & TubeSteer.side_bit(step) == 0:
closed.append(step)
if not closed.is_empty():
_open(openings, gridSize, cell, closed[random.randi_range(0, closed.size() - 1)])
static func _open(openings: PackedInt32Array, gridSize: Vector2i, cell: Vector2i, step: Vector2i) -> void:
openings[_index(cell, gridSize)] |= TubeSteer.side_bit(step)
openings[_index(cell + step, gridSize)] |= TubeSteer.side_bit(-step)
static func _carve_rect(layer: TileMapLayer, rect: Rect2i, air: Array[Vector2i]) -> void:
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))
air.append(Vector2i(x, y))
static func _index(cell: Vector2i, gridSize: Vector2i) -> int:
return cell.y * gridSize.x + cell.x
static func _is_inside(cell: Vector2i, gridSize: Vector2i) -> bool:
return cell.x >= 0 and cell.y >= 0 and cell.x < gridSize.x and cell.y < gridSize.y

View file

@ -0,0 +1 @@
uid://kou6u6xsb1p

View file

@ -1,37 +1,39 @@
class_name MazeGraph
extends RefCounted
# The maze as a graph, before any tiles: a grid of chambers joined by tubes.
# The maze as a graph, before any tiles: a grid of regions joined by tubes.
# Each region is a labyrinth of corridors (MazeCarver); the only ways between
# regions are tubes.
#
# 1. A random spanning tree over neighbouring chambers (a recursive
# 1. A random spanning tree over neighbouring regions (a recursive
# backtracker, so it has long corridors and dead ends). Its tubes are two-way.
# 2. Start is a random chamber, End the one furthest from it along the tree.
# 2. Start is a random region, End the one furthest from it along the tree.
# 3. With the tree rooted at End, some tubes on the Start-End route become
# one-way towards End.
# 4. Extra tubes join nearby chambers: two-way loops, and one-way tubes in any
# 4. Extra tubes join nearby regions: two-way loops, and one-way tubes in any
# direction.
#
# Why this can't soft-lock: every tree tube can be used towards End (two-way,
# or one-way towards End), so from every chamber the tree leads to End. Extra
# tubes only add ways, so they can't take that away. And every chamber is
# or one-way towards End), so from every region the tree leads to End. Extra
# tubes only add ways, so they can't take that away. And every region is
# reachable from Start: the route's one-way tubes point away from Start, and
# everything off the route hangs off it by two-way tubes.
#
# At most one one-way tube comes out in each chamber: air blows out of its exit
# (TubeBlower), and one blow zone can't cut a chamber in two (see docs/MAZE.md).
# (Inside a region every corridor can be crawled both ways; MazeCarver puts
# blow zones only where they don't cut a region, so this still holds.)
# With a single region, Start and End are both in it.
# MazeValidator checks the finished tiles anyway.
const AUTO = &"auto"
const MANUAL = &"manual"
const GOO = &"goo"
const ONE_WAY = &"one_way" # Goes from .from to .to only.
const EXTRA_TUBE_REACH = 2 # Extra tubes join chambers up to this many grid steps apart (diagonals count as one).
const EXTRA_TUBE_TRIES = 40 # Per extra tube, tries to find a pair of chambers not joined yet.
const EXTRA_TUBE_REACH = 2 # Extra tubes join regions up to this many grid steps apart (diagonals count as one).
const EXTRA_TUBE_TRIES = 40 # Per extra tube, tries to find a pair of regions not joined yet.
const GRID_STEPS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
var gridSize := Vector2i.ZERO # Chambers across and down.
# Per tube: {from: chamber, to: chamber, kind: AUTO/MANUAL/GOO/ONE_WAY,
var gridSize := Vector2i.ZERO # Regions across and down.
# Per tube: {from: region, to: region, kind: AUTO/MANUAL/GOO/ONE_WAY,
# isRequired: true for the tree (the maze breaks without it)}.
var tubes: Array[Dictionary] = []
var start := 0
@ -39,32 +41,32 @@ var end := 0
var _random: RandomNumberGenerator
var _level: Dictionary
var _treeNeighbors: Array[Array] = [] # Per chamber: chambers joined to it in the tree.
var _treeNeighbors: Array[Array] = [] # Per region: regions joined to it in the tree.
# screens: the maze's size in screens. level: see MazeSettings.LEVELS.
func _init(screens: Vector2i, level: Dictionary, random: RandomNumberGenerator) -> void:
_random = random
_level = level
gridSize = screens * Vector2i(level.chambersPerScreen)
_treeNeighbors.resize(chamber_count())
for chamber in chamber_count():
_treeNeighbors[chamber] = []
gridSize = screens * Vector2i(level.regionsPerScreen)
_treeNeighbors.resize(region_count())
for region in region_count():
_treeNeighbors[region] = []
_build_tree()
_pick_start_and_end()
_make_route_one_way()
_add_extra_tubes(roundi(level.extraTubesPerScreen * screens.x * screens.y))
func chamber_count() -> int:
func region_count() -> int:
return gridSize.x * gridSize.y
func grid_cell(chamber: int) -> Vector2i:
return Vector2i(chamber % gridSize.x, chamber / gridSize.x)
func grid_cell(region: int) -> Vector2i:
return Vector2i(region % gridSize.x, region / gridSize.x)
func chamber_at(cell: Vector2i) -> int:
func region_at(cell: Vector2i) -> int:
return cell.y * gridSize.x + cell.x
@ -72,12 +74,12 @@ func chamber_at(cell: Vector2i) -> int:
func _build_tree() -> void:
var visited := {}
var stack: Array[int] = [_random.randi_range(0, chamber_count() - 1)]
var stack: Array[int] = [_random.randi_range(0, region_count() - 1)]
visited[stack[0]] = true
while not stack.is_empty():
var chamber: int = stack.back()
var region: int = stack.back()
var unvisited: Array[int] = []
for neighbor in _grid_neighbors(chamber):
for neighbor in _grid_neighbors(region):
if not visited.has(neighbor):
unvisited.append(neighbor)
if unvisited.is_empty():
@ -85,48 +87,53 @@ func _build_tree() -> void:
continue
var next: int = unvisited[_random.randi_range(0, unvisited.size() - 1)]
visited[next] = true
_treeNeighbors[chamber].append(next)
_treeNeighbors[next].append(chamber)
tubes.append({from = chamber, to = next, kind = _two_way_kind(), isRequired = true})
_treeNeighbors[region].append(next)
_treeNeighbors[next].append(region)
tubes.append({from = region, to = next, kind = _two_way_kind(), isRequired = true})
stack.append(next)
func _grid_neighbors(chamber: int) -> Array[int]:
func _grid_neighbors(region: int) -> Array[int]:
var neighbors: Array[int] = []
var cell := grid_cell(chamber)
var cell := grid_cell(region)
for step in GRID_STEPS:
var next := cell + step
if next.x >= 0 and next.y >= 0 and next.x < gridSize.x and next.y < gridSize.y:
neighbors.append(chamber_at(next))
neighbors.append(region_at(next))
return neighbors
func _two_way_kind() -> StringName:
if _random.randf() >= _level.steeredShare:
return pick_two_way_kind(_random, _level.steeredShare)
# Auto, or (with chance `steeredShare`) manual or goo. MazeCarver uses this too.
static func pick_two_way_kind(random: RandomNumberGenerator, steeredShare: float) -> StringName:
if random.randf() >= steeredShare:
return AUTO
return MANUAL if _random.randf() < 0.5 else GOO
return MANUAL if random.randf() < 0.5 else GOO
func _pick_start_and_end() -> void:
start = _random.randi_range(0, chamber_count() - 1)
start = _random.randi_range(0, region_count() - 1)
var distances := _tree_distances(start)
end = start
for chamber in chamber_count():
if distances[chamber] > distances[end]:
end = chamber
for region in region_count():
if distances[region] > distances[end]:
end = region
func _tree_distances(from: int) -> PackedInt32Array:
var distances := PackedInt32Array()
distances.resize(chamber_count())
distances.resize(region_count())
distances.fill(-1)
distances[from] = 0
var queue: Array[int] = [from]
while not queue.is_empty():
var chamber: int = queue.pop_front()
for next: int in _treeNeighbors[chamber]:
var region: int = queue.pop_front()
for next: int in _treeNeighbors[region]:
if distances[next] == -1:
distances[next] = distances[chamber] + 1
distances[next] = distances[region] + 1
queue.append(next)
return distances
@ -141,7 +148,7 @@ func _make_route_one_way() -> void:
var oneWayCount := mini(_level.oneWayOnRoute, routeTubes.size())
for i in oneWayCount:
var tube := tubes[routeTubes[i]]
# Point it from the chamber nearer Start to the one nearer End.
# Point it from the region nearer Start to the one nearer End.
if route.find(tube.from) > route.find(tube.to):
var swap: int = tube.from
tube.from = tube.to
@ -149,7 +156,7 @@ func _make_route_one_way() -> void:
tube.kind = ONE_WAY
# The chambers from Start to End along the tree.
# The regions from Start to End along the tree.
func _route() -> Array[int]:
var distances := _tree_distances(end)
var route: Array[int] = [start]
@ -161,17 +168,10 @@ func _route() -> Array[int]:
return route
func _has_one_way_into(chamber: int) -> bool:
for tube in tubes:
if tube.kind == ONE_WAY and tube.to == chamber:
return true
return false
func _tube_between(chamberA: int, chamberB: int) -> int:
func _tube_between(regionA: int, regionB: int) -> int:
for i in tubes.size():
var tube := tubes[i]
if (tube.from == chamberA and tube.to == chamberB) or (tube.from == chamberB and tube.to == chamberA):
if (tube.from == regionA and tube.to == regionB) or (tube.from == regionB and tube.to == regionA):
return i
return -1
@ -179,24 +179,24 @@ func _tube_between(chamberA: int, chamberB: int) -> int:
func _add_extra_tubes(count: int) -> void:
for i in count:
for attempt in EXTRA_TUBE_TRIES:
var from := _random.randi_range(0, chamber_count() - 1)
var from := _random.randi_range(0, region_count() - 1)
var to := _random_nearby(from)
if to == -1 or _tube_between(from, to) != -1:
continue
var kind := ONE_WAY if _random.randf() < 0.5 and not _has_one_way_into(to) else _two_way_kind()
var kind := ONE_WAY if _random.randf() < 0.5 else _two_way_kind()
tubes.append({from = from, to = to, kind = kind, isRequired = false})
break
# A random other chamber within EXTRA_TUBE_REACH grid steps, or -1.
func _random_nearby(chamber: int) -> int:
var cell := grid_cell(chamber)
# A random other region within EXTRA_TUBE_REACH grid steps, or -1.
func _random_nearby(region: int) -> int:
var cell := grid_cell(region)
var offset := Vector2i(_random.randi_range(-EXTRA_TUBE_REACH, EXTRA_TUBE_REACH),
_random.randi_range(-EXTRA_TUBE_REACH, EXTRA_TUBE_REACH))
var other := cell + offset
if offset == Vector2i.ZERO or other.x < 0 or other.y < 0 or other.x >= gridSize.x or other.y >= gridSize.y:
return -1
return chamber_at(other)
return region_at(other)
func _shuffle(items: Array[int]) -> void:

View file

@ -8,7 +8,7 @@ const MENU_SCENE = "res://UI/main_menu.tscn"
@onready var layer: TileMapLayer = $TileMapLayer
@onready var player: CharacterBody2D = $Player
@onready var airflow: TubeAirflow = $TubeAirflow
@onready var blower: TubeBlower = $TubeBlower
@onready var airCurrents: TubeAirCurrents = $TubeAirCurrents
@onready var startMarker: MazeMarker = $StartMarker
@onready var endMarker: MazeMarker = $EndMarker
@onready var pauseMenu: CanvasLayer = $PauseMenu
@ -30,7 +30,7 @@ func _ready() -> void:
player.global_position = startMarker.global_position
player.reset_physics_interpolation()
airflow.refresh()
blower.refresh()
airCurrents.refresh()
endMarker.reached.connect(_on_end_reached)

View file

@ -7,7 +7,7 @@
[ext_resource type="PackedScene" path="res://UI/pause_menu.tscn" id="5_pause"]
[ext_resource type="AudioStream" path="res://Assets/Sounds/Itty Bitty 8 Bit.mp3" id="6_music"]
[ext_resource type="Script" path="res://Effects/tube_airflow.gd" id="7_airflow"]
[ext_resource type="Script" path="res://Effects/tube_blower.gd" id="10_blower"]
[ext_resource type="Script" path="res://Effects/tube_air_currents.gd" id="10_currents"]
[ext_resource type="Script" path="res://Levels/Maze/maze_marker.gd" id="8_marker"]
[ext_resource type="PackedScene" path="res://Levels/Maze/maze_win_menu.tscn" id="9_win"]
@ -32,8 +32,8 @@ isGoal = true
script = ExtResource("7_airflow")
layer = NodePath("../TileMapLayer")
[node name="TubeBlower" type="Node2D" parent="." node_paths=PackedStringArray("layer", "target")]
script = ExtResource("10_blower")
[node name="TubeAirCurrents" type="Node2D" parent="." node_paths=PackedStringArray("layer", "target")]
script = ExtResource("10_currents")
layer = NodePath("../TileMapLayer")
target = NodePath("../Player")

View file

@ -12,17 +12,27 @@ const MIN_COMPLEXITY = 1
const MAX_COMPLEXITY = 5
# Per complexity level (index 0 is level 1):
# chambersPerScreen: how the chambers split each screen (columns, rows).
# oneWayOnRoute: how many tubes on the Start-End route are one-way.
# extraTubesPerScreen: tubes added on top of the spanning tree (loops and traps).
# regionsPerScreen: how the maze regions split each screen (columns, rows).
# Regions are joined only by tubes.
# corridorWidth: corridor width in tiles (walls are 1 tile). 1 is the
# narrowest the slime gets through (checked in the game).
# braid: the share of dead ends opened into loops (0 = a perfect maze).
# oneWayOnRoute: how many tubes between regions on the Start-End route are one-way.
# extraTubesPerScreen: tubes between regions on top of the spanning tree.
# wallPipesPerScreen: short tubes through a wall inside a region (shortcuts).
# steeredShare: the share of two-way tubes that are manual or goo, not auto.
# winding: how much tubes wander on their way (0 = shortest path).
# winding: how much tubes between regions wander (0 = shortest path).
const LEVELS: Array[Dictionary] = [
{chambersPerScreen = Vector2i(2, 1), oneWayOnRoute = 0, extraTubesPerScreen = 0.0, steeredShare = 0.0, winding = 0.5},
{chambersPerScreen = Vector2i(2, 2), oneWayOnRoute = 1, extraTubesPerScreen = 0.5, steeredShare = 0.2, winding = 1.0},
{chambersPerScreen = Vector2i(2, 2), oneWayOnRoute = 2, extraTubesPerScreen = 1.0, steeredShare = 0.3, winding = 2.0},
{chambersPerScreen = Vector2i(3, 2), oneWayOnRoute = 3, extraTubesPerScreen = 1.5, steeredShare = 0.35, winding = 3.0},
{chambersPerScreen = Vector2i(3, 2), oneWayOnRoute = 4, extraTubesPerScreen = 2.0, steeredShare = 0.4, winding = 4.0},
{regionsPerScreen = Vector2i(2, 1), corridorWidth = 3, braid = 0.5, oneWayOnRoute = 0,
extraTubesPerScreen = 0.0, wallPipesPerScreen = 0.0, steeredShare = 0.0, winding = 0.5},
{regionsPerScreen = Vector2i(2, 1), corridorWidth = 2, braid = 0.3, oneWayOnRoute = 1,
extraTubesPerScreen = 0.5, wallPipesPerScreen = 1.0, steeredShare = 0.2, winding = 1.0},
{regionsPerScreen = Vector2i(2, 1), corridorWidth = 2, braid = 0.15, oneWayOnRoute = 2,
extraTubesPerScreen = 1.0, wallPipesPerScreen = 2.0, steeredShare = 0.3, winding = 2.0},
{regionsPerScreen = Vector2i(1, 1), corridorWidth = 1, braid = 0.05, oneWayOnRoute = 3,
extraTubesPerScreen = 1.0, wallPipesPerScreen = 3.0, steeredShare = 0.35, winding = 3.0},
{regionsPerScreen = Vector2i(1, 1), corridorWidth = 1, braid = 0.0, oneWayOnRoute = 4,
extraTubesPerScreen = 1.5, wallPipesPerScreen = 5.0, steeredShare = 0.4, winding = 4.0},
]
static var width := 2 # In screens.

View file

@ -0,0 +1,300 @@
class_name MazeTubeRouter
extends RefCounted
# Lays tubes into a carved maze: long tubes between regions, routed through
# the rock with AStarGrid2D (random weights so they wander), and short "wall
# pipes" through a single wall inside a region. Tubes never share a tile, so
# they can't join by accident, and their openings only face their own tiles.
#
# One-way tubes move the slime by themselves: the tile in front of the
# entrance sucks it in, and the blow zone in front of the exit
# (OneWayTube.blow_zone) blows it away. These "forced" tiles can't be stood on
# or crossed. A one-way tube only goes where MazeValidator's movement model can
# tell what happens, and where forced tiles can't cut a region in two:
# - the exit never blows up (the slime could bounce in place),
# - the zone and the tile past it ("landing") are air,
# - sideways: zone and landing are 1 tile tall, so the slime slides along a floor,
# - down: the slime falls from the landing onto a floor, through no forced tile,
# - the region's air minus all forced tiles is still one connected piece,
# - no other mouth opens onto a forced tile.
const MOUTH_CHOICES = 10 # Of the spots for a mouth nearest the other end, how many we pick from.
const ROUTE_TRIES = 16 # Pairs of mouth spots to try before giving up on a tube.
const WALL_PIPE_TRIES = 30
const MIN_SHORTCUT = 8 # A wall pipe must save at least this many tiles of corridor.
# Extra cost for routing through the walls inside a region rather than the
# rock between regions. In a 1-tile-wall maze the walls form a tree, and a tube
# through it cuts off the rock beyond, so later tubes couldn't get through.
# (Mouths also sit next to that rock, see _touches_channel.)
const INTERIOR_COST = 12.0
var mouthFronts := {} # Air tile in front of a mouth -> true.
var forcedCells := {} # Air tile the air moves the slime off (blow zones, entrance tiles) -> true.
var _keepFree := {} # Air tiles a blown slime lands on or falls through: never forced.
var _layer: TileMapLayer
var _tiles: MazeTiles
var _random: RandomNumberGenerator
var _bounds: Rect2i
var _pathfinder := AStarGrid2D.new()
var _winding := 0.0
var _interiors: Array[Rect2i] = [] # Where the corridors and their walls are.
func _init(layer: TileMapLayer, tiles: MazeTiles, random: RandomNumberGenerator, bounds: Rect2i,
winding: float, interiors: Array[Rect2i]) -> void:
_interiors = interiors
_layer = layer
_tiles = tiles
_random = random
_bounds = bounds
_winding = winding
_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 _is_air(cell))
# Routes a tube from region `fromAir` to region `toAir` (their air tiles, as
# sets). A one-way tube with nowhere safe to blow out becomes `fallbackKind`.
func route(fromAir: Dictionary, toAir: Dictionary, kind: StringName, fallbackKind: StringName) -> bool:
_randomize_weights()
var isOneWay := kind == MazeGraph.ONE_WAY
var fromMouths := _mouth_spots(fromAir, _middle(toAir), &"entrance" if isOneWay else &"")
var toMouths := _mouth_spots(toAir, _middle(fromAir), &"exit" if isOneWay else &"")
if isOneWay and (fromMouths.is_empty() or toMouths.is_empty()):
kind = fallbackKind
fromMouths = _mouth_spots(fromAir, _middle(toAir), &"")
toMouths = _mouth_spots(toAir, _middle(fromAir), &"")
for attempt in ROUTE_TRIES:
if fromMouths.is_empty() or toMouths.is_empty():
return false
var fromMouth: Dictionary = fromMouths[_random.randi_range(0, fromMouths.size() - 1)]
var toMouth: Dictionary = toMouths[_random.randi_range(0, toMouths.size() - 1)]
var path := _pathfinder.get_id_path(fromMouth.spot, toMouth.spot)
if path.is_empty():
continue
_put_tube(path, fromMouth.outward, toMouth.outward, kind)
return true
return false
# Adds a short tube through one wall tile inside region `air` (a set of its
# air tiles), joining two corridors that are far apart the long way round.
func add_wall_pipe(air: Dictionary, kind: StringName, fallbackKind: StringName) -> bool:
var tiles: Array = air.keys()
for attempt in WALL_PIPE_TRIES:
var wall: Vector2i = tiles[_random.randi_range(0, tiles.size() - 1)] + MazeCorridors.STEPS[_random.randi_range(0, 3)]
if _pathfinder.is_point_solid(wall) or _is_air(wall):
continue
for step: Vector2i in [Vector2i.RIGHT, Vector2i.DOWN]:
var sideA := wall + step
var sideB := wall - step
if not air.has(sideA) or not air.has(sideB):
continue
if _is_blocked_front(sideA) or _is_blocked_front(sideB):
continue
if _distance(air, sideA, sideB) < MIN_SHORTCUT:
continue
var pipeKind := kind
var outwardIn := step # Mouth into sideA faces `step`.
var outwardOut := -step
if kind == MazeGraph.ONE_WAY:
if _is_one_way_safe(air, wall, step, wall, -step):
outwardIn = step
outwardOut = -step
elif _is_one_way_safe(air, wall, -step, wall, step):
outwardIn = -step
outwardOut = step
else:
pipeKind = fallbackKind
var path: Array[Vector2i] = [wall]
_put_tube(path, outwardIn, outwardOut, pipeKind)
return true
return false
# ---- Mouths ----
# Rock tiles beside the region's air where a mouth can go:
# [{spot, outward}], the MOUTH_CHOICES nearest `towards`. `oneWayEnd`:
# &"entrance" or &"exit" for only spots that end of a one-way tube may use.
func _mouth_spots(air: Dictionary, towards: Vector2, oneWayEnd: StringName) -> Array[Dictionary]:
var spots: Array[Dictionary] = []
for tile: Vector2i in air:
if _is_blocked_front(tile):
continue
for step in MazeCorridors.STEPS:
var spot: Vector2i = tile - step # The mouth faces `step`, onto `tile`.
if not _pathfinder.is_point_solid(spot) and not _is_air(spot) and _touches_channel(spot):
spots.append({spot = spot, outward = step})
spots.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
return Vector2(a.spot).distance_squared_to(towards) < Vector2(b.spot).distance_squared_to(towards))
# The safety check floods the region, so only check spots until we have enough.
var chosen: Array[Dictionary] = []
for spot in spots:
if chosen.size() >= MOUTH_CHOICES:
break
if oneWayEnd == &"entrance" and not _is_one_way_safe(air, spot.spot, spot.outward, Vector2i.ZERO, Vector2i.ZERO):
continue
if oneWayEnd == &"exit" and not _is_one_way_safe(air, Vector2i.ZERO, Vector2i.ZERO, spot.spot, spot.outward):
continue
chosen.append(spot)
return chosen
# Whether `spot` is next to free rock between regions, so its tube can run
# there without going through (and cutting up) the walls inside the region.
func _touches_channel(spot: Vector2i) -> bool:
for step in MazeCorridors.STEPS:
var next := spot + step
if not _is_interior(next) and not _is_air(next) and not _pathfinder.is_point_solid(next):
return true
return false
func _is_blocked_front(tile: Vector2i) -> bool:
return forcedCells.has(tile)
# Whether a one-way tube's entrance (at `entranceSpot`, facing
# `entranceOutward`) and exit (likewise) follow the rules at the top of this
# file in region `air`. An outward of ZERO leaves that end out (it's in
# another region).
func _is_one_way_safe(air: Dictionary, entranceSpot: Vector2i, entranceOutward: Vector2i,
exitSpot: Vector2i, exitOutward: Vector2i) -> bool:
var newForced: Array[Vector2i] = []
var landing := Vector2i.ZERO
if entranceOutward != Vector2i.ZERO:
var front := entranceSpot + entranceOutward
if not air.has(front) or forcedCells.has(front) or mouthFronts.has(front) or _keepFree.has(front):
return false
newForced.append(front)
if exitOutward != Vector2i.ZERO:
if exitOutward == Vector2i.UP:
return false
var zone: Array[Vector2i] = []
for step in range(1, OneWayTube.BLOW_RANGE + 1):
zone.append(exitSpot + exitOutward * step)
landing = exitSpot + exitOutward * (OneWayTube.BLOW_RANGE + 1)
for tile in zone + [landing]:
if not air.has(tile) or forcedCells.has(tile) or newForced.has(tile):
return false
for tile in zone:
if _keepFree.has(tile):
return false
if exitOutward.y == 0 and (_is_air(tile + Vector2i.UP) or _is_air(tile + Vector2i.DOWN)):
return false
for tile in zone:
if mouthFronts.has(tile):
return false
newForced.append_array(zone)
if exitOutward == Vector2i.DOWN:
var fall := landing
while _is_air(fall + Vector2i.DOWN):
fall += Vector2i.DOWN
if forcedCells.has(fall) or newForced.has(fall):
return false
return _stays_connected(air, newForced)
# Whether the region's air, minus every forced tile and `newForced`, is one
# piece.
func _stays_connected(air: Dictionary, newForced: Array[Vector2i]) -> bool:
var open := {}
for tile: Vector2i in air:
if not forcedCells.has(tile) and not newForced.has(tile):
open[tile] = true
if open.is_empty():
return false
var first: Vector2i = open.keys()[0]
var seen := {first: true}
var queue: Array[Vector2i] = [first]
while not queue.is_empty():
var tile: Vector2i = queue.pop_back()
for step in MazeCorridors.STEPS:
var next := tile + step
if open.has(next) and not seen.has(next):
seen[next] = true
queue.append(next)
return seen.size() == open.size()
# Tiles of corridor between two air tiles of a region (a large number if
# they aren't joined).
static func _distance(air: Dictionary, from: Vector2i, to: Vector2i) -> int:
var distances := {from: 0}
var queue: Array[Vector2i] = [from]
while not queue.is_empty():
var tile: Vector2i = queue.pop_front()
if tile == to:
return distances[tile]
for step in MazeCorridors.STEPS:
var next := tile + step
if air.has(next) and not distances.has(next):
distances[next] = distances[tile] + 1
queue.append(next)
return 1 << 30
# ---- Laying tiles ----
func _randomize_weights() -> void:
for y in range(_bounds.position.y, _bounds.end.y):
for x in range(_bounds.position.x, _bounds.end.x):
var weight := 1.0 + _random.randf() * _winding
if _is_interior(Vector2i(x, y)):
weight *= INTERIOR_COST
_pathfinder.set_point_weight_scale(Vector2i(x, y), weight)
# Lays tube tiles along `path`. Its first tile's mouth faces `outwardIn`, its
# last tile's `outwardOut`. A one-way tube goes in at the first mouth.
func _put_tube(path: Array[Vector2i], outwardIn: Vector2i, outwardOut: Vector2i, kind: StringName) -> void:
var last := path.size() - 1
for i in path.size():
var cell := path[i]
var back := outwardIn if i == 0 else path[i - 1] - cell
var ahead := outwardOut if i == last else path[i + 1] - cell
var openings := TubeSteer.side_bit(back) | TubeSteer.side_bit(ahead)
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)
mouthFronts[path[0] + outwardIn] = true
mouthFronts[path[last] + outwardOut] = true
if kind == MazeGraph.ONE_WAY:
forcedCells[path[0] + outwardIn] = true
for tile in OneWayTube.blow_zone(_layer, path[last], outwardOut):
forcedCells[tile] = true
# Where the blow drops the slime: the landing tile, the one after (a
# sideways blow can slide it on) and, blowing down, the fall below.
var landing := path[last] + outwardOut * (OneWayTube.BLOW_RANGE + 1)
_keepFree[landing] = true
_keepFree[landing + outwardOut] = true
while outwardOut == Vector2i.DOWN and _is_air(landing + Vector2i.DOWN):
landing += Vector2i.DOWN
_keepFree[landing] = true
func _is_interior(cell: Vector2i) -> bool:
for rect in _interiors:
if rect.has_point(cell):
return true
return false
func _is_air(cell: Vector2i) -> bool:
return _layer.get_cell_source_id(cell) == -1
static func _middle(air: Dictionary) -> Vector2:
var total := Vector2.ZERO
for tile: Vector2i in air:
total += Vector2(tile)
return total / maxf(air.size(), 1.0)

View file

@ -0,0 +1 @@
uid://c1c8hb0riepww

View file

@ -2,218 +2,112 @@ class_name MazeValidator
extends RefCounted
# Checks a finished maze for soft-locks, from its tiles alone (it doesn't trust
# MazeGraph or MazeCarver). See docs/MAZE.md.
# MazeGraph, MazeCarver or MazeTubeRouter). See docs/MAZE.md.
#
# The slime crawls on floors, walls and ceilings and round corners, so inside a
# plain rectangle of air it can get to every tile side, and so to every tube
# mouth. That makes each chamber (a connected patch of air) one node; tubes
# are the only ways between them:
# - Ordinary and one-way tubes: in at any mouth the player could go in by
# (OneWayTube.can_enter), traced to their other end with the same
# PixelStream.trace_tube the player uses.
# - Manual and goo tubes: in at any mouth, out at any mouth of the same network.
# A mouth only leads somewhere if there's air in front of it.
#
# Air blows out of one-way exits (OneWayTube.blow_zone, TubeBlower) and knocks
# the slime away, so it can't stay in a blow zone. A blow zone is a strip of
# air tiles straight out from a wall. If it's shorter than the chamber is deep
# that way, it cuts the chamber's boundary (the loop of tile sides the slime
# crawls round) in one place only, so every tile side outside it can still be
# reached the other way round. Two zones could cut the loop twice and split the
# chamber, so each chamber may have one at most. No other mouth may open into a
# zone, and Start and End can't be in one. Then the model above still holds.
# The slime can't be pinned: outside the zone there's no push, it's always
# pushed out of the zone, and it can steer in the air.
#
# The maze passes if End can be reached from Start, and End can still be
# reached from every chamber that can be reached from Start.
# Two models, one on each side of the check, so it can't be fooled:
# - Where the slime might get to (generous): any air tile joined to Start's by
# air, or by a tube it could go into. It may not really get to all of them,
# but it can't get anywhere else.
# - Where the slime can surely get to End from (strict): SlimeMoves, the moves
# it's sure to manage, with forced tiles (suction and blow zones).
# The maze passes if every state at every tile it might get to can surely
# reach End. That's the no-soft-lock rule; Start reaching End is part of it.
var isValid := false
var problem := "" # Why it failed.
var chamberCount := 0
var reachableCount := 0 # Chambers reachable from Start.
var areaCount := 0 # Patches of air joined by air.
var reachableCount := 0 # Areas the slime might get to from Start.
var mouthCount := 0
var _layer: TileMapLayer
var _bounds: Rect2i
var _chamberAt := {} # Air tile -> chamber index.
var _chamberSizes: Array[Vector2i] = [] # Per chamber: its size in tiles.
var _links: Array[Dictionary] = [] # Per chamber: chamber -> true for each one a tube leads to.
var _moves: SlimeMoves
var _areaAt := {} # Air tile -> area index.
var _areaTiles: Array[Array] = [] # Per area: its air tiles.
var _links: Array[Dictionary] = [] # Per area: area -> true for each one a tube leads to.
func _init(layer: TileMapLayer, bounds: Rect2i, startCell: Vector2i, endCell: Vector2i) -> void:
_layer = layer
_bounds = bounds
if not _find_chambers():
_moves = SlimeMoves.new(layer, bounds)
if not _moves.problem.is_empty():
problem = _moves.problem
return
if not _chamberAt.has(startCell) or not _chamberAt.has(endCell):
if not _find_areas():
return
if not _moves.is_air(startCell) or not _moves.is_air(endCell):
problem = "Start or End is not in the air"
return
if not _check_blowers(startCell, endCell):
if _moves.is_forced(startCell) or _moves.is_forced(endCell):
problem = "Start or End is on a tile the air moves the slime off"
return
_find_links()
var reachable := _search(_chamberAt[startCell], false)
var canFinish := _search(_chamberAt[endCell], true)
reachableCount = reachable.size()
if not reachable.has(_chamberAt[endCell]):
var finished := _moves.can_finish(endCell)
if not finished.has(Vector3i(startCell.x, startCell.y, SlimeMoves.SIDES.find(Vector2i.DOWN))):
problem = "End can't be reached from Start"
return
for chamber: int in reachable:
if not canFinish.has(chamber):
problem = "Soft-lock: chamber %d is reachable but End isn't reachable from it" % chamber
return
var reachable := _reachable_areas(_areaAt[startCell])
reachableCount = reachable.size()
for area: int in reachable:
for tile: Vector2i in _areaTiles[area]:
for state in _moves.states_at(tile):
if not finished.has(state):
problem = "Soft-lock: the slime can be at %s (side %s) but can't get to End from there" % [
tile, SlimeMoves.SIDES[state.z]]
return
isValid = true
# Groups the air into chambers. False if air leaks out of the maze or a
# chamber isn't a plain rectangle (the movement model above needs that).
func _find_chambers() -> bool:
# Groups the air into areas joined by air. False if air leaks out of the maze.
func _find_areas() -> bool:
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)
if _is_air(cell) and not _chamberAt.has(cell):
if not _flood_chamber(cell, chamberCount):
return false
chamberCount += 1
_links.append({})
return true
func _flood_chamber(first: Vector2i, chamber: int) -> bool:
var cells: Array[Vector2i] = [first]
_chamberAt[first] = chamber
var low := first
var high := first
var index := 0
while index < cells.size():
var cell := cells[index]
index += 1
low = low.min(cell)
high = high.max(cell)
for direction in TubeSteer.DIRECTIONS:
var next := cell + direction
if not _is_air(next) or _chamberAt.has(next):
var first := Vector2i(x, y)
if not _moves.is_air(first) or _areaAt.has(first):
continue
if not _bounds.has_point(next):
problem = "Air leaks out of the maze at %s" % next
return false
_chamberAt[next] = chamber
cells.append(next)
var size := high - low + Vector2i.ONE
_chamberSizes.append(size)
if size.x * size.y != cells.size():
problem = "Chamber %d is not a rectangle" % chamber
return false
var tiles: Array[Vector2i] = [first]
_areaAt[first] = areaCount
var index := 0
while index < tiles.size():
var tile := tiles[index]
index += 1
for step in SlimeMoves.SIDES:
var next := tile + step
if _layer.get_cell_source_id(next) != -1 or _areaAt.has(next):
continue
if not _bounds.has_point(next):
problem = "Air leaks out of the maze at %s" % next
return false
_areaAt[next] = areaCount
tiles.append(next)
_areaTiles.append(tiles)
_links.append({})
areaCount += 1
return true
func _is_air(cell: Vector2i) -> bool:
return _layer.get_cell_source_id(cell) == -1
# Checks the blow zones of one-way exits keep the movement model true (see the
# top of this file).
func _check_blowers(startCell: Vector2i, endCell: Vector2i) -> bool:
var blownChambers := {}
var blowCellOwners := {} # Air tile in a blow zone -> the exit tube tile blowing there.
for exit in OneWayTube.find_exits(_layer):
var zone := OneWayTube.blow_zone(_layer, exit.cell, exit.outward)
var chamber: int = _chamberAt[zone[0]]
if blownChambers.has(chamber):
problem = "Chamber %d has more than one blow zone" % chamber
return false
blownChambers[chamber] = true
var depth := _chamberSizes[chamber].x if exit.outward.x != 0 else _chamberSizes[chamber].y
if zone.size() >= depth:
problem = "A blow zone spans chamber %d" % chamber
return false
for zoneCell in zone:
blowCellOwners[zoneCell] = exit.cell
if blowCellOwners.has(startCell) or blowCellOwners.has(endCell):
problem = "Start or End is in a blow zone"
return false
for mouth in _mouths():
var front: Vector2i = mouth.cell + mouth.outward
if blowCellOwners.has(front) and blowCellOwners[front] != mouth.cell:
problem = "A mouth at %s opens into a blow zone" % mouth.cell
return false
return true
# Every tube mouth: a tube tile side open onto air. [{cell, outward}].
func _mouths() -> Array[Dictionary]:
var mouths: Array[Dictionary] = []
# Every tube mouth (a tube tile side open onto air), and the areas going in
# there can lead to.
func _find_links() -> void:
for cell: Vector2i in _layer.get_used_cells():
var openings := TubeSteer.get_openings(_layer, cell)
for outward in TubeSteer.DIRECTIONS:
if openings & TubeSteer.side_bit(outward) and _chamberAt.has(cell + outward):
mouths.append({cell = cell, outward = outward})
return mouths
# Where going into each mouth can take the slime.
func _find_links() -> void:
for mouth in _mouths():
mouthCount += 1
var from: int = _chamberAt[mouth.cell + mouth.outward]
for to in _exits(mouth.cell, -mouth.outward):
_links[from][to] = true
# The chambers the slime can come out in after going into `cell` heading `direction`.
func _exits(cell: Vector2i, direction: Vector2i) -> Array[int]:
var exits: Array[int] = []
if TubeSteer.is_manual(_layer, cell) or TubeGoo.is_goo(_layer, cell):
for mouth in _network_mouths(cell):
exits.append(_chamberAt[mouth])
return exits
if not OneWayTube.can_enter(_layer, cell, direction):
return exits
var path := PixelStream.trace_tube(_layer, cell, direction)
if path.size() < 2:
return exits
var exitMouth := path[path.size() - 1]
var outward := (exitMouth - path[path.size() - 2]).normalized()
var halfTile := Vector2(_layer.tile_set.tile_size) / 2.0
var exitCell := _layer.local_to_map(_layer.to_local(exitMouth + outward * halfTile))
if _chamberAt.has(exitCell):
exits.append(_chamberAt[exitCell])
return exits
# The air tiles in front of every mouth of the steered tube network `cell` is
# in (joined the way TubeSteer and TubeGoo join tiles: same kind, both open).
func _network_mouths(first: Vector2i) -> Array[Vector2i]:
var isGoo := TubeGoo.is_goo(_layer, first)
var seen := {first: true}
var toVisit: Array[Vector2i] = [first]
var mouths: Array[Vector2i] = []
while not toVisit.is_empty():
var cell: Vector2i = toVisit.pop_back()
var openings := TubeSteer.get_openings(_layer, cell)
for direction in TubeSteer.DIRECTIONS:
if openings & TubeSteer.side_bit(direction) == 0:
for outward in SlimeMoves.SIDES:
if openings & TubeSteer.side_bit(outward) == 0 or not _areaAt.has(cell + outward):
continue
var next := cell + direction
if _chamberAt.has(next):
mouths.append(next)
continue
var isSameKind := TubeGoo.is_goo(_layer, next) if isGoo else TubeSteer.is_manual(_layer, next)
if isSameKind and TubeSteer.get_openings(_layer, next) & TubeSteer.side_bit(-direction) and not seen.has(next):
seen[next] = true
toVisit.append(next)
return mouths
mouthCount += 1
var from: int = _areaAt[cell + outward]
for exit in _moves.tube_exits(cell, -outward):
_links[from][_areaAt[Vector2i(exit.x, exit.y)]] = true
# Chambers reachable from `from` (or, if `isBackward`, that can reach it).
func _search(from: int, isBackward: bool) -> Dictionary:
func _reachable_areas(from: int) -> Dictionary:
var found := {from: true}
var queue: Array[int] = [from]
while not queue.is_empty():
var chamber: int = queue.pop_front()
for other in chamberCount:
var isLinked: bool = _links[other].has(chamber) if isBackward else _links[chamber].has(other)
if isLinked and not found.has(other):
var area: int = queue.pop_front()
for other: int in _links[area]:
if not found.has(other):
found[other] = true
queue.append(other)
return found

237
Levels/Maze/slime_moves.gd Normal file
View file

@ -0,0 +1,237 @@
class_name SlimeMoves
extends RefCounted
# A model of how the slime can move round a tile map, read from the tiles, for
# MazeValidator. It only has moves the slime is sure to manage (checked in the
# game in 1-tile corridors and shafts), so "can reach End" here really means
# the slime can. See docs/MAZE.md.
#
# A state is the slime in an air tile, stuck to one of its sides that's solid:
# Vector3i(x, y, side), side indexing SIDES. From a state the slime can:
# - slide along the surface to the next tile, if the surface goes on there,
# - turn an inside corner onto the other solid side of the same tile,
# - wrap round an outside corner onto the far side of the block it's on,
# - cross a 1-tile gap to the opposite side (a hop or a bridge),
# - let go of a ceiling and fall straight down onto a floor,
# - go into a tube mouth in the surface it's on, coming out stuck to the face
# of the mouth it leaves by (any mouth of a manual or goo network).
# "Forced" tiles move the slime without asking (it can't stay or cross):
# - the tile in front of a one-way tube's entrance sucks it in,
# - the blow zone in front of a one-way exit blows it to known spots (sideways:
# it slides onto the floor of the landing tile or the one after; down: it
# falls from the landing tile onto a floor).
# A state on a forced tile can reach End only if every place it can be moved
# to can. Exits that blow up, into a wall, sideways where it isn't 1 tile tall,
# or down through another forced tile can't be modelled, so they're a problem.
const SIDES: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
const SLIDE_AFTER_BLOW = 1 # Tiles a sideways blow can slide the slime on past the landing tile.
var problem := "" # Why the tiles can't be modelled, or "".
var _layer: TileMapLayer
var _bounds: Rect2i
var _forced := {} # Air tile -> Array of states the air moves the slime to.
var _downBlowLandings: Array[Vector2i] = []
func _init(layer: TileMapLayer, bounds: Rect2i) -> void:
_layer = layer
_bounds = bounds
_find_blow_zones()
if problem.is_empty():
_find_suction_tiles()
if problem.is_empty():
_check_down_blows()
func is_air(cell: Vector2i) -> bool:
return _bounds.has_point(cell) and _layer.get_cell_source_id(cell) == -1
func is_forced(cell: Vector2i) -> bool:
return _forced.has(cell)
# The states the slime can be in at an air tile.
func states_at(cell: Vector2i) -> Array[Vector3i]:
var states: Array[Vector3i] = []
for side in SIDES.size():
if not is_air(cell + SIDES[side]):
states.append(Vector3i(cell.x, cell.y, side))
return states
# The states the slime comes out in after going into the tube tile `cell`
# heading `direction` (none if it can't go in there).
func tube_exits(cell: Vector2i, direction: Vector2i) -> Array[Vector3i]:
var exits: Array[Vector3i] = []
if TubeSteer.is_manual(_layer, cell) or TubeGoo.is_goo(_layer, cell):
for mouth in _network_mouths(cell):
exits.append(_state(mouth.front, mouth.tile - mouth.front))
return exits
if not OneWayTube.can_enter(_layer, cell, direction):
return exits
var path := PixelStream.trace_tube(_layer, cell, direction)
if path.size() < 2:
return exits
var exitMouth := path[path.size() - 1]
var outward := Vector2i((exitMouth - path[path.size() - 2]).normalized().round())
var halfTile := Vector2(_layer.tile_set.tile_size) / 2.0
var front := _layer.local_to_map(_layer.to_local(exitMouth + Vector2(outward) * halfTile))
if is_air(front):
exits.append(_state(front, -outward))
return exits
# Every state from which the slime can get to `endCell`.
func can_finish(endCell: Vector2i) -> Dictionary:
var required := {} # State -> how many of its next states must reach End first.
var previous := {} # State -> states that lead to it.
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)
if not is_air(cell):
continue
for state in states_at(cell):
var nextStates: Array = _forced[cell] if _forced.has(cell) else _moves(state)
required[state] = nextStates.size() if _forced.has(cell) else 1
for next: Vector3i in nextStates:
if not previous.has(next):
previous[next] = []
previous[next].append(state)
var finished := {}
var queue: Array[Vector3i] = []
if not _forced.has(endCell):
queue = states_at(endCell)
for state in queue:
finished[state] = true
while not queue.is_empty():
var state: Vector3i = queue.pop_back()
for earlier: Vector3i in previous.get(state, []):
if finished.has(earlier):
continue
required[earlier] -= 1
if required[earlier] <= 0:
finished[earlier] = true
queue.append(earlier)
return finished
# ---- Moves ----
func _moves(state: Vector3i) -> Array[Vector3i]:
var moves: Array[Vector3i] = []
var cell := Vector2i(state.x, state.y)
var side := SIDES[state.z]
for along: Vector2i in [Vector2i(side.y, side.x), Vector2i(-side.y, -side.x)]:
var next := cell + along
if is_air(next) and not is_air(next + side):
moves.append(_state(next, side)) # Slide along.
if not is_air(next):
moves.append(_state(cell, along)) # Inside corner.
if is_air(next) and is_air(next + side) and not _forced.has(next):
moves.append(_state(next + side, -along)) # Round an outside corner (through `next`).
if not is_air(cell - side):
moves.append(_state(cell, -side)) # Across a 1-tile gap.
if side == Vector2i.UP and is_air(cell + Vector2i.DOWN):
var landing := _fall_from(cell)
if landing != Vector2i(-1, -1):
moves.append(_state(landing, Vector2i.DOWN))
var tube := cell + side
if TubeSteer.get_openings(_layer, tube) & TubeSteer.side_bit(-side):
moves.append_array(tube_exits(tube, side))
return moves
# Where the slime lands falling straight down from `cell`, or (-1, -1) if it
# falls through a forced tile on the way.
func _fall_from(cell: Vector2i) -> Vector2i:
while is_air(cell + Vector2i.DOWN):
cell += Vector2i.DOWN
if _forced.has(cell):
return Vector2i(-1, -1)
return cell
# ---- Forced tiles ----
func _find_blow_zones() -> void:
for exit in OneWayTube.find_exits(_layer):
var outward: Vector2i = exit.outward
var zone := OneWayTube.blow_zone(_layer, exit.cell, outward)
var landing: Vector2i = exit.cell + outward * (OneWayTube.BLOW_RANGE + 1)
var where := "The exit at %s" % exit.cell
if outward == Vector2i.UP:
problem = "%s blows up (the slime could bounce in place)" % where
return
if zone.size() < OneWayTube.BLOW_RANGE or not is_air(landing):
problem = "%s blows into a wall (it could pin the slime)" % where
return
var outcomes: Array[Vector3i] = []
if outward.y == 0:
for tile in zone + [landing]:
if is_air(tile + Vector2i.UP) or is_air(tile + Vector2i.DOWN):
problem = "%s blows sideways where it isn't 1 tile tall" % where
return
for step in SLIDE_AFTER_BLOW + 1:
var tile := landing + outward * step
if not is_air(tile) or is_air(tile + Vector2i.DOWN):
break
outcomes.append(_state(tile, Vector2i.DOWN))
else:
outcomes.append(_state(_fall_from(landing), Vector2i.DOWN))
_downBlowLandings.append(landing)
for tile in zone:
if _forced.has(tile):
problem = "Two blow zones overlap at %s" % tile
return
_forced[tile] = outcomes
# Once every forced tile is known: a down blow mustn't drop the slime through one.
func _check_down_blows() -> void:
for landing in _downBlowLandings:
if _forced.has(landing) or _fall_from(landing) == Vector2i(-1, -1):
problem = "A down blow at %s drops the slime through another forced tile" % landing
return
func _find_suction_tiles() -> void:
for entrance in OneWayTube.find_entrances(_layer):
var front: Vector2i = entrance.cell + entrance.outward
var outcomes := tube_exits(entrance.cell, -entrance.outward)
if outcomes.is_empty():
continue # Leads nowhere: it doesn't pull.
if _forced.has(front):
problem = "The entrance at %s is in a blow zone" % entrance.cell
return
_forced[front] = outcomes
# The mouths of the steered tube network `first` is in (joined the way
# TubeSteer and TubeGoo join tiles: same kind, both open): [{tile, front}].
func _network_mouths(first: Vector2i) -> Array[Dictionary]:
var isGoo := TubeGoo.is_goo(_layer, first)
var seen := {first: true}
var toVisit: Array[Vector2i] = [first]
var mouths: Array[Dictionary] = []
while not toVisit.is_empty():
var cell: Vector2i = toVisit.pop_back()
var openings := TubeSteer.get_openings(_layer, cell)
for direction in SIDES:
if openings & TubeSteer.side_bit(direction) == 0:
continue
var next := cell + direction
if is_air(next):
mouths.append({tile = cell, front = next})
continue
var isSameKind := TubeGoo.is_goo(_layer, next) if isGoo else TubeSteer.is_manual(_layer, next)
if isSameKind and TubeSteer.get_openings(_layer, next) & TubeSteer.side_bit(-direction) and not seen.has(next):
seen[next] = true
toVisit.append(next)
return mouths
static func _state(cell: Vector2i, side: Vector2i) -> Vector3i:
return Vector3i(cell.x, cell.y, SIDES.find(side))

View file

@ -0,0 +1 @@
uid://23hnncqowqs4

View file

@ -2,9 +2,9 @@
- Player (`Characters/player.gd`): the slime: crawling on any surface, hops, bridges, edge wraps, going into tubes.
- Tubes (`Effects/`): tiles the slime squeezes through. Kinds: auto (`PixelStream`), manual (`TubeSteer`), goo (`TubeGoo`), one-way (`OneWayTube`, an auto tube with one entrance).
- Tube air (`Effects/tube_airflow.gd`, `Effects/tube_blower.gd`): air through one-way tubes: motes in and out, and the blow that knocks the slime away from exits.
- Tube air (`Effects/tube_airflow.gd`, `Effects/tube_air_currents.gd`): air through one-way tubes: motes in and out, suction into entrances, blow away from exits.
- Room camera (`Levels/room_camera.gd`): screen-by-screen camera that cuts between 640x480 rooms.
- Maze generation (`Levels/Maze/`): builds, validates and plays random tube mazes (see `docs/MAZE.md`).
- Maze generation (`Levels/Maze/`): builds, validates (slime movement model) and plays random tube labyrinths (see `docs/MAZE.md`).
- Screens and transitions (`Autoloads/pixel_screen.gd`, `Autoloads/transition.gd`): the 640x480 pixel screen and the dissolve between scenes.
- Settings (`Autoloads/settings.gd`): saved key bindings and volumes.
- Menus (`UI/`): main menu, options, pause, maze setup.

View file

@ -1,168 +1,129 @@
# Maze mode
A "Maze" button on the main menu asks for a size and a complexity, then
generates a level of rock chambers joined by tubes, with a Start and an End.
generates a puzzle-book labyrinth with tubes, a Start and an End.
## Goals (checkable)
1. Main menu has a **Maze** button. It opens a setup panel (same look as
Options) with **Width** (1-4 screens), **Height** (1-3 screens) and
**Complexity** (1-5), plus **Generate** and **Back**.
2. Generate builds a maze level from those inputs and a random seed. The
same inputs and seed always give the same maze.
3. The maze spans `Width x Height` screens (one screen = 20 x 15 tiles, the
RoomCamera's room). Chambers sit inside screens; tubes run through the rock
inside a screen and across screen borders.
4. It uses the existing tube kinds (auto, manual, goo) and a new **one-way**
kind.
5. One-way tubes: orange tiles; only their entrance mouth lets the slime in;
orange motes drift into the entrance like a vacuum. Built by extending the
existing tube code (the auto tube's `PixelStream`), not by copying it.
5b. Air blows out of a one-way tube's **exit**: orange motes stream out of it,
and within 2 tiles straight out of the mouth (the "blow zone") the slime is
knocked off a wall or ceiling, or lifted off the floor (240 px/s away from
the mouth; sideways blowers also lift at 120 px/s). It can never be pinned.
6. Start and End are clearly visible (a green START pad, a gold END pad).
2. The same inputs and seed always give the same maze.
3. The maze fills `Width x Height` screens (one screen = 20 x 15 tiles, the
RoomCamera's room). Tubes run between screens and through walls.
4. **Maze-book feel:** each region is a labyrinth of narrow corridors with
1-tile walls: long winding paths, branches, dead ends. Complexity 1 is
roomy (3-tile corridors, many loops); 4-5 is a dense 1-tile labyrinth.
5. Tube kinds: auto, manual, goo (all kept) and **one-way** (orange tiles).
One-way tubes:
- only let the slime in at their entrance; orange motes drift into it;
- **suck**: the slime is pulled in as soon as its middle is on the tile in
front of the entrance, without pressing anything;
- **blow**: white motes stream out of the exit; within 1 tile of the exit
(the blow zone) the slime is knocked off a wall or ceiling, or lifted off
the floor (240 px/s away; sideways blows also lift at 120 px/s).
6. Start and End are clearly visible (green START pad, gold END pad).
Touching End shows a win panel with **New maze** and **Main menu**.
7. **No soft-locks.** For every chamber the slime can reach from Start, End is
still reachable. Checked on the finished tiles by a validator that does not
trust the generator; a failed maze is thrown away and the next seed tried.
8. A headless check generates many mazes (all sizes, complexities, many seeds)
and runs the validator on each. Target: 100 % pass on the first try.
7. **No soft-locks.** From every place the slime might get to, End must still
be surely reachable. Checked on the finished tiles by a validator that
doesn't trust the generator; a failed maze is thrown away and the next seed
tried.
8. A headless check builds many mazes and runs the validator on each, plus
negative tests the validator must reject.
What the inputs control:
| Complexity | Chambers per screen | One-way tubes on the Start-End route | Extra tubes (per screen) | Steered (manual/goo) share | Tube winding |
|---|---|---|---|---|---|
| 1 | 2 x 1 | 0 | 0 | 0 % | low |
| 2 | 2 x 2 | 1 | 0.5 | 20 % | low |
| 3 | 2 x 2 | 2 | 1 | 30 % | medium |
| 4 | 3 x 2 | 3 | 1.5 | 35 % | high |
| 5 | 3 x 2 | 4 | 2 | 40 % | high |
Extra tubes are about half one-way (traps/shortcuts), half two-way (loops).
| Complexity | Regions per screen | Corridor width | Loops (braid) | One-way on route | Extra tubes / screen | Wall pipes / screen | Steered share |
|---|---|---|---|---|---|---|---|
| 1 | 2 x 1 | 3 | 50 % | 0 | 0 | 0 | 0 % |
| 2 | 2 x 1 | 2 | 30 % | 1 | 0.5 | 1 | 20 % |
| 3 | 2 x 1 | 2 | 15 % | 2 | 1 | 2 | 30 % |
| 4 | 1 x 1 | 1 | 5 % | 3 | 1 | 3 | 35 % |
| 5 | 1 x 1 | 1 | 0 % | 4 | 1.5 | 5 | 40 % |
## Non-goals
- No change to player movement, existing levels or other menus (besides the
one button). The player only gains what the new tube kind needs: one-way
tubes only let it in at their entrance, and `blow_away()` for the air out
of their exits.
one button). The player only gains what one-way tubes need: they only let it
in at the entrance, `pull_into_tube()` and `blow_away()`.
- No tube crossings or branching tube networks in mazes.
- No ledges, hazards, items or enemies inside chambers: chambers are plain
rectangles (this is what keeps the movement model below exact).
- No saving of mazes; the seed is not shown in the UI.
- No hazards, items or enemies. No saving of mazes; the seed isn't shown.
## How the player moves (the model the check uses)
## Approaches considered (rework for maze-book layouts)
From `Characters/player.gd`: the slime crawls on floors, walls and ceilings,
wraps round outside corners and takes inside corners. So inside one closed
rectangle of air it can reach every spot on the rectangle's boundary, and so
every tube mouth in it. Chambers are therefore nodes of a graph, and the only
ways between them are tubes:
1. **Region graph + coarse-grid labyrinth per region (chosen).** Keep the
region graph (spanning tree rooted at End, one-way tubes towards End on the
route, extra tubes). Inside each region carve a classic recursive-backtracker
maze on a coarse grid (cell = corridor width, wall = 1 tile) and braid some
dead ends. Tubes between regions run in the rock between regions; short
"wall pipes" go through one wall inside a region as shortcuts.
Safe by construction: corridors are two-way, and the tree still leads to
End from every region. One-way ends only go where their forced tiles don't
cut a region (see `MazeTubeRouter`).
2. **Corridor graph with rooms.** Rooms joined by drawn corridors. More
varied shapes, but corridors cross and need their own routing, and it reads
less like a maze book.
3. **Tile-level random carving + full search.** Random walks/caves, keep if
the search passes. Little control over difficulty, many rejected tries.
- **Auto** tube (green): either end in, traced to the other end
(`PixelStream.trace_tube`, the same function the player uses). Edge both ways.
- **One-way** tube (orange): an auto tube that only accepts the slime at the
mouth whose tile is marked as the entrance (`OneWayTube.can_enter`, also used
by the player). Edge from the entrance chamber to the exit chamber only.
- **Manual / goo** tubes (grey / pink): steered; the slime can come out
of any mouth with room or back out. Edges between all their mouths' chambers.
- A mouth only counts as an exit if the tile in front of it is air (room for
the slime to reform).
Approach 1 gives the dense maze-book look directly, scales by corridor width
and braid, and keeps the old safety argument.
### Blow zones
## How the slime moves (checked in the game)
The slime can't stay in a blow zone, so the zone's tiles are taken out of the
chamber. A zone is a strip straight out from one wall, shorter than the
chamber is deep that way. It cuts the chamber's boundary loop (the tile sides
the slime crawls round) in one place only, so every other part of the loop is
still reachable the other way round. Two zones could cut the loop twice and
split the chamber, so the model holds only if:
A scripted run in 1-tile spaces showed the slime: crawls a 1-tall corridor's
floor and ceiling; gets from floor to ceiling there; climbs a 1-wide shaft up
and down; turns into a shaft above a corridor from the ceiling; falls into a
shaft below; and goes from a shaft back into a corridor. So the narrowest
corridor is 1 tile.
- each chamber has at most one blow zone (the generator lets at most one
one-way tube come out in each chamber);
- a zone is shorter than its chamber in its direction (chambers are at least
3 tiles; zones at most 2);
- no other tube mouth opens into a zone, and Start and End are not in one.
## The soft-lock check (`MazeValidator` + `SlimeMoves`)
Not pinned: outside the zone there is no push, the push always points out of
the zone, and the slime can steer in the air. A floor blower lifts it up to the
ceiling or out of the zone; it can then crawl or fall away.
Works only from the TileMapLayer, with two models:
## The soft-lock check (`MazeValidator`)
- **Might get to (generous):** any air tile joined to Start's tile by air, or
through a tube it could go into.
- **Surely gets to End from (strict, `SlimeMoves`):** a state is the slime in
an air tile stuck to one solid side. Moves: slide along a surface, turn an
inside corner, wrap an outside corner, cross a 1-tile gap, let go of a
ceiling and fall, go into a tube mouth in the surface it's on (coming out
stuck to the exit mouth's face). Forced tiles: the tile in front of an
entrance (sucked in) and blow zones (blown to known spots: sideways onto the
landing tile's floor or the next; down, falling from the landing tile). A
state on a forced tile only counts if every place it can be moved to counts.
Exits that blow up, into a wall, sideways where it isn't 1 tile tall, or down
through another forced tile are rejected (their outcome isn't sure).
Works only from the TileMapLayer:
Pass if every state at every tile the slime might get to can surely reach End.
"Start reaches End" alone isn't enough: a one-way tube, a sucking entrance or a
blow zone can drop the slime where End is out of reach.
1. Flood-fill the air cells inside the maze into chambers. Fail if air leaks
out of the maze bounds or a chamber is not a full rectangle (the movement
model above would not hold).
1b. Check the blow zone rules above (rebuilt from the tiles with
`OneWayTube.find_exits` and `blow_zone`, the same functions the game uses).
2. Find every tube mouth (a tube tile side that is open onto air).
3. Build a directed chamber graph from the tube rules above.
4. **Forward** search from the Start chamber gives `reachable`. **Backward**
search (reversed edges) from the End chamber gives `canFinish`.
5. Pass if End is in `reachable` and every chamber in `reachable` is also in
`canFinish`. That is the no-soft-lock rule; "Start reaches End" alone is not
enough, because a one-way tube could drop the slime where End is out of reach.
## Approaches considered
1. **Chamber graph first, then carve tiles (chosen).** Lay out a grid of
rectangular chambers, build a spanning tree over neighbouring chambers
(a classic maze), pick Start and End, root the tree at End, make some tree
edges on the Start-End route one-way towards End, and add extra tubes. Then
carve: rock everywhere, air chambers, each tube routed through the rock with
`AStarGrid2D` and random weights so tubes wind.
*Safe by construction:* with the tree rooted at End and every tree edge
usable towards End, every chamber can reach End, so any extra tube in any
direction is safe. The validator then checks the real tiles anyway.
2. **Tile-level random level + search.** Random caves and random tubes, then
a search over the player's moves at tile level, keep if it passes. Simple to
write but most tries fail, with no control over difficulty; the per-tile
movement search is also a big, fragile copy of `player.gd`.
3. **Template rooms stitched together.** Hand-made screens with tube stubs at
the edges, joined like jigsaw pieces. Looks good, but needs many hand-made
rooms, gives little variety per size, and one-way placement still needs the
same graph reasoning as approach 1.
4. **Graph with a solver-guided one-way search.** Start from a strongly
connected graph and keep adding one-way tubes while a solver says it is
still safe. Works, but is slower and less predictable than approach 1, which
gets the same safety for free from the rooted tree.
Approach 1 meets every goal: inputs map directly to grid size and edge counts,
chambers stay plain rectangles (so the movement model is exact), tubes cross
screens naturally, and safety does not depend on luck.
Not pinned: blow zones always have air past them and push the slime out of the
zone; suction only pulls into a tube that leads somewhere with room.
## Files
- `UI/maze_setup_menu.*` - the size/complexity panel.
- `Levels/Maze/maze_settings.gd` - the chosen inputs (static, read by the level).
- `Levels/Maze/maze_graph.gd` - chambers, spanning tree, one-way and extra tubes.
- `Levels/Maze/maze_carver.gd` - turns the graph into tiles, routes tubes.
- `Levels/Maze/maze_tiles.gd` - finds the right tile for a tube shape and kind.
- `Levels/Maze/maze_settings.gd` - inputs and the complexity table.
- `Levels/Maze/maze_graph.gd` - regions, spanning tree, one-way and extra tubes.
- `Levels/Maze/maze_corridors.gd` - carves a labyrinth into a region.
- `Levels/Maze/maze_tube_router.gd` - tubes between regions and wall pipes; one-way safety rules.
- `Levels/Maze/maze_carver.gd` - puts it together; Start and End.
- `Levels/Maze/maze_tiles.gd` - finds the tile for a tube shape and kind.
- `Levels/Maze/slime_moves.gd` - the strict movement model.
- `Levels/Maze/maze_validator.gd` - the soft-lock check.
- `Levels/Maze/maze_builder.gd` - graph, carve, check; next seed on failure.
- `Levels/Maze/maze_level.*` - the playable scene: generate, validate, place.
- `Levels/Maze/maze_marker.gd` - the Start and End pads.
- `Levels/Maze/maze_win_menu.*` - the win panel.
- `Effects/one_way_tube.gd` - one-way tube rules (entrance check).
- `Effects/pixel_stream.gd` - `trace_tube()`, moved here from `player.gd` so
the player and the validator share it.
- `Assets/level_tiles.tres` - orange alternatives 3-5 on the six two-sided
tube tiles (3 = body/exit, 4 and 5 = entrance on each side), and the
`tube_one_way` / `tube_one_way_entry` custom data layers.
- `Effects/tube_airflow.gd` - orange motes drifting into entrances and
blown out of exits.
- `Effects/tube_blower.gd` - pushes the slime in blow zones (calls the
player's `blow_away()`).
- `tests/maze_check.gd` - the headless batch check.
- `Levels/Maze/maze_level.*`, `maze_marker.gd`, `maze_win_menu.*` - the playable scene.
- `Effects/one_way_tube.gd` - one-way rules: entrance check, exits, blow zones.
- `Effects/tube_air_currents.gd` - suction and blow acting on the player.
- `Effects/tube_airflow.gd` - orange motes in, white motes out.
- `Effects/pixel_stream.gd` - `trace_tube()`, shared by player and validator.
- `Assets/level_tiles.tres` - orange one-way tiles (alternatives 3-5) and their
custom data layers.
- `tests/maze_check.gd` - the headless check.
Run the check:
`godot --headless --audio-driver Dummy --script res://tests/maze_check.gd`
The check also checks the validator rejects Start inside a blow zone, and
builds one known soft-lock (a chamber whose tubes are all
turned into one-way tubes leading in, while Start still reaches End another
way) and makes sure the validator rejects it.
Negative tests: a one-way trap (a region whose only way in is a one-way
tube), Start in a blow zone, and two hand-made maps where Start and End are
joined by air (so an area-level check passes) but a blow zone or a sucking
entrance stops the slime.

View file

@ -1,14 +1,51 @@
extends SceneTree
# Headless batch check for Maze mode: builds many mazes (every size and
# complexity, several seeds) and runs the soft-lock check on each.
# Headless check for Maze mode:
# godot --headless --audio-driver Dummy --script res://tests/maze_check.gd
# Also checks the validator catches a soft-lock, by turning one tube of a good
# maze into a one-way trap.
# 1. Builds many mazes (every size and complexity, several seeds) and runs the
# soft-lock check on each.
# 2. Negative tests: the validator must reject
# - a one-way trap (a region whose only way in is a one-way tube),
# - Start inside a blow zone,
# - a hand-made blow-zone trap and a suction trap. In both, Start and End are
# joined by air, so a check that only looks at which areas join (the old
# chamber model) would pass them.
const SEEDS_PER_SETTING = 6
const SEEDS_PER_SETTING = 4
const TILE_SET = preload("res://Assets/level_tiles.tres")
# Hand-made maps: "#" rock, "." air, "S" Start, "E" End, letters are tube tiles
# (see TUBE_KEY): [openings, kind, entry side bit].
const TUBE_KEY := {
"|": [5, MazeGraph.AUTO, 0], "-": [10, MazeGraph.AUTO, 0],
"L": [3, MazeGraph.AUTO, 0], "J": [9, MazeGraph.AUTO, 0],
"v": [5, MazeGraph.ONE_WAY, 0], "^": [5, MazeGraph.ONE_WAY, 1],
}
# A down blower over the crossing (3, 2): walking from S to the left blows the
# slime down the shaft, which it can't climb back up past the blow zone.
const WIND_TRAP: Array[String] = [
"#######",
"###v###",
"#E...S#",
"###.###",
"###.###",
"###.###",
"#######",
]
# Walking from S to E crosses the tile over a one-way entrance (4, 2): it
# sucks the slime into a pocket whose only way out leads back to the start
# side. End can't be reached at all.
const SUCTION_TRAP: Array[String] = [
"#########",
"#########",
"#S.....E#",
"###|^####",
"###|v####",
"##.....##",
"##.....##",
"#########",
]
func _initialize() -> void:
var layer := TileMapLayer.new()
@ -20,6 +57,7 @@ func _initialize() -> void:
var validCount := 0
var startTime := Time.get_ticks_msec()
for complexity in range(MazeSettings.MIN_COMPLEXITY, MazeSettings.MAX_COMPLEXITY + 1):
var levelStart := Time.get_ticks_msec()
for width in range(MazeSettings.MIN_WIDTH, MazeSettings.MAX_WIDTH + 1):
for height in range(MazeSettings.MIN_HEIGHT, MazeSettings.MAX_HEIGHT + 1):
for seedIndex in SEEDS_PER_SETTING:
@ -32,104 +70,94 @@ func _initialize() -> void:
firstTryCount += 1
for problem in builder.problems:
print(" c%d %dx%d: %s" % [complexity, width, height, problem])
print(" complexity %d: %d ms" % [complexity, Time.get_ticks_msec() - levelStart])
print("Mazes: %d, valid: %d, valid on the first try: %d (%d ms)"
% [mazeCount, validCount, firstTryCount, Time.get_ticks_msec() - startTime])
var caught := _check_trap_is_caught(layer)
print("Validator catches a one-way trap: %s" % ("yes" if caught else "NO"))
var blowCaught := _check_blow_zone_is_caught(layer)
print("Validator catches Start in a blow zone: %s" % ("yes" if blowCaught else "NO"))
quit(0 if validCount == mazeCount and caught and blowCaught else 1)
var results := {
"one-way trap": _check_one_way_trap(layer),
"Start in a blow zone": _check_start_in_blow_zone(layer),
"blow-zone trap (hand-made)": _check_map(layer, WIND_TRAP),
"suction trap (hand-made)": _check_map(layer, SUCTION_TRAP),
}
var allCaught := true
for test: String in results:
print("Validator catches %s: %s" % [test, "yes" if results[test] else "NO"])
allCaught = allCaught and results[test]
quit(0 if validCount == mazeCount and allCaught else 1)
# A good maze, checked again as if Start stood in a one-way exit's blow zone
# (the slime would be blown off it). The validator must reject it.
func _check_blow_zone_is_caught(layer: TileMapLayer) -> bool:
for blowSeed in range(4242, 4282):
# In a good maze, take a one-way tube's exit region X (not End's) and block
# every other mouth into X with rock. The tube is then X's only way in, and it
# has no way out. Tries mazes until Start can still reach End, so it's a real
# soft-lock and not just an unsolvable maze.
func _check_one_way_trap(layer: TileMapLayer) -> bool:
var tiles := MazeTiles.new(layer.tile_set)
for trapSeed in range(4242, 4302):
var builder := MazeBuilder.new(layer, Vector2i(2, 2), 3, trapSeed)
if not builder.isValid:
continue
var carver := builder.carver
for exit in OneWayTube.find_exits(layer):
var region := _region_with(carver, exit.cell + exit.outward)
if region == -1 or region == _region_with(carver, carver.endCell):
continue
for cell in layer.get_used_cells():
for outward in SlimeMoves.SIDES:
var isMouth := TubeSteer.get_openings(layer, cell) & TubeSteer.side_bit(outward) != 0
if isMouth and cell != exit.cell and carver.regionAir[region].has(cell + outward):
tiles.set_tile(layer, cell, 0, MazeTiles.ROCK)
var validator := MazeValidator.new(layer, carver.bounds, carver.startCell, carver.endCell)
if validator.problem.begins_with("Soft-lock"):
print(" one-way trap (seed %d): %s" % [trapSeed, validator.problem])
return true
if validator.isValid:
return false # Missed a real trap.
break # The map is changed now: try the next maze.
return false
# A good maze, checked again as if Start stood in a one-way exit's blow zone.
func _check_start_in_blow_zone(layer: TileMapLayer) -> bool:
for blowSeed in range(4242, 4302):
var builder := MazeBuilder.new(layer, Vector2i(2, 2), 4, blowSeed)
var exits := OneWayTube.find_exits(layer)
if not builder.isValid or exits.is_empty():
continue
var zone := OneWayTube.blow_zone(layer, exits[0].cell, exits[0].outward)
var validator := MazeValidator.new(layer, builder.carver.bounds, zone[0], builder.carver.endCell)
print(" blow zone test (seed %d): %s" % [blowSeed, validator.problem])
print(" Start in a blow zone (seed %d): %s" % [blowSeed, validator.problem])
return not validator.isValid
return false
# A real soft-lock: in a good maze, take a tube from Start's chamber to some
# chamber X (not End's) and make it one-way into X, and block every other
# mouth in X with rock. X is then reachable from Start but has no way out.
# Tries mazes until Start can still reach End some other way, so a plain
# "Start reaches End" check would pass. The validator must reject it as a
# soft-lock.
func _check_trap_is_caught(layer: TileMapLayer) -> bool:
for trapSeed in range(4242, 4282):
var builder := MazeBuilder.new(layer, Vector2i(2, 2), 3, trapSeed)
if not builder.isValid or not _set_trap(layer, builder.carver):
continue
var validator := MazeValidator.new(layer, builder.carver.bounds, builder.carver.startCell, builder.carver.endCell)
if validator.problem.begins_with("Soft-lock"):
print(" trap test (seed %d): %s" % [trapSeed, validator.problem])
return true
if validator.isValid:
return false # Missed a real trap.
return false
# Builds a hand-made map. The validator must reject it, though Start and End
# are in the same patch of air.
func _check_map(layer: TileMapLayer, map: Array[String]) -> bool:
layer.clear()
var tiles := MazeTiles.new(layer.tile_set)
var start := Vector2i.ZERO
var end := Vector2i.ZERO
for y in map.size():
for x in map[y].length():
var symbol := map[y][x]
var cell := Vector2i(x, y)
if symbol == "#":
tiles.set_tile(layer, cell, 0, MazeTiles.ROCK)
elif TUBE_KEY.has(symbol):
tiles.set_tile(layer, cell, TUBE_KEY[symbol][0], TUBE_KEY[symbol][1], TUBE_KEY[symbol][2])
elif symbol == "S":
start = cell
elif symbol == "E":
end = cell
var bounds := Rect2i(0, 0, map[0].length(), map.size())
var validator := MazeValidator.new(layer, bounds, start, end)
print(" hand-made map: %s" % validator.problem)
return not validator.isValid
# Turns the first chamber a tube from Start leads to (not End's) into a trap.
func _set_trap(layer: TileMapLayer, carver: MazeCarver) -> bool:
var startRect := _rect_with(carver, carver.startCell)
var endRect := _rect_with(carver, carver.endCell)
for mouth in _mouths_of(layer, startRect):
var tube := _follow_tube(layer, mouth.cell, mouth.outward)
var trapMouth: Vector2i = tube.cells.back()
var trapRect := _rect_with(carver, trapMouth + tube.farOutward)
if trapRect == endRect or trapRect == startRect:
continue
var tiles := MazeTiles.new(layer.tile_set)
for other in _mouths_of(layer, trapRect):
if other.cell != trapMouth:
tiles.set_tile(layer, other.cell, 0, MazeTiles.ROCK)
var cells: Array[Vector2i] = tube.cells
for i in cells.size():
var entrySide := TubeSteer.side_bit(mouth.outward) if i == 0 else 0
tiles.set_tile(layer, cells[i], TubeSteer.get_openings(layer, cells[i]), MazeGraph.ONE_WAY, entrySide)
return true
return false
func _rect_with(carver: MazeCarver, cell: Vector2i) -> Rect2i:
for rect in carver.chamberRects:
if rect.has_point(cell):
return rect
return Rect2i()
# Tube mouths opening into `rect`: [{cell, outward}].
func _mouths_of(layer: TileMapLayer, rect: Rect2i) -> Array[Dictionary]:
var mouths: Array[Dictionary] = []
for cell in layer.get_used_cells():
for outward in TubeSteer.DIRECTIONS:
if TubeSteer.get_openings(layer, cell) & TubeSteer.side_bit(outward) and rect.has_point(cell + outward):
mouths.append({cell = cell, outward = outward})
return mouths
# Walks a maze tube (a simple chain of tiles) from the mouth at `cell` to its
# other end: {cells: from `cell` on, farOutward: which way the far mouth opens}.
func _follow_tube(layer: TileMapLayer, cell: Vector2i, outward: Vector2i) -> Dictionary:
var cells: Array[Vector2i] = [cell]
var back := outward
while true:
var openings := TubeSteer.get_openings(layer, cells.back())
var ahead := Vector2i.ZERO
for direction in TubeSteer.DIRECTIONS:
if direction != back and openings & TubeSteer.side_bit(direction):
ahead = direction
var next: Vector2i = cells.back() + ahead
if layer.get_cell_source_id(next) == -1:
return {cells = cells, farOutward = ahead}
cells.append(next)
back = -ahead
return {}
func _region_with(carver: MazeCarver, cell: Vector2i) -> int:
for region in carver.regionAir.size():
if carver.regionAir[region].has(cell):
return region
return -1