Capture the Flag

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.

CaptureTheFlagPOMDP puts two teams on a grid field split by a midline. Each team has a flag. The planner drives the blue team as one joint controller; the red team belongs to the transition model and follows a stochastic role policy. Blue wins by carrying the red flag to the blue base while its own flag is still home.

Blue never sees the red players, and does not know which of K candidate cells holds the red flag. Both are inferred from one observation vector, which gives strong evidence about where the enemy is and weak evidence about where the flag is.

What the agent sees and does

  • State — a float64 vector of length 4 * n_blue + 4 * n_red + 5 (21 at the default two-a-side): blue cells, red cells, the red flag’s candidate index, a carrier index per flag, a respawn-freeze and a tagger-cooldown counter per player, and the two scores.

  • Actions (discrete) — an int in 0 .. 6 ** n_blue - 1 (36 at the default two-a-side): one joint action for the whole blue team, encoded in base 6. Each player has six actions — four moves (0 north, 1 east, 2 south, 3 west), 4 hold, and 5 scan. Scan does not move the player; it widens that player’s flag detector for the step and costs more.

  • Observations (continuous) — a tuple of 4 * n_blue + n_blue * n_red + 4 numbers (16 at the default): blue’s own cells, a noisy range to each red player per blue player, a flag-detector bit per blue player, who carries the red flag, whether blue’s flag is taken, blue’s freeze counters, and both scores. Blue sees its own team exactly – positions, freeze counters, who is carrying – plus the score and whether its own flag has been taken. It does not see the red players, the red flag cell, or which red player took its flag. A terminal state emits all -1.

Formal definition

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

State space. The notation:

  • Field. The field is a grid of \(W \times H\) cells (grid_size). A cell is written \((x, y)\) with \(x \in \{0..W-1\}\) the column and \(y \in \{0..H-1\}\) the row.

  • Trees. Some cells hold trees (trees), which no player can enter. \(G\) is the set of cells inside the field and not a tree.

  • Flag candidates. The red flag’s home is one of \(K\) candidate cells \(F = (f_1, \dots, f_K)\) (red_flag_candidates).

  • Players. There are \(n_{\text{blue}}\) blue players, numbered \(1..n_{\text{blue}}\), and \(n_{\text{red}}\) red players, numbered \(1..n_{\text{red}}\).

A state is one vector:

\[\begin{split}s = \big(&\underbrace{x^{\text{blue}}_{1:n_{\text{blue}}}}_{\text{blue cells}},\; \underbrace{x^{\text{red}}_{1:n_{\text{red}}}}_{\text{red cells}},\; k,\; c^{\text{red}}, c^{\text{blue}},\; \\ &\text{freeze}^{\text{blue}}_{1:n_{\text{blue}}}, \text{freeze}^{\text{red}}_{1:n_{\text{red}}},\; \text{cool}^{\text{blue}}_{1:n_{\text{blue}}}, \text{cool}^{\text{red}}_{1:n_{\text{red}}},\; \text{score}^{\text{blue}}, \text{score}^{\text{red}} \big)\end{split}\]
\[S = G^{n_{\text{blue}}} \times G^{n_{\text{red}}} \times \{1..K\} \times \{0..n_{\text{blue}}\} \times \{0..n_{\text{red}}\} \times \mathbb{Z}_{\geq 0}^{2(n_{\text{blue}} + n_{\text{red}})} \times \mathbb{Z}_{\geq 0}^2\]

with these components:

  • \(x^{\text{blue}}_i \in G\) — the cell of blue player \(i\); \(x^{\text{red}}_j \in G\) — the cell of red player \(j\).

  • \(k \in \{1..K\}\) — which candidate \(f_k\) is the red flag’s home.

  • \(c^{\text{red}} \in \{0..n_{\text{blue}}\}\) — the blue player carrying the red flag, \(0\) if the red flag is home; \(c^{\text{blue}} \in \{0..n_{\text{red}}\}\) — the red player carrying the blue flag, \(0\) if the blue flag is home.

  • \(\text{freeze}^{\text{blue}}_i, \text{freeze}^{\text{red}}_j\) — steps left before a tagged player may act again.

  • \(\text{cool}^{\text{blue}}_i, \text{cool}^{\text{red}}_j\) — steps left before a player who tagged someone may tag again.

  • \(\text{score}^{\text{blue}}, \text{score}^{\text{red}}\) — the number of flags each team has captured.

