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
float64vector[pac_row, pac_col, ghost positions…, pellet_mask…, score, terminal]. Construct one withenv.make_state(...)and read it withenv.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) —
0north,1east,2south,3west,4stay.Observations (discrete) — a tuple of one noisy
(row, col)per ghost. Convert to and from a flat array withenv.observation_to_arrayandenv.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_ghostsghosts.
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
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.
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:
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:
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:
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:
Each coordinate is drawn, rounded and clamped to the grid independently:
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:
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:
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 |
|
Eat a pellet |
|
Share a cell with a ghost |
|
Eat the last pellet |
|
Inside a dangerous area |
|
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 |
|---|---|---|
|
|
Grid size. |
|
5 fixed cells |
Maze layout. |
|
|
Each ghost adds two dimensions to every observation. |
|
|
Per ghost: |
|
|
Also |
|
|
How fast ghost-position noise grows with distance, capped by
|
|
|
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?
|
Discrete |
Continuous |
|---|---|---|
State |
✔️ |
❌ |
Action |
✔️ |
❌ |
Observation |
✔️ |
❌ |
Also supports |
|
|---|---|
Native C++ backend |
✔️ |
Vectorized (torch) model |
✔️ |
In the |
✔️ |
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:
DiscreteActionsEnvironmentPacMan 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:
num_ghosts (int)
pellet_reward (float)
ghost_collision_penalty (float)
step_penalty (float)
win_reward (float)
ghost_aggressiveness (float)
ghost_coordination (str)
observation_noise_factor (float)
max_observation_noise (float)
dangerous_area_radius (float)
dangerous_area_penalty (float)
is_dangerous_area_hit_terminal (bool)
discount_factor (float)
name (str)
output_dir (Path | None)
debug (bool)
reward_model_type (RewardModelType)
penalty_decay (float)
- 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_penaltywhenever 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
- compute_metrics(histories)[source]
Compute environment-specific metrics.
- Parameters:
- Return type:
- Returns:
One MetricValue per declared metric name.
- Raises:
ValueError – If
historiesis empty. Seecompute_metrics().
- episode_visualizer()[source]
Return the visualizer that writes this environment’s traces.
- Return type:
PacManVisualizer
- get_metric_names()[source]
Get names of PacMan POMDP specific metrics.
- Return type:
- 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_encountersis the per-step sum of ghost-collision and dangerous-area-step events; a step that is both counts twice.
- get_transition_cpp_ctor_kwargs()[source]
Return the cached per-env kwargs dict passed to PacManTransitionCpp.
- 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 thenp.array_equalsemantics used by the linear-scan fallback).
- 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
samplecall, 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:
- 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 lengthnum_ghosts.pellets (
Optional[Tuple[Tuple[int,int],...]]) – Active pellet positions.Nonemeans every initial pellet is active (useful for constructing initial states).score (
float) – Current game score.terminal (
bool) – Whether the state is terminal.
- Return type:
- Returns:
1-D
float64array 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.ndarrayof shape(N,)where N is the number of candidate observations. Subclasses must implement.
- 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 exposesbatch_log_likelihood(next_states_array, observation_array)) should override to avoid the loop.
- reward(state, action, next_state=None)[source]
Calculate immediate reward.
Uses the realised
next_statewhen supplied (e.g. byEnvironment.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. Whennext_stateisNone, falls back to sampling one here.
- 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. Whennext_statesis 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.
- property reward_requires_next_state: bool
Reward depends on the realised
next_stateiff hazard-terminal is on.When
is_dangerous_area_hit_terminalis 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 realisednext_statetoreward().
- 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.
- 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 exposesbatch_sample(states_array)) should override to avoid the loop.
- 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.
- simulate_random_rollout(state, action_sampler, max_depth, discount_factor, depth=0)[source]
Estimate the value of
statevia 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 asample()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:
- 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_ghostsand the pellet count by every such reader, which would be a second definition free to drift from this one.
See also
Batched torch model:
POMDPPlanners.environments.pacman_pomdp.pacman_vectorized_model.PacManVectorizedModelBase Environment Class — the full catalog and the environment interface.