The Bomberman Game

  • + 0 comments

    Observation: There is a pattern: --> The blast at 3rd second, 7th second, 11th second.... will be the same. --> Similarly, the blast at 5th second, 9th second, ... and so on will be the same. What we can do is to create a function that gets us the output grid for the 3rd second (1st blast). Now if we run that function again with the input of the 1st blast, we will get the output for the 5th second (2nd blast)

    My code:

    const filledGrid = (grid) => {
      return grid.map((row) =>
        row
          .split("")
          .map((ele) => "O")
          .join("")
      );
    };
    
    const secondPattern = (grid) => {
      let newGrid = grid.map((row) => row.split("").map((el) => "O"));
      for (let i = 0; i < grid.length; i++) {
        for (let j = 0; j < grid[0].length; j++) {
          if (grid[i][j] === "O") {
            newGrid[i][j] = ".";
            if (i > 0) {
              newGrid[i - 1][j] = ".";
            }
            if (j > 0) {
              newGrid[i][j - 1] = ".";
            }
            if (i < grid.length - 1) {
              newGrid[i + 1][j] = ".";
            }
            if (j < grid[0].length - 1) {
              newGrid[i][j + 1] = ".";
            }
          }
        }
      }
      return newGrid.map((row) => row.join(""));
    };
    
    function bomberMan(n, grid) {
        // Write your code here
        if (n === 1) return grid;
        if(n % 2 === 0) return filledGrid(grid);
        let secondPatternMatch = false;
        for(let i = 2; i <=n; i++)
        {
            if(i % 2 !== 0)
            {
                secondPatternMatch = !secondPatternMatch;
            }
        }
        return secondPatternMatch ? secondPattern(grid) : secondPattern(secondPattern(grid)); 
        
    
    }
    

    What I am doing is using a flag variable to check the seconds.

    
    

    `