diff --git a/Assets/level_tiles.tres b/Assets/level_tiles.tres index 717a26e..9a895d6 100755 --- a/Assets/level_tiles.tres +++ b/Assets/level_tiles.tres @@ -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) @@ -24,7 +24,27 @@ texture_region_size = Vector2i(32, 32) 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_3 = 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_3 = true +1:0/4/custom_data_4 = 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_3 = true +1:0/5/custom_data_4 = 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) @@ -41,6 +61,26 @@ texture_region_size = Vector2i(32, 32) 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 +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_3 = 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_3 = true +2:0/4/custom_data_4 = 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_3 = true +2:0/5/custom_data_4 = 4 3:0/next_alternative_id = 3 3:0/0 = 0 3:0/0/physics_layer_0/polygon_0/points = PackedVector2Array(-16, -16, -3, -16, -3, -3, -16, -3) @@ -64,7 +104,7 @@ texture_region_size = Vector2i(32, 32) 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 +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) @@ -81,7 +121,27 @@ texture_region_size = Vector2i(32, 32) 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_3 = 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_3 = true +4:0/4/custom_data_4 = 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_3 = true +4:0/5/custom_data_4 = 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) @@ -98,7 +158,27 @@ texture_region_size = Vector2i(32, 32) 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_3 = 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_3 = true +5:0/4/custom_data_4 = 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_3 = true +5:0/5/custom_data_4 = 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) @@ -115,7 +195,27 @@ texture_region_size = Vector2i(32, 32) 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_3 = 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_3 = true +0:1/4/custom_data_4 = 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_3 = true +0:1/5/custom_data_4 = 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) @@ -132,6 +232,26 @@ texture_region_size = Vector2i(32, 32) 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_3 = 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_3 = true +1:1/4/custom_data_4 = 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_3 = true +1:1/5/custom_data_4 = 4 [resource] tile_size = Vector2i(32, 32) @@ -142,4 +262,8 @@ custom_data_layer_1/name = "tube_manual" custom_data_layer_1/type = 1 custom_data_layer_2/name = "tube_goo" custom_data_layer_2/type = 1 +custom_data_layer_3/name = "tube_one_way" +custom_data_layer_3/type = 1 +custom_data_layer_4/name = "tube_one_way_entry" +custom_data_layer_4/type = 2 sources/0 = SubResource("TileSetAtlasSource_0cw2b") diff --git a/Characters/player.gd b/Characters/player.gd index 44eb90c..69253d5 100755 --- a/Characters/player.gd +++ b/Characters/player.gd @@ -50,6 +50,8 @@ const LAND_PITCH_MAX = 1.15 # (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). +# A one-way one ("tube_one_way" tiles) is an ordinary tube we can only go into +# at its entrance (OneWayTube). 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 @@ -1049,6 +1050,8 @@ 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: @@ -1056,41 +1059,13 @@ func _find_tube_towards(direction: Vector2, extraReach := 0.0) -> Dictionary: var tube := {layer = layer, cell = cell, direction = direction} if TubeSteer.is_manual(layer, cell) or TubeGoo.is_goo(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] diff --git a/Effects/one_way_tube.gd b/Effects/one_way_tube.gd new file mode 100644 index 0000000..147123f --- /dev/null +++ b/Effects/one_way_tube.gd @@ -0,0 +1,49 @@ +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. TubeVacuum shows where the entrances are. + +const ONE_WAY_LAYER = "tube_one_way" +const ENTRY_LAYER = "tube_one_way_entry" + + +# 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: +# [{mouth: global point, outward: Vector2}]. +static func find_entrances(layer: TileMapLayer) -> Array[Dictionary]: + var entrances: Array[Dictionary] = [] + for cell in layer.get_used_cells(): + var entrySide := get_entry_side(layer, cell) + if entrySide == 0 or not is_one_way(layer, cell): + continue + for direction in TubeSteer.DIRECTIONS: + if TubeSteer.side_bit(direction) == entrySide and layer.get_cell_source_id(cell + direction) == -1: + entrances.append({mouth = TubeSteer.cell_point(layer, cell, direction), outward = Vector2(direction)}) + return entrances diff --git a/Effects/one_way_tube.gd.uid b/Effects/one_way_tube.gd.uid new file mode 100644 index 0000000..03b9502 --- /dev/null +++ b/Effects/one_way_tube.gd.uid @@ -0,0 +1 @@ +uid://4mxas52xepeu diff --git a/Effects/pixel_stream.gd b/Effects/pixel_stream.gd index 04f35ec..c2d5a7e 100755 --- a/Effects/pixel_stream.gd +++ b/Effects/pixel_stream.gd @@ -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: diff --git a/Effects/tube_vacuum.gd b/Effects/tube_vacuum.gd new file mode 100644 index 0000000..9437e1d --- /dev/null +++ b/Effects/tube_vacuum.gd @@ -0,0 +1,63 @@ +class_name TubeVacuum +extends Node2D + +# Orange motes drifting into the entrance of every one-way tube (OneWayTube) in +# `layer`, like dust sucked into a vacuum: they start out spread in a fan in +# front of the mouth, speed up as they get close, and funnel into it. +# Call refresh() after changing the layer's tiles. + +const MOTES_PER_MOUTH = 18 +const REACH = 40.0 # How far out from the mouth motes start, in px. +const SPREAD = 22.0 # How far to the side of the mouth motes can start, in px. +const TRIP_TIME = 1.1 # Seconds from appearing to vanishing into the mouth. +const FADE_IN = 0.2 # The share of the trip spent fading in. +const MOTE_COLOR = Color(1.0, 0.6, 0.2) +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 + +var _entrances: Array[Dictionary] = [] +var _time := 0.0 + + +func _ready() -> void: + top_level = true # Entrances are in global coordinates. + z_index = 1 # In front of the tiles. + refresh() + + +func refresh() -> void: + _entrances = OneWayTube.find_entrances(layer) if layer != null else [] + queue_redraw() + + +func _process(delta: float) -> void: + if _entrances.is_empty(): + return + _time += delta + queue_redraw() + + +func _draw() -> void: + for mouthIndex in _entrances.size(): + var entrance: Dictionary = _entrances[mouthIndex] + var outward: Vector2 = entrance.outward + var across := outward.orthogonal() + for moteIndex in MOTES_PER_MOUTH: + # Each mote loops on its own offset, and gets a fresh random start + # each trip. + var tripClock := _time / TRIP_TIME + 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 := random.randf_range(-1.0, 1.0) * SPREAD + var lighten := random.randf() * MOTE_LIGHTEN + var moteSize := Vector2.ONE * (2.0 if random.randf() < BIG_MOTE_SHARE else 1.0) + # Slow at first, then faster and faster into the mouth. + var remaining := 1.0 - progress * progress + var at: Vector2 = entrance.mouth + outward * (REACH * remaining) + across * (side * remaining) + var color := MOTE_COLOR.lightened(lighten) + color.a = clampf(progress / FADE_IN, 0.0, 1.0) + draw_rect(Rect2(at.floor(), moteSize), color) diff --git a/Effects/tube_vacuum.gd.uid b/Effects/tube_vacuum.gd.uid new file mode 100644 index 0000000..fb3fa50 --- /dev/null +++ b/Effects/tube_vacuum.gd.uid @@ -0,0 +1 @@ +uid://d550q8xkxngm diff --git a/Levels/Maze/maze_builder.gd b/Levels/Maze/maze_builder.gd new file mode 100644 index 0000000..013deb9 --- /dev/null +++ b/Levels/Maze/maze_builder.gd @@ -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.winding) + 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]) diff --git a/Levels/Maze/maze_builder.gd.uid b/Levels/Maze/maze_builder.gd.uid new file mode 100644 index 0000000..7c9271f --- /dev/null +++ b/Levels/Maze/maze_builder.gd.uid @@ -0,0 +1 @@ +uid://4l311qg7el07 diff --git a/Levels/Maze/maze_carver.gd b/Levels/Maze/maze_carver.gd new file mode 100644 index 0000000..b604ea1 --- /dev/null +++ b/Levels/Maze/maze_carver.gd @@ -0,0 +1,181 @@ +class_name MazeCarver +extends RefCounted + +# Turns a MazeGraph into tiles: rock everywhere, a rectangle of air for each +# chamber, and each tube routed through the rock between its two chambers. +# +# Each screen (one RoomCamera room) is split into a grid of regions, one per +# chamber. A chamber is a random rectangle inside its region with at least a +# tile of rock all round, so chambers never touch and never cross a screen +# border. Tubes are routed with AStarGrid2D over the rock, with random weights +# so they wander; tubes never share a tile, so they can't join by accident. + +const MIN_CHAMBER_SIZE = 3 # Tiles of air across and down, at least. +const MIN_ROCK = 3 # Rock left in a region beside its chamber, across and down, at least (when there's room). +const MOUTH_CHOICES = 4 # Of the spots for a mouth nearest the other chamber, how many we pick from. +const ROUTE_TRIES = 8 # Pairs of mouth spots to try before giving up on a tube. + +var chamberRects: Array[Rect2i] = [] +var bounds := Rect2i() # The whole maze, in tiles. +var startCell := Vector2i.ZERO # The air tile Start sits on (on a chamber's floor). +var endCell := Vector2i.ZERO +var isComplete := false # Whether every tube the maze needs got a route. +var routedTubeCount := 0 + +var _layer: TileMapLayer +var _tiles: MazeTiles +var _random: RandomNumberGenerator +var _pathfinder := AStarGrid2D.new() +var _winding := 0.0 + + +func _init(graph: MazeGraph, screens: Vector2i, layer: TileMapLayer, random: RandomNumberGenerator, winding: float) -> void: + _layer = layer + _tiles = MazeTiles.new(layer.tile_set) + _random = random + _winding = winding + var screenTiles := Vector2i(RoomCamera.ROOM_SIZE) / layer.tile_set.tile_size + bounds = Rect2i(Vector2i.ZERO, screenTiles * screens) + + _fill_rock() + _carve_chambers(graph, screenTiles) + _setup_pathfinder() + isComplete = true + for tube in graph.tubes: + if _carve_tube(tube): + routedTubeCount += 1 + elif tube.isRequired: + isComplete = false + return + startCell = _floor_cell(chamberRects[graph.start]) + endCell = _floor_cell(chamberRects[graph.end]) + + +func _fill_rock() -> void: + _layer.clear() + for y in range(bounds.position.y, bounds.end.y): + for x in range(bounds.position.x, bounds.end.x): + _tiles.set_tile(_layer, Vector2i(x, y), 0, MazeTiles.ROCK) + + +func _carve_chambers(graph: MazeGraph, screenTiles: Vector2i) -> void: + var split: Vector2i = graph.gridSize / (bounds.size / screenTiles) + for chamber in graph.chamber_count(): + var region := _region(graph.grid_cell(chamber), split, screenTiles) + var size := Vector2i(_random_size(region.size.x), _random_size(region.size.y)) + var corner := Vector2i(_random.randi_range(region.position.x + 1, region.end.x - 1 - size.x), + _random.randi_range(region.position.y + 1, region.end.y - 1 - size.y)) + var rect := Rect2i(corner, size) + chamberRects.append(rect) + for y in range(rect.position.y, rect.end.y): + for x in range(rect.position.x, rect.end.x): + _layer.erase_cell(Vector2i(x, y)) + + +# The tiles a chamber's region covers. The last region in each screen row or +# column takes what's left over. +static func _region(gridCell: Vector2i, split: Vector2i, screenTiles: Vector2i) -> Rect2i: + var screen := gridCell / split + var inScreen := gridCell % split + var regionSize := screenTiles / split + var position := screen * screenTiles + inScreen * regionSize + var size := regionSize + if inScreen.x == split.x - 1: + size.x = screenTiles.x - inScreen.x * regionSize.x + if inScreen.y == split.y - 1: + size.y = screenTiles.y - inScreen.y * regionSize.y + return Rect2i(position, size) + + +# A chamber size for a region `regionSize` tiles long: room for MIN_ROCK +# beside it if possible, and always a tile of rock each side. +func _random_size(regionSize: int) -> int: + var largest := maxi(regionSize - MIN_ROCK, MIN_CHAMBER_SIZE) + return mini(_random.randi_range(MIN_CHAMBER_SIZE, largest), regionSize - 2) + + +# A random tile along the bottom row of a chamber. +func _floor_cell(rect: Rect2i) -> Vector2i: + return Vector2i(_random.randi_range(rect.position.x, rect.end.x - 1), rect.end.y - 1) + + +# ---- Tubes ---- + +func _setup_pathfinder() -> void: + _pathfinder.region = bounds + _pathfinder.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER + _pathfinder.default_compute_heuristic = AStarGrid2D.HEURISTIC_MANHATTAN + _pathfinder.update() + # Tubes go through rock only, and never through the maze's outer edge. + for y in range(bounds.position.y, bounds.end.y): + for x in range(bounds.position.x, bounds.end.x): + var cell := Vector2i(x, y) + var isEdge := x == bounds.position.x or y == bounds.position.y or x == bounds.end.x - 1 or y == bounds.end.y - 1 + _pathfinder.set_point_solid(cell, isEdge or _layer.get_cell_source_id(cell) == -1) + + +# Routes `tube` and puts its tiles down. False if there's no way through. +func _carve_tube(tube: Dictionary) -> bool: + var fromRect := chamberRects[tube.from] + var toRect := chamberRects[tube.to] + _randomize_weights() + var fromMouths := _mouth_spots(fromRect, toRect) + var toMouths := _mouth_spots(toRect, fromRect) + for attempt in ROUTE_TRIES: + if fromMouths.is_empty() or toMouths.is_empty(): + return false + var fromMouth: Vector2i = fromMouths[_random.randi_range(0, fromMouths.size() - 1)] + var toMouth: Vector2i = toMouths[_random.randi_range(0, toMouths.size() - 1)] + var path := _pathfinder.get_id_path(fromMouth, toMouth) + if path.is_empty(): + continue + _put_tube_tiles(path, fromRect, toRect, tube.kind) + return true + return false + + +# Random extra cost on every tile, so routes wander instead of always taking +# the shortest way. +func _randomize_weights() -> void: + for y in range(bounds.position.y, bounds.end.y): + for x in range(bounds.position.x, bounds.end.x): + _pathfinder.set_point_weight_scale(Vector2i(x, y), 1.0 + _random.randf() * _winding) + + +# Free rock tiles touching `rect`'s sides, where a mouth into it can go: the +# MOUTH_CHOICES nearest `towards`. +func _mouth_spots(rect: Rect2i, towards: Rect2i) -> Array[Vector2i]: + var spots: Array[Vector2i] = [] + for x in range(rect.position.x, rect.end.x): + spots.append(Vector2i(x, rect.position.y - 1)) + spots.append(Vector2i(x, rect.end.y)) + for y in range(rect.position.y, rect.end.y): + spots.append(Vector2i(rect.position.x - 1, y)) + spots.append(Vector2i(rect.end.x, y)) + spots = spots.filter(func(spot: Vector2i) -> bool: return not _pathfinder.is_point_solid(spot)) + var target := Vector2(towards.get_center()) + spots.sort_custom(func(a: Vector2i, b: Vector2i) -> bool: + return Vector2(a).distance_squared_to(target) < Vector2(b).distance_squared_to(target)) + return spots.slice(0, MOUTH_CHOICES) + + +# Lays tube tiles along `path`, from a mouth into `fromRect` to one into `toRect`. +func _put_tube_tiles(path: Array[Vector2i], fromRect: Rect2i, toRect: Rect2i, kind: StringName) -> void: + var last := path.size() - 1 + for i in path.size(): + var cell := path[i] + var back := _side_towards(cell, fromRect) if i == 0 else path[i - 1] - cell + var ahead := _side_towards(cell, toRect) if i == last else path[i + 1] - cell + var openings := TubeSteer.side_bit(back) | TubeSteer.side_bit(ahead) + # A one-way tube's way in is its mouth into `fromRect`. + var entrySide := TubeSteer.side_bit(back) if kind == MazeGraph.ONE_WAY and i == 0 else 0 + _tiles.set_tile(_layer, cell, openings, kind, entrySide) + _pathfinder.set_point_solid(cell) + + +# Which way from `cell` (just outside `rect`) the rect is. +static func _side_towards(cell: Vector2i, rect: Rect2i) -> Vector2i: + for direction in TubeSteer.DIRECTIONS: + if rect.has_point(cell + direction): + return direction + return Vector2i.ZERO diff --git a/Levels/Maze/maze_carver.gd.uid b/Levels/Maze/maze_carver.gd.uid new file mode 100644 index 0000000..d012227 --- /dev/null +++ b/Levels/Maze/maze_carver.gd.uid @@ -0,0 +1 @@ +uid://b3q5n3qxcy811 diff --git a/Levels/Maze/maze_graph.gd b/Levels/Maze/maze_graph.gd new file mode 100644 index 0000000..1fc935f --- /dev/null +++ b/Levels/Maze/maze_graph.gd @@ -0,0 +1,197 @@ +class_name MazeGraph +extends RefCounted + +# The maze as a graph, before any tiles: a grid of chambers joined by tubes. +# +# 1. A random spanning tree over neighbouring chambers (a recursive +# backtracker, so it has long corridors and dead ends). Its tubes are two-way. +# 2. Start is a random chamber, End the one furthest from it along the tree. +# 3. With the tree rooted at End, some tubes on the Start-End route become +# one-way towards End. +# 4. Extra tubes join nearby chambers: two-way loops, and one-way tubes in any +# direction. +# +# Why this can't soft-lock: every tree tube can be used towards End (two-way, +# or one-way towards End), so from every chamber the tree leads to End. Extra +# tubes only add ways, so they can't take that away. And every chamber is +# 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. +# MazeValidator checks the finished tiles anyway. + +const AUTO = &"auto" +const MANUAL = &"manual" +const GOO = &"goo" +const ONE_WAY = &"one_way" # Goes from .from to .to only. +const EXTRA_TUBE_REACH = 2 # Extra tubes join chambers up to this many grid steps apart (diagonals count as one). +const EXTRA_TUBE_TRIES = 40 # Per extra tube, tries to find a pair of chambers not joined yet. + +const GRID_STEPS: Array[Vector2i] = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT] + +var gridSize := Vector2i.ZERO # Chambers across and down. +# Per tube: {from: chamber, to: chamber, kind: AUTO/MANUAL/GOO/ONE_WAY, +# 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 chamber: chambers joined to it in the tree. + + +# screens: the maze's size in screens. level: see MazeSettings.LEVELS. +func _init(screens: Vector2i, level: Dictionary, random: RandomNumberGenerator) -> void: + _random = random + _level = level + gridSize = screens * Vector2i(level.chambersPerScreen) + _treeNeighbors.resize(chamber_count()) + for chamber in chamber_count(): + _treeNeighbors[chamber] = [] + _build_tree() + _pick_start_and_end() + _make_route_one_way() + _add_extra_tubes(roundi(level.extraTubesPerScreen * screens.x * screens.y)) + + +func chamber_count() -> int: + return gridSize.x * gridSize.y + + +func grid_cell(chamber: int) -> Vector2i: + return Vector2i(chamber % gridSize.x, chamber / gridSize.x) + + +func chamber_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, chamber_count() - 1)] + visited[stack[0]] = true + while not stack.is_empty(): + var chamber: int = stack.back() + var unvisited: Array[int] = [] + for neighbor in _grid_neighbors(chamber): + 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[chamber].append(next) + _treeNeighbors[next].append(chamber) + tubes.append({from = chamber, to = next, kind = _two_way_kind(), isRequired = true}) + stack.append(next) + + +func _grid_neighbors(chamber: int) -> Array[int]: + var neighbors: Array[int] = [] + var cell := grid_cell(chamber) + for step in GRID_STEPS: + var next := cell + step + if next.x >= 0 and next.y >= 0 and next.x < gridSize.x and next.y < gridSize.y: + neighbors.append(chamber_at(next)) + return neighbors + + +func _two_way_kind() -> StringName: + if _random.randf() >= _level.steeredShare: + return AUTO + return MANUAL if _random.randf() < 0.5 else GOO + + +func _pick_start_and_end() -> void: + start = _random.randi_range(0, chamber_count() - 1) + var distances := _tree_distances(start) + end = start + for chamber in chamber_count(): + if distances[chamber] > distances[end]: + end = chamber + + +func _tree_distances(from: int) -> PackedInt32Array: + var distances := PackedInt32Array() + distances.resize(chamber_count()) + distances.fill(-1) + distances[from] = 0 + var queue: Array[int] = [from] + while not queue.is_empty(): + var chamber: int = queue.pop_front() + for next: int in _treeNeighbors[chamber]: + if distances[next] == -1: + distances[next] = distances[chamber] + 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 chamber 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 chambers 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(chamberA: int, chamberB: int) -> int: + for i in tubes.size(): + var tube := tubes[i] + if (tube.from == chamberA and tube.to == chamberB) or (tube.from == chamberB and tube.to == chamberA): + 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, chamber_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 chamber within EXTRA_TUBE_REACH grid steps, or -1. +func _random_nearby(chamber: int) -> int: + var cell := grid_cell(chamber) + var offset := Vector2i(_random.randi_range(-EXTRA_TUBE_REACH, EXTRA_TUBE_REACH), + _random.randi_range(-EXTRA_TUBE_REACH, EXTRA_TUBE_REACH)) + var other := cell + offset + if offset == Vector2i.ZERO or other.x < 0 or other.y < 0 or other.x >= gridSize.x or other.y >= gridSize.y: + return -1 + return chamber_at(other) + + +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 diff --git a/Levels/Maze/maze_graph.gd.uid b/Levels/Maze/maze_graph.gd.uid new file mode 100644 index 0000000..8d28e27 --- /dev/null +++ b/Levels/Maze/maze_graph.gd.uid @@ -0,0 +1 @@ +uid://dryfv7ixywpgx diff --git a/Levels/Maze/maze_level.gd b/Levels/Maze/maze_level.gd new file mode 100644 index 0000000..73d36d6 --- /dev/null +++ b/Levels/Maze/maze_level.gd @@ -0,0 +1,37 @@ +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 vacuum: TubeVacuum = $TubeVacuum +@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() + vacuum.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() diff --git a/Levels/Maze/maze_level.gd.uid b/Levels/Maze/maze_level.gd.uid new file mode 100644 index 0000000..d714b17 --- /dev/null +++ b/Levels/Maze/maze_level.gd.uid @@ -0,0 +1 @@ +uid://dlu55d2gpt7v8 diff --git a/Levels/Maze/maze_level.tscn b/Levels/Maze/maze_level.tscn new file mode 100644 index 0000000..1bd7215 --- /dev/null +++ b/Levels/Maze/maze_level.tscn @@ -0,0 +1,49 @@ +[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_vacuum.gd" id="7_vacuum"] +[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="TubeVacuum" type="Node2D" parent="." node_paths=PackedStringArray("layer")] +script = ExtResource("7_vacuum") +layer = NodePath("../TileMapLayer") + +[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 diff --git a/Levels/Maze/maze_marker.gd b/Levels/Maze/maze_marker.gd new file mode 100644 index 0000000..0328034 --- /dev/null +++ b/Levels/Maze/maze_marker.gd @@ -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() diff --git a/Levels/Maze/maze_marker.gd.uid b/Levels/Maze/maze_marker.gd.uid new file mode 100644 index 0000000..f931a42 --- /dev/null +++ b/Levels/Maze/maze_marker.gd.uid @@ -0,0 +1 @@ +uid://cma1smhm8dlsh diff --git a/Levels/Maze/maze_settings.gd b/Levels/Maze/maze_settings.gd new file mode 100644 index 0000000..0455e93 --- /dev/null +++ b/Levels/Maze/maze_settings.gd @@ -0,0 +1,35 @@ +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): +# chambersPerScreen: how the chambers split each screen (columns, rows). +# oneWayOnRoute: how many tubes on the Start-End route are one-way. +# extraTubesPerScreen: tubes added on top of the spanning tree (loops and traps). +# steeredShare: the share of two-way tubes that are manual or goo, not auto. +# winding: how much tubes wander on their way (0 = shortest path). +const LEVELS: Array[Dictionary] = [ + {chambersPerScreen = Vector2i(2, 1), oneWayOnRoute = 0, extraTubesPerScreen = 0.0, steeredShare = 0.0, winding = 0.5}, + {chambersPerScreen = Vector2i(2, 2), oneWayOnRoute = 1, extraTubesPerScreen = 0.5, steeredShare = 0.2, winding = 1.0}, + {chambersPerScreen = Vector2i(2, 2), oneWayOnRoute = 2, extraTubesPerScreen = 1.0, steeredShare = 0.3, winding = 2.0}, + {chambersPerScreen = Vector2i(3, 2), oneWayOnRoute = 3, extraTubesPerScreen = 1.5, steeredShare = 0.35, winding = 3.0}, + {chambersPerScreen = Vector2i(3, 2), oneWayOnRoute = 4, extraTubesPerScreen = 2.0, steeredShare = 0.4, winding = 4.0}, +] + +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] diff --git a/Levels/Maze/maze_settings.gd.uid b/Levels/Maze/maze_settings.gd.uid new file mode 100644 index 0000000..84bf86e --- /dev/null +++ b/Levels/Maze/maze_settings.gd.uid @@ -0,0 +1 @@ +uid://bpxh33oqy0yps diff --git a/Levels/Maze/maze_tiles.gd b/Levels/Maze/maze_tiles.gd new file mode 100644 index 0000000..dd0c1b8 --- /dev/null +++ b/Levels/Maze/maze_tiles.gd @@ -0,0 +1,61 @@ +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, GOO, 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" +const GOO_LAYER = "tube_goo" + +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 + if data.get_custom_data(GOO_LAYER): + return MazeGraph.GOO + return MazeGraph.AUTO + + +static func _key(openings: int, kind: StringName, entrySide: int) -> String: + return "%d/%s/%d" % [openings, kind, entrySide] diff --git a/Levels/Maze/maze_tiles.gd.uid b/Levels/Maze/maze_tiles.gd.uid new file mode 100644 index 0000000..1533a5c --- /dev/null +++ b/Levels/Maze/maze_tiles.gd.uid @@ -0,0 +1 @@ +uid://bs83p4ifap33y diff --git a/Levels/Maze/maze_validator.gd b/Levels/Maze/maze_validator.gd new file mode 100644 index 0000000..0ac3fc3 --- /dev/null +++ b/Levels/Maze/maze_validator.gd @@ -0,0 +1,171 @@ +class_name MazeValidator +extends RefCounted + +# Checks a finished maze for soft-locks, from its tiles alone (it doesn't trust +# MazeGraph or MazeCarver). See docs/MAZE.md. +# +# The slime crawls on floors, walls and ceilings and round corners, so inside a +# plain rectangle of air it can get to every tile side, and so to every tube +# mouth. That makes each chamber (a connected patch of air) one node; tubes +# are the only ways between them: +# - Ordinary and one-way tubes: in at any mouth the player could go in by +# (OneWayTube.can_enter), traced to their other end with the same +# PixelStream.trace_tube the player uses. +# - Manual and goo tubes: in at any mouth, out at any mouth of the same network. +# A mouth only leads somewhere if there's air in front of it. +# +# The maze passes if End can be reached from Start, and End can still be +# reached from every chamber that can be reached from Start. + +var isValid := false +var problem := "" # Why it failed. +var chamberCount := 0 +var reachableCount := 0 # Chambers reachable from Start. +var mouthCount := 0 + +var _layer: TileMapLayer +var _bounds: Rect2i +var _chamberAt := {} # Air tile -> chamber index. +var _links: Array[Dictionary] = [] # Per chamber: chamber -> true for each one a tube leads to. + + +func _init(layer: TileMapLayer, bounds: Rect2i, startCell: Vector2i, endCell: Vector2i) -> void: + _layer = layer + _bounds = bounds + if not _find_chambers(): + return + if not _chamberAt.has(startCell) or not _chamberAt.has(endCell): + problem = "Start or End is not in the air" + return + _find_links() + var reachable := _search(_chamberAt[startCell], false) + var canFinish := _search(_chamberAt[endCell], true) + reachableCount = reachable.size() + if not reachable.has(_chamberAt[endCell]): + problem = "End can't be reached from Start" + return + for chamber: int in reachable: + if not canFinish.has(chamber): + problem = "Soft-lock: chamber %d is reachable but End isn't reachable from it" % chamber + return + isValid = true + + +# Groups the air into chambers. False if air leaks out of the maze or a +# chamber isn't a plain rectangle (the movement model above needs that). +func _find_chambers() -> bool: + for y in range(_bounds.position.y, _bounds.end.y): + for x in range(_bounds.position.x, _bounds.end.x): + var cell := Vector2i(x, y) + if _is_air(cell) and not _chamberAt.has(cell): + if not _flood_chamber(cell, chamberCount): + return false + chamberCount += 1 + _links.append({}) + return true + + +func _flood_chamber(first: Vector2i, chamber: int) -> bool: + var cells: Array[Vector2i] = [first] + _chamberAt[first] = chamber + var low := first + var high := first + var index := 0 + while index < cells.size(): + var cell := cells[index] + index += 1 + low = low.min(cell) + high = high.max(cell) + for direction in TubeSteer.DIRECTIONS: + var next := cell + direction + if not _is_air(next) or _chamberAt.has(next): + continue + if not _bounds.has_point(next): + problem = "Air leaks out of the maze at %s" % next + return false + _chamberAt[next] = chamber + cells.append(next) + var size := high - low + Vector2i.ONE + if size.x * size.y != cells.size(): + problem = "Chamber %d is not a rectangle" % chamber + return false + return true + + +func _is_air(cell: Vector2i) -> bool: + return _layer.get_cell_source_id(cell) == -1 + + +# Every tube mouth (a tube tile side open onto air) and where going in there +# can take the slime. +func _find_links() -> void: + for cell: Vector2i in _layer.get_used_cells(): + var openings := TubeSteer.get_openings(_layer, cell) + if openings == 0: + continue + for outward in TubeSteer.DIRECTIONS: + if openings & TubeSteer.side_bit(outward) == 0 or not _chamberAt.has(cell + outward): + continue + mouthCount += 1 + var from: int = _chamberAt[cell + outward] + for to in _exits(cell, -outward): + _links[from][to] = true + + +# The chambers the slime can come out in after going into `cell` heading `direction`. +func _exits(cell: Vector2i, direction: Vector2i) -> Array[int]: + var exits: Array[int] = [] + if TubeSteer.is_manual(_layer, cell) or TubeGoo.is_goo(_layer, cell): + for mouth in _network_mouths(cell): + exits.append(_chamberAt[mouth]) + return exits + if not OneWayTube.can_enter(_layer, cell, direction): + return exits + var path := PixelStream.trace_tube(_layer, cell, direction) + if path.size() < 2: + return exits + var exitMouth := path[path.size() - 1] + var outward := (exitMouth - path[path.size() - 2]).normalized() + var halfTile := Vector2(_layer.tile_set.tile_size) / 2.0 + var exitCell := _layer.local_to_map(_layer.to_local(exitMouth + outward * halfTile)) + if _chamberAt.has(exitCell): + exits.append(_chamberAt[exitCell]) + return exits + + +# The air tiles in front of every mouth of the steered tube network `cell` is +# in (joined the way TubeSteer and TubeGoo join tiles: same kind, both open). +func _network_mouths(first: Vector2i) -> Array[Vector2i]: + var isGoo := TubeGoo.is_goo(_layer, first) + var seen := {first: true} + var toVisit: Array[Vector2i] = [first] + var mouths: Array[Vector2i] = [] + while not toVisit.is_empty(): + var cell: Vector2i = toVisit.pop_back() + var openings := TubeSteer.get_openings(_layer, cell) + for direction in TubeSteer.DIRECTIONS: + if openings & TubeSteer.side_bit(direction) == 0: + continue + var next := cell + direction + if _chamberAt.has(next): + mouths.append(next) + continue + var isSameKind := TubeGoo.is_goo(_layer, next) if isGoo else TubeSteer.is_manual(_layer, next) + if isSameKind and TubeSteer.get_openings(_layer, next) & TubeSteer.side_bit(-direction) and not seen.has(next): + seen[next] = true + toVisit.append(next) + return mouths + + +# Chambers reachable from `from` (or, if `isBackward`, that can reach it). +func _search(from: int, isBackward: bool) -> Dictionary: + var found := {from: true} + var queue: Array[int] = [from] + while not queue.is_empty(): + var chamber: int = queue.pop_front() + for other in chamberCount: + var isLinked: bool = _links[other].has(chamber) if isBackward else _links[chamber].has(other) + if isLinked and not found.has(other): + found[other] = true + queue.append(other) + return found diff --git a/Levels/Maze/maze_validator.gd.uid b/Levels/Maze/maze_validator.gd.uid new file mode 100644 index 0000000..4358b49 --- /dev/null +++ b/Levels/Maze/maze_validator.gd.uid @@ -0,0 +1 @@ +uid://h4jrviq4iob1 diff --git a/Levels/Maze/maze_win_menu.gd b/Levels/Maze/maze_win_menu.gd new file mode 100644 index 0000000..3f6e264 --- /dev/null +++ b/Levels/Maze/maze_win_menu.gd @@ -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) diff --git a/Levels/Maze/maze_win_menu.gd.uid b/Levels/Maze/maze_win_menu.gd.uid new file mode 100644 index 0000000..a1319b6 --- /dev/null +++ b/Levels/Maze/maze_win_menu.gd.uid @@ -0,0 +1 @@ +uid://ci7k8243ofmh0 diff --git a/Levels/Maze/maze_win_menu.tscn b/Levels/Maze/maze_win_menu.tscn new file mode 100644 index 0000000..94573fd --- /dev/null +++ b/Levels/Maze/maze_win_menu.tscn @@ -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"] diff --git a/UI/main_menu.gd b/UI/main_menu.gd index 9f8cd40..ebfae44 100755 --- a/UI/main_menu.gd +++ b/UI/main_menu.gd @@ -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() diff --git a/UI/main_menu.tscn b/UI/main_menu.tscn index 108f25e..68f10b7 100755 --- a/UI/main_menu.tscn +++ b/UI/main_menu.tscn @@ -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"] diff --git a/UI/maze_setup_menu.gd b/UI/maze_setup_menu.gd new file mode 100644 index 0000000..596e9a9 --- /dev/null +++ b/UI/maze_setup_menu.gd @@ -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() diff --git a/UI/maze_setup_menu.gd.uid b/UI/maze_setup_menu.gd.uid new file mode 100644 index 0000000..1ee394f --- /dev/null +++ b/UI/maze_setup_menu.gd.uid @@ -0,0 +1 @@ +uid://b27nx62tb7qa0 diff --git a/UI/maze_setup_menu.tscn b/UI/maze_setup_menu.tscn new file mode 100644 index 0000000..49b9974 --- /dev/null +++ b/UI/maze_setup_menu.tscn @@ -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"] diff --git a/docs/COMPONENTS.md b/docs/COMPONENTS.md new file mode 100644 index 0000000..37ecb0d --- /dev/null +++ b/docs/COMPONENTS.md @@ -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`), goo (`TubeGoo`), one-way (`OneWayTube`, an auto tube with one entrance). +- Tube effects (`Effects/tube_vacuum.gd`): visual effects tied to tube tiles, such as motes drifting into one-way entrances. +- Room camera (`Levels/room_camera.gd`): screen-by-screen camera that cuts between 640x480 rooms. +- Maze generation (`Levels/Maze/`): builds, validates and plays random tube mazes (see `docs/MAZE.md`). +- 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. diff --git a/docs/MAZE.md b/docs/MAZE.md new file mode 100644 index 0000000..9a4a1dc --- /dev/null +++ b/docs/MAZE.md @@ -0,0 +1,138 @@ +# Maze mode + +A "Maze" button on the main menu asks for a size and a complexity, then +generates a level of rock chambers joined by tubes, with a Start and an End. + +## Goals (checkable) + +1. Main menu has a **Maze** button. It opens a setup panel (same look as + Options) with **Width** (1-4 screens), **Height** (1-3 screens) and + **Complexity** (1-5), plus **Generate** and **Back**. +2. Generate builds a maze level from those inputs and a random seed. The + same inputs and seed always give the same maze. +3. The maze spans `Width x Height` screens (one screen = 20 x 15 tiles, the + RoomCamera's room). Chambers sit inside screens; tubes run through the rock + inside a screen and across screen borders. +4. It uses the existing tube kinds (auto, manual, goo) and a new **one-way** + kind. +5. One-way tubes: orange tiles; only their entrance mouth lets the slime in; + orange motes drift into the entrance like a vacuum. Built by extending the + existing tube code (the auto tube's `PixelStream`), not by copying it. +6. Start and End are clearly visible (a green START pad, a gold END pad). + Touching End shows a win panel with **New maze** and **Main menu**. +7. **No soft-locks.** For every chamber the slime can reach from Start, End is + still reachable. Checked on the finished tiles by a validator that does not + trust the generator; a failed maze is thrown away and the next seed tried. +8. A headless check generates many mazes (all sizes, complexities, many seeds) + and runs the validator on each. Target: 100 % pass on the first try. + +What the inputs control: + +| Complexity | Chambers per screen | One-way tubes on the Start-End route | Extra tubes (per screen) | Steered (manual/goo) share | Tube winding | +|---|---|---|---|---|---| +| 1 | 2 x 1 | 0 | 0 | 0 % | low | +| 2 | 2 x 2 | 1 | 0.5 | 20 % | low | +| 3 | 2 x 2 | 2 | 1 | 30 % | medium | +| 4 | 3 x 2 | 3 | 1.5 | 35 % | high | +| 5 | 3 x 2 | 4 | 2 | 40 % | high | + +Extra tubes are about half one-way (traps/shortcuts), half two-way (loops). + +## Non-goals + +- No change to player movement, existing levels or other menus (besides the + one button). The player only gains the "one-way tubes only let you in at + their entrance" rule, which is part of the new tube kind. +- No tube crossings or branching tube networks in mazes. +- No ledges, hazards, items or enemies inside chambers: chambers are plain + rectangles (this is what keeps the movement model below exact). +- No saving of mazes; the seed is not shown in the UI. + +## How the player moves (the model the check uses) + +From `Characters/player.gd`: the slime crawls on floors, walls and ceilings, +wraps round outside corners and takes inside corners. So inside one closed +rectangle of air it can reach every spot on the rectangle's boundary, and so +every tube mouth in it. Chambers are therefore nodes of a graph, and the only +ways between them are tubes: + +- **Auto** tube (green): either end in, traced to the other end + (`PixelStream.trace_tube`, the same function the player uses). Edge both ways. +- **One-way** tube (orange): an auto tube that only accepts the slime at the + mouth whose tile is marked as the entrance (`OneWayTube.can_enter`, also used + by the player). Edge from the entrance chamber to the exit chamber only. +- **Manual / goo** tubes (grey / pink): steered; the slime can come out + of any mouth with room or back out. Edges between all their mouths' chambers. +- A mouth only counts as an exit if the tile in front of it is air (room for + the slime to reform). + +## The soft-lock check (`MazeValidator`) + +Works only from the TileMapLayer: + +1. Flood-fill the air cells inside the maze into chambers. Fail if air leaks + out of the maze bounds or a chamber is not a full rectangle (the movement + model above would not hold). +2. Find every tube mouth (a tube tile side that is open onto air). +3. Build a directed chamber graph from the tube rules above. +4. **Forward** search from the Start chamber gives `reachable`. **Backward** + search (reversed edges) from the End chamber gives `canFinish`. +5. Pass if End is in `reachable` and every chamber in `reachable` is also in + `canFinish`. That is the no-soft-lock rule; "Start reaches End" alone is not + enough, because a one-way tube could drop the slime where End is out of reach. + +## Approaches considered + +1. **Chamber graph first, then carve tiles (chosen).** Lay out a grid of + rectangular chambers, build a spanning tree over neighbouring chambers + (a classic maze), pick Start and End, root the tree at End, make some tree + edges on the Start-End route one-way towards End, and add extra tubes. Then + carve: rock everywhere, air chambers, each tube routed through the rock with + `AStarGrid2D` and random weights so tubes wind. + *Safe by construction:* with the tree rooted at End and every tree edge + usable towards End, every chamber can reach End, so any extra tube in any + direction is safe. The validator then checks the real tiles anyway. +2. **Tile-level random level + search.** Random caves and random tubes, then + a search over the player's moves at tile level, keep if it passes. Simple to + write but most tries fail, with no control over difficulty; the per-tile + movement search is also a big, fragile copy of `player.gd`. +3. **Template rooms stitched together.** Hand-made screens with tube stubs at + the edges, joined like jigsaw pieces. Looks good, but needs many hand-made + rooms, gives little variety per size, and one-way placement still needs the + same graph reasoning as approach 1. +4. **Graph with a solver-guided one-way search.** Start from a strongly + connected graph and keep adding one-way tubes while a solver says it is + still safe. Works, but is slower and less predictable than approach 1, which + gets the same safety for free from the rooted tree. + +Approach 1 meets every goal: inputs map directly to grid size and edge counts, +chambers stay plain rectangles (so the movement model is exact), tubes cross +screens naturally, and safety does not depend on luck. + +## Files + +- `UI/maze_setup_menu.*` - the size/complexity panel. +- `Levels/Maze/maze_settings.gd` - the chosen inputs (static, read by the level). +- `Levels/Maze/maze_graph.gd` - chambers, spanning tree, one-way and extra tubes. +- `Levels/Maze/maze_carver.gd` - turns the graph into tiles, routes tubes. +- `Levels/Maze/maze_tiles.gd` - finds the right tile for a tube shape and kind. +- `Levels/Maze/maze_validator.gd` - the soft-lock check. +- `Levels/Maze/maze_builder.gd` - graph, carve, check; next seed on failure. +- `Levels/Maze/maze_level.*` - the playable scene: generate, validate, place. +- `Levels/Maze/maze_marker.gd` - the Start and End pads. +- `Levels/Maze/maze_win_menu.*` - the win panel. +- `Effects/one_way_tube.gd` - one-way tube rules (entrance check). +- `Effects/pixel_stream.gd` - `trace_tube()`, moved here from `player.gd` so + the player and the validator share it. +- `Assets/level_tiles.tres` - orange alternatives 3-5 on the six two-sided + tube tiles (3 = body/exit, 4 and 5 = entrance on each side), and the + `tube_one_way` / `tube_one_way_entry` custom data layers. +- `Effects/tube_vacuum.gd` - the orange motes drifting into entrances. +- `tests/maze_check.gd` - the headless batch check. + +Run the check: +`godot --headless --audio-driver Dummy --script res://tests/maze_check.gd` + +The check also builds one known soft-lock (a chamber whose tubes are all +turned into one-way tubes leading in, while Start still reaches End another +way) and makes sure the validator rejects it. diff --git a/tests/maze_check.gd b/tests/maze_check.gd new file mode 100644 index 0000000..4c187d8 --- /dev/null +++ b/tests/maze_check.gd @@ -0,0 +1,121 @@ +extends SceneTree + +# Headless batch check for Maze mode: builds many mazes (every size and +# complexity, several seeds) and runs the soft-lock check on each. +# godot --headless --audio-driver Dummy --script res://tests/maze_check.gd +# Also checks the validator catches a soft-lock, by turning one tube of a good +# maze into a one-way trap. + +const SEEDS_PER_SETTING = 6 +const TILE_SET = preload("res://Assets/level_tiles.tres") + + +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): + 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("Mazes: %d, valid: %d, valid on the first try: %d (%d ms)" + % [mazeCount, validCount, firstTryCount, Time.get_ticks_msec() - startTime]) + + var caught := _check_trap_is_caught(layer) + print("Validator catches a one-way trap: %s" % ("yes" if caught else "NO")) + quit(0 if validCount == mazeCount and caught else 1) + + +# A real soft-lock: in a good maze, take a tube from Start's chamber to some +# chamber X (not End's), and turn every tube with a mouth in X into a one-way +# tube that only leads into X. X is then reachable from Start but has no way +# out. Tries mazes until Start can still reach End some other way, so a plain +# "Start reaches End" check would pass. The validator must reject it as a +# soft-lock. +func _check_trap_is_caught(layer: TileMapLayer) -> bool: + for trapSeed in range(4242, 4282): + var builder := MazeBuilder.new(layer, Vector2i(2, 2), 3, trapSeed) + if not builder.isValid or not _set_trap(layer, builder.carver): + continue + var validator := MazeValidator.new(layer, builder.carver.bounds, builder.carver.startCell, builder.carver.endCell) + if validator.problem.begins_with("Soft-lock"): + print(" trap test (seed %d): %s" % [trapSeed, validator.problem]) + return true + if validator.isValid: + return false # Missed a real trap. + return false + + +# Turns the first chamber a tube from Start leads to (not End's) into a trap. +func _set_trap(layer: TileMapLayer, carver: MazeCarver) -> bool: + var startRect := _rect_with(carver, carver.startCell) + var endRect := _rect_with(carver, carver.endCell) + var trapRect := Rect2i() + for mouth in _mouths_of(layer, startRect): + var tube := _follow_tube(layer, mouth.cell, mouth.outward) + var farRect := _rect_with(carver, tube.cells.back() + tube.farOutward) + if farRect != endRect and farRect != startRect: + trapRect = farRect + break + if trapRect.size == Vector2i.ZERO: + return false + var tiles := MazeTiles.new(layer.tile_set) + for mouth in _mouths_of(layer, trapRect): + var tube := _follow_tube(layer, mouth.cell, mouth.outward) + var cells: Array[Vector2i] = tube.cells + for i in cells.size(): + var cell := cells[i] + var isEntrance := i == cells.size() - 1 + var entrySide := TubeSteer.side_bit(tube.farOutward) if isEntrance else 0 + tiles.set_tile(layer, cell, TubeSteer.get_openings(layer, cell), MazeGraph.ONE_WAY, entrySide) + return true + + +func _rect_with(carver: MazeCarver, cell: Vector2i) -> Rect2i: + for rect in carver.chamberRects: + if rect.has_point(cell): + return rect + return Rect2i() + + +# Tube mouths opening into `rect`: [{cell, outward}]. +func _mouths_of(layer: TileMapLayer, rect: Rect2i) -> Array[Dictionary]: + var mouths: Array[Dictionary] = [] + for cell in layer.get_used_cells(): + for outward in TubeSteer.DIRECTIONS: + if TubeSteer.get_openings(layer, cell) & TubeSteer.side_bit(outward) and rect.has_point(cell + outward): + mouths.append({cell = cell, outward = outward}) + return mouths + + +# Walks a maze tube (a simple chain of tiles) from the mouth at `cell` to its +# other end: {cells: from `cell` on, farOutward: which way the far mouth opens}. +func _follow_tube(layer: TileMapLayer, cell: Vector2i, outward: Vector2i) -> Dictionary: + var cells: Array[Vector2i] = [cell] + var back := outward + while true: + var openings := TubeSteer.get_openings(layer, cells.back()) + var ahead := Vector2i.ZERO + for direction in TubeSteer.DIRECTIONS: + if direction != back and openings & TubeSteer.side_bit(direction): + ahead = direction + var next: Vector2i = cells.back() + ahead + if layer.get_cell_source_id(next) == -1: + return {cells = cells, farOutward = ahead} + cells.append(next) + back = -ahead + return {} diff --git a/tests/maze_check.gd.uid b/tests/maze_check.gd.uid new file mode 100644 index 0000000..302d27c --- /dev/null +++ b/tests/maze_check.gd.uid @@ -0,0 +1 @@ +uid://cafvd1fo6x1xh