maze-generator-assets-lib/generator.gd
2025-02-28 23:05:41 +01:00

56 lines
1.5 KiB
GDScript

extends Sprite2D
var maze_pos = Vector2i(0, 0) # start position for the generator
var dir_history = []
var directions = [Vector2i.UP, Vector2i.RIGHT, Vector2i.DOWN, Vector2i.LEFT]
var tile_n = Vector2i(0, 0) # no visited # dark blue
var tile_v = Vector2i(0, 1) # visited # light blue
var tile_s = Vector2i(1, 1) # visited and stuck # blue
signal done
@onready var Maze = $"../maze"
func _ready() -> void:
Maze.set_cell(maze_pos,0,tile_v) # set first cell as visited
func get_neighbors():
"get surrounding not visited neighbors"
var dlist = []
for dir in directions:
var next_pos = maze_pos + dir * 2
if $"../maze".get_cell_atlas_coords(next_pos) == tile_n:
dlist.append(dir)
print(dlist)
return dlist
func _process(delta: float) -> void:
var dlist = get_neighbors() # possible directions list
if dlist.is_empty():
if dir_history.is_empty():
print("Maze generation completed")
done.emit()
set_process(false)
return
# remove current cell in history if stuck and go back
var removed_item = dir_history.pop_back()
$"../maze".set_cell(maze_pos-removed_item, 0, tile_s)
$"../maze".set_cell(maze_pos, 0, tile_s)
maze_pos = maze_pos - removed_item*2
else:
# 2.1 pick random neighbar
var dir = dlist.pick_random()
# remove walls between the cells
$"../maze".set_cell(maze_pos + dir, 0, tile_v)
# add direction to history
dir_history.append(dir)
# set new cell
maze_pos += dir * 2
$"../maze".set_cell(maze_pos, 0, tile_v)
position = 16 * maze_pos+Vector2i(1, 1) # just set sprite position