PacMan

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.

Clear every pellet in a walled maze while ghosts hunt you. PacMan’s own position is known; the ghosts’ positions are only observed through noise that grows with distance, so the agent has to reason about where a ghost probably is rather than where it was last seen.

It is the package’s largest discrete state space, which makes it a useful stress test for tree-search planners: the belief is over ghost positions, and a planner that collapses it to a point estimate walks into ghosts.

What the agent sees and does

  • State — a flat float64 vector [pac_row, pac_col, ghost positions…, pellet_mask…, score, terminal]. Construct one with env.make_state(...) and read it with env.get_pacman_pos, env.get_ghost_positions, env.get_pellets, env.get_score, env.get_terminal. These are methods on the environment, not module-level functions.

  • Actions (discrete) — 0 north, 1 east, 2 south, 3 west, 4 stay.

  • Observations (discrete) — a tuple of one noisy (row, col) per ghost. Convert to and from a flat array with env.observation_to_array and env.array_to_observation.

Formal definition

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

State space. The state space uses:

  • Maze. The maze is \(M \times N\) cells, a cell written (row, column).

  • Walls. The wall set is \(\mathcal{W}\); the free cells are \(G\).

  • Pellets. There are \(P\) initial pellet cells \(c_1, \dots, c_P\).

  • Ghosts. There are \(g\) = num_ghosts ghosts.

\[s = \big(x,\; (y_k)_{k=1}^{g},\; \mathbf{m},\; \text{score},\; \top\big), \qquad S = G \times G^{g} \times \{0,1\}^{P} \times \mathbb{R} \times \{0,1\}\]

The components of the state are:

  • \(x\) — PacMan’s cell;

  • \(y_k\) — ghost \(k\)’s cell;

  • \(\mathbf{m}\) — the pellet mask (\(m_p = 1\) still there);

  • \(\text{score}\) — the running score;

  • \(\top\) — an absorbing terminal flag.

The state space is the package’s largest discrete one: \(|G|^{g+1} 2^{P}\).

Action space

\[A = \{\textsf{N}, \textsf{E}, \textsf{S}, \textsf{W}, \textsf{stay}\} = \{0,1,2,3,4\}\]

Action \(a\) moves PacMan one cell by \(\Delta_a\) (row change, column change):

  • \(0\) north \((-1, 0)\);

  • \(1\) east \((0, 1)\);

  • \(2\) south \((1, 0)\);

  • \(3\) west \((0, -1)\);

  • \(4\) stay \((0, 0)\).

Observation space. One cell per ghost; PacMan’s own cell is not part of it. A terminal state reports \((-1, -1)\) for every ghost.

\[Z = \big(\{0..M{-}1\} \times \{0..N{-}1\}\big)^{g} \cup \{(-1, -1)^{g}\}\]

Transition model. \(\mathrm{d}\) is the Manhattan distance between two cells. \(\top\) is absorbing. Otherwise one step resolves in this order.

PacMan moves, deterministically; a move into a wall or off the grid keeps the cell:

