i wrote a minesweeper in JavaScript which was working fine for a while, and then randomly on 1 run (i was trying to improve the styling) it gave me this:
note the "1" in the upper-right corner as well as 2 missing 1's two and three spaces below it
here is my function for adding numbers to squares:
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;
}
}
my program works on using a table and each td has an id 0-99
Nice game. But you commit the common error of counting the last index. Do you see that your table have size of 11x11 = 121
? But in your program you use
var rowAmount = 10;
var columnAmount = 10;
cellAmount = columnAmount * rowAmount;
which is wrong. The for loop also explicitly assume there are 11 column:
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>";
}
but idValue
is using 10 column. It means that your program will ignore the last column. Change that in all your codes and you will be fine.