minesweeper
minesweeper copied to clipboard
Off by one error on app.js, line 54 & 152
The code-block containing the line 152 is as follows:
if (currentId < 89) {
const newId = squares[parseInt(currentId) +width].id
//const newId = parseInt(currentId) +width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
As it stands, if we were to click square #89, then the very last square in the grid, #99, would not be run through the click function.
We should instead check for currentId < 90
to avoid this off by one error:
if (currentId < 90) {
const newId = squares[parseInt(currentId) +width].id
//const newId = parseInt(currentId) +width ....refactor
const newSquare = document.getElementById(newId)
click(newSquare)
}
After fixing this, we also have to change line 54:
if (i < 89 && squares[i +width].classList.contains('bomb')) total ++
We likewise should add 1 to the amount we are checking:
if (i < 90 && squares[i +width].classList.contains('bomb')) total ++
I think this is the reason why you'd get into this situation (please see the picture attached). Anyway, great code. I am a newbie and I enjoy your educational videos on YT.
OK, I went through the checks and I think it should be as the following:
if (i > 0 && !isLeftEdge && squares[i -1].classList.contains('bomb')) total ++
if (i > 9 && !isRightEdge && squares[i +1 -width].classList.contains('bomb')) total ++
if (i > 9 && squares[i - width].classList.contains('bomb')) total ++
if (i > 10 && !isLeftEdge && squares[i -1 -width].classList.contains('bomb')) total++
if (i < 99 && !isRightEdge && squares[i +1].classList.contains('bomb')) total++
if (i < 90 && !isLeftEdge && squares[i -1 +width].classList.contains('bomb')) total++
if (i < 89 && !isRightEdge && squares[i +1 +width].classList.contains('bomb')) total++
if (i < 90 && squares[i +width].classList.contains('bomb')) total++
if(squares[i].classList.contains('valid')){
// left bomb
if(i > 0 && !isLeftEdge && squares[i-1].classList.contains('bomb')) total++
// top-right #10
if(i > 9 && !isRightEdge && squares[i+1-width].classList.contains('bomb')) total++
// top
if (i >= 10 && squares[i-width].classList.contains('bomb')) total ++
// top-left
if (i >= 11 && !isLeftEdge && squares[i-1-width].classList.contains('bomb')) total ++
// right
if (i <= 98 && !isRightEdge && squares[i+1].classList.contains('bomb')) total ++
// bottom-left
if (i < 90 && !isLeftEdge && squares[i-1+width].classList.contains('bomb')) total ++
// bottom-right
if (i <= 88 && !isRightEdge && squares[i+1+width].classList.contains('bomb')) total ++
// bottom
if (i <= 89 && squares[i+width].classList.contains('bomb')) total ++
squares[i].setAttribute('data', total)
}