Merge branch 'maze' into main

Maze mode: generated tube mazes with one-way tubes, blow and suction
zones, a soft-lock validator, and manual tubes only (goo tubes removed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SnekInAScarf 2026-11-16 15:04:26 -08:00
commit bb3dc29f48
46 changed files with 2595 additions and 632 deletions

View file

@ -7,7 +7,7 @@ texture = ExtResource("1_ufwbk")
texture_region_size = Vector2i(32, 32)
0:0/0 = 0
0:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, -16, 16)
1:0/next_alternative_id = 3
1:0/next_alternative_id = 6
1:0/0 = 0
1:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3)
1:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16)
@ -18,13 +18,27 @@ texture_region_size = Vector2i(32, 32)
1:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3)
1:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16)
1:0/1/custom_data_0 = 10
1:0/2 = 2
1:0/2/modulate = Color(1, 0.7, 0.95, 1)
1:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3)
1:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16)
1:0/2/custom_data_0 = 10
1:0/2/custom_data_2 = true
2:0/next_alternative_id = 3
1:0/3 = 3
1:0/3/modulate = Color(1.7, 0.95, 0.3, 1)
1:0/3/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3)
1:0/3/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16)
1:0/3/custom_data_0 = 10
1:0/3/custom_data_2 = true
1:0/4 = 4
1:0/4/modulate = Color(1.7, 0.95, 0.3, 1)
1:0/4/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3)
1:0/4/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16)
1:0/4/custom_data_0 = 10
1:0/4/custom_data_2 = true
1:0/4/custom_data_3 = 2
1:0/5 = 5
1:0/5/modulate = Color(1.7, 0.95, 0.3, 1)
1:0/5/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -16, -3)
1:0/5/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, 16, 3, 16, 16, -16, 16)
1:0/5/custom_data_0 = 10
1:0/5/custom_data_2 = true
1:0/5/custom_data_3 = 8
2:0/next_alternative_id = 6
2:0/0 = 0
2:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16)
2:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16)
@ -35,13 +49,27 @@ texture_region_size = Vector2i(32, 32)
2:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16)
2:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16)
2:0/1/custom_data_0 = 5
2:0/2 = 2
2:0/2/modulate = Color(1, 0.7, 0.95, 1)
2:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16)
2:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16)
2:0/2/custom_data_0 = 5
2:0/2/custom_data_2 = true
3:0/next_alternative_id = 3
2:0/3 = 3
2:0/3/modulate = Color(1.7, 0.95, 0.3, 1)
2:0/3/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16)
2:0/3/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16)
2:0/3/custom_data_0 = 5
2:0/3/custom_data_2 = true
2:0/4 = 4
2:0/4/modulate = Color(1.7, 0.95, 0.3, 1)
2:0/4/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16)
2:0/4/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16)
2:0/4/custom_data_0 = 5
2:0/4/custom_data_2 = true
2:0/4/custom_data_3 = 1
2:0/5 = 5
2:0/5/modulate = Color(1.7, 0.95, 0.3, 1)
2:0/5/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 16, -16, 16)
2:0/5/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, 16, 3, 16)
2:0/5/custom_data_0 = 5
2:0/5/custom_data_2 = true
2:0/5/custom_data_3 = 4
3:0/next_alternative_id = 4
3:0/0 = 0
3:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
3:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
@ -56,15 +84,15 @@ texture_region_size = Vector2i(32, 32)
3:0/1/physics_layer_0/polygon_2/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
3:0/1/physics_layer_0/polygon_3/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
3:0/1/custom_data_0 = 15
3:0/2 = 2
3:0/2/modulate = Color(1, 0.7, 0.95, 1)
3:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
3:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
3:0/2/physics_layer_0/polygon_2/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
3:0/2/physics_layer_0/polygon_3/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
3:0/2/custom_data_0 = 15
3:0/2/custom_data_2 = true
4:0/next_alternative_id = 3
3:0/3 = 3
3:0/3/modulate = Color(1.7, 0.95, 0.3, 1)
3:0/3/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
3:0/3/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
3:0/3/physics_layer_0/polygon_2/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
3:0/3/physics_layer_0/polygon_3/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
3:0/3/custom_data_0 = 15
3:0/3/custom_data_2 = true
4:0/next_alternative_id = 6
4:0/0 = 0
4:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16)
4:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
@ -75,13 +103,27 @@ texture_region_size = Vector2i(32, 32)
4:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16)
4:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
4:0/1/custom_data_0 = 3
4:0/2 = 2
4:0/2/modulate = Color(1, 0.7, 0.95, 1)
4:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16)
4:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
4:0/2/custom_data_0 = 3
4:0/2/custom_data_2 = true
5:0/next_alternative_id = 3
4:0/3 = 3
4:0/3/modulate = Color(1.7, 0.95, 0.3, 1)
4:0/3/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16)
4:0/3/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
4:0/3/custom_data_0 = 3
4:0/3/custom_data_2 = true
4:0/4 = 4
4:0/4/modulate = Color(1.7, 0.95, 0.3, 1)
4:0/4/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16)
4:0/4/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
4:0/4/custom_data_0 = 3
4:0/4/custom_data_2 = true
4:0/4/custom_data_3 = 1
4:0/5 = 5
4:0/5/modulate = Color(1.7, 0.95, 0.3, 1)
4:0/5/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, 3, 16, 3, 16, 16, -16, 16)
4:0/5/physics_layer_0/polygon_1/points = PackedVector2Array(3, -16, 16, -16, 16, -3, 3, -3)
4:0/5/custom_data_0 = 3
4:0/5/custom_data_2 = true
4:0/5/custom_data_3 = 2
5:0/next_alternative_id = 6
5:0/0 = 0
5:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3)
5:0/0/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
@ -92,13 +134,27 @@ texture_region_size = Vector2i(32, 32)
5:0/1/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3)
5:0/1/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
5:0/1/custom_data_0 = 9
5:0/2 = 2
5:0/2/modulate = Color(1, 0.7, 0.95, 1)
5:0/2/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3)
5:0/2/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
5:0/2/custom_data_0 = 9
5:0/2/custom_data_2 = true
0:1/next_alternative_id = 3
5:0/3 = 3
5:0/3/modulate = Color(1.7, 0.95, 0.3, 1)
5:0/3/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3)
5:0/3/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
5:0/3/custom_data_0 = 9
5:0/3/custom_data_2 = true
5:0/4 = 4
5:0/4/modulate = Color(1.7, 0.95, 0.3, 1)
5:0/4/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3)
5:0/4/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
5:0/4/custom_data_0 = 9
5:0/4/custom_data_2 = true
5:0/4/custom_data_3 = 1
5:0/5 = 5
5:0/5/modulate = Color(1.7, 0.95, 0.3, 1)
5:0/5/physics_layer_0/polygon_0/points = PackedVector2Array(3, -16, 16, -16, 16, 16, -16, 16, -16, 3, 3, 3)
5:0/5/physics_layer_0/polygon_1/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3)
5:0/5/custom_data_0 = 9
5:0/5/custom_data_2 = true
5:0/5/custom_data_3 = 8
0:1/next_alternative_id = 6
0:1/0 = 0
0:1/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3)
0:1/0/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
@ -109,13 +165,27 @@ texture_region_size = Vector2i(32, 32)
0:1/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3)
0:1/1/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
0:1/1/custom_data_0 = 12
0:1/2 = 2
0:1/2/modulate = Color(1, 0.7, 0.95, 1)
0:1/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3)
0:1/2/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
0:1/2/custom_data_0 = 12
0:1/2/custom_data_2 = true
1:1/next_alternative_id = 3
0:1/3 = 3
0:1/3/modulate = Color(1.7, 0.95, 0.3, 1)
0:1/3/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3)
0:1/3/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
0:1/3/custom_data_0 = 12
0:1/3/custom_data_2 = true
0:1/4 = 4
0:1/4/modulate = Color(1.7, 0.95, 0.3, 1)
0:1/4/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3)
0:1/4/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
0:1/4/custom_data_0 = 12
0:1/4/custom_data_2 = true
0:1/4/custom_data_3 = 4
0:1/5 = 5
0:1/5/modulate = Color(1.7, 0.95, 0.3, 1)
0:1/5/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, 16, 3, 16, 3, -3, -16, -3)
0:1/5/physics_layer_0/polygon_1/points = PackedVector2Array(-16, 3, -3, 3, -3, 16, -16, 16)
0:1/5/custom_data_0 = 12
0:1/5/custom_data_2 = true
0:1/5/custom_data_3 = 8
1:1/next_alternative_id = 6
1:1/0 = 0
1:1/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16)
1:1/0/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
@ -126,12 +196,26 @@ texture_region_size = Vector2i(32, 32)
1:1/1/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16)
1:1/1/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
1:1/1/custom_data_0 = 6
1:1/2 = 2
1:1/2/modulate = Color(1, 0.7, 0.95, 1)
1:1/2/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16)
1:1/2/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
1:1/2/custom_data_0 = 6
1:1/2/custom_data_2 = true
1:1/3 = 3
1:1/3/modulate = Color(1.7, 0.95, 0.3, 1)
1:1/3/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16)
1:1/3/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
1:1/3/custom_data_0 = 6
1:1/3/custom_data_2 = true
1:1/4 = 4
1:1/4/modulate = Color(1.7, 0.95, 0.3, 1)
1:1/4/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16)
1:1/4/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
1:1/4/custom_data_0 = 6
1:1/4/custom_data_2 = true
1:1/4/custom_data_3 = 2
1:1/5 = 5
1:1/5/modulate = Color(1.7, 0.95, 0.3, 1)
1:1/5/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, 16, -16, 16, -3, -3, -3, -3, 16, -16, 16)
1:1/5/physics_layer_0/polygon_1/points = PackedVector2Array(3, 3, 16, 3, 16, 16, 3, 16)
1:1/5/custom_data_0 = 6
1:1/5/custom_data_2 = true
1:1/5/custom_data_3 = 4
[resource]
tile_size = Vector2i(32, 32)
@ -140,6 +224,8 @@ custom_data_layer_0/name = "tube_openings"
custom_data_layer_0/type = 2
custom_data_layer_1/name = "tube_manual"
custom_data_layer_1/type = 1
custom_data_layer_2/name = "tube_goo"
custom_data_layer_2/name = "tube_one_way"
custom_data_layer_2/type = 1
custom_data_layer_3/name = "tube_one_way_entry"
custom_data_layer_3/type = 2
sources/0 = SubResource("TileSetAtlasSource_0cw2b")

View file

