我正在尝试在网页中制作 ms 的空白或“0”功能。
目标:
在我的身上发生了什么:应该发生什么:
红色方 block 表示被点击的按钮,绿色圆圈表示其相邻的方 block /方 block 。
我实现此功能的方法或逻辑是:
- 第 1 步:如果单击的按钮是 0,则显示其相邻的图 block 。
- 第 2 步:对于每个相邻的图 block ,如果该图 block 为 0,则显示该图 block 的相邻图 block 。依此类推,直到显示每个连接的 0 的所有相邻图 block 。
我的函数的代码:(参数是被点击的按钮的坐标。例如上图中的红色方 block /瓦片坐标为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<2;j++){
cordsx = x;
cordsy = y;
if(i === 0 && j === 0){
continue;
}
else{
cordsx += j;
cordsy += i;
//if this ^ offset is within the grid:
if((cordsx >= 0 && cordsx < 10) && (cordsy >= 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("<p id='number'>"+coordinates.parent().attr("data-value")+"</p>");
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”属性是该图 block 附近的炸弹数量。 如果图 block 已显示,属性“data-revealed”为真,否则为假。两者都有作用,不用太担心。
每个磁贴按钮的代码:
$(".tiles").click(function(){
//if this button is clicked, reveal this tile
$(this).empty().append("<p id='number'>"+$(this).parent().attr("data-value")+"</p>");
$(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 循环应该针对被单击的图 block 的每个相邻图 block 运行,但是当它为第一个图 block 运行函数时,它忘记了所有其他相邻的瓷砖。我需要让函数在所有相邻的 0 block 上运行,并在所有相邻的 0 block 上运行,依此类推。
感谢您的帮助,这是一个很难解释的问题=/。我搜索了很多地方,但找不到答案。很抱歉这个很长很具体的问题。
最佳答案
我认为问题出在您的两个 for 循环上,它们使用名为 i 和 j 的全局变量,每次调用 RevealNearbyTiles() 时它们都是相同的。您可以使用以下代码修复此问题...
for(var i=-1; i<2; i++){ //for every adjacent tile:
for(var j=-1;j<2;j++){
我认为发生的事情是您的算法运行直到它遇到显示所有相邻图 block 的情况(例如 i = 1,j = 1),然后它退出带有这些值的调用链并退出每个循环而不是而不是继续执行它们。
关于javascript - 扫雷显示附近的瓷砖功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34459086/