The Bomberman Game

  • + 0 comments

    Java8 solution, just switch between the two states of the grid:

        public static List<String> bomberMan(int n, List<String> grid) {
        // Write your code here
        if(n==1){return grid;}
        if(n%2==0) {
            int length = grid.get(0).length();
            
            String oString = repeatChar('O', length);
            for(int i=0; i<grid.size(); i++){
                grid.set(i, oString);
            }
            return grid;
        }
        
        
        grid = switchStates(grid);
        if(n%4==3){return grid;}
        return switchStates(grid);
        
        }
        
        
        public static String repeatChar(char c, int times) {
            StringBuilder sb = new StringBuilder(times);
            for (int i = 0; i < times; i++) {
                sb.append(c);
            }
            return sb.toString();
        }
        
        // function to switch between the 2 states -
        // from seconds 3-7-11-15---n%4==3
        // to seconds 5-9-13-17---n%4==1
        public static List<String> switchStates(List<String> grid){
        char[][] charArray = new char[grid.size()][];
    
        for (int i = 0; i < grid.size(); i++) {
                charArray[i] = grid.get(i).toCharArray(); // Convert each String to a char[]
            }
        for(int i=0; i<grid.size(); i++){
          second: for(int j=0; j<charArray[0].length; j++){
              int[][] positions = {{i+1, j}, {i-1, j}, {i, j+1}, {i, j-1}};
              if (grid.get(i).charAt(j) == '.'){
                  for(int[] pos : positions){
                      int x = pos[0];
                      int y = pos[1];
                      if(x>=0 && x < grid.size() && y >= 0 && y < charArray[0].length){
                          if(grid.get(x).charAt(y) == 'O'){
                              continue second;
                          }
                      }
                  }
                  charArray[i][j] = 'O';
              }
              else {
                  
                  charArray[i][j] = '.';
                  for(int[] pos : positions){
                      int x = pos[0];
                      int y = pos[1];
                      if(x>=0 && x < grid.size() && y >= 0 && y < charArray[0].length){
                          charArray[x][y] = '.';
                      }
                  } 
              }
          }  
        }
        for(int i =0 ; i < charArray.length; i++){
            String s = new String(charArray[i]);
            grid.set(i, s);
        }
        return grid;
        }