@ -48,8 +48,10 @@ const LAND_PITCH_MAX = 1.15
# open (the "tube_openings" custom data). Holding into a tube's mouth squeezes us
# in as pixels. An ordinary tube streams us through to the other end
# (PixelStream). A manual one ("tube_manual" tiles) lets the player steer us
# 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).
# through it, round corners and either way at crossings (TubeSteer).
# A one-way one ("tube_one_way" tiles) is an ordinary tube we can only go into
# 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
@ -59,7 +61,6 @@ const TUBE_WIDTH = 6.0 # The channel drawn through the tiles in LevelTiles.png.
# The longest our pixels stretch in a tube (two tiles). They bunch up to fit.
const TUBE_MAX_FLOW_LENGTH = 64.0
const TUBE_ENTRY_REACH = 2.0 # How close our side must be to a tube mouth to go in.
const TUBE_MAX_TILES = 256 # Give up following a tube this long.
const TUBE_REENTRY_DELAY = 0.3 # So we don't dive straight back in.
const TUBE_ENTER_HOLD_TIME = 0.35 # How long to press into a mouth before we squeeze in.
# How straight into a mouth we must press (dot product with the way in; 0.9 is
@ -137,9 +138,8 @@ var tubeSqueezeDirection := Vector2.ZERO # Which way into that mouth.
var isInTube := false
var tubePixels: PixelStream # Our pixels streaming through an ordinary tube, or null.
# Our pixels being steered through a manual tube (a TubeSteer) or a goo tube (a
# TubeGoo), or null. Both have start(), steer(), isFinished and exitPose.
var tubeSteer: Variant = null
# Our pixels being steered through a manual tube, or null.
var tubeSteer: TubeSteer = null
var tubeExitPose := {} # Where the stream comes out (see _tube_exit_pose).
var tubeReentryCooldown := 0.0
var timeSpentSqueezingIntoTube := 0.0
@ -1049,48 +1049,22 @@ func _find_tube_towards(direction: Vector2, extraReach := 0.0) -> Dictionary:
var cell := layer.local_to_map(layer.to_local(probe))
if _get_tube_openings(layer, cell) & _tube_side_bit(-direction) == 0:
continue
if not OneWayTube.can_enter(layer, cell, Vector2i(direction)):
continue # The exit end of a one-way tube.
# The mouth must be within our width, and touching (or nearly) our side.
var toMouth := _tube_cell_point(layer, cell, -direction) - global_position
if absf(toMouth.dot(across)) > radius or toMouth.dot(direction) > reach:
continue
var tube := {layer = layer, cell = cell, direction = direction}
if TubeSteer.is_manual(layer, cell) or TubeGoo.is_goo(layer, cell):
if TubeSteer.is_manual(layer, cell):
return tube
var path := _trace_tube(layer, cell, direction)
var path := PixelStream.trace_tube(layer, cell, Vector2i(direction))
if not path.is_empty() and not _tube_exit_pose_for(path).is_empty():
tube.path = path
return tube
return {}
# The tube's path from the mouth of `cell` we go in heading `direction`, round
# each bend, to the mouth it comes out of into an empty tile. Empty if it's
# blocked or a dead end.
func _trace_tube(layer: TileMapLayer, cell: Vector2i, direction: Vector2) -> PackedVector2Array:
var path := PackedVector2Array([_tube_cell_point(layer, cell, -direction)])
for step in TUBE_MAX_TILES:
var openings := _get_tube_openings(layer, cell)
if openings & _tube_side_bit(-direction) == 0:
return PackedVector2Array() # This tile doesn't connect to the last one.
# Straight on if we can (through crossings), otherwise round the bend.
if openings & _tube_side_bit(direction) == 0:
var turn := direction.orthogonal()
if openings & _tube_side_bit(turn) == 0:
turn = -turn
if openings & _tube_side_bit(turn) == 0:
return PackedVector2Array() # Dead end.
path.append(_tube_cell_point(layer, cell, Vector2.ZERO))
direction = turn
var nextCell := cell + Vector2i(direction)
if layer.get_cell_source_id(nextCell) == -1:
path.append(_tube_cell_point(layer, cell, direction))
return path
cell = nextCell
return PackedVector2Array()
# Where we come out of the ordinary tube along `path` (see _tube_exit_pose).
func _tube_exit_pose_for(path: PackedVector2Array) -> Dictionary:
var exitMouth := path[path.size() - 1]
@ -1143,13 +1117,10 @@ func _enter_tube(tube: Dictionary) -> void:
if not wallPose.is_empty():
wallPose.startTransform = spriteTransform # The goo still starts as we look now.
entryPose = wallPose
if TubeGoo.is_goo(tube.layer, tube.cell):
tubeSteer = TubeGoo.new()
else:
tubeSteer = TubeSteer.new()
tubeSteer.indicatorColor = tubeIndicatorColor
tubeSteer.indicatorBorderColor = tubeIndicatorBorderColor
tubeSteer.indicatorRadius = tubeIndicatorRadius
tubeSteer = TubeSteer.new()
tubeSteer.indicatorColor = tubeIndicatorColor
tubeSteer.indicatorBorderColor = tubeIndicatorBorderColor
tubeSteer.indicatorRadius = tubeIndicatorRadius
get_parent().add_child(tubeSteer)
tubeSteer.start(sprite, tube.layer, tube.cell, Vector2i(tube.direction), TUBE_WIDTH, TUBE_MAX_FLOW_LENGTH,
entryPose, _tube_exit_pose, REST_FRAME)
@ -1193,6 +1164,38 @@ func get_camera_focus() -> Vector2:
return global_position
# 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:
if isInTube or isWrapping or isBridging:
return
isStickingToWall = false
isStickingToCeiling = false
isHoppingAcross = false
timeSpentUnstickingWall = 0.0
timeSpentUnstickingCeiling = 0.0
timeSpentHoldingEdge = 0.0
timeSpentHoldingUpOnFloor = 0.0
timeSpentSqueezingIntoTube = 0.0
if push.x != 0.0 and velocity.x * signf(push.x) < absf(push.x):
velocity.x = push.x
if push.y != 0.0 and velocity.y * signf(push.y) < absf(push.y):
velocity.y = push.y
func _exit_tube(pose: Dictionary, delta: float) -> void:
isInTube = false
tubeReentryCooldown = TUBE_REENTRY_DELAY

81
Effects/one_way_tube.gd Normal file
View file

@ -0,0 +1,81 @@
class_name OneWayTube
extends RefCounted
# One-way tubes are ordinary tubes (the slime streams through as a PixelStream)
# 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 (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 = 1 # How many tiles out of an exit mouth the air blows.
# Whether the tile at `cell` is part of a one-way tube.
static func is_one_way(layer: TileMapLayer, cell: Vector2i) -> bool:
var data := layer.get_cell_tile_data(cell)
if data == null or not data.has_custom_data(ONE_WAY_LAYER):
return false
return data.get_custom_data(ONE_WAY_LAYER)
# The side bit of `cell`'s entrance mouth, or 0 if it has none.
static func get_entry_side(layer: TileMapLayer, cell: Vector2i) -> int:
var data := layer.get_cell_tile_data(cell)
if data == null or not data.has_custom_data(ENTRY_LAYER):
return 0
return data.get_custom_data(ENTRY_LAYER)
# Whether the slime may go into the tube at `cell` heading `direction`. Always
# true for other kinds of tube.
static func can_enter(layer: TileMapLayer, cell: Vector2i, direction: Vector2i) -> bool:
if not is_one_way(layer, cell):
return true
return get_entry_side(layer, cell) & TubeSteer.side_bit(-direction) != 0
# Every entrance mouth in the layer that opens onto an empty tile (see _find_mouths).
static func find_entrances(layer: TileMapLayer) -> Array[Dictionary]:
return _find_mouths(layer, true)
# Every exit mouth in the layer that opens onto an empty tile (see _find_mouths).
# Air blows out of these: see blow_zone() and TubeAirCurrents.
static func find_exits(layer: TileMapLayer) -> Array[Dictionary]:
return _find_mouths(layer, false)
# The empty tiles the air out of an exit mouth reaches: up to BLOW_RANGE tiles
# straight out from the tube tile `cell`'s side `outward`, stopping at anything
# solid. MazeCarver uses this before the tube's tiles are down, so it only
# looks at the tiles in front.
static func blow_zone(layer: TileMapLayer, cell: Vector2i, outward: Vector2i) -> Array[Vector2i]:
var zone: Array[Vector2i] = []
for step in range(1, BLOW_RANGE + 1):
var zoneCell := cell + outward * step
if layer.get_cell_source_id(zoneCell) != -1:
break
zone.append(zoneCell)
return zone
# One-way mouths opening onto an empty tile, entrances or exits:
# [{cell, mouth: global point, outward: Vector2i}].
static func _find_mouths(layer: TileMapLayer, isEntrance: bool) -> Array[Dictionary]:
var mouths: Array[Dictionary] = []
for cell in layer.get_used_cells():
if not is_one_way(layer, cell):
continue
var openings := TubeSteer.get_openings(layer, cell)
var entrySide := get_entry_side(layer, cell)
for direction in TubeSteer.DIRECTIONS:
var side := TubeSteer.side_bit(direction)
if openings & side == 0 or layer.get_cell_source_id(cell + direction) != -1:
continue
if (side == entrySide) == isEntrance:
mouths.append({cell = cell, mouth = TubeSteer.cell_point(layer, cell, direction), outward = direction})
return mouths

View file

@ -0,0 +1 @@
uid://4mxas52xepeu

View file

@ -15,7 +15,7 @@ extends Node2D
# in the sprite. Pixels flying between the two don't get one: it would speckle
# them all in black.
# Where the slime's pixels draw while in a tube (this and TubeSteer and TubeGoo):
# Where the slime's pixels draw while in a tube (this and TubeSteer):
# behind the tiles (z 0), which only show them through the tube's see-through
# channel. Goo going in or out of a mouth is hidden where it overlaps the tile.
# A background must go lower than this, or on its own CanvasLayer.
@ -24,6 +24,7 @@ const SPEED = 240.0 # How fast pixels flow along the path, in px/s.
const ROW_SPACING = 1.0 # Gap between rows of pixels in the stream, unless that would make it too long.
const GATHER_TIME = 0.12 # How long the nearest pixels take to reach the entry mouth.
const LAND_TIME = 0.15 # How long the last pixels out take to reach their spot.
const MAX_TRACE_TILES = 256 # Give up following a tube this long.
const SETTLED_DISTANCE = 1.0 # Pixels within this of their spot in the sprite get an outline.
var isFinished := false
@ -73,6 +74,34 @@ func start(sprite: Sprite2D, path: PackedVector2Array, width: float, maxLength:
_rowSpacing = minf(ROW_SPACING, maxLength / _rowCount)
# The path through an ordinary tube from the mouth of `cell` we go in heading
# `direction`, round each bend, to the mouth it comes out of into an empty tile.
# Empty if it's blocked or a dead end. The Player and MazeValidator use this.
static func trace_tube(layer: TileMapLayer, cell: Vector2i, direction: Vector2i) -> PackedVector2Array:
var path := PackedVector2Array([TubeSteer.cell_point(layer, cell, -direction)])
for step in MAX_TRACE_TILES:
var openings := TubeSteer.get_openings(layer, cell)
if openings & TubeSteer.side_bit(-direction) == 0:
return PackedVector2Array() # This tile doesn't connect to the last one.
# Straight on if we can (through crossings), otherwise round the bend.
if openings & TubeSteer.side_bit(direction) == 0:
var turn := Vector2i(-direction.y, direction.x)
if openings & TubeSteer.side_bit(turn) == 0:
turn = -turn
if openings & TubeSteer.side_bit(turn) == 0:
return PackedVector2Array() # Dead end.
path.append(TubeSteer.cell_point(layer, cell, Vector2i.ZERO))
direction = turn
var nextCell := cell + direction
if layer.get_cell_source_id(nextCell) == -1:
path.append(TubeSteer.cell_point(layer, cell, direction))
return path
cell = nextCell
return PackedVector2Array()
# The frame's opaque pixels (black ones too: they're the eyes) as .positions
# (global, through `spriteTransform`) and .colors. TubeSteer uses this too.
static func get_frame_pixels(sprite: Sprite2D, frame: int, spriteTransform: Transform2D) -> Dictionary:

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

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

80
Effects/tube_airflow.gd Normal file
View file

@ -0,0 +1,80 @@
class_name TubeAirflow
extends Node2D
# 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, 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
const INTAKE_REACH = 40.0 # How far out from an entrance motes start, in px.
const INTAKE_SPREAD = 22.0 # How far to the side of an entrance motes can start, in px.
const BLOW_SPREAD = 14.0 # How far to the side blown motes drift by the end, in px.
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) # 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.
@export var layer: TileMapLayer
# Per mouth: {mouth, outward: Vector2, isIntake, reach: px, spread: px, tripTime}.
var _mouths: Array[Dictionary] = []
var _time := 0.0
func _ready() -> void:
top_level = true # Mouths are in global coordinates.
z_index = 1 # In front of the tiles.
refresh()
func refresh() -> void:
_mouths.clear()
if layer == null:
return
for entrance in OneWayTube.find_entrances(layer):
_mouths.append({mouth = entrance.mouth, outward = Vector2(entrance.outward), isIntake = true,
reach = INTAKE_REACH, spread = INTAKE_SPREAD, tripTime = TRIP_TIME})
var tileLength := float(layer.tile_set.tile_size.x)
for exit in OneWayTube.find_exits(layer):
var zoneLength := OneWayTube.blow_zone(layer, exit.cell, exit.outward).size()
_mouths.append({mouth = exit.mouth, outward = Vector2(exit.outward), isIntake = false,
reach = zoneLength * tileLength, spread = BLOW_SPREAD, tripTime = BLOW_TRIP_TIME})
queue_redraw()
func _process(delta: float) -> void:
if _mouths.is_empty():
return
_time += delta
queue_redraw()
func _draw() -> void:
for mouthIndex in _mouths.size():
var mouth: Dictionary = _mouths[mouthIndex]
var across: Vector2 = mouth.outward.orthogonal()
for moteIndex in MOTES_PER_MOUTH:
# Each mote loops on its own offset, and gets a fresh random path
# each trip.
var tripClock: float = _time / mouth.tripTime + float(moteIndex) / MOTES_PER_MOUTH
var trip := floori(tripClock)
var progress := tripClock - trip
var random := RandomNumberGenerator.new()
random.seed = hash(Vector3i(mouthIndex, moteIndex, trip))
var side: float = random.randf_range(-1.0, 1.0) * mouth.spread
var lighten := random.randf() * MOTE_LIGHTEN
var moteSize := Vector2.ONE * (2.0 if random.randf() < BIG_MOTE_SHARE else 1.0)
# How far out the mote is, from 0 (at the mouth) to 1 (at its reach).
# 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 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

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

