extends Node3D

var start_scene = preload("res://start.tscn")
var finish_scene = preload("res://finish.tscn")
var floor_model = preload("res://floor_model.tscn")
var wall_model = preload("res://wall_model.tscn")
var player_scene = preload("res://player.tscn")  # Загрузка сцены игрока

var grid_size = Vector3(2, 0, 2)
var maze_width = 10
var maze_depth = 10
var min_distance = 10  # Минимальное расстояние между стартом и финишем

func _ready():
        randomize()
        Engine.max_fps = 75
        var start_pos
        var finish_pos
        
        while true:
                start_pos = Vector3(randi() % maze_width, 0, randi() % maze_depth)
                finish_pos = Vector3(randi() % maze_width, 0, randi() % maze_depth)
                
                # Проверяем, что расстояние больше или равно min_distance
                if start_pos.distance_to(finish_pos) >= min_distance:
                        break
        
        var maze = generate_maze(start_pos, finish_pos)
        
        # Создаем старт и финиш
        var start_instance = start_scene.instantiate()
        start_instance.position = start_pos * grid_size
        add_child(start_instance)
        
        var finish_instance = finish_scene.instantiate()
        finish_instance.position = finish_pos * grid_size
        add_child(finish_instance)
        
        # Создаем пол под финишем, если его нет
        if maze[int(finish_pos.z)][int(finish_pos.x)] == 0:
                var finish_floor_instance = floor_model.instantiate()
                finish_floor_instance.position = Vector3(finish_pos.x, 0, finish_pos.z) * grid_size
                add_child(finish_floor_instance)
                maze[int(finish_pos.z)][int(finish_pos.x)] = 1  # Помечаем, что пол есть
        
        # Создаем экземпляр игрока на стартовой позиции
        var player_instance = player_scene.instantiate()
        player_instance.position = Vector3(start_pos.x * grid_size.x, 1.0, start_pos.z * grid_size.z)  # Устанавливаем позицию игрока с высотой 1.5
        add_child(player_instance)

        # Создаем пол лабиринта и стены
        for z in range(maze_depth):
                for x in range(maze_width):
                        if maze[z][x] == 1:
                                var floor_instance = floor_model.instantiate()
                                floor_instance.position = Vector3(x, 0, z) * grid_size
                                add_child(floor_instance)

                                # Проверяем и создаем стены
                                create_walls(x, z, maze)

func generate_maze(start, end):
        var maze = []
        for z in range(maze_depth):
                maze.append([])
                for x in range(maze_width):
                        maze[z].append(0)

        var current = start
        var path = [current]
        maze[int(current.z)][int(current.x)] = 1

        while current != end:
                var directions = [Vector3.RIGHT, Vector3.LEFT, Vector3.FORWARD, Vector3.BACK]
                directions.shuffle()

                var moved = false
                for dir in directions:
                        var next_pos = current + dir
                        if next_pos.x >= 0 && next_pos.x < maze_width && next_pos.z >= 0 && next_pos.z < maze_depth:
                                if maze[int(next_pos.z)][int(next_pos.x)] == 0:
                                        # Проверяем количество соседних клеток
                                        if count_neighbors(maze, next_pos) < 3:  # Ограничиваем количество соседей
                                                current = next_pos
                                                maze[int(current.z)][int(current.x)] = 1
                                                path.append(current)
                                                moved = true
                                                break

                if not moved:
                        if path.size() > 0:
                                current = path.pop_back()
                        else:
                                break

        return maze

func count_neighbors(maze: Array, pos: Vector3) -> int:
        var count = 0
        var directions = [Vector3.RIGHT, Vector3.LEFT, Vector3.FORWARD, Vector3.BACK]

        for dir in directions:
                var neighbor_pos = pos + dir
                if neighbor_pos.x >= 0 && neighbor_pos.x < maze_width && neighbor_pos.z >= 0 && neighbor_pos.z < maze_depth:
                        if maze[int(neighbor_pos.z)][int(neighbor_pos.x)] == 1:
                                count += 1

        return count

func create_walls(x: int, z: int, maze: Array):
        # Проверяем наличие стен вокруг текущей клетки (x, z)
        
        # Проверка на стену слева
        if x == 0 || (maze[z][x - 1] == 0 && maze[z][x] == 1):
                create_wall(Vector3(x - 0.5, 0.5, z) * grid_size, Vector3(0, deg_to_rad(90), 0))

        # Проверка на стену справа
        if x == maze_width - 1 || (x + 1 < maze_width && maze[z][x + 1] == 0 && maze[z][x] == 1):
                create_wall(Vector3(x + 0.5, 0.5, z) * grid_size, Vector3(0, deg_to_rad(90), 0))

        # Проверка на стену впереди
        if z == maze_depth - 1 || (z + 1 < maze_depth && maze[z + 1][x] == 0 && maze[z][x] == 1):
                create_wall(Vector3(x, 0.5, z + 0.5) * grid_size, Vector3(0, deg_to_rad(0), 0))

        # Проверка на стену сзади
        if z == 0 || (maze[z - 1][x] == 0 && maze[z][x] == 1):
                create_wall(Vector3(x, 0.5, z - 0.5) * grid_size, Vector3(0, deg_to_rad(0), 0))

func create_wall(position: Vector3, rotation: Vector3):
        var wall_instance = wall_model.instantiate()
        wall_instance.position = position
        wall_instance.rotation = rotation
        add_child(wall_instance)
оптимизируй код