Tutorial: Environment Logic

Introduction

Now that we have a basic understanding of the structure of environment repositories, we can start thinking about the fun part - environment logic!

For this tutorial, we will be creating a two-player game consisting of a prisoner, trying to escape, and a guard, trying to catch the prisoner. This game will be played on a 7x7 grid, where:

  • The prisoner starts in the top left corner,

  • The guard starts in the bottom right corner,

  • The escape door is randomly placed in the middle of the grid

  • Both the prisoner and the guard can move in any of the four cardinal directions (up, down, left, right).

Code

/custom-environment/env/custom_environment.py
import functools
import random
from copy import copy

import numpy as np
from gymnasium.spaces import Discrete, MultiDiscrete

from pettingzoo import ParallelEnv


class CustomEnvironment(ParallelEnv):
    """The metadata holds environment constants.

    The "name" metadata allows the environment to be pretty printed.
    """

    metadata = {
        "name": "custom_environment_v0",
    }

    def __init__(self):
        """The init method takes in environment arguments.

        Should define the following attributes:
        - escape x and y coordinates
        - guard x and y coordinates
        - prisoner x and y coordinates
        - timestamp
        - possible_agents

        Note: as of v1.18.1, the action_spaces and observation_spaces attributes are deprecated.
        Spaces should be defined in the action_space() and observation_space() methods.
        If these methods are not overridden, spaces will be inferred from self.observation_spaces/action_spaces, raising a warning.

        These attributes should not be changed after initialization.
        """
        self.escape_y = None
        self.escape_x = None
        self.guard_y = None
        self.guard_x = None
        self.prisoner_y = None
        self.prisoner_x = None
        self.timestep = None
        self.possible_agents = ["prisoner", "guard"]

    def reset(self, seed=None, options=None):
        """Reset set the environment to a starting point.

        It needs to initialize the following attributes:
        - agents
        - timestamp
        - prisoner x and y coordinates
        - guard x and y coordinates
        - escape x and y coordinates
        - observation
        - infos

        And must set up the environment so that render(), step(), and observe() can be called without issues.
        """
        self.agents = copy(self.possible_agents)
        self.timestep = 0

        self.prisoner_x = 0
        self.prisoner_y = 0

        self.guard_x = 6
        self.guard_y = 6

        self.escape_x = random.randint(2, 5)
        self.escape_y = random.randint(2, 5)

        observations = dict.fromkeys(
            self.agents,
            (
                self.prisoner_x + 7 * self.prisoner_y,
                self.guard_x + 7 * self.guard_y,
                self.escape_x + 7 * self.escape_y,
            ),
        )

        # Get dummy infos. Necessary for proper parallel_to_aec conversion
        infos = {a: {} for a in self.agents}

        return observations, infos

    def step(self, actions):
        """Takes in an action for the current agent (specified by agent_selection).

        Needs to update:
        - prisoner x and y coordinates
        - guard x and y coordinates
        - terminations
        - truncations
        - rewards
        - timestamp
        - infos

        And any internal state used by observe() or render()
        """
        # Execute actions
        prisoner_action = actions["prisoner"]
        guard_action = actions["guard"]

        if prisoner_action == 0 and self.prisoner_x > 0:
            self.prisoner_x -= 1
        elif prisoner_action == 1 and self.prisoner_x < 6:
            self.prisoner_x += 1
        elif prisoner_action == 2 and self.prisoner_y > 0:
            self.prisoner_y -= 1
        elif prisoner_action == 3 and self.prisoner_y < 6:
            self.prisoner_y += 1

        if guard_action == 0 and self.guard_x > 0:
            self.guard_x -= 1
        elif guard_action == 1 and self.guard_x < 6:
            self.guard_x += 1
        elif guard_action == 2 and self.guard_y > 0:
            self.guard_y -= 1
        elif guard_action == 3 and self.guard_y < 6:
            self.guard_y += 1

        # Check termination conditions
        terminations = dict.fromkeys(self.agents, False)
        rewards = dict.fromkeys(self.agents, 0)
        if self.prisoner_x == self.guard_x and self.prisoner_y == self.guard_y:
            rewards = {"prisoner": -1, "guard": 1}
            terminations = dict.fromkeys(self.agents, True)

        elif self.prisoner_x == self.escape_x and self.prisoner_y == self.escape_y:
            rewards = {"prisoner": 1, "guard": -1}
            terminations = dict.fromkeys(self.agents, True)

        # Check truncation conditions (overwrites termination conditions)
        truncations = dict.fromkeys(self.agents, False)
        if self.timestep > 100:
            rewards = {"prisoner": 0, "guard": 0}
            truncations = {"prisoner": True, "guard": True}
        self.timestep += 1

        # Get observations
        observations = dict.fromkeys(
            self.agents,
            (
                self.prisoner_x + 7 * self.prisoner_y,
                self.guard_x + 7 * self.guard_y,
                self.escape_x + 7 * self.escape_y,
            ),
        )

        # Get dummy infos (not used in this example)
        infos = {a: {} for a in self.agents}

        if any(terminations.values()) or all(truncations.values()):
            self.agents = []

        return observations, rewards, terminations, truncations, infos

    def render(self):
        """Renders the environment."""
        grid = np.full((7, 7), " ")
        grid[self.prisoner_y, self.prisoner_x] = "P"
        grid[self.guard_y, self.guard_x] = "G"
        grid[self.escape_y, self.escape_x] = "E"
        print(f"{grid} \n")

    # Observation space should be defined here.
    # lru_cache allows observation and action spaces to be memoized, reducing clock cycles required to get each agent's space.
    # If your spaces change over time, remove this line (disable caching).
    @functools.cache
    def observation_space(self, agent):
        # gymnasium spaces are defined and documented here: https://gymnasium.farama.org/api/spaces/
        return MultiDiscrete([7 * 7] * 3)

    # Action space should be defined here.
    # If your spaces change over time, remove this line (disable caching).
    @functools.cache
    def action_space(self, agent):
        return Discrete(4)

Parallel and AEC environments

The example above implements a ParallelEnv. Its step(actions) accepts actions for all active agents and returns the observations, rewards, terminations, truncations, and infos together. When this game finishes, it sets self.agents = []. It does not use the AEC-specific agent selector, dead steps, or cumulative reward bookkeeping.

An AECEnv instead processes one selected agent per step. If you are writing an AEC environment, you must account for two kinds of reward state:

  • self.rewards[agent] is the reward assigned to that agent by the current transition. It is cleared when there is no new reward; it is not a running episode score.

  • self._cumulative_rewards[agent] accumulates rewards until that agent next takes a turn. env.last() reads the cumulative reward for the currently selected agent. After its live action is processed, the environment resets that agent’s cumulative entry, and self._accumulate_rewards() adds the transition’s self.rewards to the cumulative entries for all agents.

For example, suppose the last move in a two-player AEC game gives the winner 1 and the loser 0, with no earlier rewards. That move sets self.rewards, marks both agents terminated, and accumulates the rewards. Each terminated agent can still be selected once more: the caller reads its final reward and termination flag with env.last(), then calls env.step(None). That final dead step removes the agent and its reward entries. Having empty reward dictionaries after both dead steps is expected; the rewards were available through last() before removal.

An AEC environment’s step() should handle a selected agent that is already terminated or truncated with self._was_dead_step(action) and return immediately. It must also update cumulative rewards after assigning new rewards, including terminal rewards. For a concrete implementation, see the Rock–Paper–Scissors AEC step() method; for the dead-step lifecycle and a caller-side agent_iter() example, see Basic Usage: Variable Numbers of Agents (Death).