\(s\) is the state an action is taken from and \(s'\) the state after the step; a prime marks a component of \(s'\), as in \(x^{\text{blue}\prime}_i\).

Action space. One action per blue player, issued together as one joint action:

\[A = \{0, \dots, 5\}^{n_{\text{blue}}}, \qquad |A| = 6^{n_{\text{blue}}}\]

The joint action is the base-6 integer \(a = \sum_{i=1}^{n_{\text{blue}}} a_i 6^{i-1}\), where \(a_i\) is blue player \(i\)’s action:

  • \(0\) — move north, \(y + 1\);

  • \(1\) — move east, \(x + 1\);

  • \(2\) — move south, \(y - 1\);

  • \(3\) — move west, \(x - 1\);

  • \(4\) — hold: stay in place;

  • \(5\) — scan: stay in place, and read the flag detector at longer range this step.

Only blue is controlled; the red players move as part of \(T\).

Observation space. Each observation is one vector with these components, in order:

  • \(x^{\text{blue}}_{1:n_{\text{blue}}} \in G^{n_{\text{blue}}}\) — every blue player’s cell, exact.

  • \(\hat d_{ij} \in \{0..d_{\max}\}\) for every blue player \(i\) and red player \(j\), ordered by \(i\) then \(j\) — a noisy reading of the Manhattan distance from \(i\) to \(j\), where \(d_{\max} = W + H - 2\) is the largest distance on the field.

  • \(z_i \in \{0, 1\}\) for every blue player \(i\) — a noisy flag-detector bit; \(z_i = 1\) is more likely the closer player \(i\) is to the red flag.

  • \(c^{\text{red}} \in \{0..n_{\text{blue}}\}\) — the blue player carrying the red flag, \(0\) if none, exact.

  • \(\mathbb{1}[c^{\text{blue}} \neq 0] \in \{0, 1\}\) — \(1\) if a red player is carrying the blue flag, exact; which red player is not observed.

  • \(\text{freeze}^{\text{blue}}_{1:n_{\text{blue}}}\) — every blue player’s freeze counter, exact.

  • \(\text{score}^{\text{blue}}, \text{score}^{\text{red}}\) — both scores, exact.

\[\begin{split}Z = \;&G^{n_{\text{blue}}} \times \{0..d_{\max}\}^{n_{\text{blue}} n_{\text{red}}} \times \{0,1\}^{n_{\text{blue}}} \\ &\times \{0..n_{\text{blue}}\} \times \{0,1\} \times \mathbb{Z}_{\geq 0}^{n_{\text{blue}}} \times \mathbb{Z}_{\geq 0}^2 \;\cup\; \{(-1, \dots, -1)\}\end{split}\]

The red players’ cells, \(k\), and the red counters are not observed. A terminal state emits the all \(-1\) vector.

Transition model. The model uses:

  • \(p_s\) = slip_probability;

  • \(p_r\) = red_pursuit_probability;

  • \(r\) = red_alert_radius;

  • \(n_d\) = n_red_defenders;

  • \(F_{\max}\) = freeze_steps;

  • \(C_{\max}\) = tagger_cooldown_steps;

  • \(m\) = midline;

  • \(b^{\text{blue}}, b^{\text{red}}\) = blue_base, red_base;

  • \(h^{\text{blue}}\) = blue_flag_cell, \(h^{\text{red}} = f_k\);

  • \(\mathrm{d}\), the Manhattan distance.

The blue half is left of the midline, the red half right of it:

\[H^{\text{blue}} = \{(x, y) \in G : x < m\}, \qquad H^{\text{red}} = \{(x, y) \in G : x > m\}\]

