Skip to content

API reference

Environments

gridhunt.make

make(env_id, render_mode=None, trainable_prey=None, **kwargs)

Create a registered GridHunt environment.

Parameters:

Name Type Description Default
env_id str

a registered ID such as "GridHunt-ClassicStag-v0"; see list_envs.

required
render_mode str | None

None, "console", "rgb_array" or "gui".

None
trainable_prey

ids of prey to control as agents instead of moving by rule.

None
**kwargs

override any setting of the registered scenario (for example max_steps, observation_mode, reward_mode, predators); see GridHunt for all of them. communication=k adds a k-token message channel (CommunicationWrapper).

{}

Returns:

Type Description

A PettingZoo ParallelEnv.

Example

env = gridhunt.make("GridHunt-ToxicStag-v0", max_steps=200, reward_mode="team") observations, infos = env.reset(seed=0)

gridhunt.list_envs

list_envs()

IDs of the registered environments, for use with make.

gridhunt.core.GridHunt

GridHunt(grid_size, predators, prey, max_steps, entities=None, render_mode=None, action_mode='single', observation_mode='coords', gui_config=None, trainable_prey=None, terrain_config=None, observation_encoders=None, use_action_mask=False, agent_role_map=None, encoder_order=None, reward_mode='individual', prey_motion='static', prey_move_probability=0.5)

Bases: ParallelEnv

Grid predator-prey environment with a PettingZoo ParallelEnv API.

Use gridhunt.make for the registered scenarios; construct this class (or a scenario subclass) directly to build a custom one.

Parameters:

Name Type Description Default
grid_size

(width, height) of the grid.

required
predators

list of gridhunt.Predator (the controllable agents).

required
prey

list of gridhunt.Prey (or a subclass such as Stag or Hare).

required
max_steps

episode length; agents are truncated after this many steps.

required
entities

non-capturable objects, drawn by the renderer but never observed by agents (for example cues shown only to a human participant).

None
render_mode

None, "console", "rgb_array" or "gui" (the last two need pip install "gridhunt[render]").

None
observation_mode

one of observation_modes: "coords" (prey, predator and terrain coordinates), "flat_coords" (prey and predator coordinates), "one_hot" (one-hot grids; agents with limited_vision get an egocentric grid).

'coords'
gui_config

buttons, dropdowns and the information bar for render_mode="gui".

None
trainable_prey

ids of prey that are controlled as agents instead of moving by rule.

None
terrain_config

terrain types with passability, speed and generation settings.

None
observation_encoders list[str] | None

extra features appended to observations: "agent_centric" and/or "action_mask".

None
use_action_mask bool

report each agent's valid moves in infos[agent_id]["action_mask"] (int8).

False
agent_role_map dict[str, list[str]] | None

{role: [agent ids]} for the agent_centric encoder (default: predator and trainable prey roles).

None
encoder_order list[str] | None

order in which the observation encoders are appended.

None
reward_mode str

"individual" (rewarded for own captures) or "team" (every predator receives the team reward).

'individual'
prey_motion str

"static", "random" or "flee" for non-trainable prey.

'static'
prey_move_probability float

probability that a moving prey moves on a given step.

0.5

reset

reset(seed=None, options=None)

step

step(actions)

state

state()

Compact global state for centralised critics (PettingZoo ParallelEnv.state).

Layout, all values in [0, 1]: - per agent (possible_agents order): x, y normalized by the grid size - per prey (sorted ids): x, y, present (0 once removed), toxic - per terrain type (sorted): a flattened one-hot grid of its cells

action_mask

action_mask(agent_id)

Which of the 5 actions move the agent (stay is always valid), as float32 0/1 values.

Uses the movement rules without randomness: a cell that can be entered with some probability counts as reachable.

render

render()

Draw the current state.

Returns an RGB array of shape (height, width, 3) for render_mode="rgb_array", prints the grid for "console" and updates the window for "gui".

close

close()

Close the window and release rendering resources.

set_entities

set_entities(entities)

Replace the human-only entities; they appear at the next reset().

Entities are drawn by the renderer but are never part of observations, state() or the dynamics. Entities without a position are placed on a random cell at every reset.

set_prey

set_prey(prey)

