The Bomberman Game

  • + 2 comments

    Do some examples on paper and then observe this patter:

    1. The grid is always full with bombs if n is even
    2. The grid at 3 seconds is the detonation of the initial state bombs
    3. The grid at 5 seconds it the detonation of the grid at 3 seconds
    4. Grids 3, 7, 11, ... are repeating
    5. Grids 5, 9, 13, ... are repeating

    So the algorithm becomes:

    1. If n is even, return an all bomb grid
    2. Calculate grid at three seconds
    3. Calculate grid at five seconds
    4. If n is 3, 7, 11, ... return three second grid
    5. If n is 5, 9, 13, ... return five second grid
    6. if n < 3, return initial grid

    Solution

    def get_detonated_grid(bomb_grid):
        rows = len(bomb_grid)
        cols = len(bomb_grid[0])
        
        detonated_grid = []
        for i in range(rows):
            detonated_grid.append([])
            for j in range(cols):
                detonated_grid[i].append('O')
        
        for i in range(rows):
            for j in range(cols):
                if bomb_grid[i][j] == '.':
                    continue
                detonated_grid[i][j] = '.'
                if i > 0:
                    detonated_grid[i-1][j] = '.'
                if i < rows - 1:
                    detonated_grid[i+1][j] = '.'
                if j > 0:
                    detonated_grid[i][j-1] = '.'
                if j < cols - 1:
                    detonated_grid[i][j+1] = '.'
        
        return detonated_grid
    
    def all_bomb_grid(r, c):
        return [['O'] * c] * r
        
    def to_output(grid):
        return [''.join(row) for row in grid]
    
    def bomberMan(n, grid):
        if n == 1:
            return grid
            
        all_bombs = all_bomb_grid(r, c)
        
        if n % 2 == 0:
            return to_output(all_bombs)
        
        # The grid at three seconds is the detonation from initial state
        three_second_grid = get_detonated_grid(grid)
        
        # The grid at five seconds is the detonation from the bombs
        # on the three second grid
        
        # The 3, 7, 11, ... grids repeat
        # The 5, 9, 13, ... grids repeat
        
        if n == 3 or (n - 3) % 4 == 0:
            return to_output(three_second_grid)
        else:
            return to_output(get_detonated_grid(three_second_grid))