View file

@ -1,534 +0,0 @@
class_name TubeGoo
extends Node2D
# The slime squeezed into a goo tube as a shapeless amount of goo, with no head
# or tail. The goo fills a connected patch of the tubes (a line, or a T or plus
# shape where it spans a crossing), and moves by growing at one spot while
# shrinking by the same amount at all its other tips at once.
#
# Steering: pressing a direction grows the goo at the growth point nearest the
# one it last grew at (the "active" point) that can grow that way. A growth
# point is any tip, or any spot the goo covers with an empty branch beside it.
# So in a straight tube pressing back grows the far tip (reversing), and with
# the goo spanning a crossing, pressing into a side branch sprouts the middle
# into it while both ends drain towards it.
# Tips also look ahead along straight tube, so pressing towards a turn before
# reaching it carries the tip there.
# Every growth point pulses faintly. The one the input is using pulses brighter.
#
# Past each mouth with room for the slime is a straight "outside line". Goo out
# there gathers into the slime's shape. Once all of it is out far enough, it
# reforms: isFinished goes true and exitPose says where. The goo starts out on
# the entry mouth's line, in the shape of the sprite that went in, so backing
# all the way out reforms us where we went in.
#
# The track is made of vertices one pixel apart, and the goo moves a vertex at a
# time. Each vertex holds one row of pixels across the tube. If the goo would
# be longer than maxLength, the rows hold more pixels (overlapping) instead.
const SPEED = 150.0 # How fast the goo grows while pressed, in px/s.
const GATHER_DISTANCE = 24 # How far past a mouth goo goes before it's in its place in the slime.
# How much of the input must point along a way for the goo to grow along it
# (0.5 lets diagonals pick either way).
const MIN_PULL = 0.5
const LOOKAHEAD = 48 # How far along straight tube a tip looks for a turn the input points along.
const MAX_TILES = 1024 # Stop mapping a tube network this big.
const MAX_STEPS_PER_FRAME = 8
const PULSE_SPEED = 7.0 # Radians per second.
const PULSE_ALPHA = 0.5 # How strongly growth points pulse.
const ACTIVE_PULSE_ALPHA = 0.9 # How strongly the one being grown pulses.
const PULSE_LENGTH = 3 # How many vertices into a branch the pulse shows.
const SHOW_ACTIVE = false # Outline the active point, for debugging.
const NO_GROWTH = Vector2i(-1, -1)
const DIRECTIONS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
var isFinished := false
var exitPose := {} # The pose we came out as (see start()).
# The track's vertices.
var _positions := PackedVector2Array()
var _neighbors: Array[Array] = [] # Per vertex: the vertices next to it.
var _lines := PackedInt32Array() # Per vertex: the outside line it's on, or -1 in the tubes.
var _depths := PackedInt32Array() # Per vertex on an outside line: how far out it is (1 = just past the mouth).
# The outside lines.
var _lineMouths := PackedVector2Array()
var _lineOutwards := PackedVector2Array()
var _lineStarts := PackedInt32Array() # The vertex at depth 1.
var _linePoses: Array[Dictionary] = [] # The pose we come out as there.
var _lineShapes: Array[Dictionary] = [] # That pose's pixels nearest the mouth first, worked out when needed.
var _lineLength := 0
var _entryLine := -1
# The goo.
var _rowAt := PackedInt32Array() # Per vertex: the row of pixels there, or -1 if empty.
var _shrunkAt := PackedInt32Array() # Per vertex: when the goo last shrank back to it.
var _clock := 0
var _active := -1
var _growth := 0.0 # Growth we're owed but haven't done, in vertices.
var _cue := NO_GROWTH # (vertex, empty vertex it grew into) for the brighter pulse.
var _time := 0.0
# The pixels: row r holds pixels r * _pixelsPerRow up to the next row's, going
# across its _laneCount lanes and round again.
var _rowCount := 0
var _laneCount := 1
var _pixelsPerRow := 1
var _colors := PackedColorArray()
var _spots := PackedVector2Array() # Where each pixel goes in the shape it's gathering into outside.
var _spotColors := PackedColorArray()
var _rowLines := PackedInt32Array() # Per row: the outside line its spots are for, or -1.
var _endFrame := {} # The frame we reform as, in the sprite's space.
# Squeezes into the tube at `entryCell` heading `entryDirection`.
# Poses are {spriteTransform: Transform2D, ...plus whatever the caller wants
# back in exitPose}. entryPose is the slime as it is now (or, if it has a
# .startTransform, that's the slime as it is now and the rest is where backing out puts us). findPose(mouth:
# Vector2, outward: Vector2) gives the pose for coming out of a mouth, or {} if
# there's no room. endFrame: the frame we reform as. maxLength: the longest the
# goo can be.
func start(sprite: Sprite2D, layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i,
width: float, maxLength: float, entryPose: Dictionary, findPose: Callable, endFrame: int) -> void:
top_level = true
global_position = Vector2.ZERO
z_index = PixelStream.GOO_Z_INDEX
_laneCount = maxi(int(width), 1)
var from := PixelStream.get_frame_pixels(sprite, sprite.frame, entryPose.get("startTransform", entryPose.spriteTransform))
_endFrame = PixelStream.get_frame_pixels(sprite, endFrame, Transform2D.IDENTITY)
if from.colors.is_empty() or _endFrame.colors.is_empty():
exitPose = entryPose
isFinished = true
return
# If the frame we reform as has more pixels, or the last row isn't full,
# some are doubled up so none go missing.
var pixelCount := maxi(from.colors.size(), _endFrame.colors.size())
_rowCount = mini(ceili(float(pixelCount) / _laneCount), maxi(int(maxLength), 1))
_pixelsPerRow = ceili(float(pixelCount) / _rowCount)
_lineLength = _rowCount + GATHER_DISTANCE
_build_track(layer, entryCell, entryDirection, entryPose, findPose)
if _entryLine == -1:
exitPose = entryPose
isFinished = true
return
# The goo starts out on the entry mouth's line, far enough out that every
# pixel is still in its place in the sprite. The pixels nearest the mouth
# are in the rows nearest it, so they go in first.
var count := _rowCount * _pixelsPerRow
var order := _sorted_by_distance(from.positions, _lineMouths[_entryLine])
for i in count:
var k: int = order[int(float(i) * order.size() / count)]
_colors.append(from.colors[k])
_spots.append(from.positions[k])
_spotColors.append(from.colors[k])
_rowLines.resize(_rowCount)
_rowLines.fill(_entryLine)
for row in _rowCount:
_rowAt[_line_vertex(_entryLine, GATHER_DISTANCE + row)] = row
_active = _line_vertex(_entryLine, GATHER_DISTANCE)
# Moves the goo for one physics frame. input: the player's input, with y down.
func steer(input: Vector2, delta: float) -> void:
if isFinished:
return
_cue = NO_GROWTH
if input == Vector2.ZERO:
_growth = 0.0
return
input = input.normalized()
_growth += SPEED * delta
for i in MAX_STEPS_PER_FRAME:
if _growth < 1.0:
break
var growth := _choose_growth(input)
if growth == NO_GROWTH:
_growth = 0.0 # Nowhere to grow the way the input points.
break
_cue = growth
_grow(growth.x, growth.y)
_growth -= 1.0
if _check_all_out():
return
# Where the goo last grew, in global coordinates (for the camera). The goo has
# no head, so this is the end the player is pushing.
func get_focus() -> Vector2:
if _active == -1:
return global_position
return _positions[_active]
func _process(delta: float) -> void:
_time += delta
queue_redraw()
# ---- Setup ----
# Maps out the goo tube network from `entryCell` as vertices a pixel apart,
# plus an outside line past each mouth we can come out of.
func _build_track(layer: TileMapLayer, entryCell: Vector2i, entryDirection: Vector2i,
entryPose: Dictionary, findPose: Callable) -> void:
var cellVertices := {entryCell: _add_vertex(TubeSteer.cell_point(layer, entryCell, Vector2i.ZERO))}
var toVisit: Array[Vector2i] = [entryCell]
while not toVisit.is_empty() and cellVertices.size() < MAX_TILES:
var cell: Vector2i = toVisit.pop_front()
var openings := TubeSteer.get_openings(layer, cell)
for direction in DIRECTIONS:
if openings & TubeSteer.side_bit(direction) == 0:
continue
var nextCell := cell + direction
if is_goo(layer, nextCell) and TubeSteer.get_openings(layer, nextCell) & TubeSteer.side_bit(-direction):
if not cellVertices.has(nextCell):
cellVertices[nextCell] = _add_vertex(TubeSteer.cell_point(layer, nextCell, Vector2i.ZERO))
toVisit.append(nextCell)
# Each pair of tiles is joined once, from its left or top tile.
if direction == Vector2i.RIGHT or direction == Vector2i.DOWN:
_join(cellVertices[cell], cellVertices[nextCell])
elif layer.get_cell_source_id(nextCell) == -1:
# A mouth into open space.
var mouthPosition := TubeSteer.cell_point(layer, cell, direction)
var mouth := _add_vertex(mouthPosition)
_join(cellVertices[cell], mouth)
var isEntry := cell == entryCell and direction == -entryDirection
var pose: Dictionary = entryPose if isEntry else findPose.call(mouthPosition, Vector2(direction))
if pose.is_empty():
continue # No room out there: a dead end.
if isEntry:
_entryLine = _lineMouths.size()
_add_outside_line(mouth, Vector2(direction), pose)
# Otherwise it opens into something solid: a dead end.
func _add_vertex(at: Vector2, line := -1, depth := 0) -> int:
_positions.append(at)
_neighbors.append([])
_lines.append(line)
_depths.append(depth)
_rowAt.append(-1)
_shrunkAt.append(0)
return _positions.size() - 1
func _connect(a: int, b: int) -> void:
_neighbors[a].append(b)
_neighbors[b].append(a)
# Joins two vertices with a straight run of vertices a pixel apart.
func _join(a: int, b: int) -> void:
var from := _positions[a]
var to := _positions[b]
var steps := maxi(roundi(from.distance_to(to)), 1)
var previous := a
for step in range(1, steps):
var vertex := _add_vertex(from.lerp(to, float(step) / steps))
_connect(previous, vertex)
previous = vertex
_connect(previous, b)
func _add_outside_line(mouth: int, outward: Vector2, pose: Dictionary) -> void:
var line := _lineMouths.size()
_lineMouths.append(_positions[mouth])
_lineOutwards.append(outward)
_linePoses.append(pose)
_lineShapes.append({})
_lineStarts.append(_positions.size())
var previous := mouth
for depth in range(1, _lineLength + 1):
var vertex := _add_vertex(_positions[mouth] + outward * depth, line, depth)
_connect(previous, vertex)
previous = vertex
func _line_vertex(line: int, depth: int) -> int:
return _lineStarts[line] + depth - 1
# ---- Growing ----
# Where to grow for the input: (a goo vertex, the empty vertex beside it to grow
# into), nearest the active point. NO_GROWTH if there's nowhere.
func _choose_growth(input: Vector2) -> Vector2i:
var distances := _goo_distances_from(_active)
var best := NO_GROWTH
var bestDistance := 0
var bestPull := 0.0
for vertex in _rowAt.size():
if _rowAt[vertex] == -1:
continue
for next: int in _neighbors[vertex]:
if not _can_grow_into(vertex, next):
continue
var pull := input.dot(_direction(vertex, next))
if pull < MIN_PULL and _is_tip(vertex):
pull = _lookahead_pull(vertex, next, input)
if pull < MIN_PULL:
continue
var distance := distances[vertex]
if best == NO_GROWTH or distance < bestDistance or (distance == bestDistance and pull > bestPull):
best = Vector2i(vertex, next)
bestDistance = distance
bestPull = pull
return best
# Whether the goo at `vertex` can grow into `next`: it's empty, and growing
# there wouldn't join up with goo somewhere else (round a loop).
func _can_grow_into(vertex: int, next: int) -> bool:
if _rowAt[next] != -1:
return false
for other: int in _neighbors[next]:
if other != vertex and _rowAt[other] != -1:
return false
return true
# From a tip growing into `next`, how well the input points along a way on from
# the turn or junction at the end of the straight run ahead.
func _lookahead_pull(tip: int, next: int, input: Vector2) -> float:
var previous := tip
var current := next
for i in LOOKAHEAD:
var ways := _neighbors[current].filter(func(other: int) -> bool: return other != previous)
var isStraightOn := ways.size() == 1 and _direction(current, ways[0]).is_equal_approx(_direction(previous, current))
if isStraightOn and _rowAt[ways[0]] == -1:
previous = current
current = ways[0]
continue
var best := -INF
for way: int in ways:
if _rowAt[way] == -1:
best = maxf(best, input.dot(_direction(current, way)))
return best
return -INF
# Grows the goo from `vertex` into `next`, and shrinks it at the tip that's gone
# longest without shrinking. Taking turns like this drains all the tips at once.
# The goo between that tip and `next` flows along a vertex.
func _grow(vertex: int, next: int) -> void:
_rowAt[next] = -2 # Goo, but which row is sorted out below.
var tip := _pick_tip_to_shrink(next)
var path := _goo_path(tip, next)
for i in range(path.size() - 1, 0, -1):
_rowAt[path[i]] = _rowAt[path[i - 1]]
_rowAt[tip] = -1
_clock += 1
_shrunkAt[path[1]] = _clock
_active = next
for i in range(1, path.size()):
_update_row_line(_rowAt[path[i]], path[i])
func _pick_tip_to_shrink(exclude: int) -> int:
var best := -1
for vertex in _rowAt.size():
if _rowAt[vertex] == -1 or vertex == exclude or not _is_tip(vertex):
continue
if best == -1 or _shrunkAt[vertex] < _shrunkAt[best]:
best = vertex
return best
func _is_tip(vertex: int) -> bool:
var gooNeighbors := 0
for other: int in _neighbors[vertex]:
if _rowAt[other] != -1:
gooNeighbors += 1
return gooNeighbors <= 1
# How far each vertex is from `from` through the goo (-1 if it isn't goo).
func _goo_distances_from(from: int) -> PackedInt32Array:
var distances := PackedInt32Array()
distances.resize(_rowAt.size())
distances.fill(-1)
distances[from] = 0
var queue: Array[int] = [from]
while not queue.is_empty():
var vertex: int = queue.pop_front()
for other: int in _neighbors[vertex]:
if _rowAt[other] != -1 and distances[other] == -1:
distances[other] = distances[vertex] + 1
queue.append(other)
return distances
# The vertices from `from` to `to` through the goo.
func _goo_path(from: int, to: int) -> PackedInt32Array:
var cameFrom := {to: -1}
var queue: Array[int] = [to]
while not queue.is_empty() and not cameFrom.has(from):
var vertex: int = queue.pop_front()
for other: int in _neighbors[vertex]:
if _rowAt[other] != -1 and not cameFrom.has(other):
cameFrom[other] = vertex
queue.append(other)
var path := PackedInt32Array()
var vertex := from
while vertex != -1:
path.append(vertex)
vertex = cameFrom[vertex]
return path
# When a row moves onto an outside line, picks the spots its pixels gather
# into there. The first rows out take the spots furthest from the mouth.
func _update_row_line(row: int, vertex: int) -> void:
var line := _lines[vertex]
if line == _rowLines[row]:
return
_rowLines[row] = line
if line == -1:
return
var alreadyOut := 0
for depth in range(1, _lineLength + 1):
var other := _rowAt[_line_vertex(line, depth)]
if other >= 0 and other != row:
alreadyOut += 1
var group := _rowCount - 1 - alreadyOut
var shape := _get_line_shape(line)
var pointCount: int = shape.positions.size()
for slot in _pixelsPerRow:
var i := row * _pixelsPerRow + slot
var k := int(float(group * _pixelsPerRow + slot) * pointCount / (_rowCount * _pixelsPerRow))
_spots[i] = shape.positions[k]
_spotColors[i] = shape.colors[k]
# The pixels of the frame we reform as, placed as the line's pose, nearest the
# mouth first.
func _get_line_shape(line: int) -> Dictionary:
if not _lineShapes[line].is_empty():
return _lineShapes[line]
var spriteTransform: Transform2D = _linePoses[line].spriteTransform
var placed := PackedVector2Array()
for local: Vector2 in _endFrame.positions:
placed.append(spriteTransform * local)
var positions := PackedVector2Array()
var colors := PackedColorArray()
for k: int in _sorted_by_distance(placed, _lineMouths[line]):
positions.append(placed[k])
colors.append(_endFrame.colors[k])
_lineShapes[line] = {positions = positions, colors = colors}
return _lineShapes[line]
# Finishes if all the goo is out on one line, far enough to be back in shape.
func _check_all_out() -> bool:
var line := _lines[_active]
if line == -1:
return false
var outCount := 0
for depth in range(GATHER_DISTANCE, _lineLength + 1):
if _rowAt[_line_vertex(line, depth)] != -1:
outCount += 1
if outCount < _rowCount:
return false
exitPose = _linePoses[line]
isFinished = true
return true
func _direction(from: int, to: int) -> Vector2:
return (_positions[to] - _positions[from]).normalized()
# Indices of `points`, nearest to `target` first.
static func _sorted_by_distance(points: PackedVector2Array, target: Vector2) -> Array:
var order := range(points.size())
order.sort_custom(func(a: int, b: int) -> bool:
return points[a].distance_squared_to(target) < points[b].distance_squared_to(target))
return order
# ---- Drawing ----
func _draw() -> void:
if _colors.is_empty():
return
for vertex in _rowAt.size():
var row := _rowAt[vertex]
if row < 0:
continue
var line := _lines[vertex]
var across := _across(vertex)
for slot in _pixelsPerRow:
var i := row * _pixelsPerRow + slot
var laneOffset := across * (slot % _laneCount - (_laneCount - 1) / 2.0)
var spot := _positions[vertex] + laneOffset
var color := _colors[i]
if line != -1:
# Out past a mouth: gathering into its place in the slime.
var gathered := clampf(float(_depths[vertex]) / GATHER_DISTANCE, 0.0, 1.0)
spot = (_lineMouths[line] + laneOffset).lerp(_spots[i], gathered)
color = color.lerp(_spotColors[i], gathered)
draw_rect(Rect2(spot.floor(), Vector2.ONE), color)
_draw_growth_cues()
if SHOW_ACTIVE and _active != -1:
draw_rect(Rect2(_positions[_active].floor() - Vector2.ONE, Vector2.ONE * 3), Color.RED, false)
# A faint pulse just into each empty branch the goo could grow into, brighter
# for the one it's growing into now.
func _draw_growth_cues() -> void:
var pulse := 0.5 + 0.5 * sin(_time * PULSE_SPEED)
for vertex in _rowAt.size():
if _rowAt[vertex] == -1 or _lines[vertex] != -1:
continue
for next: int in _neighbors[vertex]:
if not _can_grow_into(vertex, next):
continue
var isActive := _cue == Vector2i(vertex, next)
var color := Color(1, 1, 1, (ACTIVE_PULSE_ALPHA if isActive else PULSE_ALPHA) * pulse)
var direction := _direction(vertex, next)
var across := _across_for(direction)
# Start past the goo's edge: at a junction, the goo crossing it
# spreads half a tube's width into the branch.
var firstStep := _laneCount / 2 + 1
for step in range(firstStep, firstStep + PULSE_LENGTH):
for lane in _laneCount:
var spot := _positions[vertex] + direction * step + across * (lane - (_laneCount - 1) / 2.0)
draw_rect(Rect2(spot.floor(), Vector2.ONE), color)
# Which way a row's lanes spread at `vertex`: across the tube there.
func _across(vertex: int) -> Vector2:
var line := _lines[vertex]
if line != -1:
return _across_for(_lineOutwards[line])
# Along the tube to goo next to it if there is some (at a bend or junction
# there's more than one way), otherwise to any neighbour.
var along := Vector2.ZERO
for other: int in _neighbors[vertex]:
if along == Vector2.ZERO or _rowAt[other] != -1:
along = _direction(vertex, other)
if _rowAt[other] != -1:
break
return _across_for(along)
# Rows across a tube going `along` always spread the same way (rightwards or
# downwards), so pixels don't swap sides when the goo changes direction.
static func _across_for(along: Vector2) -> Vector2:
return Vector2.DOWN if absf(along.x) > absf(along.y) else Vector2.RIGHT
# ---- Tube tiles ----
# Whether the tile at `cell` is a goo tube (the "tube_goo" custom data).
static func is_goo(layer: TileMapLayer, cell: Vector2i) -> bool:
var data := layer.get_cell_tile_data(cell)
if data == null or not data.has_custom_data("tube_goo"):
return false
return data.get_custom_data("tube_goo")

