Battleship

One recorded episode planned by PFT-DPW, replayed in 3D. Drag to orbit, scroll to zoom, and use the bar to play, scrub and switch camera.

BattleshipPOMDP searches for a hidden, fixed fleet on a square board. Probe one cell at a time and hit every occupied cell to finish.

The sensor is exact and the fleet never moves, so all the uncertainty is in the initial layout. Every probe removes the fleet layouts that disagree with its reading, and nothing ever adds one back.

What the agent sees and does

  • State — a float64 vector of length 2 * board_size ** 2: fleet occupancy per cell, then a probed flag per cell. Occupancy is hidden from the agent.

  • Actions (discrete) — an int, row * board_size + column, that probes one cell; coordinates start at zero.

  • Observations (discrete) — exact: 1 for a hit and 0 for a miss. Probing changes only the record of visited cells, never the fleet.

Formal definition

The environment is the POMDP \(\langle S, A, Z, T, O, R, b_0, \gamma \rangle\).

State space. The state space uses:

  • \(n\) — board_size.

  • \(C = \{0, \dots, n^2 - 1\}\) — the cells in row-major order.

  • \(\mathcal{L} \subseteq \{0,1\}^{C}\) — the set of legal fleet layouts: the occupancy vectors reachable by placing every ship in ship_lengths straight, within the board, without overlap (and without touching when allow_adjacent_ships=False).

A state is a layout paired with the set of cells probed so far:

\[S = \mathcal{L} \times \{0,1\}^{C}, \qquad s = (u, m)\]

where \(u_j = 1\) means cell \(j\) holds a ship and \(m_j = 1\) means it has been probed. The vector is stored flat as \([u_0 \dots u_{n^2-1},\, m_0 \dots m_{n^2-1}]\).

Action space. One probe per cell:

\[A = C, \qquad a = \text{row} \cdot n + \text{column}\]

Action \(a\) probes cell \(a\); rows and columns start at \(0\).

Observation space

\[Z = \{\textsf{MISS}, \textsf{HIT}\} = \{0, 1\}\]

\(\textsf{HIT}\) means the probed cell holds a ship, \(\textsf{MISS}\) that it does not.

Transition model. Deterministic, and it never touches the fleet — probing only records that a cell was visited:

\[T\big((u', m') \mid (u, m), a\big) = \mathbb{1}[u' = u] \cdot \mathbb{1}[m' = m + e_a]\]

where \(e_a\) sets bit \(a\). Because \(u\) is constant along a trajectory, all uncertainty is in the initial draw; the agent only rules out layouts and never tracks a moving target.

Observation model. Noiseless:

