我的Lua迷宫生成器,它是编织的。

我正在编写一个 Lua 脚本,使用堆栈实现了递归回溯(Recursive Backtracker)算法来生成迷宫。目前迷宫生成时出现了交叉,我无法找出逻辑上的问题所在。下面的函数将 x 和 y 作为起点输入,生成一个二维结构的迷宫(由表格组成的表格):

local function buildMazeInternal(x,y,maze)

    local stack = {}
    local directions = {'North','East','South','West'}

    table.insert(stack,{x=x,y=y})

    while #stack > 0 do
        local index = 1
        local nextX = x
        local nextY = y
        local braid = false

        for i = #directions, 2, -1 do -- backwards
            local r = calc:Roll(1,i) -- 在 1 和 i 之间选择一个随机数
            directions[i], directions[r] = directions[r], directions[i] -- 将随机选择的项目与位置 i 交换
        end

        while index <= #directions and nextX == x and nextY == y do
            if directions[index] == 'North' and y > 1 and not maze[y-1][x].Visited then
                maze[y][x].North = true
                maze[y-1][x].South = true
                nextY = y-1
            elseif directions[index] == 'East' and x < width and not maze[y][x+1].Visited then
                maze[y][x].East = true
                maze[y][x+1].West = true
                nextX = x+1
            elseif directions[index] == 'South' and y < height and not maze[y+1][x].Visited then
                maze[y][x].South = true
                maze[y+1][x].North = true
                nextY = y+1
            elseif directions[index] == 'West' and x > 1 and not maze[y][x-1].Visited then
                maze[y][x].West = true
                maze[y][x-1].East = true
                nextX = x-1
            else
                index = index + 1
            end
        end

        if nextX ~= x or nextY ~= y then
            x = nextX
            y = nextY
            maze[y][x].Visited = true
            table.insert(stack,{x=x,y=y})
        else
            x = stack[#stack].x
            y = stack[#stack].y
            table.remove(stack)
        end
    end
end

我知道我漏掉了什么,但我似乎找不到问题。请注意,calc:Roll(1,100) 方法是我应用程序中的 .net 方法,用于模拟掷骰子,此处为投掷 1 个 100 面骰,它可以替换为调用 math.Random(1,100) 来在应用程序外使用。

点赞
用户312586
用户312586

我看到至少一个问题。当你想要“向上前进”时,你会检查“上面的单元格”是否已被访问,如果已经被访问,你将“跳过”向上前进。

在我看来,这并不正确。如果你想要向上前进,但是从当前单元格“上方”有一个被访问过但是有“向下”出口的单元格,你仍然应该可以向上前进(而不是因为它被访问过而跳过)。

其他方向也是一样的。

就这些。

2015-01-21 12:42:03
用户2733505
用户2733505

我在 Reddit 发帖后找到了答案。我没有将初始单元格标记为已访问,导致它可以被重复通过。更正方法是在 table.insert(stack,{x=x,y=y}) 之前立即添加 maze[y][x].Visited = true

2015-01-26 13:18:11