View file

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

View file

@ -0,0 +1,35 @@
class_name MazeBuilder
extends RefCounted
# Makes a maze in a TileMapLayer: graph, then tiles, then the soft-lock check.
# A maze that fails (a tube couldn't be routed, or the check found a problem)
# is thrown away and the next seed tried. MazeLevel and tests/maze_check.gd
# use this.
const MAX_ATTEMPTS = 30
var isValid := false
var attempts := 0 # How many mazes it took (1 = the first one passed).
var usedSeed := 0
var carver: MazeCarver
var validator: MazeValidator
var problems: Array[String] = [] # Why each thrown-away maze failed.
func _init(layer: TileMapLayer, screens: Vector2i, complexity: int, firstSeed: int) -> void:
var level := MazeSettings.get_level(complexity)
for attempt in MAX_ATTEMPTS:
attempts = attempt + 1
usedSeed = firstSeed + attempt
var random := RandomNumberGenerator.new()
random.seed = usedSeed
var graph := MazeGraph.new(screens, level, random)
carver = MazeCarver.new(graph, screens, layer, random, level)
if not carver.isComplete:
problems.append("seed %d: a tube couldn't be routed" % usedSeed)
continue
validator = MazeValidator.new(layer, carver.bounds, carver.startCell, carver.endCell)
if validator.isValid:
isValid = true
return
problems.append("seed %d: %s" % [usedSeed, validator.problem])

View file