\[O(o \mid (u', m'), a) = \mathbb{1}[o = u'_a]\]

The sensor is exact, so every probe is a hard constraint that cuts \(\mathcal{L}\) down rather than reweighting it.

Reward function. Only a new hit pays:

\[\begin{split}R\big((u, m), a\big) = \begin{cases} +\texttt{hit\_reward} & u_a = 1 \text{ and } m_a = 0 \\ -\texttt{miss\_penalty} & \text{otherwise} \end{cases}\end{split}\]

so \(R \in [-\texttt{miss\_penalty},\, \texttt{hit\_reward}]\). Re-probing a cell already known to hold a ship scores as water: exactly one branch fires per step, and nothing stacks. Note \(R\) reads the pre-probe mask, which is what makes it a function of \((s, a)\) alone.

Initial belief. Uniform over legal layouts, nothing probed:

\[b_0\big((u, 0)\big) = \frac{1}{|\mathcal{L}|}, \qquad u \in \mathcal{L}\]

with the pre-probe observation fixed at \(\textsf{MISS}\), which carries no information. max_layouts caps the enumeration of \(\mathcal{L}\) used by the exact belief.

Discount. \(\gamma\) = discount_factor, default \(0.99\).

Terminal set. Every occupied cell probed:

\[S_T = \{(u, m) : u_j \leq m_j \ \text{for all } j \in C\}\]

Hitting the runner’s step limit first is a timeout, recorded separately from completion.

Rewards

A new hit earns hit_reward (default 1.0). Water and repeated probes of any cell earn -miss_penalty (default -0.1), including another probe of a known hit.

Key settings

The default board is 5 by 5, with straight ships of lengths 3, 2 and 2. Ships may touch, including diagonally, unless allow_adjacent_ships=False.

Visualization

Runs write a trace of each episode through the environment’s episode visualizer. The results site replays it in 3D, as the replay on this page does.

Can I use?

BattleshipPOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

✔️

❌

Also supports

Native C++ backend

❌

Vectorized (torch) model

✔️ BattleshipVectorizedModel (all configurations)

In the get_environment registry

❌

Optional dependencies

None

Example

from POMDPPlanners.environments.battleship_pomdp import BattleshipPOMDP

env = BattleshipPOMDP(board_size=5, ship_lengths=(3, 2, 2))

Parameters

class POMDPPlanners.environments.battleship_pomdp.BattleshipPOMDP(board_size=5, ship_lengths=(3, 2, 2), allow_adjacent_ships=True, hit_reward=1.0, miss_penalty=0.1, max_layouts=2000000, discount_factor=0.99, name='Battleship', output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: DiscreteActionsEnvironment

Battleship as a POMDP: probe a hidden fleet until every ship cell is hit.

Dynamics:

Deterministic. Action a is the flat index of the cell to probe; probing sets that cell’s probe flag and changes nothing else. The occupancy half never changes, which is what makes the fleet “hidden and fixed” rather than something the agent can disturb.

Observation model:

Deterministic and noiseless: HIT if the probed cell is occupied, MISS otherwise. The agent already knows which cells it probed, so the observation adds exactly one bit per step, and only for a cell it has not seen before.

Reward:

hit_reward for probing an occupied cell that had not been probed; -miss_penalty for anything else — water, or a repeat of any cell. Exactly one of the two fires per step, so the two never stack and the declared range is the tighter pair, not their sum.

Terminal:

Every occupied cell has been probed. There is no failure terminal: an episode that does not finish inside the runner’s step budget is a timeout, which the metrics report separately from completion.

Parameters:
board_size

Side length of the square board.

ship_lengths

Ship lengths making up the fleet.

allow_adjacent_ships

Whether ships may touch, including diagonally.

hit_reward

Reward for a newly hit ship cell.

miss_penalty

Magnitude of the penalty for a miss or a repeat probe.

num_cells

board_size ** 2.

num_ship_cells

Total occupied cells, sum(ship_lengths).

Example

>>> import numpy as np
>>> np.random.seed(0)
>>> env = BattleshipPOMDP()
>>> state = env.initial_state_dist().sample()[0]
>>> next_state, observation, reward = env.sample_next_step(state, 0)
>>> observation in (0, 1)
True
>>> env.is_terminal(state)
False
action_to_cell(action)[source]

Return the (row, col) the probe action action targets.

Return type:

Tuple[int, int]

Parameters:

action (int)

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

BattleshipVisualizer

get_actions()[source]

Return every probe action: one per board cell, in row-major order.

Return type:

List[int]

get_metric_specs()[source]

Declare the Battleship metrics.

Completion reduces with ANY rather than ALL: sinking the fleet is a thing that happens once and stays true, not a condition every step has to hold. ended_by_* reduce with LAST — a completed episode’s last recorded step is the terminal bookkeeping step, where the board is sunk, and a timed-out episode’s last step is an ordinary probe from a board that is not.

There is no danger metric: nothing in Battleship can be damaged, entered or violated. The nearest thing is the repeat probe — an action that cannot buy information and only burns a turn — which is reported as a count.

Return type:

List[StepInfoMetric]

Returns:

One spec per metric named in BattleshipPOMDPMetrics.

hash_action(action)[source]

Return a hashable key for a probe action (already an int).

Return type:

Hashable

Parameters:

action (Any)

hash_observation(observation)[source]

Return a hashable key agreeing with is_equal_observation().

Return type:

Hashable

Parameters:

observation (Any)

initial_observation_dist()[source]

The pre-probe observation, which carries no information.

Return type:

DiscreteDistribution

initial_state_dist()[source]

Uniform distribution over legal fleet placements, nothing probed.

Return type:

Distribution

is_equal_observation(observation1, observation2)[source]

Check whether two hit/miss observations are the same.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_terminal(state)[source]

Whether every occupied cell has been probed.

Return type:

bool

Parameters:

state (ndarray)

property layouts: FleetLayoutTable

The enumerated legal fleet layouts for this board geometry.

observation_log_probability(next_state, action, observations)[source]

Log-likelihood of each candidate observation. Deterministic.

Parameters:
  • next_state (ndarray) – The post-probe state.

  • action (int) – The probed cell index.

  • observations (Any) – Candidate observations.

Return type:

ndarray

Returns:

0.0 for the observation the sensor would emit, -inf otherwise. -inf is deliberate rather than a floored value: an impossible reading really has zero likelihood here, and the base WeightedParticleBelief path already floors it with eps before normalising. This environment does not override observation_log_probability_per_state, precisely so that flooring stays in play for any caller that does use a generic filter.

occupancy(state)[source]

Return the hidden occupancy half of state as a bool array.

Return type:

ndarray

Parameters:

state (ndarray)

probed(state)[source]

Return the observed probe half of state as a bool array.

Return type:

ndarray

Parameters:

state (ndarray)

reward(state, action, next_state=None)[source]

Score one probe.

The reward is a pure function of (state, action): whether the probe lands on a new ship cell is decided by the state it is taken from, so next_state is accepted and ignored, and reward_requires_next_state stays False.

Parameters:
  • state (ndarray) – The state the probe is taken from.

  • action (int) – The probed cell index.

  • next_state (Any) – Unused.

Return type:

float

Returns:

hit_reward for a newly hit ship cell, -miss_penalty otherwise.

reward_batch(states, action, next_states=None)[source]

Score one probe against a batch of states.

Parameters:
Return type:

ndarray

Returns:

(N,) float64 array agreeing element-wise with reward().

sample_next_state(state, action, n_samples=1)[source]

Apply the probe. Deterministic, so every sample is the same state.

Parameters:
  • state (ndarray) – Current state.

  • action (int) – Flat index of the probed cell.

  • n_samples (int) – How many successor samples to return. Defaults to 1.

Return type:

Any

Returns:

A single float64 state when n_samples == 1, else an (n_samples, 2 * num_cells) float64 array.

sample_next_state_batch(states, action)[source]

Apply one probe to every input state.

Parameters:
  • states (Any) – (N, 2 * num_cells) array-like of particles.

  • action (int) – The probed cell index, shared by every particle.

Return type:

ndarray

Returns:

(N, 2 * num_cells) float64 array. The dtype matches sample_next_state() so a particle filter mixing the two paths cannot silently change particle precision.

sample_next_step(state, action)[source]

Probe once: successor, observation and reward from one native call.

Returns the same triple as the base implementation, which calls sample_next_state(), sample_observation() and reward() in turn; all three are deterministic, so one call that computes them together returns the same values.

Parameters:
  • state (ndarray) – The state the probe is taken from.

  • action (int) – The probed cell index.

Return type:

Tuple[Any, int, float]

Returns:

(next_state, observation, reward).

sample_observation(next_state, action, n_samples=1)[source]

Report whether the probed cell holds a ship. Deterministic.

Parameters:
  • next_state (ndarray) – The post-probe state.

  • action (int) – The probed cell index.

  • n_samples (int) – How many observation samples to return. Defaults to 1.

Return type:

Any

Returns:

HIT or MISS when n_samples == 1, else a list of n_samples copies of it.

simulate_random_rollout(state, action_sampler, max_depth, discount_factor, depth=0)[source]

Random rollout run by the native kernel.

Draws max_depth - depth actions uniformly over the cells with np.random.randint up front, as the RockSample and Pac-Man kernels do, and ignores action_sampler. The rollout stops at the first terminal state, so actions past it are drawn and not used. The return is summed in the same order as python_random_rollout, so for the same actions the two agree exactly.

Parameters:
  • state (Any) – The state the rollout starts from.

  • action_sampler (Any) – Unused; actions are uniform over the cells.

  • max_depth (int) – Depth at which the rollout stops.

  • discount_factor (float) – Per-step discount factor.

  • depth (int) – Depth already used by the search tree. Defaults to 0.

Return type:

float

Returns:

The discounted return of the rollout.

step_info(state, action, next_state)[source]

Report the per-step channels this environment’s metrics are built on.

Draws no randomness: every channel is read straight off state and action.

Parameters:
  • state (Any) – The state the probe was taken from, or the final state on the terminal bookkeeping step.

  • action (Any) – The probed cell, or None on the terminal step.

  • next_state (Any) – The realised successor, or None on the terminal step. The two probe-outcome channels are scored against state, because whether a probe is a new hit is decided by the board it was taken from — the same convention reward() uses. The board-progress channels are scored against next_state instead, and that is deliberate: the episode runner checks its step budget before it checks terminality, so an episode whose final allowed probe sinks the fleet never records a terminal bookkeeping step. Reading progress from state alone would score that episode as an unfinished timeout with the last hit missing, which is wrong in the one place it matters most.

Return type:

Dict[str, float]

Returns:

The channels named by BattleshipStepChannel. The three probe-outcome channels report 0.0 on the terminal step, where no probe was taken; the board-progress channels are still reported there, because a completed episode’s final board is recorded only on that step.

transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate successor. Deterministic.

Parameters:
  • state (ndarray) – Current state.

  • action (int) – The probed cell index.

  • next_states (Any) – Candidate successors.

Return type:

ndarray

Returns:

0.0 for the one realisable successor, -inf otherwise.

See also