\(\Delta_a\) is the one-cell move of action \(a\), and \(\mathrm{side}(a)\) is the set of the two moves at right angles to it — a north or south move slips east or west, an east or west move slips north or south:

\[\begin{split}&\Delta_0 = (0, 1),\; \Delta_1 = (1, 0),\; \Delta_2 = (0, -1),\; \Delta_3 = (-1, 0), \\ &\mathrm{side}(0) = \mathrm{side}(2) = \{1, 3\},\; \mathrm{side}(1) = \mathrm{side}(3) = \{0, 2\}\end{split}\]

\(\mathrm{blk}_x(y)\) keeps a player at \(x\) when the target \(y\) is a tree or off the field; \(N(x)\) is \(x\) and its free neighbours:

\[\begin{split}\mathrm{blk}_x(y) = \begin{cases} y & y \in G \\ x & y \notin G \end{cases}, \qquad N(x) = \{x\} \cup \{x + \Delta_a \in G : a \in \{0..3\}\}\end{split}\]

\(\delta_x\) is the distribution that puts probability 1 on cell \(x\), and \(\mathcal{U}(N)\) is the uniform distribution over a set of cells \(N\). A step applies, in order:

Blue moves. A frozen, holding or scanning player stays. Otherwise it moves as chosen, or slips to a right angle with probability \(p_s\). With \(x = x^{\text{blue}}_i\):

\[\begin{split}x^{\text{blue}\prime}_i \sim \begin{cases} \delta_x & \text{freeze}^{\text{blue}}_i > 0 \;\lor\; a_i \in \{4, 5\} \\ (1 - p_s)\,\delta_{\mathrm{blk}_x(x + \Delta_{a_i})} + \sum_{a' \in \mathrm{side}(a_i)} \tfrac{p_s}{2}\,\delta_{\mathrm{blk}_x(x + \Delta_{a'})} & \text{otherwise} \end{cases}\end{split}\]

Red moves. Each red player first picks a target \(q_j\):

  • the red base if it carries the blue flag;

  • the blue flag if it is an attacker (\(j > n_d\));

  • otherwise, as a defender, the nearest blue player in the red half \(\iota_j\) if one is within \(r\), else the free cell beside the red flag nearest the red base.

With \(x = x^{\text{red}}_j\):

\[\begin{split}q_j &= \begin{cases} b^{\text{red}} & c^{\text{blue}} = j \\ h^{\text{blue}} & j > n_d \\ \iota_j & j \le n_d,\; \mathrm{d}(x, \iota_j) \le r \\ \operatorname{arg\,min}_{y \in N(h^{\text{red}}) \setminus \{h^{\text{red}}\}} \mathrm{d}(y, b^{\text{red}}) & \text{otherwise} \end{cases}, \\ \iota_j &= \operatorname{arg\,min}_{x^{\text{blue}\prime}_i \in H^{\text{red}}} \mathrm{d}(x, x^{\text{blue}\prime}_i)\end{split}\]

It then steps toward \(q_j\) with probability \(p_r\) and to a random neighbour otherwise; a frozen red player stays:

\[\begin{split}x^{\text{red}\prime}_j &\sim \begin{cases} \delta_x & \text{freeze}^{\text{red}}_j > 0 \\ (1 - p_r)\,\mathcal{U}\big(N(x)\big) + p_r\,\mathcal{U}\big(N^\star_j\big) & \text{otherwise} \end{cases}, \\ N^\star_j &= \operatorname{arg\,min}_{y \in N(x)} \mathrm{d}(y, q_j)\end{split}\]

Pick-up. An unfrozen player on the other team’s flag takes it if no one carries it; the lowest index wins a tie:

\[\begin{split}c^{\text{red}} \leftarrow \min\{i : x^{\text{blue}\prime}_i = h^{\text{red}},\; \text{freeze}^{\text{blue}}_i = 0\} \quad \text{if } c^{\text{red}} = 0, \\ c^{\text{blue}} \leftarrow \min\{j : x^{\text{red}\prime}_j = h^{\text{blue}},\; \text{freeze}^{\text{red}}_j = 0\} \quad \text{if } c^{\text{blue}} = 0\end{split}\]

