The Bomberman Game

  • + 0 comments

    JS

    function bomberMan(n, grid) {
        grid.forEach((row, index) => {
            grid[index] = [...row].map(cell => (cell == "O") ? 0 : null);
        });
        let clock = 2;
        n = (n > 2) ? (n % 4 + 4) : n;
        while (clock <= n) {
            grid.forEach((row, index) => {
                grid[index] = row.map(cell => (cell == null) ? clock : cell);
            });
            if (++clock <= n) {
                grid.forEach((row, rowIndex) => {
                    row.forEach((cell, cellIndex) => {
                        if (cell == clock - 3) {
                            if (rowIndex > 0 && grid[rowIndex - 1][cellIndex] != clock - 3) {
                                grid[rowIndex - 1][cellIndex] = null;
                            }
                            if (rowIndex < grid.length - 1 && grid[rowIndex + 1][cellIndex] != clock - 3) {
                                grid[rowIndex + 1][cellIndex] = null;
                            }
                            if (cellIndex > 0 && grid[rowIndex][cellIndex - 1] != clock - 3) {
                                grid[rowIndex][cellIndex - 1] = null;
                            }
                            if (cellIndex < grid[0].length - 1 && grid[rowIndex][cellIndex + 1] != clock - 3) {
                                grid[rowIndex][cellIndex + 1] = null;
                            }
                            grid[rowIndex][cellIndex] = null;
                        }
                    });
                });
                clock++;
            }
        }
        grid.forEach((row, index) => {
            grid[index] = row.map(cell => (cell == null) ? "." : "O").join("");
        });
        return grid;
    }