\[\begin{split}x' = \begin{cases} x + \Delta_a & x + \Delta_a \in G \\ x & \text{otherwise} \end{cases}\end{split}\]

Ghosts move, each from its own stochastic policy, evaluated against PacMan’s pre-move cell \(x\). Let \(\mathcal{M}(y_k)\) be the valid moves from \(y_k\). An aggressive ghost is a Boltzmann pursuer over Manhattan distance, with temperature \(t\) = ghost_aggressiveness:

\[\Pr[y'_k = u] = \frac{\exp\big(-\mathrm{d}(u, x)/t\big)} {\sum_{v \in \mathcal{M}(y_k)} \exp\big(-\mathrm{d}(v, x)/t\big)}, \qquad u \in \mathcal{M}(y_k)\]

Small \(t\) makes a near-greedy chaser; large \(t\) tends to a uniform random walk. A patrol ghost continues in its stored direction while that move is valid, else rotates clockwise and picks uniformly from \(\mathcal{M}(y_k)\). An ambush ghost is deterministic: it minimizes a score that penalizes leaving the ring \(\mathrm{d} \in [2, 4]\) around PacMan by \(+10\), so it loiters at intercept range instead of closing. ghost_coordination selects whether ghosts also condition on each other.

Collision. The episode ends if PacMan and any ghost share a cell or swap cells — without the swap case a ghost would walk through PacMan:

\[\top' = 1 \quad\text{if}\quad \exists k:\; y'_k = x' \;\vee\; \big(y_k = x' \wedge y'_k = x\big)\]

Pellets. Landing on an active pellet clears it and adds pellet_reward to \(\text{score}\). If no pellet remains, \(\top' = 1\).

Hazard. A hazard zone is the set of cells within Euclidean distance dangerous_area_radius of a centre in dangerous_areas. When is_dangerous_area_hit_terminal, entering a zone ends the episode — always under the constant penalty model, and with probability \(e^{-\rho(x')/\lambda}\) under the distance-decayed one, where \(\rho(x')\) is the Euclidean distance from \(x'\) to the nearest centre and \(\lambda\) = penalty_decay. This is taken last, and only when the step has not already ended, so the terminal flag stays absorbing.

Observation model. PacMan’s own cell is known and never reported; the observation is one noisy cell per ghost. The noise grows with the distance to the ghost and then saturates:

\[\sigma_k = \mathrm{clip}\big(\texttt{observation\_noise\_factor} \cdot \mathrm{d}(y'_k, x'),\; 10^{-6},\; \texttt{max\_observation\_noise}\big)\]

Each coordinate is drawn, rounded and clamped to the grid independently:

\[\hat{y}_k = \mathrm{clip}\big(\mathrm{round}(y'_k + n_k),\; 0,\; (M{-}1, N{-}1)\big), \qquad n_k \sim \mathcal{N}(0, \sigma_k^2 I)\]

so the likelihood of a reading is the Gaussian mass of its rounding bin, with the two end bins absorbing the tails. A terminal state reports \((-1, -1)\) for every ghost. At the defaults an adjacent ghost has \(\sigma_k = 0.3\) cells and a ghost five or more cells away has \(\sigma_k = 1.5\) — which is what makes a point estimate of ghost positions a losing policy.

Reward function. Terminal states pay \(0\). Otherwise, evaluated against the realised transition:

\[\begin{split}R(s, a, s') = \;&\texttt{step\_penalty} \;+\; \texttt{pellet\_reward} \cdot \mathbb{1}[\text{pellet eaten}] \\ &+\; \texttt{ghost\_collision\_penalty} \cdot \mathbb{1}[\text{collision}] \\ &+\; \texttt{win\_reward} \cdot \mathbb{1}[\mathbf{m}' = \mathbf{0}] \;-\; D(x')\end{split}\]

where the hazard term \(D\) depends on reward_model_type, with \(p_D\) = dangerous_area_penalty and \(\rho(x')\) the Euclidean distance from \(x'\) to the nearest hazard centre:

  • CONSTANT_HAZARD_PENALTY: \(D(x') = p_D \cdot \mathbb{1}[x' \text{ in a hazard zone}]\).

  • ZERO_MEAN_HAZARD_SHOCK: if \(x'\) is in a hazard zone, \(D(x') = \pm p_D\) with probability \(\tfrac12\) each; else \(D(x') = 0\).

  • DISTANCE_DECAYED_HAZARD_PENALTY: \(D(x') = p_D\) with probability \(e^{-\rho(x')/\lambda}\), else \(0\).

with \(\lambda\) = penalty_decay. With no dangerous_areas, \(D = 0\).

Note

reward_batch called without next_states returns only the deterministic terms — step penalty, pellet, win — and omits the collision penalty, because that depends on the stochastic ghost draw. Pass the realised successors to get numbers that agree with the scalar path.

Initial belief. Fully known, a single state:

\[b_0(s) = \mathbb{1}[s = s_0], \qquad s_0 = \big(x_0,\, (y_k^0),\, \mathbf{1},\, 0,\, 0\big)\]

with:

  • \(x_0\) = initial_pacman_pos;

  • \(y_k^0\) the ghosts’ start cells (initial_ghost_positions);

  • every pellet present;

  • score 0;

  • not terminal.

Uncertainty does not come from the prior here — it accumulates from the observation noise as the ghosts move. The initial observation distribution is \(O\) at \(s_0\), not a point mass, so the first reading is already noisy.

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

Terminal set. \(S_T = \{s : \top = 1\}\) — reached by a collision, by clearing the last pellet, or by a terminal hazard hit.

Rewards

Event

Reward

Every non-terminal step

step_penalty (default -1.0)

Eat a pellet

pellet_reward (+10.0)

Share a cell with a ghost

ghost_collision_penalty (-100.0)

Eat the last pellet

win_reward (+100.0)

Inside a dangerous area

-dangerous_area_penalty

Warning

dangerous_area_penalty is a positive magnitude that gets subtracted here, the opposite of the convention in RockSample and Push, where the penalty is added and so must be passed negative.

Key settings

Argument

Default

What it changes

maze_size

(7, 7)

Grid size.

walls

5 fixed cells

Maze layout.

num_ghosts

1

Each ghost adds two dimensions to every observation.

ghost_strategies

["aggressive"]

Per ghost: "aggressive", "patrol" or "ambush".

ghost_coordination

"independent"

Also "coordinated" or "mixed".

observation_noise_factor

0.3

How fast ghost-position noise grows with distance, capped by max_observation_noise (1.5).

discount_factor

0.95

create_simple_maze_pacman(maze_size=7, num_walls=5, num_ghosts=1, seed=None) builds a randomized maze if you want variation across episodes.

An episode ends on a ghost collision, on clearing the last pellet, or on a hazard hit when is_dangerous_area_hit_terminal=True.

Can I use?

PacManPOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

✔️

❌

Also supports

Native C++ backend

✔️

Vectorized (torch) model

✔️ PacManVectorizedModel (some configurations; others raise NotImplementedError)

In the get_environment registry

✔️

Optional dependencies

None

Example

from POMDPPlanners.environments.pacman_pomdp import PacManPOMDP

env = PacManPOMDP(maze_size=(7, 7), num_ghosts=1)

state = env.initial_state_dist().sample(1)[0]
east = 1
observation = env.sample_observation(state, east)
print(env.get_pacman_pos(state), "believes ghosts near", observation)

Parameters

class POMDPPlanners.environments.pacman_pomdp.PacManPOMDP(maze_size=(7, 7), walls=None, initial_pellets=None, initial_pacman_pos=(0, 0), num_ghosts=1, initial_ghost_positions=None, initial_ghost_pos=None, pellet_reward=10.0, ghost_collision_penalty=-100.0, step_penalty=-1.0, win_reward=100.0, ghost_aggressiveness=2.0, ghost_coordination='independent', ghost_strategies=None, observation_noise_factor=0.3, max_observation_noise=1.5, dangerous_areas=None, dangerous_area_radius=1.0, dangerous_area_penalty=5.0, is_dangerous_area_hit_terminal=False, discount_factor=0.95, name='PacManPOMDP', output_dir=None, debug=False, reward_model_type=RewardModelType.CONSTANT_HAZARD_PENALTY, penalty_decay=1.0)[source]

Bases: DiscreteActionsEnvironment

PacMan POMDP environment inspired by the classic arcade game.

This environment implements a simplified PacMan game where PacMan must collect pellets while avoiding a single ghost. The ghost position is only partially observable through noisy sensor readings.

Parameters:
maze_size

Grid dimensions as (rows, cols)

walls

Set of wall positions as (row, col) tuples

initial_pellets

List of initial pellet positions

pellet_reward

Reward for collecting a pellet

ghost_collision_penalty

Penalty for collision with ghost

step_penalty

Cost per action

win_reward

Reward for collecting all pellets

ghost_aggressiveness

Temperature parameter for ghost movement policy

observation_noise_factor

Multiplier for observation noise based on distance

max_observation_noise

Maximum noise standard deviation

dangerous_areas

List of (row, col) centers of circular hazard zones

dangerous_area_radius

Radius (in grid cells) defining each hazard zone

dangerous_area_penalty

Penalty subtracted when PacMan ends a step inside a zone

Example

>>> import numpy as np
>>> np.random.seed(42)  # For reproducible results
>>>
>>> # Initialize environment
>>> env = PacManPOMDP(maze_size=(7, 7))
>>>
>>> # Get initial state and actions
>>> initial_state = env.initial_state_dist().sample()[0]
>>> actions = env.get_actions()
>>>
>>> # Sample complete step using convenience method
>>> action = actions[0]
>>> next_state, observation, reward = env.sample_next_step(initial_state, action)
>>>
>>> # Check terminal condition
>>> env.is_terminal(initial_state)
False

Example

Construct an env with a circular hazard zone — PacMan is penalised by dangerous_area_penalty whenever its realised next position lies inside the zone, but the zone does not block movement or terminate.

>>> import numpy as np
>>> np.random.seed(0)
>>> env = PacManPOMDP(
...     maze_size=(7, 7),
...     dangerous_areas={(3, 3)},
...     dangerous_area_radius=1.0,
...     dangerous_area_penalty=5.0,
... )
>>> state = env.initial_state_dist().sample()[0]
>>> _ = env.sample_next_step(state, env.get_actions()[0])
>>> env.dangerous_area_penalty
5.0
array_to_observation(arr)[source]

Convert a flat numpy array back to a PacMan observation tuple.

Parameters:

arr (ndarray) – 1-D array of shape (2 * num_ghosts,).

Return type:

Tuple[Tuple[int, int], ...]

Returns:

Observation as tuple of (row, col) tuples.

compute_metrics(histories)[source]

Compute environment-specific metrics.

Parameters:

histories (List[History]) – List of simulation histories.

Return type:

List[MetricValue]

Returns:

One MetricValue per declared metric name.

Raises:

ValueError – If histories is empty. See compute_metrics().

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

PacManVisualizer

get_actions()[source]

Get all available actions.

Return type:

List[int]

get_ghost_positions(state)[source]

Return ghost positions as a tuple of (row, col) pairs.

Return type:

Tuple[Tuple[int, int], ...]

Parameters:

state (ndarray)

get_metric_names()[source]

Get names of PacMan POMDP specific metrics.

Return type:

List[str]

Returns:

List containing metric names including standard metrics (task_completion_rate, average_pellets_collected, average_episode_length, average_closest_ghost_distance, average_collisions, average_dangerous_area_steps, average_dangerous_encounters) and dynamically generated per-ghost distance metrics for multi-ghost scenarios (average_ghost_0_distance, average_ghost_1_distance, etc.). average_dangerous_encounters is the per-step sum of ghost-collision and dangerous-area-step events; a step that is both counts twice.

get_observation_cpp_ctor_kwargs()[source]

Return the kwargs dict passed to PacManObservationCpp.

Return type:

Dict[str, Any]

get_pacman_pos(state)[source]

Return PacMan’s (row, col) position from a state array.

Return type:

Tuple[int, int]

Parameters:

state (ndarray)

get_pellets(state)[source]

Return the tuple of active pellet positions.

Return type:

Tuple[Tuple[int, int], ...]

Parameters:

state (ndarray)

get_score(state)[source]

Return the state’s score as a Python float.

Return type:

float

Parameters:

state (ndarray)

get_terminal(state)[source]

Return whether the state is terminal.

Return type:

bool

Parameters:

state (ndarray)

get_transition_cpp_ctor_kwargs()[source]

Return the cached per-env kwargs dict passed to PacManTransitionCpp.

Return type:

Dict[str, Any]

hash_action(action)[source]

Return a hashable key consistent with action equality.

Used by tree-search planners to index action children of a belief node in O(1). The returned key MUST satisfy:

action_a == action_b   (per env's notion of equality)
==> hash_action(action_a) == hash_action(action_b)

Subclasses with non-hashable actions (e.g. np.ndarray) must override to return a hashable surrogate (tobytes() is the standard choice for ndarray actions, which mirrors the np.array_equal semantics used by the linear-scan fallback).

Parameters:

action (Any) – Action to hash.

Return type:

Hashable

Returns:

A hashable key derived from action.

property initial_ghost_pos: Tuple[int, int]

returns first ghost position.

Type:

Backward compatibility

initial_observation_dist()[source]

Get the initial observation distribution.

Returns a live distribution that draws fresh noisy ghost-position observations from the true initial state on each sample call, instead of the previous Dirac wrapper around a single pre-drawn sample (which collapsed the entire initial-belief observation prior to a point mass).

Return type:

Distribution

initial_state_dist()[source]

Get initial state distribution.

Return type:

DiscreteDistribution

is_equal_observation(observation1, observation2)[source]

Check if two observations are equal.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_terminal(state)[source]

Check if state is terminal.

Return type:

bool

Parameters:

state (ndarray)

make_state(*, pacman_pos, ghost_positions, pellets=None, score=0.0, terminal=False)[source]

Build a PacMan state array in the canonical layout.

The array layout is [pac_row, pac_col, g0_row, g0_col, ..., pellet_mask[0..P-1], score, terminal].

Parameters:
  • pacman_pos (Tuple[int, int]) – PacMan grid position (row, col).

  • ghost_positions (Tuple[Tuple[int, int], ...]) – Per-ghost positions as a tuple of length num_ghosts.

  • pellets (Optional[Tuple[Tuple[int, int], ...]]) – Active pellet positions. None means every initial pellet is active (useful for constructing initial states).

  • score (float) – Current game score.

  • terminal (bool) – Whether the state is terminal.

Return type:

ndarray

Returns:

1-D float64 array of shape (self._state_dim,).

Raises:

ValueError – If any argument has the wrong type or length, or if a pellet position was not registered at env construction.

observation_log_probability(next_state, action, observations)[source]

Log-probability of each candidate observation under (next_state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate observations. Subclasses must implement.

Return type:

ndarray

Parameters:
observation_log_probability_per_state(next_states, action, observation)[source]

Log-probability of one observation under each candidate next-state.

Used by particle filters: given N candidate next-states and ONE observation, return N log-likelihoods.

The default implementation falls back to a per-state Python loop delegating to observation_log_probability(). Native-backed envs (those whose observation kernel exposes batch_log_likelihood(next_states_array, observation_array)) should override to avoid the loop.

Parameters:
  • next_states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of candidate next-states.

  • action (int) – The action that was executed.

  • observation (Any) – A single observation.

Return type:

ndarray

Returns:

ndarray of shape (N,) with log-probabilities or log-PDFs.

observation_to_array(obs)[source]

Convert a PacMan observation tuple to a flat numpy array.

Parameters:

obs (Tuple[Tuple[int, int], ...]) – Observation as tuple of ghost (row, col) positions.

Return type:

ndarray

Returns:

1-D array of shape (2 * num_ghosts,).

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

Calculate immediate reward.

Uses the realised next_state when supplied (e.g. by Environment.sample_next_step()) so the collision penalty and win bonus reflect the same stochastic ghost transition as the trajectory rather than a fresh independent draw. When next_state is None, falls back to sampling one here.

Return type:

float

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

Calculate rewards for a batch of states.

Accepts a 2-D numpy array of shape (N, state_dim) on the fast vectorized path, or a sequence of 1-D state arrays on the fallback per-particle path.

Without next_states, computes deterministic reward components only (step penalty, pellet collection, win bonus); ghost collision penalty is excluded because it depends on the stochastic ghost transition. When next_states is supplied (e.g. by a caller that already realised the batch transition), the collision penalty is included against those realised draws so the per- particle batch reward agrees with the trajectory-driven single-state path.

Return type:

ndarray

Parameters:
property reward_requires_next_state: bool

Reward depends on the realised next_state iff hazard-terminal is on.

When is_dangerous_area_hit_terminal is enabled, the dangerous-area penalty is deterministic given the terminal slot set during the transition, so drivers must sample the transition first and pass the realised next_state to reward().

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

Sample one or more next states for (state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single next state of the env’s native type. When n_samples > 1: an array-like of length n_samples (numeric envs return np.ndarray of shape (n_samples, *dim); structured envs return List[T]).

Return type:

Any

Parameters:
sample_next_state_batch(states, action)[source]

Sample one next state per input state, all under the same action.

Used by particle filters: given N current particles and one action, draw N next states (one per particle) in a single vectorized call.

The default implementation falls back to a per-state Python loop delegating to sample_next_state(). Native-backed envs (those whose state-transition kernel exposes batch_sample(states_array)) should override to avoid the loop.

Parameters:
  • states (Any) – A sequence (length N) or ndarray of shape (N, *dim) of input particles.

  • action (int) – A single action to apply to every particle.

Returns:

np.ndarray of shape (N, *dim). For structured envs (Tiger strings, Pacman tuples): a list of length N.

Return type:

ndarray

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

Sample one or more observations for (next_state, action).

Hot-path entry point used by MCTS planners and particle filters. Subclasses must implement.

Returns:

a single observation. When n_samples > 1: an array-like of length n_samples.

Return type:

Any

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

Estimate the value of state via a native C++ random rollout.

Pre-draws all action indices in NumPy, then delegates the entire trajectory (transition + reward accumulation) to the C++ kernel. This avoids per-step Python frame overhead for the common path.

Parameters:
  • state (Any) – Current state ndarray.

  • action_sampler (Any) – Object with a sample() method returning a random action; only used to pre-draw action integers.

  • max_depth (int) – Maximum rollout depth.

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

  • depth (int) – Current depth consumed by the search tree. Defaults to 0.

Return type:

float

Returns:

Discounted cumulative reward along the sampled trajectory.

state_layout()[source]

Return where each field sits in a state array built by make_state().

The readers above are the way Python code should take a state apart. A consumer outside Python cannot call them — a browser viewer replaying a trace gets belief particles as raw arrays and has to slice them itself — so the layout is published here rather than re-derived from num_ghosts and the pellet count by every such reader, which would be a second definition free to drift from this one.

Return type:

Dict[str, int]

Returns:

Index of each field in the canonical layout, plus the array’s total dim. Ghost g occupies ghosts_start + 2 * g and the slot after it; the pellet mask spans pellets_start up to (but excluding) pellets_end.

transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate next state under (state, action).

Returns np.ndarray of shape (N,) where N is the number of candidate next states. Subclasses must implement.

Return type:

ndarray

Parameters:

See also