(unchanged when the set is empty).

Tagging. A player caught on an opponent’s cell in the opponent’s half is sent home, frozen, and drops the flag; the tagger cools down. Red tags first: for \(j = 1..n_{\text{red}}\), red player \(j\) tags the lowest \(i\) with

\[x^{\text{blue}\prime}_i = x^{\text{red}\prime}_j \in H^{\text{red}},\quad \text{freeze}^{\text{blue}}_i = \text{freeze}^{\text{red}}_j = \text{cool}^{\text{red}}_j = 0\]
\[\Rightarrow\; x^{\text{blue}\prime}_i \leftarrow b^{\text{blue}},\; \text{freeze}^{\text{blue}\prime}_i \leftarrow F_{\max},\; \text{cool}^{\text{red}\prime}_j \leftarrow C_{\max},\; c^{\text{red}} \leftarrow 0 \text{ if } c^{\text{red}} = i\]

Then the same with colours swapped (\(H^{\text{blue}}\), \(b^{\text{red}}\), \(c^{\text{blue}}\)), skipping blue players tagged this step.

Scoring. A team scores when its carrier stands on its own base while its own flag is home; the captured flag goes back home:

\[\begin{split}\sigma^{\text{blue}} &= \mathbb{1}\big[c^{\text{red}} \ne 0 \wedge x^{\text{blue}\prime}_{c^{\text{red}}} = b^{\text{blue}} \wedge c^{\text{blue}} = 0\big], \\ \sigma^{\text{red}} &= \mathbb{1}\big[c^{\text{blue}} \ne 0 \wedge x^{\text{red}\prime}_{c^{\text{blue}}} = b^{\text{red}} \wedge c^{\text{red}} = 0\big]\end{split}\]
\[\begin{split}\text{score}^{\text{blue}\prime} = \text{score}^{\text{blue}} + \sigma^{\text{blue}},\; \text{score}^{\text{red}\prime} = \text{score}^{\text{red}} + \sigma^{\text{red}}, \\ c^{\text{red}\prime} = (1 - \sigma^{\text{blue}})\,c^{\text{red}},\; c^{\text{blue}\prime} = (1 - \sigma^{\text{red}})\,c^{\text{blue}}\end{split}\]

Counters. Every freeze and cooldown not just set by a tag counts down by one:

\[\text{freeze}' = \max(\text{freeze} - 1, 0), \qquad \text{cool}' = \max(\text{cool} - 1, 0)\]

