我用 JavaScript 写了一个扫雷器,它工作了一段时间,然后随机运行 1 次(我试图改进样式)它给了我这个:
请注意右上角的“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