尝试编写一个递归程序,揭示所有相邻的空格

我正在尝试制作扫雷的克隆版本。在这个游戏中,有一个特性,每当你点击一个空框时,所有相邻的空格都会被揭示,并且相邻的那些空格也会被揭示。

现在,当我尝试实现这个功能时,它只会显示我点击的那个方块的8个相邻方块,而不显示其他相邻的空格。

这是我现在运行的代码(它有两个参数row和col):

local rowCords = {row-16, row, row+16}
local colCords = {col-16, col, col+16}

--Check surroundings
for r = 1, 3, 1 do
    for c = 1, 3, 1 do
        curRow = rowCords[r]
        curCol = colCords[c]

        if (curRow >= 16 and curRow <= 400 and curCol >= 16 and curCol <= 176) then
            if boardCords[Board:getBox(curRow, curCol)].value == 1 then
                boardCords[Board:getBox(curRow, curCol)].revealed = true
            end
        end
    end
end
点赞
用户12918181
用户12918181

在你的算法中你只检查了9个瓦片,但你必须对已检查的瓦片进行递归检查。因此,你的算法应该是这样的:

function revealTile(row, col)
  if (row >= 16 and row <= 400 and col >= 16 and col <= 176) then
    local tile = boardCords[Board:getBox(row, col)]
    -- 尝试揭示瓦片
    if not tile.revealed and tile.value == 1 then
      tile.revealed = true
      -- 尝试揭示周围的瓦片
      for r = row-16,row+16,16 do
        for c = col-16,col+16,16 do
          revealTile(r, c)
        end
      end
    end
  end
end
2021-03-05 18:00:43