@ -0,0 +1 @@
uid://4l311qg7el07

175
Levels/Maze/maze_carver.gd Normal file
View file

@ -0,0 +1,175 @@
class_name MazeCarver
extends RefCounted
# Turns a MazeGraph into tiles: rock everywhere, a labyrinth of corridors and
# a few open halls in each region (MazeCorridors), tubes (MazeTubeRouter):
# between regions, long open rides, wall pipes. Then Start and End on floors.
#
# Each screen (one RoomCamera room) is split into a grid of regions, one per
# 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 REGION_BORDER = 2 # Rock tiles round the inside of each region: room for tubes between regions.
const MIN_OPEN_RIDE = 12 # Tiles an open tube is long, at least.
const OPEN_RIDE_TRIES = 3 # Per open tube: pairs of places to try.
const FAR_SAMPLES = 8 # To pick a far-off end for an open tube, the furthest of this many random tiles.
var regionRects: Array[Rect2i] = []
var regionAir: Array[Dictionary] = [] # Per region: its air tiles (tile -> true).
var openAir := {} # Air tiles tubes may run through: halls, and corridors 3 or more wide.
var bounds := Rect2i() # The whole maze, in tiles.
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
var _layer: TileMapLayer
var _tiles: MazeTiles
var _random: RandomNumberGenerator
var _router: MazeTubeRouter
func _init(graph: MazeGraph, screens: Vector2i, layer: TileMapLayer, random: RandomNumberGenerator, level: Dictionary) -> void:
_layer = layer
_tiles = MazeTiles.new(layer.tile_set)
_random = random
var screenTiles := Vector2i(RoomCamera.ROOM_SIZE) / layer.tile_set.tile_size
bounds = Rect2i(Vector2i.ZERO, screenTiles * screens)
_fill_rock()
_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, regionAir, openAir)
isComplete = true
for tube in graph.tubes:
var fallback := MazeGraph.pick_two_way_kind(random, level.steeredShare)
var fromAir := regionAir[tube.from]
var toAir := regionAir[tube.to]
if _router.route(fromAir, MazeTubeRouter.middle(toAir), toAir, MazeTubeRouter.middle(fromAir), tube.kind, fallback):
routedTubeCount += 1
elif tube.isRequired:
isComplete = false
return
var screenCount: int = screens.x * screens.y
_add_open_tubes(graph, roundi(level.openTubesPerScreen * screenCount), level.steeredShare)
_add_wall_pipes(roundi(level.wallPipesPerScreen * screenCount), 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:
_layer.clear()
for y in range(bounds.position.y, bounds.end.y):
for x in range(bounds.position.x, bounds.end.x):
_tiles.set_tile(_layer, Vector2i(x, y), 0, MazeTiles.ROCK)
func _carve_regions(graph: MazeGraph, screenTiles: Vector2i, level: Dictionary) -> void:
var split: Vector2i = graph.gridSize / (bounds.size / screenTiles)
for region in graph.region_count():
var rect := _region(graph.grid_cell(region), split, screenTiles)
regionRects.append(rect)
var area := rect.grow(-REGION_BORDER)
var air := {}
for tile in MazeCorridors.carve(_layer, area, level.corridorWidth, level.braid, _random):
air[tile] = true
if level.corridorWidth >= 3:
openAir[tile] = true
for tile in MazeCorridors.carve_halls(_layer, area, level.hallsPerRegion, _random):
air[tile] = true
openAir[tile] = true
regionAir.append(air)
# 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
var regionSize := screenTiles / split
var position := screen * screenTiles + inScreen * regionSize
var size := regionSize
if inScreen.x == split.x - 1:
size.x = screenTiles.x - inScreen.x * regionSize.x
if inScreen.y == split.y - 1:
size.y = screenTiles.y - inScreen.y * regionSize.y
return Rect2i(position, size)
# Long rides: from somewhere in a region to somewhere far off in it or in a
# neighbouring region (maybe on another screen), through rock and open air.
func _add_open_tubes(graph: MazeGraph, count: int, steeredShare: float) -> void:
for i in count:
var twoWay := MazeGraph.pick_two_way_kind(_random, steeredShare)
var kind := MazeGraph.ONE_WAY if _random.randf() < 0.35 else twoWay
for attempt in OPEN_RIDE_TRIES:
var from := _random.randi_range(0, graph.region_count() - 1)
var to := graph.region_at((graph.grid_cell(from) + Vector2i(_random.randi_range(-1, 1), _random.randi_range(-1, 1))).clamp(Vector2i.ZERO, graph.gridSize - Vector2i.ONE))
if regionAir[from].is_empty() or regionAir[to].is_empty():
continue
var start := _random_tile(regionAir[from])
var end := _far_tile(regionAir[to], start)
if _router.route(regionAir[from], Vector2(start), regionAir[to], Vector2(end), kind, twoWay, MIN_OPEN_RIDE):
break
func _random_tile(air: Dictionary) -> Vector2i:
var tiles: Array = air.keys()
return tiles[_random.randi_range(0, tiles.size() - 1)]
func _far_tile(air: Dictionary, from: Vector2i) -> Vector2i:
var best := _random_tile(air)
for i in FAR_SAMPLES:
var tile := _random_tile(air)
if Vector2(tile).distance_squared_to(Vector2(from)) > Vector2(best).distance_squared_to(Vector2(from)):
best = tile
return best
# 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
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)
# 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
func _random_floor(air: Dictionary) -> Vector2i:
var floors := _floors(air)
return floors[_random.randi_range(0, floors.size() - 1)]
# 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 @@
uid://b3q5n3qxcy811

View file

@ -0,0 +1,114 @@
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]
const HALL_MIN = Vector2i(4, 3)
const HALL_MAX = Vector2i(7, 5)
# 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
# Carves `count` open halls (rooms of 4-7 x 3-5 tiles) into `area`, over the
# corridors, and returns their tiles. They join corridors into loops and give
# tubes open air to run through.
static func carve_halls(layer: TileMapLayer, area: Rect2i, count: int, random: RandomNumberGenerator) -> Array[Vector2i]:
var hall: Array[Vector2i] = []
for i in count:
var size := Vector2i(random.randi_range(HALL_MIN.x, HALL_MAX.x), random.randi_range(HALL_MIN.y, HALL_MAX.y)).min(area.size)
var corner := Vector2i(random.randi_range(area.position.x, area.end.x - size.x),
random.randi_range(area.position.y, area.end.y - size.y))
_carve_rect(layer, Rect2i(corner, size), hall)
return hall
# 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

204
Levels/Maze/maze_graph.gd Normal file
View file

@ -0,0 +1,204 @@
class_name MazeGraph
extends RefCounted
# 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 regions (a recursive
# backtracker, so it has long corridors and dead ends). Its tubes are two-way.
# 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 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 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.
# (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 ONE_WAY = &"one_way" # Goes from .from to .to only.
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 # Regions across and down.
# Per tube: {from: region, to: region, kind: AUTO/MANUAL/ONE_WAY,
# isRequired: true for the tree (the maze breaks without it)}.
var tubes: Array[Dictionary] = []
var start := 0
var end := 0
var _random: RandomNumberGenerator
var _level: Dictionary
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.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 region_count() -> int:
return gridSize.x * gridSize.y
func grid_cell(region: int) -> Vector2i:
return Vector2i(region % gridSize.x, region / gridSize.x)
func region_at(cell: Vector2i) -> int:
return cell.y * gridSize.x + cell.x
# ---- Building ----
func _build_tree() -> void:
var visited := {}
var stack: Array[int] = [_random.randi_range(0, region_count() - 1)]
visited[stack[0]] = true
while not stack.is_empty():
var region: int = stack.back()
var unvisited: Array[int] = []
for neighbor in _grid_neighbors(region):
if not visited.has(neighbor):
unvisited.append(neighbor)
if unvisited.is_empty():
stack.pop_back()
continue
var next: int = unvisited[_random.randi_range(0, unvisited.size() - 1)]
visited[next] = 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(region: int) -> Array[int]:
var neighbors: Array[int] = []
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(region_at(next))
return neighbors
func _two_way_kind() -> StringName:
return pick_two_way_kind(_random, _level.steeredShare)
# Auto, or (with chance `steeredShare`) manual. MazeCarver uses this too.
static func pick_two_way_kind(random: RandomNumberGenerator, steeredShare: float) -> StringName:
return MANUAL if random.randf() < steeredShare else AUTO
func _pick_start_and_end() -> void:
start = _random.randi_range(0, region_count() - 1)
var distances := _tree_distances(start)
end = start
for region in region_count():
if distances[region] > distances[end]:
end = region
func _tree_distances(from: int) -> PackedInt32Array:
var distances := PackedInt32Array()
distances.resize(region_count())
distances.fill(-1)
distances[from] = 0
var queue: Array[int] = [from]
while not queue.is_empty():
var region: int = queue.pop_front()
for next: int in _treeNeighbors[region]:
if distances[next] == -1:
distances[next] = distances[region] + 1
queue.append(next)
return distances
# Turns some tree tubes on the Start-End route one-way, pointing towards End.
func _make_route_one_way() -> void:
var route := _route()
var routeTubes: Array[int] = []
for i in range(route.size() - 1):
routeTubes.append(_tube_between(route[i], route[i + 1]))
_shuffle(routeTubes)
var oneWayCount := mini(_level.oneWayOnRoute, routeTubes.size())
for i in oneWayCount:
var tube := tubes[routeTubes[i]]
# 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
tube.to = swap
tube.kind = ONE_WAY
# The regions from Start to End along the tree.
func _route() -> Array[int]:
var distances := _tree_distances(end)
var route: Array[int] = [start]
while route.back() != end:
for next: int in _treeNeighbors[route.back()]:
if distances[next] == distances[route.back()] - 1:
route.append(next)
break
return route
func _tube_between(regionA: int, regionB: int) -> int:
for i in tubes.size():
var tube := tubes[i]
if (tube.from == regionA and tube.to == regionB) or (tube.from == regionB and tube.to == regionA):
return i
return -1
func _add_extra_tubes(count: int) -> void:
for i in count:
for attempt in EXTRA_TUBE_TRIES:
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 else _two_way_kind()
tubes.append({from = from, to = to, kind = kind, isRequired = false})
break
# 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 region_at(other)
func _shuffle(items: Array[int]) -> void:
for i in range(items.size() - 1, 0, -1):
var j := _random.randi_range(0, i)
var swap := items[i]
items[i] = items[j]
items[j] = swap

View file

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

39
Levels/Maze/maze_level.gd Normal file
View file

@ -0,0 +1,39 @@
extends Node2D
# A generated maze (see docs/MAZE.md). Builds the maze from MazeSettings when
# it loads, puts the player on Start, and shows the win panel at End.
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 airCurrents: TubeAirCurrents = $TubeAirCurrents
@onready var startMarker: MazeMarker = $StartMarker
@onready var endMarker: MazeMarker = $EndMarker
@onready var pauseMenu: CanvasLayer = $PauseMenu
@onready var winMenu: MazeWinMenu = $WinMenu
func _ready() -> void:
var firstSeed := MazeSettings.mazeSeed if MazeSettings.mazeSeed != 0 else randi()
MazeSettings.mazeSeed = 0 # The next maze gets a new one.
var builder := MazeBuilder.new(layer, Vector2i(MazeSettings.width, MazeSettings.height),
MazeSettings.complexity, firstSeed)
if not builder.isValid:
push_error("Couldn't make a maze: %s" % ", ".join(builder.problems))
Transition.change_scene(MENU_SCENE)
return
startMarker.position = layer.map_to_local(builder.carver.startCell)
endMarker.position = layer.map_to_local(builder.carver.endCell)
player.global_position = startMarker.global_position
player.reset_physics_interpolation()
airflow.refresh()
airCurrents.refresh()
endMarker.reached.connect(_on_end_reached)
func _on_end_reached() -> void:
pauseMenu.process_mode = Node.PROCESS_MODE_DISABLED # So Escape can't unpause under the win panel.
winMenu.open()

