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
float64vector of length4 * 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
intin0 .. 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 (0north,1east,2south,3west),4hold, and5scan. 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 + 4numbers (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:
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:
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.
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:
\(\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:
\(\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:
\(\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\):
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\):
It then steps toward \(q_j\) with probability \(p_r\) and to a random neighbour otherwise; a frozen red player stays:
Pick-up. An unfrozen player on the other team’s flag takes it if no one carries it; the lowest index wins a tie:
(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
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:
Counters. Every freeze and cooldown not just set by a tag counts down by one:
Observation model. The observation is drawn from the successor state \(s'\) and the joint action \(a\):
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:
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\):
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):
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:
\(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:
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:
with score_to_win = 1 by default.
Step order
One step resolves in a fixed order:
blue moves;
red moves;
flags are picked up;
tags are resolved;
scores are awarded;
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 ( |
+100.0 |
Red scores ( |
-100.0 |
Blue player tagged ( |
-25.0 each |
Red player tagged ( |
+10.0 each |
First pick-up ( |
+20.0 |
Move or hold ( |
-1.0 per player |
Scan ( |
-2.0 per player |
Key settings
The defaults:
a 9 by 7 field (
grid_size=(9, 7)) split at columnmidline=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=1capture ends the episode;discount_factordefaults to0.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_rateandended_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?
|
Discrete |
Continuous |
|---|---|---|
State |
✔️ |
❌ |
Action |
✔️ |
❌ |
Observation |
❌ |
✔️ |
Also supports |
|
|---|---|
Native C++ backend |
❌ |
Vectorized (torch) model |
✔️ |
In the |
✔️ |
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:
DiscreteActionsEnvironmentTeam capture-the-flag on a grid, with hidden red players and a hidden flag.
- Parameters:
midline (int)
n_blue (int)
n_red (int)
n_red_defenders (int)
slip_probability (float)
range_error_probability (float)
red_pursuit_probability (float)
red_alert_radius (int)
freeze_steps (int)
tagger_cooldown_steps (int)
detector_half_distance_move (float)
detector_half_distance_scan (float)
score_to_win (int)
capture_reward (float)
concede_penalty (float)
tagged_penalty (float)
tag_reward (float)
pickup_reward (float)
move_cost (float)
scan_cost (float)
discount_factor (float)
output_dir (Path | None)
debug (bool)
use_queue_logger (bool)
- 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
- get_metric_specs()[source]
Declare every metric this environment reports.
- Return type:
- Returns:
One spec per channel, in the order
CaptureTheFlagMetricsdeclares 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.
- hash_observation(observation)[source]
Return a hashable key agreeing with
is_equal_observation().
- 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:
- Returns:
The exact opening observation distribution, or the single most likely observation when the support is larger than
_MAX_ENUMERATED_OBSERVATIONSand enumerating it would cost more than it informs.
- initial_state_dist()[source]
Opening distribution: everything known but the red flag’s cell.
- Return type:
- Returns:
A uniform distribution over the red flag candidates.
- is_equal_observation(observation1, observation2)[source]
Return whether two observations are identical.
- 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.
- observation_log_probability_per_state(next_states, action, observation)[source]
Log-likelihood of one observation under each candidate successor.
- Parameters:
- Return type:
- Returns:
One log-likelihood per candidate, equal to what
observation_log_probability()returns for each one.
- reward(state, action, next_state=None)[source]
Reward for one transition.
- Parameters:
- Return type:
- Returns:
The immediate reward.
- 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.
- 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.
- sample_observation(next_state, action, n_samples=1)[source]
Sample the blue team’s observation of a successor state.
- Parameters:
- Return type:
- Returns:
One observation tuple when
n_samplesis 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.randomup front, one per remaining step, as the other native rollouts do;action_sampleris used only when the Python reference runs.- Parameters:
- Return type:
- Returns:
The discounted sum of rewards until
max_depthor a terminal state.
- step_info(state, action, next_state)[source]
Report per-step channels for this transition.
- Parameters:
- Return type:
- 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.
See also
POMDPPlanners.environments.capture_the_flag_pomdp.CaptureTheFlagPOMDPBase Environment Class — the full catalog and the environment interface.