Bomberman Agent

← Back to Projects

The Bomberman Agent is a reinforcement learning agent that learns to play the classic video game Bomberman. The agent uses MCTS (Monte Carlo Tree Search) to explore the game tree and select the best move by utilizing a deep network for evaluation. The Agent is trained using self-play, where it plays against itself to improve its strategy.

Bomberman Agent

The Agent (Name in image: LITTLE_GUY) is implemented in Python with PyTorch and was created for the MLE course. Specific restrictions were that it had to run on the CPU with limited time per move.

Implementation Details

Network Architecture

The network takes as input a 3x4x7 tensor. The 12 spatial cells come from a diamond with diagonal length 5 centred on the agent, with the agent's own cell removed (since the agent's position is always the same, it adds no information). The 7 channels encode coins, crates, bombs, explosions, walls, other agents, and bomb availability.

AlphaGo, DeepMind's program that defeated world champion Go players, popularised combining deep residual networks with MCTS: the network guides the search by evaluating positions (value head) and suggesting promising moves (policy head), replacing the random rollouts of classical MCTS. The same architecture was later generalised in AlphaZero to work for any two-player game purely through self-play, without any human game data. The network here follows the same dual-headed ResNet design:

Monte Carlo Tree Search

The MCTS keeps a tree of game states across the search. Each node stores the game state, visit count, accumulated value, a prior probability from the policy head, immediate reward, and a running max value. When a leaf node is expanded, the policy head's output initialises the priors of the new child nodes, and the value head evaluates the position instead of running random rollouts. Node selection uses UCT:

UCB(node, action) = total_value / visits
                  + C * sqrt(log(parent.visits) / visits)

After the time budget is exhausted, the action with the highest visit count is chosen. Keeping the search on CPU within a strict per-move time limit was the main constraint, which limited how deeply the tree could be explored.

Here is an extract of the code showcasing the deep network:

"""
This module contains the model for the evaluation and policy network of the MCTS.
Input is the local game state in a pattern around the agent. The pattern is a
diamond with diagonal length 5, centered on the agent. The agent's own cell is
removed since its position is constant and carries no information, leaving 12 cells.
These are arranged into a 3x4 grid. The convolutions make sense since neighbour
relations are preserved in this layout. Multiple layers exist for coins, crates,
bombs, explosions, walls, agents, and bomb availability. So the input is a 3x4x7 stack.

The first Block is a convolutional Block. Then there is a number of residual Blocks.
Lastly, there are two heads, one for the value and one for the policy. The value head is
a single neuron with a tanh activation function. It outputs the value of the state in
the range of -1 to 1. The policy head outputs the probabilities for each action.
"""

import torch
import torch.nn as nn

ACTIONS = ["UP", "DOWN", "LEFT", "RIGHT", "WAIT", "BOMB"]


class ConvolutionalBlock(nn.Module):
    def __init__(self, in_channels, out_channels=2**7, kernel_size=3, stride=1, padding=1):
        super(ConvolutionalBlock, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
        self.batch_norm = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU()

    def forward(self, x):
        x = self.conv(x)
        x = self.batch_norm(x)
        x = self.relu(x)
        return x


class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels=2**7, kernel_size=3, stride=1, padding=1):
        super(ResidualBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding)
        self.batch_norm1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU()
        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size, stride, padding)
        self.batch_norm2 = nn.BatchNorm2d(out_channels)

    def forward(self, x):
        residual = x
        x = self.conv1(x)
        x = self.batch_norm1(x)
        x = self.relu(x)
        x = self.conv2(x)
        x = self.batch_norm2(x)
        x += residual
        x = self.relu(x)
        return x


class ValueHead(nn.Module):
    def __init__(self, in_channels, out_size):
        super(ValueHead, self).__init__()
        self.conv = nn.Conv2d(in_channels, 1, 1)
        self.batch_norm = nn.BatchNorm2d(1)
        self.relu = nn.ReLU()
        self.fc = nn.Linear(12, out_size)
        self.tanh = nn.Tanh()

    def forward(self, x):
        x = self.conv(x)
        x = self.batch_norm(x)
        x = self.relu(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        x = self.tanh(x)
        return x


class PolicyHead(nn.Module):
    def __init__(self, in_channels, out_size=6):
        super(PolicyHead, self).__init__()
        self.conv = nn.Conv2d(in_channels, 2, 1)
        self.batch_norm = nn.BatchNorm2d(2)
        self.relu = nn.ReLU()
        self.fc = nn.Linear(24, out_size)
        self.softmax = nn.Softmax(dim=1)

    def forward(self, x):
        x = self.conv(x)
        x = self.batch_norm(x)
        x = self.relu(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)
        x = self.softmax(x)
        return x


class MCTSNetwork(nn.Module):
    def __init__(self, in_channels=7, hidden_size=2**7, residual_blocks=1):
        super().__init__()
        self.conv_block = ConvolutionalBlock(in_channels)
        self.residual_blocks = nn.Sequential(
            *[ResidualBlock(hidden_size) for _ in range(residual_blocks)]
        )
        self.value_head = ValueHead(hidden_size, 1)
        self.policy_head = PolicyHead(hidden_size)

    def forward(self, x):
        x = self.conv_block(x)
        x = self.residual_blocks(x)
        value = self.value_head(x)
        policy = self.policy_head(x)
        return value, policy


def load_model(path):
    model = MCTSNetwork()
    model.load_state_dict(torch.load(path, map_location=torch.device("cpu")))
    return model


def save_model(model, path):
    torch.save(model.state_dict(), path)

Results

Competition results were not published. The main challenge was fitting a meaningful search within the strict per-move time budget on CPU - more network depth means fewer MCTS steps per turn, directly hurting search quality. The table below shows MCTS steps achievable in 0.5 s as a function of the number of residual blocks (averaged over 20 runs):

Residual blocksMCTS steps / 0.5 s
0316
1237
2185
3155
4132
5115
6100
793
882
972

Two residual blocks was chosen as the final configuration, balancing model capacity against search depth. The input neighbourhood was also reduced from the originally planned radius-4 diamond (36 cells) to a radius-2 diamond with the centre removed (12 cells, 3×4), which reduced inference time further.

Two other factors limited performance. Training throughput was bottlenecked by game state simulation: even with the network on GPU, state updates run on CPU in Python, so the GPU sat mostly idle. And with four players each having six possible actions, the branching factor is large. Unlike Go, each state transition in Bomberman also requires non-trivial bookkeeping: ticking bombs, resolving explosions, conditionally spawning coins on destroyed crates, and updating bomb availability - all of which adds overhead per MCTS step.

Outlook

I would like to revisit this project with more compute. The obvious path is a faster state update implementation - Rust would be a natural fit - combined with a larger network trained on GPU. An interesting alternative would be to drop MCTS at inference time entirely: train with MCTS to generate high-quality policy targets, then use the policy head alone to pick actions. That way the heavy GPU-trained network only runs once per move on CPU, sidestepping the search budget problem while still benefiting from the self-play training signal.