Home > Enterprise >  how to fix the corner problem in a minesweeper?
how to fix the corner problem in a minesweeper?

Time:05-11

I'm coding the reveal function trying to use recursion but I have a problem, when the cycle runs at the corner it doesn't find any cell and returns an error, I've seen that this operator '?.' returns the value or undefined even if there is no value, but I cant figure how this operator could be included in my cycle

export function reveal(boardWithMines: CellEnum[][], boardWithOutMines: CellEnum[][], x: number, y: number) {  
    if (boardWithOutMines[x][y] === CellEnum.Hidden || boardWithMines[x][y] === CellEnum.Cero) {
        boardWithOutMines[x][y] = boardWithMines[x][y];
        for (let xOffset = -1; xOffset <= 1; xOffset  ) {
            for (let yOffset = -1; yOffset <= 1; yOffset  ) {
                reveal(boardWithMines, boardWithOutMines, x   xOffset, y   yOffset);
            }
        }
    }
}

This is the error that shows up in the console

CodePudding user response:

Check the bounds in the loops:

export function reveal(boardWithMines: CellEnum[][], boardWithOutMines: CellEnum[][], x: number, y: number) {  
    if (boardWithOutMines[x][y] === CellEnum.Hidden || boardWithMines[x][y] === CellEnum.Cero) {
        boardWithOutMines[x][y] = boardWithMines[x][y];
        for (let i = Math.max(0, x-1), iMax = Math.min(boardWithMines.length, x 2); i < iMax;   i) {
            for (let j = Math.max(0, y-1), jMax = Math.min(boardWithMines[i].length, y 2); j < jMax;   j) {
                reveal(boardWithMines, boardWithOutMines, i, j);
            }
        }
    }
}
  • Related