lua - 我正在编织的 Lua 迷宫生成器

标签 lua maze

我正在构建一个 Lua 脚本,该脚本使用使用堆栈而不是递归实现的递归回溯器版本生成迷宫。目前迷宫正在编织,我似乎无法弄清楚这是在我的逻辑中发生的位置。下面的函数将 x 和 y 作为生成迷宫的起点,迷宫是 2d 结构(表格表):

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) -- select a random number between 1 and i
            directions[i], directions[r] = directions[r], directions[i] -- swap the randomly selected item to position 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) 的调用在我的应用程序之外使用。

最佳答案

我看到至少一个问题。当你去“想去”时,你检查“向上的单元格”是否被访问,如果是,你“跳过”向上。

恕我直言,这似乎不正确。如果你想向上,但从当前单元格“向上”的单元格被访问了 但有一个“向下”退出 ,您应该仍然可以向上(而不是因为它被访问而跳过)。

这同样适用于其他方向。

这就是我得到的。

关于lua - 我正在编织的 Lua 迷宫生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28052404/

相关文章:

c - 是否可以将结构存储到链表中?

lua - 为表分配变量

c# - 将图像转换为要绘制的线条数组

lua - 可以在 corona 中制作 zip 文件吗?

algorithm - 动态迷宫突变

python - python中不规则点之间的坐标列表

scope - Lua: "required"模块中的变量作用域是什么?

function - 我可以在 Lua shell 提示符下运行函数吗?

algorithm - 使用 Prim 算法实现随机生成的迷宫

c - 找出迷宫中某个案例的 x 和 y(在 C 中)