Replace the prey settings (for example a stag's toxic probability) from the next reset().

The new prey must have the same ids as the current ones, so observation and state spaces stay the same.

observation_space cached

observation_space(agent)

Return agent observation space.

action_space cached

action_space(agent)

gridhunt.wrappers.CommunicationWrapper

CommunicationWrapper(env, vocab_size)

Bases: ParallelEnv

Adds an explicit communication channel ("cheap talk") to a GridHunt env.

Each step every agent chooses a move and one of vocab_size message tokens, encoded as a single action: action = move + num_moves * token. Every agent's next observation ends with all agents' tokens from that step (one one-hot block per agent, in possible_agents order; all zero after reset). The tokens are also appended to state() so centralised critics see them, and are reported in every agent's infos[agent_id]["messages"].

Tokens have no meaning to the environment: any meaning must be learned. Moves 0-4 are therefore still valid actions (token 0).

Agents and prey

gridhunt.agents.Predator

Predator(predator_id, position=None, status=None, capture_power=1, limited_vision_radius=1, speed=1, render_sprite=MAGENTA_HUNTER_SPRITE, immune_to_terrain=False, restricted_terrains=None)

Controllable hunter agent.

gridhunt.agents.Prey

Prey(prey_id, reward, position=None, prey_type=None, respawn=False, status=None, capture_power_required=1, console_sprite='T', render_sprite=STAG_SPRITE, overcrowding_penalty=0, speed=1, immune_to_terrain=False, restricted_terrains=None)

Capturable target.

gridhunt.agents.Stag

Stag(prey_id, position=None, capture_power_required=2)

Bases: Prey

Cooperative high-value prey.

gridhunt.agents.Hare

Hare(prey_id, render_sprite=HARE_SPRITE, speed=1, position=None)

Bases: Prey

Solo low-value prey.

gridhunt.agents.ToxicStag

ToxicStag(prey_id, position=None, toxic_probability=0.5, toxic_render_sprite=TOXIC_STAG_SPRITE, toxic_lifetime=5)

Bases: Prey

Stag variant with toxic/healthy respawn state.

Each time it appears the stag is toxic with probability toxic_probability. A toxic stag that nobody catches moves to a random cell after toxic_lifetime steps, with its toxicity drawn again; a healthy one stays until it is caught.

steps a toxic stag stays put. An int (the benchmark uses 5), a (low, high)

pair to draw it uniformly from that range each time the stag turns toxic, or None for a toxic stag that stays until it is caught. A fixed lifetime is a cue in itself: a stag that has stayed longer than that must be healthy, so agents without the toxicity flag can infer it.

gridhunt.agents.Building

Building(prey_id, position=None, reward=1, capture_power_required=1, trap_probability=0.0, trap_penalty=0, console_sprite='B', render_sprite=BUILDING_SPRITE)

Bases: Prey

Static raid target.

gridhunt.agents.Pig

Pig(prey_id, render_sprite=None, speed=1, position=None)

Bases: Prey

Pig chase target.

gridhunt.agents.Entity

Entity(entity_id, position=None, console_sprite='E', render_sprite=PLANT_SPRITE)

Non-capturable world object.

Scripted policies

gridhunt.policies

Scripted (non-learning) policies: baselines and ready-made teammates.

  • RandomPolicy: uniform random actions.
  • IdlePolicy: always STILL.
  • GreedyPolicy: each predator walks the shortest path (BFS over the moves it can actually make, by the environment's movement rules) to the prey with the best reward per step of distance, and waits on it until captured. With its defaults it reads the true state, including whether a stag is toxic, so it is an informed heuristic, not an upper bound.

Every policy can be called two ways:

  • policy.act(env, agent_id), as the benchmark does;
  • policy(observation, agent_id, env), the teammate interface used by gridhunt.hat.

Policies read the environment state (env.predators, env.prey, env.terrain_at) and never draw from the environment's random generators, so they do not change its trajectory.

RandomPolicy

RandomPolicy(seed=0)

Bases: _Policy

Uniform random actions from its own seeded generator.

IdlePolicy

Bases: _Policy

Always STILL.

GreedyPolicy

GreedyPolicy(active_agents=None, prey_types=None, avoid_harmful=True)

Bases: _Policy

Scripted team: go to the best reward-per-distance prey and wait there.

Parameters:

Name Type Description Default
active_agents

the predators actually playing (default: all). Prey needing more capture power than these agents have together are ignored, so a team that has lost a member re-plans instead of waiting for a partner who never comes.

None
prey_types

only chase prey of these types (for example ("hare",)); default: all.

None
avoid_harmful

skip prey whose current reward is negative (a toxic stag). With False the policy ignores that hidden information and values every prey at its absolute reward, as a team that cannot tell toxic stags apart would.

True

Human-agent teaming

gridhunt.hat.HumanSession

HumanSession(env, humans=None, teammates=None, teams=None, initial_team=None, buttons=(), pause_button=True, info=None, log=None, step_interval=None, turn_timeout=None, gui_config=None, info_lines=2, fps=30, headless=False, event_source=None, pause_key=pygame.K_p, quit_key=pygame.K_ESCAPE, keys=None)

Run episodes of a GridHunt environment with human participants.

Parameters:

Name Type Description Default
env

a GridHunt environment, created without a render mode; the session opens the window.

required
humans

{agent_id: key_map} for agents controlled from the keyboard, where a key map is {pygame_key: action} such as ARROW_KEYS or WASD_KEYS.

None
teammates

{agent_id: policy} for AI-controlled agents. A policy is called as policy(observation, agent_id, env) and returns an action; if it has a reset() method it is called at the start of every episode. The scripted policies in gridhunt.policies and the pretrained ones in gridhunt.zoo work as is.

None
teams

{name: {agent_id: policy}}: alternative sets of teammates. Each team gets a button that puts it in control; initial_team (default: the first) starts.

None
buttons

extra Button objects.

()
pause_button

add a Pause button (the pause key works either way).

True
info

text for the information bar, or callable(session) -> str; default: episode, step, score and the team in control.

None
log

a gridhunt.hat.SessionLog, or None for no logging.

None
step_interval

seconds per step. None (default when there are humans) waits for every human to choose; a number advances on a timer, and humans who have not pressed a key by then stay still.

None
turn_timeout

when waiting for humans, give up after this many seconds and let them stay still (logged with the source "timeout"). Default: wait indefinitely.

None
gui_config

extra renderer settings. "vision_mask" defaults to the human's own view when one participant plays an agent with limited vision, and to the whole board otherwise; set it to None or an agent id to choose.

None
info_lines

lines reserved for the information text.

2
fps

frames drawn per second while waiting.

30
headless

draw to a hidden window instead of showing one (tests, dry runs).

False
event_source

callable returning the pending pygame events (default pygame.event.get); scripted tests replace it.

None
pause_key

key that pauses and resumes (default P).

K_p
quit_key

key that ends the session (default Escape).

K_ESCAPE
keys

{pygame_key: callback} extra key bindings; callback(session) runs when the key is pressed (also while paused), like a button. For example {pygame.K_r: lambda s: s.reset_board()}.

None

run_episode

run_episode(seed=None, max_steps=None, stop_when=None, start_paused=False, **fields)

Play one episode and return an EpisodeResult.

Parameters:

Name Type Description Default
seed

passed to env.reset.

None
max_steps

end after this many steps (the environment's own limit still applies).

None
stop_when

callable(session) -> bool checked after every step, for example lambda s: s.captures >= 50.

None
start_paused

show the episode but hold it until resume() is called (for example from a button), such as when participants rate the situation first.

False
**fields

extra values stored in the episode's log records (for example a condition).

{}

ask

ask(questionnaire, responder=None)

Show a questionnaire in the window; returns {item_id: answer} (logged).

set_team

set_team(name)

Put a team of policies in control from the next step on.

toggle_pause

toggle_pause()

end_episode

end_episode(reason='skipped')

End the current episode after this frame (for example from a Skip button).

quit

quit()

End the episode and mark the session as finished.

log_event

log_event(name, **data)

Write an event record (if logging) tagged with the current episode and step.

episode_t is the time in seconds since the episode started (None before the first episode), so the time from an episode appearing to a button press can be read directly.

close

close()

gridhunt.hat.Button dataclass

Button(label, on_press)

A button in the information bar. on_press(session) runs when it is clicked.

gridhunt.hat.EpisodeResult dataclass

EpisodeResult(episode, seed, steps, team_return, captures, end_reason, duration_s)

gridhunt.hat.SessionLog

SessionLog(directory, participant='anonymous', condition=None, metadata=None, log_state=True, on_record=None)

Writes one participant's session to JSON Lines.

Parameters:

Name Type Description Default
directory

folder for the log files (created if needed).

required
participant

participant id, used in the file name.

'anonymous'
condition

experimental condition, stored in every file.

None
metadata

any extra information to store in the metadata file.

None
log_state

also store env.state() (the global state vector) on every step.

True
on_record

called with every record after it is written, for example to forward events to a lab streaming or eye-tracking system.

None

write

write(record_type, **fields)

Write one record and return it.

update_metadata

update_metadata(**fields)

close

close()

gridhunt.hat.read_log

read_log(path)

Read a session's JSON Lines log into a list of records.

gridhunt.hat.Questionnaire

Questionnaire(items, title=None, id=None, font_size=20, theme=None)

An ordered list of items: Message, Likert, Scale, Choice, Text.

Parameters:

Name Type Description Default
items

the items, shown in order.

required
title

shown above every item with the item number, and stored as the log's id.

None
id

id stored in the log (default: the title).

None
font_size

text size in pixels.

20
theme

a pygame_gui theme (dict or path) to restyle the screens completely.

None

gridhunt.hat.Message dataclass

Message(text, button='Continue', id=None)

A screen of text with a single button, for instructions and breaks.

gridhunt.hat.Likert dataclass

Likert(id, prompt, points=7, anchors=('Strongly disagree', 'Strongly agree'))

A rating on a scale of points (answer: 1..points).

gridhunt.hat.Choice dataclass

Choice(id, prompt, options=list())

One option out of several (answer: the option text).

gridhunt.hat.Text dataclass

Text(id, prompt, required=False, button='Next')

Free text (answer: the text entered).

Pretrained teams

gridhunt.zoo

Pretrained teams from the GridHunt benchmark, runnable with numpy alone.

Each model is one trained team (IPPO, MAPPO or HAPPO) for one benchmark scenario, exported from the benchmark runs. Two runs per scenario and algorithm are published: the seed with the median final score (representative of the algorithm) and the best seed (the strongest teammates). Models are downloaded on first use, checked against their SHA-256 hash and cached.

from gridhunt import zoo

zoo.list_models(scenario="toxic_stag")
team = zoo.load("toxic_stag", "mappo", rank="best")
env = team.make_env()                       # the scenario exactly as it was trained
observations, _ = env.reset(seed=0)
while env.agents:
    observations, *_ = env.step(team.act(observations))

A team is also a teammate for gridhunt.hat.HumanSession: it is called as team(observation, agent_id, env), so teammates={"predator_1": team} lets a trained agent play alongside a participant.

Downloads go to $GRIDHUNT_ZOO_DIR or ~/.cache/gridhunt/zoo; set $GRIDHUNT_ZOO_URL to use a mirror.

ZooTeam

ZooTeam(meta, arrays, rng=None)

A trained team: one actor per agent (IPPO, HAPPO) or one shared actor (MAPPO).

logits

logits(agent, observation)

Action logits for one agent; observation may be one vector or a batch.

act_agent

act_agent(agent, observation, greedy=False)

One agent's action. Sampled from the policy by default (as the benchmark evaluates).

act

act(observations, greedy=False)

Actions for every agent in observations (a dict from env.reset/env.step).

__call__

__call__(observation, agent_id, env=None)

Teammate interface for gridhunt.hat.HumanSession.

reset

reset()

Nothing to reset: the policies have no memory.

make_env

make_env(**overrides)

The environment the team was trained in (benchmark settings), with optional overrides.

Observation settings must stay as trained; overriding max_steps or render_mode is fine.

list_models

list_models(scenario=None, algo=None, rank=None)

Published models, optionally filtered: a list of dicts with scenario, algo, rank, seed, env_id, file, sha256 and the final evaluation score.

load

load(scenario, algo, rank='median', seed=None, rng=None)

Load a published team.

Parameters:

Name Type Description Default
scenario

a benchmark scenario name, for example "toxic_stag"; see list_models.

required
algo

"ippo", "mappo" or "happo".

required
rank

"median" (the run with the median final score) or "best".

'median'
seed

pick a specific training seed instead of a rank (only if that run is published).

None
rng

seed or numpy.random.Generator for sampling actions.

None

load_file

load_file(path, rng=None)

Load a team from a local .npz file written by the benchmark's export script.

cache_dir

cache_dir()

Where downloaded models are kept.