Observation model. The observation is drawn from the successor state \(s'\) and the joint action \(a\):

\[o = \big(x^{\text{blue}\prime}_{1:n_{\text{blue}}},\; \underbrace{\hat{d}_{ij}}_{n_{\text{blue}} \times n_{\text{red}}},\; \underbrace{z_{1:n_{\text{blue}}}}_{\text{flag detector}},\; c^{\text{red}\prime},\; \mathbb{1}[c^{\text{blue}\prime} \neq 0],\; \text{freeze}^{\text{blue}\prime}_{1:n_{\text{blue}}},\; \text{score}^{\text{blue}\prime}, \text{score}^{\text{red}\prime}\big)\]

Blue’s cells, the red-flag carrier, whether the blue flag is taken, blue’s freeze counters and the scores are copied exactly from \(s'\): an observation that disagrees with them has likelihood zero, not merely a small one. The range readings \(\hat d_{ij}\) and the flag-detector bits \(z_i\) are noisy, and drawn independently:

Range readings. Blue player \(i\) reads the Manhattan distance \(\mathrm{d}\) to red player \(j\), correct with probability \(1 - p_e\) where \(p_e\) = range_error_probability (default \(0.2\)), and off by one otherwise:

\[\begin{split}\Pr[\hat{d}_{ij} = v] = \begin{cases} 1 - p_e & v = d_{ij} \\ p_e / 2 & v = d_{ij} \pm 1 \end{cases}, \qquad d_{ij} = \mathrm{d}(x^{\text{blue}\prime}_i, x^{\text{red}\prime}_j)\end{split}\]

clipped to \([0, d_{\max}]\), \(d_{\max} = W + H - 2\), with the out-of-range mass folded back onto the endpoint, so it sums to one at the field’s extremes too.

Flag detector. Blue player \(i\) reads one bit \(z_i\), a noisy signal that the red flag is near: \(z_i = 1\) is likelier the nearer player \(i\) is to the red flag’s cell \(f_k\):

\[\Pr[z_i = 1] = \tfrac{1}{2}\big(1 + 2^{-d^f_i / d_0(a_i)}\big), \qquad d^f_i = \mathrm{d}(x^{\text{blue}\prime}_i, f_k)\]

where \(a_i\) is player \(i\)’s action and \(d_0(a_i)\) is the distance at which the reading is right with probability \(0.75\): detector_half_distance_scan (default \(4.0\)) when \(a_i = 5\) (scan) and detector_half_distance_move (default \(1.5\)) otherwise — the same \(\tfrac{1}{2}(1 + 2^{-d/d_0})\) law RockSample uses, so it never drops below \(\tfrac{1}{2}\).

A terminal state emits the sentinel \(o = (-1, \dots, -1)\).

The asymmetry between the range readings and the flag-detector bits is the planning problem. The \(n_{\text{blue}} n_{\text{red}}\) range readings multiply: at the default two-a-side, moving one red player a single cell changes two of the four readings and costs a factor of \(((1-p_e)/(p_e/2))^2 = 64\) in likelihood. One flag scan barely separates the candidates. Strong evidence about where the enemy is, weak evidence about where the flag is.

Reward function. Additive over the realised transition, so it needs \(s'\) (reward_requires_next_state is True):

\[\begin{split}R(s, a, s') = \;&\texttt{capture\_reward} \cdot \Delta\text{score}^{\text{blue}} \;-\; \texttt{concede\_penalty} \cdot \Delta\text{score}^{\text{red}} \\ &-\; \texttt{tagged\_penalty} \cdot n_{\text{suffered}} \;+\; \texttt{tag\_reward} \cdot n_{\text{inflicted}} \\ &+\; \texttt{pickup\_reward} \cdot \mathbb{1}[c^{\text{red}} = 0 \wedge c^{\text{red}\prime} \neq 0] \;-\; \sum_{i=1}^{n_{\text{blue}}} \mathrm{cost}(a_i)\end{split}\]

where:

  • \(\Delta\text{score}\) is a team’s score in \(s'\) minus its score in \(s\);

  • \(n_{\text{suffered}}\) and \(n_{\text{inflicted}}\) are the numbers of blue and red players tagged this step;

  • \(a_i\) is blue player \(i\)’s action.

Every blue player pays for its action, frozen or not:

\[\begin{split}\mathrm{cost}(a_i) = \begin{cases} \texttt{move\_cost} \;(\text{default } 1) & a_i \in \{0, 1, 2, 3, 4\} \text{ (a move or hold)} \\ \texttt{scan\_cost} \;(\text{default } 2) & a_i = 5 \text{ (scan)} \end{cases}\end{split}\]

\(R(s, a, s') = 0\) for terminal \(s\). A tag is read off the freeze counters: a player that was not frozen in \(s\) and has freeze freeze_steps in \(s'\) was tagged this step. None of these terms exclude each other, so the declared reward_range is the joint worst case, not the largest single term.

Initial belief. Everything is known except which candidate \(k\) holds the red flag:

\[b_0\big(s(k)\big) = \tfrac{1}{K}, \qquad k \in \{1, \dots, K\}\]

where \(s(k)\) has:

  • every blue player on the blue base;

  • every red player on the red base;

  • no flag carried;

  • every freeze counter, cooldown and score at zero.

The opening observation is drawn from the observation model averaged over the \(K\) candidates, so a filter that weights it stays uniform over the candidates instead of favouring the nearer ones. When there are more than 8192 possible opening observations, the environment returns the single most likely one instead of listing them all.

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

Terminal set. The states where either team has captured score_to_win flags:

\[S_T = \{s : \text{score}^{\text{blue}} \geq \texttt{score\_to\_win} \ \text{or}\ \text{score}^{\text{red}} \geq \texttt{score\_to\_win}\}\]

with score_to_win = 1 by default.

Step order

One step resolves in a fixed order:

  1. blue moves;

  2. red moves;

  3. flags are picked up;

  4. tags are resolved;

  5. scores are awarded;

  6. counters tick.

Changing the order changes the outcome. Pick-up runs before tagging, so a player tagged while standing on the flag cell has already taken the flag and therefore drops it. Both scoring conditions are judged against the same carrier indices, which keeps blue scoring and red scoring mutually exclusive – each needs the other side’s flag to be home.

Tagging and respawn

A player is tagged when an opponent shares its cell in the enemy half, and only by a tagger that is neither frozen nor on cooldown. Being tagged does not end the episode: the player returns to its own base, drops any flag it carried, and is frozen for freeze_steps. The tagger is put on cooldown for tagger_cooldown_steps, which is what stops a defender camping the flag and tagging repeatedly.

Rewards

The reward terms:

  • scoring earns capture_reward;

  • conceding costs concede_penalty;

  • each blue player tagged costs tagged_penalty;

  • each red player tagged earns tag_reward;

  • first pick-up earns pickup_reward;

  • every player pays its action’s cost.

None of these exclude each other, so the declared reward range is the joint worst case rather than the largest single term.

Default values, from the constructor:

Event

Reward

Blue scores (capture_reward)

+100.0

Red scores (concede_penalty)

-100.0

Blue player tagged (tagged_penalty)

-25.0 each

Red player tagged (tag_reward)

+10.0 each

First pick-up (pickup_reward)

+20.0

Move or hold (move_cost)

-1.0 per player

Scan (scan_cost)

-2.0 per player

Key settings

The defaults:

  • a 9 by 7 field (grid_size=(9, 7)) split at column midline=4;

  • two players per team (n_blue=2, n_red=2), one of them a red defender (n_red_defenders=1);

  • blue moves slip sideways with probability slip_probability=0.1;

  • a range badge reads off by one with probability range_error_probability=0.2;

  • a red player steps toward its target with probability red_pursuit_probability=0.7;

  • score_to_win=1 capture ends the episode;

  • discount_factor defaults to 0.98.

The reward arguments are listed under Rewards above.

Metrics

  • The completion metric is task_completion_rate.

  • Episodes are also split by why they ended – ended_by_goal_rate, ended_by_failure_rate and ended_by_timeout_rate – because a completion rate alone cannot tell a planner taking bad risks from one given too small a step budget.

  • Alongside episode length, the environment reports tags suffered and inflicted, steps spent holding the enemy flag, and exposure in the enemy half as both a count and a per-episode maximum.

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.

Limits

VOPP plans on CaptureTheFlagVectorizedModel, the torch model in capture_the_flag_vectorized_model. The model reads every rule parameter from the environment and accepts every configuration the constructor accepts, so no configuration is declined. The model draws its random numbers in a different order from the scalar environment, so the two agree in distribution but not draw for draw: the same seed gives a different episode under each.

Can I use?

CaptureTheFlagPOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

❌

✔️

Also supports

Native C++ backend

❌

Vectorized (torch) model

✔️ CaptureTheFlagVectorizedModel (every configuration)

In the get_environment registry

✔️

Optional dependencies

None

Example

from POMDPPlanners.environments.capture_the_flag_pomdp import CaptureTheFlagPOMDP

env = CaptureTheFlagPOMDP(grid_size=(9, 7), midline=4, n_blue=2, n_red=2)

Parameters

class POMDPPlanners.environments.capture_the_flag_pomdp.CaptureTheFlagPOMDP(grid_size=(9, 7), midline=4, trees=None, n_blue=2, n_red=2, n_red_defenders=1, blue_base=(0, 3), red_base=(8, 3), blue_flag_cell=(1, 3), red_flag_candidates=None, slip_probability=0.1, range_error_probability=0.2, red_pursuit_probability=0.7, red_alert_radius=3, freeze_steps=3, tagger_cooldown_steps=2, detector_half_distance_move=1.5, detector_half_distance_scan=4.0, score_to_win=1, capture_reward=100.0, concede_penalty=100.0, tagged_penalty=25.0, tag_reward=10.0, pickup_reward=20.0, move_cost=1.0, scan_cost=2.0, discount_factor=0.98, output_dir=None, debug=False, use_queue_logger=False)[source]

Bases: DiscreteActionsEnvironment

Team capture-the-flag on a grid, with hidden red players and a hidden flag.

Parameters:
grid_size

Field size as (width, height).

midline

Column index of the neutral midline. Blue owns columns below it, red owns columns above it.

trees

Impassable cells, sorted.

n_blue

Number of blue players, controlled jointly by the planner.

n_red

Number of red players, driven by the environment’s role policy.

red_flag_candidates

Cells the red flag may occupy; which one is hidden.

layout

Index offsets into the flat state vector.

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

CaptureTheFlagVisualizer

free_cells()[source]

List every cell a player may stand on.

Return type:

List[Tuple[int, int]]

Returns:

All free cells, in column-major order.

get_actions()[source]

Return every joint action id.

Return type:

List[int]

get_metric_names()[source]

Return every metric name, in declaration order.

Return type:

List[str]

get_metric_specs()[source]

Declare every metric this environment reports.

Return type:

List[StepInfoMetric]

Returns:

One spec per channel, in the order CaptureTheFlagMetrics declares the names.

guard_post(flag_cell)[source]

Return the cell an idle defender stands on to watch a flag.

Beside the flag, never on it. A defender parked on the objective makes the objective unreachable: pick-up resolves before tagging, so an attacker arriving on the cell takes the flag and is tagged on the same step, every time, and the flag returns home. Standing one cell away leaves the approach contestable, which is both how the real game is played and what makes the defender’s alert radius mean anything.

Parameters:

flag_cell (Tuple[int, int]) – The flag being watched.

Return type:

Tuple[int, int]

Returns:

The free neighbour nearest the defender’s own base, or the flag cell itself when it has no free neighbour to stand on.

hash_action(action)[source]

Return a hashable key for a joint action id.

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]

Observation distribution before the first action.

This is a real draw from the observation model, not a representative reading. Everything but the red flag’s cell is known at spawn, so the distribution is the mixture over the candidates of the sensor noise each one implies – and a filter that weights the opening observation through observation_log_probability() therefore stays uniform over the candidates instead of favouring the nearer ones.

Return type:

Distribution

Returns:

The exact opening observation distribution, or the single most likely observation when the support is larger than _MAX_ENUMERATED_OBSERVATIONS and enumerating it would cost more than it informs.

initial_state_dist()[source]

Opening distribution: everything known but the red flag’s cell.

Return type:

Distribution

Returns:

A uniform distribution over the red flag candidates.

is_blue_half(cell)[source]

Return whether a cell belongs to the blue half.

Return type:

bool

Parameters:

cell (Tuple[int, int])

is_equal_observation(observation1, observation2)[source]

Return whether two observations are identical.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_free(cell)[source]

Return whether a cell is inside the field and not a tree.

Parameters:

cell (Tuple[int, int]) – The (x, y) cell to test.

Return type:

bool

Returns:

True if a player may stand on the cell.

is_red_half(cell)[source]

Return whether a cell belongs to the red half.

Return type:

bool

Parameters:

cell (Tuple[int, int])

is_terminal(state)[source]

Return whether either side has reached the winning score.

Return type:

bool

Parameters:

state (ndarray)

observation_log_probability(next_state, action, observations)[source]

Log-likelihood of each observation under a successor state.

The exactly-observed components act as a delta factor: an observation that disagrees with them is impossible, not merely unlikely.

Parameters:
  • next_state (ndarray) – The realised successor state.

  • action (int) – The joint action taken to reach it.

  • observations (Any) – Candidate observations.

Return type:

ndarray

Returns:

One log-likelihood per candidate.

observation_log_probability_per_state(next_states, action, observation)[source]

Log-likelihood of one observation under each candidate successor.

Parameters:
  • next_states (Any) – Candidate successor states, shape (N, state_size).

  • action (Any) – The joint action taken to reach them.

  • observation (Any) – The single observation to score.

Return type:

ndarray

Returns:

One log-likelihood per candidate, equal to what observation_log_probability() returns for each one.

red_flag_cell(state)[source]

Return the red flag’s home cell for a state.

Parameters:

state (ndarray) – A state vector.

Return type:

Tuple[int, int]

Returns:

The candidate cell the red flag belongs to in this state.

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

Reward for one transition.

Parameters:
  • state (ndarray) – The state the step was taken from.

  • action (int) – The joint action id.

  • next_state (Any) – The realised successor. Sampled here when None, which callers should avoid: it consumes randomness and returns the reward of a different draw than the trajectory took.

Return type:

float

Returns:

The immediate reward.

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

Rewards for a batch of transitions.

Parameters:
  • states (Any) – Array of state vectors.

  • action (int) – The joint action id applied to every state.

  • next_states (Any) – Realised successors, one per state.

Return type:

ndarray

Returns:

One reward per transition.

property reward_requires_next_state: bool

Whether reward() needs the realised successor.

Returns:

scoring, tagging and pick-up are all properties of the realised transition, not of (state, action) alone.

Return type:

Always True

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

Sample the successor state.

Runs the C++ model; _python_sample_next_state() is the reference it is tested against.

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

  • action (int) – Joint action id.

  • n_samples (int) – Number of independent samples to draw.

Return type:

Any

Returns:

One state vector when n_samples is 1, otherwise a list of them.

sample_next_state_batch(states, action)[source]

Sample one successor for each state in a batch.

Parameters:
  • states (Any) – Array of state vectors, shape (N, state_size).

  • action (int) – Joint action id applied to every state.

Return type:

ndarray

Returns:

Successor states as a (N, state_size) float64 array, matching the dtype of the single-state path.

sample_next_step(state, action)[source]

Sample successor, observation and reward in one C++ call.

Same result as the base class’s three calls – the reward is scored on the drawn successor – without two extra round trips into Python.

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

  • action (Any) – Joint action id.

Return type:

Tuple[Any, Any, float]

Returns:

(next_state, observation, reward).

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

Sample the blue team’s observation of a successor state.

Parameters:
  • next_state (ndarray) – The realised successor state.

  • action (int) – The joint action taken to reach it, which sets each player’s detector range.

  • n_samples (int) – Number of independent samples to draw.

Return type:

Any

Returns:

One observation tuple when n_samples is 1, otherwise a list.

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

Random rollout run in C++, used by the planners’ rollout dispatcher.

Joint actions are drawn uniformly with np.random up front, one per remaining step, as the other native rollouts do; action_sampler is used only when the Python reference runs.

Parameters:
  • state (Any) – Starting state vector.

  • action_sampler (Any) – Sampler the Python fallback draws actions from.

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

  • discount_factor (float) – Per-step discount.

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

Return type:

float

Returns:

The discounted sum of rewards until max_depth or a terminal state.

step_info(state, action, next_state)[source]

Report per-step channels for this transition.

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

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

  • next_state (Any) – The realised successor, or None on the terminal step.

Return type:

Dict[str, float]

Returns:

The per-step channels. Transition-derived channels report zero on the terminal step; state-derived ones still report, because the episode-end channels are read from the final state.

transition_log_probability(state, action, next_states)[source]

Log-probability of each candidate successor.

Parameters:
  • state (ndarray) – The state the step was taken from.

  • action (int) – The joint action id.

  • next_states (Any) – Candidate successor state vectors.

Return type:

ndarray

Returns:

One log-probability per candidate; -inf for unreachable ones.

See also