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
float64vector of length2 * 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:
1for a hit and0for 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_lengthsstraight, within the board, without overlap (and without touching whenallow_adjacent_ships=False).
A state is a layout paired with the set of cells probed so far:
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:
Action \(a\) probes cell \(a\); rows and columns start at \(0\).
Observation space
\(\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:
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:
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:
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:
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:
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?
|
Discrete |
Continuous |
|---|---|---|
State |
✔️ |
❌ |
Action |
✔️ |
❌ |
Observation |
✔️ |
❌ |
Also supports |
|
|---|---|
Native C++ backend |
❌ |
Vectorized (torch) model |
✔️ |
In the |
❌ |
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:
DiscreteActionsEnvironmentBattleship as a POMDP: probe a hidden fleet until every ship cell is hit.
- Dynamics:
Deterministic. Action
ais 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:
HITif the probed cell is occupied,MISSotherwise. 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_rewardfor probing an occupied cell that had not been probed;-miss_penaltyfor 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
- episode_visualizer()[source]
Return the visualizer that writes this environment’s traces.
- Return type:
BattleshipVisualizer
- get_metric_specs()[source]
Declare the Battleship metrics.
Completion reduces with
ANYrather thanALL: sinking the fleet is a thing that happens once and stays true, not a condition every step has to hold.ended_by_*reduce withLAST— 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:
- Returns:
One spec per metric named in
BattleshipPOMDPMetrics.
- hash_observation(observation)[source]
Return a hashable key agreeing with
is_equal_observation().
- initial_observation_dist()[source]
The pre-probe observation, which carries no information.
- Return type:
- initial_state_dist()[source]
Uniform distribution over legal fleet placements, nothing probed.
- Return type:
- is_equal_observation(observation1, observation2)[source]
Check whether two hit/miss observations are the same.
- 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:
- Return type:
- Returns:
0.0for the observation the sensor would emit,-infotherwise.-infis deliberate rather than a floored value: an impossible reading really has zero likelihood here, and the baseWeightedParticleBeliefpath already floors it withepsbefore normalising. This environment does not overrideobservation_log_probability_per_state, precisely so that flooring stays in play for any caller that does use a generic filter.
- 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, sonext_stateis accepted and ignored, andreward_requires_next_statestaysFalse.
- sample_next_state(state, action, n_samples=1)[source]
Apply the probe. Deterministic, so every sample is the same state.
- sample_next_state_batch(states, action)[source]
Apply one probe to every input state.
- Parameters:
- Return type:
- Returns:
(N, 2 * num_cells)float64array. The dtype matchessample_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()andreward()in turn; all three are deterministic, so one call that computes them together returns the same values.
- sample_observation(next_state, action, n_samples=1)[source]
Report whether the probed cell holds a ship. Deterministic.
- simulate_random_rollout(state, action_sampler, max_depth, discount_factor, depth=0)[source]
Random rollout run by the native kernel.
Draws
max_depth - depthactions uniformly over the cells withnp.random.randintup front, as the RockSample and Pac-Man kernels do, and ignoresaction_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 aspython_random_rollout, so for the same actions the two agree exactly.- Parameters:
- Return type:
- 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
stateandaction.- Parameters:
state (
Any) – The state the probe was taken from, or the final state on the terminal bookkeeping step.action (
Any) – The probed cell, orNoneon the terminal step.next_state (
Any) – The realised successor, orNoneon the terminal step. The two probe-outcome channels are scored againststate, because whether a probe is a new hit is decided by the board it was taken from — the same conventionreward()uses. The board-progress channels are scored againstnext_stateinstead, 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 fromstatealone 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:
- Returns:
The channels named by
BattleshipStepChannel. The three probe-outcome channels report0.0on 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.
See also
Base Environment Class — the full catalog and the environment interface.