View file

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

View file

@ -0,0 +1,55 @@
[gd_scene format=3]
[ext_resource type="Script" path="res://Levels/Maze/maze_level.gd" id="1_maze"]
[ext_resource type="PackedScene" path="res://Characters/player.tscn" id="2_player"]
[ext_resource type="TileSet" path="res://Assets/level_tiles.tres" id="3_tiles"]
[ext_resource type="Script" path="res://Levels/room_camera.gd" id="4_camera"]
[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_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"]
[node name="MazeLevel" type="Node2D"]
script = ExtResource("1_maze")
[node name="TileMapLayer" type="TileMapLayer" parent="."]
tile_set = ExtResource("3_tiles")
[node name="StartMarker" type="Area2D" parent="."]
script = ExtResource("8_marker")
[node name="EndMarker" type="Area2D" parent="."]
script = ExtResource("8_marker")
label = "END"
color = Color(1, 0.85, 0.25, 1)
isGoal = true
[node name="Player" parent="." instance=ExtResource("2_player")]
[node name="TubeAirflow" type="Node2D" parent="." node_paths=PackedStringArray("layer")]
script = ExtResource("7_airflow")
layer = NodePath("../TileMapLayer")
[node name="TubeAirCurrents" type="Node2D" parent="." node_paths=PackedStringArray("layer", "target")]
script = ExtResource("10_currents")
layer = NodePath("../TileMapLayer")
target = NodePath("../Player")
[node name="RoomCamera" type="Camera2D" parent="." node_paths=PackedStringArray("target")]
script = ExtResource("4_camera")
target = NodePath("../Player")
[node name="PauseMenu" parent="." instance=ExtResource("5_pause")]
visible = false
[node name="WinMenu" parent="." instance=ExtResource("9_win")]
visible = false
[node name="MusicPlayer" type="AudioStreamPlayer" parent="."]
stream = ExtResource("6_music")
volume_db = -20.0
autoplay = true
bus = &"Music"
parameters/looping = true

View file

@ -0,0 +1,58 @@
class_name MazeMarker
extends Area2D
# A maze's Start or End: a glowing pad on the floor with a label over it.
# Stand it on the middle of an air tile whose floor is below. The End one
# sends `reached` when the player touches it.
signal reached
const PAD_SIZE = Vector2(28, 4)
const PAD_DROP = 12.0 # How far below our position the pad's top is (16 is the floor).
const GLOW_HEIGHT = 20.0
const PULSE_SPEED = 3.0 # Radians per second.
const LABEL_RISE = 18.0 # How far above our position the label sits.
const LABEL_FONT_SIZE = 8
const TOUCH_SIZE = Vector2(20, 20)
@export var label := "START"
@export var color := Color(0.3, 1.0, 0.45)
@export var isGoal := false
var _time := 0.0
func _ready() -> void:
z_index = 1 # In front of the tiles.
monitoring = isGoal
var shape := RectangleShape2D.new()
shape.size = TOUCH_SIZE
var collision := CollisionShape2D.new()
collision.shape = shape
add_child(collision)
body_entered.connect(_on_body_entered)
func _process(delta: float) -> void:
_time += delta
queue_redraw()
func _draw() -> void:
var pulse := 0.5 + 0.5 * sin(_time * PULSE_SPEED)
# A glow rising off the pad, fading upwards.
var glowSteps := int(GLOW_HEIGHT)
for step in glowSteps:
var glow := color
glow.a = (1.0 - float(step) / glowSteps) * (0.15 + 0.15 * pulse)
draw_rect(Rect2(-PAD_SIZE.x / 2.0, PAD_DROP - step - 1, PAD_SIZE.x, 1), glow)
draw_rect(Rect2(Vector2(-PAD_SIZE.x / 2.0, PAD_DROP), PAD_SIZE), color.lightened(0.3 * pulse))
var font := ThemeDB.fallback_font
var textWidth := font.get_string_size(label, HORIZONTAL_ALIGNMENT_LEFT, -1, LABEL_FONT_SIZE).x
draw_string(font, Vector2(-textWidth / 2.0, -LABEL_RISE), label, HORIZONTAL_ALIGNMENT_LEFT, -1,
LABEL_FONT_SIZE, color.lightened(0.2 * pulse))
func _on_body_entered(body: Node2D) -> void:
if isGoal and body is CharacterBody2D:
reached.emit()

View file

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

View file

@ -0,0 +1,48 @@
class_name MazeSettings
extends RefCounted
# What the player picked for the next maze (the Maze setup panel sets these,
# MazeLevel reads them), and what each complexity level means. See docs/MAZE.md.
const MIN_WIDTH = 1
const MAX_WIDTH = 4
const MIN_HEIGHT = 1
const MAX_HEIGHT = 3
const MIN_COMPLEXITY = 1
const MAX_COMPLEXITY = 5
# Per complexity level (index 0 is level 1):
# 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).
# hallsPerRegion: open rooms carved over the corridors.
# oneWayOnRoute: how many tubes between regions on the Start-End route are one-way.
# extraTubesPerScreen: tubes between regions on top of the spanning tree.
# openTubesPerScreen: long rides through open air and rock, within or
# between neighbouring regions.
# wallPipesPerScreen: short tubes through a wall inside a region (shortcuts).
# steeredShare: the share of two-way tubes that are manual, not auto.
# winding: how much tubes wander (0 = shortest path).
const LEVELS: Array[Dictionary] = [
{regionsPerScreen = Vector2i(2, 1), corridorWidth = 3, braid = 0.5, hallsPerRegion = 0, oneWayOnRoute = 0,
extraTubesPerScreen = 0.5, openTubesPerScreen = 1.5, wallPipesPerScreen = 0.0, steeredShare = 0.3, winding = 2.0},
{regionsPerScreen = Vector2i(2, 1), corridorWidth = 2, braid = 0.3, hallsPerRegion = 1, oneWayOnRoute = 1,
extraTubesPerScreen = 1.0, openTubesPerScreen = 2.0, wallPipesPerScreen = 1.0, steeredShare = 0.35, winding = 3.0},
{regionsPerScreen = Vector2i(2, 1), corridorWidth = 2, braid = 0.15, hallsPerRegion = 1, oneWayOnRoute = 2,
extraTubesPerScreen = 1.5, openTubesPerScreen = 3.0, wallPipesPerScreen = 2.0, steeredShare = 0.4, winding = 4.0},
{regionsPerScreen = Vector2i(1, 1), corridorWidth = 1, braid = 0.05, hallsPerRegion = 2, oneWayOnRoute = 3,
extraTubesPerScreen = 1.5, openTubesPerScreen = 3.5, wallPipesPerScreen = 3.0, steeredShare = 0.4, winding = 5.0},
{regionsPerScreen = Vector2i(1, 1), corridorWidth = 1, braid = 0.0, hallsPerRegion = 3, oneWayOnRoute = 4,
extraTubesPerScreen = 2.0, openTubesPerScreen = 4.5, wallPipesPerScreen = 5.0, steeredShare = 0.45, winding = 6.0},
]
static var width := 2 # In screens.
static var height := 1
static var complexity := 2
static var mazeSeed := 0 # 0: pick a new random one when the maze is made.
static func get_level(level: int) -> Dictionary:
return LEVELS[clampi(level, MIN_COMPLEXITY, MAX_COMPLEXITY) - MIN_COMPLEXITY]

View file

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

58
Levels/Maze/maze_tiles.gd Normal file
View file

@ -0,0 +1,58 @@
class_name MazeTiles
extends RefCounted
# Finds the tile for a tube of a given shape and kind in a TileSet, by reading
# the tiles' custom data (so nothing here hard-codes atlas positions).
# Kinds are MazeGraph's: AUTO, MANUAL, ONE_WAY, plus ROCK for solid tiles.
const ROCK = &"rock"
# The TileSet custom data layers (see player.gd and the tube scripts).
const OPENINGS_LAYER = "tube_openings"
const MANUAL_LAYER = "tube_manual"
var _sourceId := -1
var _tiles := {} # "openings/kind/entrySide" -> [atlas coords, alternative].
func _init(tileSet: TileSet) -> void:
for sourceIndex in tileSet.get_source_count():
var sourceId := tileSet.get_source_id(sourceIndex)
var source := tileSet.get_source(sourceId) as TileSetAtlasSource
if source == null:
continue
_sourceId = sourceId
for tileIndex in source.get_tiles_count():
var coords := source.get_tile_id(tileIndex)
for alternativeIndex in source.get_alternative_tiles_count(coords):
var alternative := source.get_alternative_tile_id(coords, alternativeIndex)
var data := source.get_tile_data(coords, alternative)
var key := _key(data.get_custom_data(OPENINGS_LAYER), _kind_of(data),
data.get_custom_data(OneWayTube.ENTRY_LAYER))
if not _tiles.has(key):
_tiles[key] = [coords, alternative]
return
# Puts the tile at `cell`. openings: TUBE_OPEN_... bits (0 for rock).
# entrySide: for a one-way tube's entrance tile, the side bit of its way in.
func set_tile(layer: TileMapLayer, cell: Vector2i, openings: int, kind: StringName, entrySide := 0) -> bool:
var key := _key(openings, kind, entrySide)
if not _tiles.has(key):
push_error("MazeTiles: no tile for openings %d, kind %s, entry %d" % [openings, kind, entrySide])
return false
layer.set_cell(cell, _sourceId, _tiles[key][0], _tiles[key][1])
return true
static func _kind_of(data: TileData) -> StringName:
if data.get_custom_data(OPENINGS_LAYER) == 0:
return ROCK
if data.get_custom_data(OneWayTube.ONE_WAY_LAYER):
return MazeGraph.ONE_WAY
if data.get_custom_data(MANUAL_LAYER):
return MazeGraph.MANUAL
return MazeGraph.AUTO
static func _key(openings: int, kind: StringName, entrySide: int) -> String:
return "%d/%s/%d" % [openings, kind, entrySide]

View file

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

View file

@ -0,0 +1,433 @@
class_name MazeTubeRouter
extends RefCounted
# Lays tubes into a carved maze, routed with AStarGrid2D (random weights so
# they wander): long tubes between regions and across screens, "open" tubes
# that run through open air (halls, wide corridors) where the slime can still
# get round them, and short "wall pipes" through a single wall.
# Tubes may cross another tube of the same kind at a straight tile, making a
# cross tile: auto and one-way tubes go straight through it (two separate
# rides), manual tubes join into one network you steer through.
# Otherwise tubes never share a tile, and their openings only face their own
# tiles, so they can't join by accident.
#
# 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 CROSSING_RETRIES = 4 # Re-routes when a path uses a tube tile it can't cross.
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 or open air, see _touches_channel.)
const INTERIOR_COST = 12.0
const OPEN_AIR_COST = 0.6 # Open air is cheap: tubes there are seen and ridden past.
const CROSSING_COST = 3.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 or covered.
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.
var _regionAir: Array[Dictionary] = [] # Per region: its air tiles (shared with MazeCarver).
var _openAir := {} # Air tiles tubes may run through.
var _tubeKinds := {} # Tube tile -> its kind.
func _init(layer: TileMapLayer, tiles: MazeTiles, random: RandomNumberGenerator, bounds: Rect2i,
winding: float, interiors: Array[Rect2i], regionAir: Array[Dictionary], openAir: Dictionary) -> void:
_layer = layer
_tiles = tiles
_random = random
_bounds = bounds
_winding = winding
_interiors = interiors
_regionAir = regionAir
_openAir = openAir
_pathfinder.region = bounds
_pathfinder.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
_pathfinder.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN
_pathfinder.update()
# Routes a tube from region `fromAir` (mouth near `fromTowards`) to region
# `toAir` (near `toTowards`); the regions may be the same. A one-way tube with
# nowhere safe for its ends becomes `fallbackKind`. Fails if no route at least
# `minLength` tiles long fits.
func route(fromAir: Dictionary, fromTowards: Vector2, toAir: Dictionary, toTowards: Vector2,
kind: StringName, fallbackKind: StringName, minLength := 1) -> bool:
_prepare_pathfinder(kind)
var isOneWay := kind == MazeGraph.ONE_WAY
var fromMouths := _mouth_spots(fromAir, fromTowards, &"entrance" if isOneWay else &"")
var toMouths := _mouth_spots(toAir, toTowards, &"exit" if isOneWay else &"")
if isOneWay and (fromMouths.is_empty() or toMouths.is_empty()):
kind = fallbackKind
_prepare_pathfinder(kind)
fromMouths = _mouth_spots(fromAir, fromTowards, &"")
toMouths = _mouth_spots(toAir, toTowards, &"")
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)]
if fromMouth.spot == toMouth.spot:
continue
# Both ends in one region: they mustn't get in each other's way.
if kind == MazeGraph.ONE_WAY and fromAir == toAir \
and not _is_one_way_safe(fromAir, fromMouth.spot, fromMouth.outward, toMouth.spot, toMouth.outward):
continue
var path := _find_path(fromMouth, toMouth, kind)
if path.size() < minLength or not _fits(path, fromMouth, toMouth, kind):
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()
if tiles.is_empty():
return false
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 not _bounds.grow(-1).has_point(wall) or _tubeKinds.has(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
# ---- Routing ----
# Sets which tiles a `kind` tube may go through, and random weights.
func _prepare_pathfinder(kind: StringName) -> void:
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
var weight := 1.0 + _random.randf() * _winding
var isSolid := isEdge
if _tubeKinds.has(cell):
isSolid = isSolid or not _can_cross(cell, kind)
weight *= CROSSING_COST
elif _is_air(cell):
isSolid = isSolid or not _openAir.has(cell) or _is_protected(cell)
weight *= OPEN_AIR_COST
elif _is_interior(cell):
weight *= INTERIOR_COST
_pathfinder.set_point_solid(cell, isSolid)
_pathfinder.set_point_weight_scale(cell, weight)
# Whether a new `kind` tube may cross the tube tile at `cell`: same kind, a
# straight tile (it then goes straight across it), and not a mouth.
func _can_cross(cell: Vector2i, kind: StringName) -> bool:
if _tubeKinds[cell] != kind:
return false
var openings := TubeSteer.get_openings(_layer, cell)
if openings != 5 and openings != 10:
return false
for step in MazeCorridors.STEPS:
if openings & TubeSteer.side_bit(step) and _is_air(cell + step):
return false
return true
# A path between two mouth spots that crosses tubes only straight across.
func _find_path(fromMouth: Dictionary, toMouth: Dictionary, kind: StringName) -> Array[Vector2i]:
var blocked: Array[Vector2i] = [fromMouth.spot + fromMouth.outward, toMouth.spot + toMouth.outward]
for tile in blocked:
_pathfinder.set_point_solid(tile)
var path: Array[Vector2i] = []
for attempt in CROSSING_RETRIES:
path = _pathfinder.get_id_path(fromMouth.spot, toMouth.spot)
var badCrossing := _bad_crossing(path)
if badCrossing == Vector2i(-1, -1):
break
_pathfinder.set_point_solid(badCrossing)
blocked.append(badCrossing)
path = []
for tile in blocked:
_pathfinder.set_point_solid(tile, _tubeKinds.has(tile) and not _can_cross(tile, kind) or (_is_air(tile) and (not _openAir.has(tile) or _is_protected(tile))))
return path
# The first tube tile `path` uses without going straight across it, or (-1, -1).
func _bad_crossing(path: Array[Vector2i]) -> Vector2i:
for i in path.size():
var cell := path[i]
if not _tubeKinds.has(cell):
continue
if i == 0 or i == path.size() - 1:
return cell
var across := path[i + 1] - path[i - 1]
var openings := TubeSteer.get_openings(_layer, cell)
var isStraightAcross := (across.x != 0 and openings == 5) or (across.y != 0 and openings == 10)
if not isStraightAcross:
return cell
return Vector2i(-1, -1)
# Whether laying `path` keeps the rules: its own mouth fronts and air moves
# stay clear, and every region it covers air in stays in one piece.
func _fits(path: Array[Vector2i], fromMouth: Dictionary, toMouth: Dictionary, kind: StringName) -> bool:
var own := {fromMouth.spot + fromMouth.outward: true, toMouth.spot + toMouth.outward: true}
if kind == MazeGraph.ONE_WAY:
for tile in _blow_landing_tiles(toMouth.spot, toMouth.outward):
own[tile] = true
for tile in OneWayTube.blow_zone(_layer, toMouth.spot, toMouth.outward):
own[tile] = true
var covered := {} # Region -> air tiles the path covers.
for tile in path:
if own.has(tile):
return false
if _is_air(tile):
var region := _region_of(tile)
if not covered.has(region):
covered[region] = []
covered[region].append(tile)
for region: int in covered:
if not _stays_connected(_regionAir[region], covered[region]):
return false
return true
func _region_of(tile: Vector2i) -> int:
for region in _regionAir.size():
if _regionAir[region].has(tile):
return region
return -1
func _is_protected(tile: Vector2i) -> bool:
return mouthFronts.has(tile) or forcedCells.has(tile) or _keepFree.has(tile)
# ---- 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 _is_air(spot) and not _tubeKinds.has(spot) and not _pathfinder.is_point_solid(spot) \
and _touches_channel(spot, step):
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` (a mouth facing `outward`) is next to free rock between
# regions or open air, so its tube can run there without going through (and
# cutting up) the walls inside a region.
func _touches_channel(spot: Vector2i, outward: Vector2i) -> bool:
for step in MazeCorridors.STEPS:
var next := spot + step
if step != outward and not _pathfinder.is_point_solid(next) and (not _is_interior(next) or _is_air(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
for tile in zone + [landing]:
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) -> 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 ----
# 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. Tube
# tiles it goes straight across become cross tiles; air it covers stops being
# air.
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]
if _is_air(cell):
_regionAir[_region_of(cell)].erase(cell)
_openAir.erase(cell)
if _tubeKinds.has(cell):
_tiles.set_tile(_layer, cell, 15, kind) # Straight across another tube.
continue
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)
_tubeKinds[cell] = kind
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
for tile in _blow_landing_tiles(path[last], outwardOut):
_keepFree[tile] = true
# Where a blow out of the exit at `spot` facing `outward` drops the slime: the
# landing tile, the one after (a sideways blow can slide it on) and, blowing
# down, the fall below.
func _blow_landing_tiles(spot: Vector2i, outward: Vector2i) -> Array[Vector2i]:
var landing := spot + outward * (OneWayTube.BLOW_RANGE + 1)
var tiles: Array[Vector2i] = [landing, landing + outward]
while outward == Vector2i.DOWN and _is_air(landing + Vector2i.DOWN):
landing += Vector2i.DOWN
tiles.append(landing)
return tiles
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

@ -0,0 +1,113 @@
class_name MazeValidator
extends RefCounted
# Checks a finished maze for soft-locks, from its tiles alone (it doesn't trust
# MazeGraph, MazeCarver or MazeTubeRouter). See docs/MAZE.md.
#
# 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 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 _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
_moves = SlimeMoves.new(layer, bounds)
if not _moves.problem.is_empty():
problem = _moves.problem
return
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 _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 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
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 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 first := Vector2i(x, y)
if not _moves.is_air(first) or _areaAt.has(first):
continue
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
# 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 SlimeMoves.SIDES:
if openings & TubeSteer.side_bit(outward) == 0 or not _areaAt.has(cell + outward):
continue
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
func _reachable_areas(from: int) -> Dictionary:
var found := {from: true}
var queue: Array[int] = [from]
while not queue.is_empty():
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

View file

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

View file

@ -0,0 +1,31 @@
class_name MazeWinMenu
extends CanvasLayer
# Shown when the player reaches a maze's End: a new maze with the same size and
# complexity, or back to the main menu. Pauses the game while it's up (its
# process_mode is Always, like the pause menu).
const MAZE_SCENE = "res://Levels/Maze/maze_level.tscn"
const MENU_SCENE = "res://UI/main_menu.tscn"
@onready var newMazeButton: Button = $CenterContainer/PanelContainer/VBoxContainer/NewMazeButton
func _ready() -> void:
hide()
func open() -> void:
show()
get_tree().paused = true
newMazeButton.grab_focus()
func _on_new_maze_button_pressed() -> void:
get_tree().paused = false # The paused state carries over to the new scene.
Transition.change_scene(MAZE_SCENE)
func _on_main_menu_button_pressed() -> void:
get_tree().paused = false
Transition.change_scene(MENU_SCENE)

View file

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

View file

@ -0,0 +1,46 @@
[gd_scene format=3]
[ext_resource type="Script" path="res://Levels/Maze/maze_win_menu.gd" id="1_win"]
[node name="WinMenu" type="CanvasLayer"]
process_mode = 3
layer = 10
script = ExtResource("1_win")
[node name="Dim" type="ColorRect" parent="."]
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
color = Color(0, 0, 0, 0.5)
[node name="CenterContainer" type="CenterContainer" parent="."]
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
[node name="PanelContainer" type="PanelContainer" parent="CenterContainer"]
layout_mode = 2
[node name="VBoxContainer" type="VBoxContainer" parent="CenterContainer/PanelContainer"]
custom_minimum_size = Vector2(160, 0)
layout_mode = 2
[node name="Title" type="Label" parent="CenterContainer/PanelContainer/VBoxContainer"]
layout_mode = 2
text = "You made it!"
horizontal_alignment = 1
[node name="NewMazeButton" type="Button" parent="CenterContainer/PanelContainer/VBoxContainer"]
layout_mode = 2
text = "New maze"
[node name="MainMenuButton" type="Button" parent="CenterContainer/PanelContainer/VBoxContainer"]
layout_mode = 2
text = "Main menu"
[connection signal="pressed" from="CenterContainer/PanelContainer/VBoxContainer/NewMazeButton" to="." method="_on_new_maze_button_pressed"]
[connection signal="pressed" from="CenterContainer/PanelContainer/VBoxContainer/MainMenuButton" to="." method="_on_main_menu_button_pressed"]

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

@ -0,0 +1,235 @@
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 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):
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 manual tube network `first` is in (joined the way
# TubeSteer joins tiles: both manual, both open): [{tile, front}].
func _network_mouths(first: Vector2i) -> Array[Dictionary]:
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
if TubeSteer.is_manual(_layer, next) 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

@ -5,22 +5,35 @@ const FIRST_LEVEL = "res://Levels/test_level.tscn"
@onready var mainPanel = $CenterContainer
@onready var startButton = $CenterContainer/VBoxContainer/StartButton
@onready var mazeButton = $CenterContainer/VBoxContainer/MazeButton
@onready var optionsButton = $CenterContainer/VBoxContainer/OptionsButton
@onready var optionsMenu = $OptionsMenu
@onready var mazeSetupMenu = $MazeSetupMenu
func _ready() -> void:
# Keyboard focus on Start so arrow keys + Enter work right away.
startButton.grab_focus()
func _unhandled_input(event: InputEvent) -> void:
# Escape backs out of the options screen.
# Escape backs out of the options or maze screen.
if event.is_action_pressed("pause") and optionsMenu.visible:
optionsMenu.close()
get_viewport().set_input_as_handled()
elif event.is_action_pressed("pause") and mazeSetupMenu.visible:
mazeSetupMenu.close()
get_viewport().set_input_as_handled()
func _on_start_button_pressed() -> void:
Transition.change_scene(FIRST_LEVEL)
func _on_maze_button_pressed() -> void:
mainPanel.hide()
mazeSetupMenu.open()
func _on_maze_setup_menu_closed() -> void:
mainPanel.show()
mazeButton.grab_focus()
func _on_options_button_pressed() -> void:
mainPanel.hide()
optionsMenu.open()

View file

@ -2,6 +2,7 @@
[ext_resource type="Script" path="res://UI/main_menu.gd" id="1_main"]
[ext_resource type="PackedScene" path="res://UI/options_menu.tscn" id="2_options"]
[ext_resource type="PackedScene" path="res://UI/maze_setup_menu.tscn" id="3_maze"]
[node name="MainMenu" type="Control"]
layout_mode = 3
@ -48,6 +49,10 @@ layout_mode = 2
layout_mode = 2
text = "Start"
[node name="MazeButton" type="Button" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
text = "Maze"
[node name="OptionsButton" type="Button" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
text = "Options"
@ -60,6 +65,11 @@ text = "Quit"
layout_mode = 1
[connection signal="pressed" from="CenterContainer/VBoxContainer/StartButton" to="." method="_on_start_button_pressed"]
[node name="MazeSetupMenu" parent="." instance=ExtResource("3_maze")]
layout_mode = 1
[connection signal="pressed" from="CenterContainer/VBoxContainer/MazeButton" to="." method="_on_maze_button_pressed"]
[connection signal="closed" from="MazeSetupMenu" to="." method="_on_maze_setup_menu_closed"]
[connection signal="pressed" from="CenterContainer/VBoxContainer/OptionsButton" to="." method="_on_options_button_pressed"]
[connection signal="pressed" from="CenterContainer/VBoxContainer/QuitButton" to="." method="_on_quit_button_pressed"]
[connection signal="closed" from="OptionsMenu" to="." method="_on_options_menu_closed"]

53
UI/maze_setup_menu.gd Normal file
View file

@ -0,0 +1,53 @@
extends Control
# The Maze button's panel: pick the maze's size (in screens) and complexity,
# then Generate. Laid out like the options screen. What each setting does is
# in MazeSettings and docs/MAZE.md.
signal closed
const MAZE_SCENE = "res://Levels/Maze/maze_level.tscn"
@onready var widthBox: SpinBox = $CenterContainer/PanelContainer/VBoxContainer/SettingList/WidthBox
@onready var heightBox: SpinBox = $CenterContainer/PanelContainer/VBoxContainer/SettingList/HeightBox
@onready var complexityBox: SpinBox = $CenterContainer/PanelContainer/VBoxContainer/SettingList/ComplexityBox
@onready var generateButton: Button = $CenterContainer/PanelContainer/VBoxContainer/Buttons/GenerateButton
func _ready() -> void:
hide()
_set_range(widthBox, MazeSettings.MIN_WIDTH, MazeSettings.MAX_WIDTH)
_set_range(heightBox, MazeSettings.MIN_HEIGHT, MazeSettings.MAX_HEIGHT)
_set_range(complexityBox, MazeSettings.MIN_COMPLEXITY, MazeSettings.MAX_COMPLEXITY)
func open() -> void:
widthBox.value = MazeSettings.width
heightBox.value = MazeSettings.height
complexityBox.value = MazeSettings.complexity
show()
generateButton.grab_focus()
func close() -> void:
hide()
closed.emit()
static func _set_range(box: SpinBox, lowest: int, highest: int) -> void:
box.min_value = lowest
box.max_value = highest
box.step = 1
box.rounded = true
func _on_generate_button_pressed() -> void:
MazeSettings.width = int(widthBox.value)
MazeSettings.height = int(heightBox.value)
MazeSettings.complexity = int(complexityBox.value)
MazeSettings.mazeSeed = 0
Transition.change_scene(MAZE_SCENE)
func _on_back_button_pressed() -> void:
close()

View file

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

75
UI/maze_setup_menu.tscn Normal file
View file

@ -0,0 +1,75 @@
[gd_scene format=3]
[ext_resource type="Script" path="res://UI/maze_setup_menu.gd" id="1_setup"]
[node name="MazeSetupMenu" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_setup")
[node name="CenterContainer" type="CenterContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
[node name="PanelContainer" type="PanelContainer" parent="CenterContainer"]
layout_mode = 2
[node name="VBoxContainer" type="VBoxContainer" parent="CenterContainer/PanelContainer"]
custom_minimum_size = Vector2(260, 0)
layout_mode = 2
[node name="Title" type="Label" parent="CenterContainer/PanelContainer/VBoxContainer"]
layout_mode = 2
text = "Maze"
horizontal_alignment = 1
[node name="SettingList" type="GridContainer" parent="CenterContainer/PanelContainer/VBoxContainer"]
layout_mode = 2
columns = 2
[node name="WidthLabel" type="Label" parent="CenterContainer/PanelContainer/VBoxContainer/SettingList"]
layout_mode = 2
size_flags_horizontal = 3
text = "Width (screens)"
[node name="WidthBox" type="SpinBox" parent="CenterContainer/PanelContainer/VBoxContainer/SettingList"]
layout_mode = 2
[node name="HeightLabel" type="Label" parent="CenterContainer/PanelContainer/VBoxContainer/SettingList"]
layout_mode = 2
size_flags_horizontal = 3
text = "Height (screens)"
[node name="HeightBox" type="SpinBox" parent="CenterContainer/PanelContainer/VBoxContainer/SettingList"]
layout_mode = 2
[node name="ComplexityLabel" type="Label" parent="CenterContainer/PanelContainer/VBoxContainer/SettingList"]
layout_mode = 2
size_flags_horizontal = 3
text = "Complexity"
[node name="ComplexityBox" type="SpinBox" parent="CenterContainer/PanelContainer/VBoxContainer/SettingList"]
layout_mode = 2
[node name="Buttons" type="HBoxContainer" parent="CenterContainer/PanelContainer/VBoxContainer"]
layout_mode = 2
alignment = 1
[node name="GenerateButton" type="Button" parent="CenterContainer/PanelContainer/VBoxContainer/Buttons"]
layout_mode = 2
text = "Generate"
[node name="BackButton" type="Button" parent="CenterContainer/PanelContainer/VBoxContainer/Buttons"]
layout_mode = 2
text = "Back"
[connection signal="pressed" from="CenterContainer/PanelContainer/VBoxContainer/Buttons/GenerateButton" to="." method="_on_generate_button_pressed"]
[connection signal="pressed" from="CenterContainer/PanelContainer/VBoxContainer/Buttons/BackButton" to="." method="_on_back_button_pressed"]

11
docs/COMPONENTS.md Normal file
View file

@ -0,0 +1,11 @@
# Components
- 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`), one-way (`OneWayTube`, an auto tube with one entrance).
- 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 (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.
- Carry items (`Items/`): things the slime can pick up and carry.

148
docs/MAZE.md Normal file
View file

@ -0,0 +1,148 @@
# Maze mode
A "Maze" button on the main menu asks for a size and a complexity, then
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. 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 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.** 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.
9. **Lots of long tube rides**, many through open space: tubes run through
open halls and wide corridors where the slime can still get round them,
wind through rock and cross screens. Tubes of the same kind may **cross**
at a cross tile: auto and one-way tubes go straight across (two separate
rides); manual tubes join into one network you steer through
(checked in the game: a manual junction turns, an auto one goes straight).
| Complexity | Regions / screen | Corridor | Loops | Halls / region | One-way on route | Extra tubes / screen | Open rides / screen | Wall pipes / screen | Steered share |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 2 x 1 | 3 | 50 % | 0 | 0 | 0.5 | 1.5 | 0 | 30 % |
| 2 | 2 x 1 | 2 | 30 % | 1 | 1 | 1 | 2 | 1 | 35 % |
| 3 | 2 x 1 | 2 | 15 % | 1 | 2 | 1.5 | 3 | 2 | 40 % |
| 4 | 1 x 1 | 1 | 5 % | 2 | 3 | 1.5 | 3.5 | 3 | 40 % |
| 5 | 1 x 1 | 1 | 0 % | 3 | 4 | 2 | 4.5 | 5 | 45 % |
Open rides are at least 12 tiles long and go from one spot to a far one in the
same or a neighbouring region (often on another screen). Tube winding goes up
with complexity.
## Non-goals
- No change to player movement, existing levels or other menus (besides the
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 hazards, items or enemies. No saving of mazes; the seed isn't shown.
## Approaches considered (rework for maze-book layouts)
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, plus open halls. Tubes between regions run in the rock between
regions; open rides run through rock and open air (halls, corridors 3+
wide) as long as each region's air stays in one piece; short "wall pipes"
go through one wall inside a region as shortcuts. Same-kind tubes may cross
straight across each other.
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.
Approach 1 gives the dense maze-book look directly, scales by corridor width
and braid, and keeps the old safety argument.
## How the slime moves (checked in the game)
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.
## The soft-lock check (`MazeValidator` + `SlimeMoves`)
Works only from the TileMapLayer, with two models:
- **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; auto and one-way tubes go straight across
cross tiles, manual networks let it leave by any of their mouths).
Tube tiles standing in open air are solid like rock: the slime crawls on
them. 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).
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.
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` - 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.*`, `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`
Junction test: one hand-made map with a cross tile must pass as manual tubes
and fail as auto tubes.
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.

