微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试编写一个递归程序来显示所有相邻的空白图块

如何解决尝试编写一个递归程序来显示所有相邻的空白图块

我正在尝试克隆扫雷舰。在那个游戏中,有一个功能,当你点击一个空方块时,所有相邻的空牌都会被显示出来,并且与这些空牌相邻的空牌也会被显示出来。

现在,当我尝试实现此功能时,它仅显示我单击的图块的 8 个相邻图块,而不显示显示的空图块旁边的任何其他空图块

这是我现在正在运行的代码(它有 2 个参数 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,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   

解决方法

在您的算法中,您只检查了 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)]
    -- Try to reveal tile
    if not tile.revealed and tile.value == 1 then
      tile.revealed = true
      -- Try to reveal surroundings
      for r = row-16,row+16,16 do
        for c = col-16,col+16,16 do
          revealTile(r,c)
        end
      end
    end
  end
end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。