扫雷显示附近的瓷砖function

我试图在网页中创建ms的空白或“0”function。

目标:

我的发生了什么: 会发生什么:

红色方块表示单击的按钮,绿色圆圈表示其相邻的正方形/平铺。

我做这个function的方法或逻辑是:

  • 步骤1:如果单击的按钮为0,则显示其相邻的切片。
  • 步骤2:对于每个相邻的图块,如果该图块为0,则显示该图块的相邻图块。 依此类推,直到显示每个连接的0的所有相邻图块。

我的函数的代码:(参数是点击的按钮的坐标。例如,上图中的红色方块/图块具有坐标3,6)

function RevealNearbyTiles(y,x){ var cordsx; //cordsx and cordsy represent the adjacent tiles of the coordinates (the parameters). var cordsy; var coordinates; for(i=-1; i<2; i++){ //for every adjacent tile: for(j=-1;j= 0 && cordsx = 0 && cordsy < 10)){ //the coordinates of the tile. coordinates = $("#mstable tr:nth-of-type("+(cordsy+1)+") td:nth-of-type("+(cordsx+1)+") .tiles"); //if it has not been revealed if(coordinates.parent().attr("data-revealed") === "false"){ //reveal this coordinate. coordinates.empty().append("

"+coordinates.parent().attr("data-value")+"

"); coordinates.parent().attr("data-revealed", "true"); //if this coordinate is 0 if(coordinates.parent().attr("data-value") === " "){ //reveal this coordiantes' nerabytiles RevealNearbyTiles(cordsy,cordsx); } } } } } } }

属性“data-value”是磁贴附近炸弹的数量。 如果显示图块,则“data-revealed”属性为true,否则为false。 他们都工作,不要太担心他们。

每个图块按钮的代码:

 $(".tiles").click(function(){ //if this button is clicked, reveal this tile $(this).empty().append("

"+$(this).parent().attr("data-value")+"

"); $(this).parent().attr("data-revealed","true"); //if this tile's value is 0, call the function if($(this).parent().attr("data-value") === " "){ RevealNearbyTiles($(this).parent().data("index").a,$(this).parent().data("index").b); } });

我认为问题是: for循环应该为单击的tile的每个相邻tile运行,但是当它运行第一个tile的函数时,它会忘记所有其他相邻tile。 我需要这样做,以便该函数在0的所有相邻图块上运行,并在所有相邻图块上运行0,依此类推。

感谢您的帮助,这是一个难以解释的问题= /。 我搜索了很多地方但找不到答案。 对不起,这是一个非常长的具体问题。

我认为问题在于你的两个for循环,他们使用名为i和j的全局变量,对于每次调用RevealNearbyTiles()都是相同的。 您可以使用以下代码解决此问题…

 for(var i=-1; i<2; i++){ //for every adjacent tile: for(var j=-1;j<2;j++){ 

我认为发生的事情是你的算法一直运行直到它发现它已经显示所有相邻的区块(例如i = 1,j = 1)的情况下,然后它用这些值退出调用链并退出每个循环而不是继续执行他们。