Developing an AI Model for the Battleship Game using Reinforcement Learning
Introduction
This project aims to develop an advanced AI model for the classic game of Battleship using gradient-based reinforcement learning techniques. The goal is to create an AI agent that can play Battleship efficiently, achieving an average of 60 moves or fewer to complete a game. Unlike traditional algorithms or probabilistic methods, this approach leverages deep reinforcement learning to enable the AI to learn optimal strategies through experience.
Table of Contents
Project Structure
The project consists of the following components:
- Game Implementation: A Battleship environment that adheres to OpenAI Gym interface standards.
- AI Model Development: A Deep Q-Network (DQN) agent that uses gradient-based reinforcement learning.
- Training Process: Code to train the AI agent within the game environment.
- Testing and Evaluation: Scripts to evaluate the performance of the trained agent and analyze metrics.
Prerequisites
- Python 3.7+
- TensorFlow 2.x or PyTorch (This implementation uses TensorFlow)
- NumPy
- Matplotlib (for plotting if needed)
Install the required packages using:
pip install numpy tensorflow
Game Implementation
We define the Battleship game as an environment where the agent interacts by choosing grid coordinates to fire upon. The environment provides feedback in the form of rewards and observations of the game state.
- Grid size:
10x10
- Ships are placed randomly at the start of each episode.
- Ships include:
- Carrier (5 cells)
- Battleship (4 cells)
- Cruiser (3 cells)
- Submarine (3 cells)
- Destroyer (2 cells)
- The game ends when all ships are sunk.
AI Model Development
Reinforcement Learning Approach
We use the Deep Q-Network (DQN) algorithm, a gradient-based reinforcement learning method. The agent learns a policy that maps observations of the game state to actions (grid positions to fire upon) to maximize cumulative rewards.
Key Components:
- States: The current state of the game board (hit/miss/unknown).
- Actions: Selecting a grid coordinate to attack.
- Rewards:
- Hit a ship:
+1
- Miss:
-0.1
- Sinking a ship: Additional
+5
- Invalid action (firing at the same spot):
-1
Neural Network Architecture
- Input Layer: Flattened game board state (
10x10 grid).
- Hidden Layers: Two hidden layers with ReLU activation.
- Output Layer: Q-values for each possible action (
100 outputs for 10x10 grid).
Implementation Details
- Experience Replay: To stabilize training, we use a replay buffer to store and sample past experiences.
- Epsilon-Greedy Policy: Balances exploration and exploitation.
- Target Network: A separate network to compute target Q-values for stability.
Data Generation and Training Process
The agent learns by playing multiple episodes of the game:
- Initialization: Reset the game environment.
- Action Selection: Choose an action based on the epsilon-greedy policy.
- Environment Step: Execute the action and observe the reward and next state.
- Store Experience: Save the experience in the replay buffer.
- Training Step: Sample a minibatch from the replay buffer and perform a gradient descent step.
- Target Network Update: Periodically update the target network weights.
Testing and Evaluation
Performance Metrics
- Average Moves per Game: The primary metric is the average number of moves taken to win the game over multiple episodes.
- Win Rate: The proportion of games the agent successfully completes.
- Reward per Episode: Average cumulative reward.
Results Analysis
After training, we evaluate the agent over 1000 episodes to determine if it meets the objective of completing the game in 60 moves or fewer on average.
Note: Detailed performance metrics and plots will be displayed in the evaluation section.
Instructions for Setup and Execution
-
Clone the Repository: Download or clone the project code.
-
Install Dependencies:
pip install numpy tensorflow
-
Run Training Script:
python train.py
- This will start the training process and save the trained model as
dqn_model.h5.
-
Run Evaluation Script:
python evaluate.py
- This script will load the trained model and evaluate its performance.
Conclusion
We developed a gradient-based reinforcement learning model using the DQN algorithm to play Battleship efficiently. The AI agent learns to strategize its moves to locate and sink all ships in the shortest number of moves possible, aiming for an average of 60 moves or fewer per game.
Full Source Code
Below are the source code files required for this project.
battleship_env.py
import numpy as np
import random
class BattleshipEnv:
def __init__(self, grid_size=10):
self.grid_size = grid_size
self.action_space = grid_size * grid_size
self.state_size = grid_size * grid_size
self.reset()
def reset(self):
self.board = np.zeros((self.grid_size, self.grid_size), dtype=int)
self.mask = np.zeros((self.grid_size, self.grid_size), dtype=int)
self.ships = []
self.place_ships()
self.done = False
self.total_moves = 0
return self.get_state()
def place_ships(self):
ship_sizes = [5, 4, 3, 3, 2] # Carrier, Battleship, Cruiser, Submarine, Destroyer
for size in ship_sizes:
placed = False
while not placed:
orientation = random.choice(['H', 'V'])
if orientation == 'H':
row = random.randint(0, self.grid_size - 1)
col = random.randint(0, self.grid_size - size)
if np.sum(self.board[row, col:col+size]) == 0:
self.board[row, col:col+size] = 1
self.ships.append({'size': size, 'hits': 0})
placed = True
else:
row = random.randint(0, self.grid_size - size)
col = random.randint(0, self.grid_size - 1)
if np.sum(self.board[row:row+size, col]) == 0:
self.board[row:row+size, col] = 1
self.ships.append({'size': size, 'hits': 0})
placed = True
def get_state(self):
# 0: unknown, 1: miss, 2: hit
return self.mask.flatten()
def step(self, action):
if self.done:
raise Exception("Game over. Please reset the environment.")
row = action // self.grid_size
col = action % self.grid_size
reward = 0
info = {}
self.total_moves += 1
if self.mask[row, col] != 0:
# Already hit this cell
reward = -1 # Penalty for invalid move
return self.get_state(), reward, self.done, info
if self.board[row, col] == 1:
# Hit a ship
self.mask[row, col] = 2
reward = 1
# Update ship hits
for ship in self.ships:
# Check if this ship is sunk
ship_cells = np.argwhere(self.board == 1)
hit_cells = np.argwhere(self.mask == 2)
if set(map(tuple, ship_cells)).issubset(set(map(tuple, hit_cells))):
ship['hits'] = ship['size']
# Check if all ships are sunk
if all(ship['hits'] == ship['size'] for ship in self.ships):
self.done = True
else:
# Missed
self.mask[row, col] = 1
reward = -0.1
return self.get_state(), reward, self.done, info
dqn_agent.py
import numpy as np
import tensorflow as tf
from tensorflow.keras import models, layers, optimizers
class DQNAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size # 100 for 10x10 grid
self.action_size = action_size # 100 for 10x10 grid
self.memory = []
self.gamma = 0.95 # Discount factor
self.epsilon = 1.0 # Exploration probability
self.epsilon_min = 0.1
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.batch_size = 64
self.train_start = 1000
self.memory_size = 2000
self.model = self.build_model()
self.target_model = self.build_model()
self.update_target_model()
def build_model(self):
model = models.Sequential()
model.add(layers.Dense(128, input_dim=self.state_size, activation='relu'))
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(self.action_size, activation='linear'))
model.compile(loss='mse', optimizer=optimizers.Adam(lr=self.learning_rate))
return model
def update_target_model(self):
self.target_model.set_weights(self.model.get_weights())
def remember(self, state, action, reward, next_state, done):
if len(self.memory) > self.memory_size:
self.memory.pop(0)
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
# Epsilon-greedy action selection
if np.random.rand() <= self.epsilon:
return np.random.randint(self.action_size)
q_values = self.model.predict(state[np.newaxis, :])
return np.argmax(q_values[0])
def replay(self):
if len(self.memory) < self.train_start:
return
minibatch = np.random.choice(len(self.memory), min(self.batch_size, len(self.memory)), replace=False)
states = np.zeros((len(minibatch), self.state_size))
targets = np.zeros((len(minibatch), self.action_size))
for i, index in enumerate(minibatch):
state, action, reward, next_state, done = self.memory[index]
target = self.model.predict(state[np.newaxis, :])[0]
if done:
target[action] = reward
else:
t = self.target_model.predict(next_state[np.newaxis, :])[0]
target[action] = reward + self.gamma * np.amax(t)
states[i] = state
targets[i] = target
self.model.train_on_batch(states, targets)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
train.py
from battleship_env import BattleshipEnv
from dqn_agent import DQNAgent
import numpy as np
EPISODES = 1000
if __name__ == "__main__":
env = BattleshipEnv()
state_size = env.state_size
action_size = env.action_space
agent = DQNAgent(state_size, action_size)
for e in range(EPISODES):
state = env.reset()
done = False
total_moves = 0
while not done:
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
agent.remember(state, action, reward, next_state, done)
state = next_state
total_moves += 1
if done:
agent.update_target_model()
print(f"Episode: {e+1}/{EPISODES}, Moves: {total_moves}, Epsilon: {agent.epsilon:.2}")
break
agent.replay()
# Save the trained model
agent.model.save('dqn_model.h5')
evaluate.py
from battleship_env import BattleshipEnv
from dqn_agent import DQNAgent
import numpy as np
from tensorflow.keras.models import load_model
EPISODES = 1000
if __name__ == "__main__":
env = BattleshipEnv()
state_size = env.state_size
action_size = env.action_space
agent = DQNAgent(state_size, action_size)
agent.model = load_model('dqn_model.h5')
total_moves_list = []
for e in range(EPISODES):
state = env.reset()
done = False
total_moves = 0
while not done:
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
state = next_state
total_moves += 1
if done:
total_moves_list.append(total_moves)
print(f"Evaluation Episode: {e+1}/{EPISODES}, Moves: {total_moves}")
break
average_moves = np.mean(total_moves_list)
print(f"Average Moves over {EPISODES} episodes: {average_moves}")
Acknowledgments
- OpenAI Gym: For standardizing the interface of the environment.
- Deep Reinforcement Learning: Techniques and algorithms inspired by research in the field.