Nordax Nordax - 8 days ago 8
HTML Question

How to reveal empty cells in a minesweeper game?

I've been working on programming a minesweeper game using javascript/jquery. I can't seem to get the empty cell revealed. My algorithm was to reveal 8 adjacents of the clicked empty cell. When i click on the div, I get clicked 8 times in console and it messes up the adjElements values. Any help how to make it work?

Here what i've done so far.

//my divs are generated with a function from id '#s-1' to '#s-81'
var adj=[-10,-9,-8,-1,1,8,9,10];

$('.grid').find('div').click(function(event) {

var div=this.id;
var numDiv=div.replace( /[^\d.]/g, '' );
revealSquare(numDiv);
});


var revealSquare=function(square) {

if(!($(square).hasClass('isMine'))) {

if($(square).find('span').text()=='') {

revealEmptyCells(square);

}
}


};


var revealEmptyCells=function(clickDiv) {

$.each(adj, function(index, val) {

if(val+clickDiv>0 && val+clickDiv<=81) {

var adjElements=val+clickDiv;
console.log('adj: '+adjElements); //it reveals odd numbers like for div #s-1 it reveals 19
$('#s-'+adjElements).css({
border: '4px solid #d4d4d3',
});
}

});
}


Assuming that the clicked div is empty, and I removed the val+clickDiv>0 and val+clickDiv<=81; If I click on div s-1, the adj elements are -101,-91,-81,-11,11,81,91,101. Why do I get these values?

Answer

When you perform the + operation, and one of the operands is a string, then the result will not be the mathematical sum, but the concatenation of the two:

In your case the following is not a number, but a string:

div.replace( /[^\d.]/g, '' )

To solve this, just add the unitary + before it:

+div.replace( /[^\d.]/g, '' )

Now numDiv will be a number and will have the desired effect in an addition.