181
tests/maze_check.gd Normal file
View file

@ -0,0 +1,181 @@
extends SceneTree
# Headless check for Maze mode:
# godot --headless --audio-driver Dummy --script res://tests/maze_check.gd
# 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.
# 3. Junctions: one hand-made map with a cross tile, as manual tubes (you steer
# at the junction: End is reachable, must pass) and as auto tubes (they go
# straight across: End is out of reach, must fail).
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].
# "|", "-" and "+" (cross) take the kind the map is checked with.
const TUBE_KEY := {
"|": [5, &"", 0], "-": [10, &"", 0], "+": [15, &"", 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.
# S's only tube crosses another at (3, 3). Steering (manual) turns up to E;
# an auto tube goes straight on to the dead end P (and back).
const JUNCTION: Array[String] = [
"#######",
"###E###",
"###|###",
"#S-+-.#",
"###|###",
"###.###",
"#######",
]
const SUCTION_TRAP: Array[String] = [
"#########",
"#########",
"#S.....E#",
"###|^####",
"###|v####",
"##.....##",
"##.....##",
"#########",
]
func _initialize() -> void:
var layer := TileMapLayer.new()
layer.tile_set = TILE_SET
root.add_child(layer)
var mazeCount := 0
var firstTryCount := 0
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:
var firstSeed := 1000 * seedIndex + 37 * complexity + 7 * width + height
var builder := MazeBuilder.new(layer, Vector2i(width, height), complexity, firstSeed)
mazeCount += 1
if builder.isValid:
validCount += 1
if builder.attempts == 1:
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 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)": not _check_map(layer, WIND_TRAP, MazeGraph.AUTO),
"suction trap (hand-made)": not _check_map(layer, SUCTION_TRAP, MazeGraph.AUTO),
"auto crossing going straight (hand-made)": not _check_map(layer, JUNCTION, MazeGraph.AUTO),
}
var junctionPasses := _check_map(layer, JUNCTION, MazeGraph.MANUAL)
print("Validator passes a manual junction you steer through: %s" % ("yes" if junctionPasses else "NO"))
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 and junctionPasses else 1)
# 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(" Start in a blow zone (seed %d): %s" % [blowSeed, validator.problem])
return not validator.isValid
return false
# Builds a hand-made map with `kind` for the generic tube symbols, and returns
# whether the validator passes it.
func _check_map(layer: TileMapLayer, map: Array[String], kind: StringName) -> 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):
var symbolKind: StringName = TUBE_KEY[symbol][1] if TUBE_KEY[symbol][1] != &"" else kind
tiles.set_tile(layer, cell, TUBE_KEY[symbol][0], symbolKind, 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): %s" % [kind, validator.problem if not validator.isValid else "valid"])
return validator.isValid
func _region_with(carver: MazeCarver, cell: Vector2i) -> int:
for region in carver.regionAir.size():
if carver.regionAir[region].has(cell):
return region
return -1

1
tests/maze_check.gd.uid Normal file
View file

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