2013-08-18 42 views
4

我写了一个JavaScript扫雷艇这是随机1个运行工作正常了一会儿,然后(我正在试图改善造型),它给了我这样的:JavaScript的扫雷艇放置不必要的“1”

stupid 1 in upper right corner

注意“1”,在右上角还有2人失踪下方1的两个和三个空间

这里是我将这些数字相平方功能:

function nextToBombCheck(event) { 
    //reset bomb count 
bombCount = 0 ; 
    //initialize variable for checking nerby boxes 
var nextToBox = 0; 
    //asign the box's id as a number 
var boxNum = parseInt(event.id); 

var checkSide = 0; 

for (var i = 9 ; i <= 11 ; i++) { 
    nextToBox = boxNum + i; 
     //check if its a wrap 
    if ((nextToBox%10 === 0 && boxNum%10 === 9) || (nextToBox%10 === 9 && boxNum%10 === 0)) { 
     continue; 
     //check boxes below 
    } else if (bomb.indexOf(nextToBox) >= 0) { 
     bombCount++; 
    } 
} 

for (i = -1 ; i <= 1 ; i++) { 
    nextToBox = boxNum + i; 
     //check if its a wrap (above and below wont work anyway) 
    if ((nextToBox%10 === 0 && boxNum%10 === 9) || (nextToBox%10 === 9 && boxNum%10 === 0)) { 
     continue; 
     //check boxes alongside 
    } else if (bomb.indexOf(nextToBox) >= 0) { 
     bombCount++; 
    } 
} 

for (i = -11 ; i <= -9 ; i++) { 
    nextToBox = boxNum + i; 
    if ((nextToBox%10 === 0 && boxNum%10 === 9) || (nextToBox%10 === 9 && boxNum%10 === 0)) { 
     continue; 
     //check boxes above 
    } else if (bomb.indexOf(nextToBox) >= 0) { 
     bombCount++; 
    } 
} 
     //set class(colors) based on bombCount 
    event.className = classList[ bombCount ]; 
if (bombCount !== 0) { 
     //write number of neighboring bombs 
    event.innerHTML = bombCount; 
} 
} 

我的程序适用于使用一个表,每个TD都有一个id 0-99

heres a link if that helps

回答

2

好的游戏。但是你犯了计算最后一个索引的常见错误。你看到你的桌子的尺寸是11x11 = 121吗?但在你的程序中使用

var rowAmount = 10; 
var columnAmount = 10; 

cellAmount = columnAmount * rowAmount; 

这是错误的。 for循环还明确假定有11列:

for (i = 0 ; i <= rowAmount ; i++) { 
    gameBox += "<tr>"; 
    for (var j = 0 ; j <= columnAmount ; j++) { 
     var idValue = i * 10 + j; 
     gameBox += "<td class = 'box' id = '" + idValue + "' onclick = 'process(this);' ></td>"; } 
    gameBox += "</tr>"; 
} 

idValue正在使用10列。这意味着你的程序将忽略最后一列。改变你的所有代码,你会没事的。

+0

你的权利我最初写它是正确的,并且最近从在循环中放置10变为使用变量因为当我让用户可以编辑大小和搞砸了 –

1

我相信,你可以在截图中看到的问题是关系到具有相同ID的多个元素来自Chrome检查员。您可以注意到该行的最后一个单元格和下一行的第一个单元格具有相同的ID。对于所有行都是如此。

enter image description here

+0

它看起来像你的代码适用于有10个单元格的行,但是你在每行内有11个单元格 – haynar

+0

非常有帮助 –

0

而是使用模弄虚作假等,使用X和Y坐标,并具有以下功能:根据给定XY得到小区ID,即

function getCellId(x, y) { 
    return 'cell-' + x + '-' + y); 
} 

并命名您的小区ID的cell-0-0 - >cell-9-9

然后相邻小区是

(x - 1, y - 1) 
(x,  y - 1) 
(x + 1, y - 1) 
(x - 1, y ) 
(x + 1, y ) 
(x - 1, y + 1) 
(x,  y + 1) 
(x + 1, y + 1) 

这个问题可以有也可以AVO只要使用了这种方法即可。