A Guide to Multi-Agent Simulation Environments: From Grids to Particles
This article explores the selection of multi-agent simulation environments for reinforcement learning. It covers the core challenges of multi-agent systems—non-stationarity, credit assignment, and communication—and categorizes common simulation environments from simple grids to complex adversarial games. A comparative analysis and a custom grid environment code example are provided to help researchers choose the right benchmark for their algorithms.
1. Why Use Simulation Environments?
Reinforcement learning learns policies through repeated interactions with the environment. Testing directly on real systems is costly, risky, and sample-inefficient, often requiring massive interactions to converge. Simulation environments abstract real tasks into programs, enabling fast resets and parallel execution of multiple instances. Researchers can therefore test ideas at a low cost.
Early deep reinforcement learning research heavily used video games as test scenarios. Games offer clear reward signals, reproducible state transitions, and accelerated execution, making them foundational for algorithm incubation. As research shifted from single-agent to multi-agent, environment requirements evolved. A qualified multi-agent environment must allow multiple decision-makers to act simultaneously while clearly expressing their competitive, cooperative, and communicative relationships.
2. Three Challenges in Multi-Agent Problems
Compared to single-agent reinforcement learning, multi-agent reinforcement learning (MARL) presents three main challenges.
1. Non-stationarity: Every agent’s policy is updating. For a specific agent, the updates of other agents alter the environment’s state transition rules. Thus, single-agent convergence theories cannot be directly applied. This phenomenon can be observed in experiments: when two independently learning agents train in the same grid, if one adjusts its policy, the other’s reward curve might suddenly drop and oscillate for hundreds of episodes.
2. Credit Assignment: When a team receives a shared reward, it is difficult to determine each agent’s contribution. Properly decomposing the global return into individual returns is a core issue in collaborative tasks. A minimal experiment involves letting one group of agents share a “reward only when all reach the goal” signal, while another group receives individual rewards for reaching the goal. Comparing the learning speed of both groups illustrates the impact of credit assignment methods on the outcome.
3. Communication and Coordination: Agents may need to exchange information. The content, frequency, and bandwidth limits of communication will all affect final performance. For example, if an agent with only a local view cannot inform its partner of a discovered target location, both might redundantly visit the same place.
These challenges manifest even in simple environments. Therefore, a good benchmark environment should be able to isolate or amplify a specific challenge, helping researchers pinpoint the weak links in their algorithms.
3. Four Types of Environments from Simple to Complex
By complexity, common environments are roughly divided into four tiers. Small experiments in papers usually start with the first two tiers, followed by validation on the third and fourth tiers.
3.1 Basic Grid Environments
Grid environments are the most intuitive starting point. Agents are located on a 2D grid and can move up, down, left, and right (four directions), or diagonally can be added for a total of eight directions. Tasks typically involve reaching a target or completing a collection.
States generally include each agent’s coordinates, and sometimes obstacle positions and other agents’ locations. Actions are discrete indices, for example, 0 for up, 1 for down, 2 for left, and 3 for right. A common reward definition grants +1 for reaching the goal and -0.01 per step to encourage the agent to complete the task promptly.
Researchers can write their own grid environments, as the code volume is usually small. The core only requires implementing three parts: reset, state transition, and reward calculation.
3.2 Multi-Agent Grid Environments
By adding multiple agents to a basic grid, tasks like exploration coverage, target assignment, and path conflict resolution can be constructed. For instance, several agents must occupy different target points, and the team only receives a task reward when all targets are covered. This design simultaneously involves coordination and credit assignment.
The open-source community offers small multi-agent grid environments that can be used directly or slightly modified. Before selecting one, verify three things: whether the map generation method is controllable, whether the reward definition matches the experimental design, and whether the observation range is consistent with the research question.
3.3 Continuous Space Particle Environments
Particle environments are more complex simulation platforms. Agents and landmarks move on a 2D continuous plane, and states include continuous variables like position, velocity, and relative positions. Taking the MPE (Multi-Agent Particle Environments) in PettingZoo as an example, there are three common scenarios:
- simple_spread: Multiple agents collaborate to cover all landmarks, a cooperative scenario.
- simple_tag: Pursuers catch an evader, a competitive scenario.
- simple_reference and simple_speaker_listener: One agent sends information, and another acts on it, used for studying communication.
The observation dimension in MPE depends on the scenario and the number of agents. Specific dimensions should be based on the observation_space of the used version, and parameter names and default values should follow that version’s documentation. Default actions are five discrete options: no move, left, right, down, and up. With the continuous action option enabled, actions become 2D continuous vectors. If an algorithm only supports discrete actions, continuous control vectors can be mapped to a finite set of directions, such as choosing one of four actions based on the vector’s primary direction.
Researchers can also inherit existing environment classes to modify reward functions or task logic, quickly building new tasks.
3.4 Complex Games and Large-Scale Adversarial Environments
The final tier includes large-scale adversarial environments like the StarCraft Multi-Agent Challenge (SMAC) and Google Research Football. They feature high-dimensional states, numerous agents, and long episode durations, making them suitable for testing algorithmic scalability under real-world complexity.
These environments typically depend on the game itself or an external engine. Taking SMAC as an example, StarCraft II and its map files must be installed, and installation steps and licensing requirements should be verified in advance. Training usually requires distributed sampling and significant computing power, making it more suitable as a validation step after the algorithm matures, rather than for early debugging.
4. Environment Selection Comparison
The table below compares the four environment types across the same set of dimensions.
| Dimension | Basic Grid | Multi-Agent Grid | Continuous Particle | Large-Scale Adversarial |
|---|---|---|---|---|
| Typical Tasks | Single-agent reaching goal | Target assignment, area coverage | Collaborative coverage, pursuit, communication | Unit micro-management, team battles |
| State | Coordinates, may include obstacles | Agent coordinates and map | Position, velocity, relative position | High-dim local or global observation |
| Action | Discrete | Discrete | Default discrete, can switch to continuous | Usually discrete, depends on env |
| Reward | Sparse or dense | Individual and team combinable | Often team reward, adjustable | Win/loss plus intermediate rewards |
| Step Speed | Fast | Fast | Medium | Slow |
| Parallelism & Rendering | Easy to parallelize, rendering toggleable | Easy to parallelize, rendering toggleable | Parallelizable, rendering toggleable | Engine-dependent, requires distributed |
| Suitable Stage | Algorithm correctness | Basic behaviors | Communication and collaboration | Scalability |
Selection can be judged from the following aspects:
- Whether the environment reflects the researched difficulty, such as communication, credit assignment, or adversarial gaming.
- Whether the observation is global or local, and the action is discrete or continuous, ensuring both match the algorithm interface.
- Whether the reward can adjust difficulty via parameters and supports team rewards.
- The single-step simulation speed, parallel execution capability, and whether rendering can be turned off.
- Whether the number of agents can be flexibly adjusted, and if the code is easy to inherit and modify.
- Whether the random seed is controllable, the version is fixed, and the documentation is complete.
General conclusion: First, use a basic grid to confirm the algorithm has no obvious errors. Switch to continuous particle environments when studying communication or collaboration. Only consider large-scale adversarial environments after the previous two steps are stable.
5. Custom Grid Environment Interface
Most multi-agent environments follow a similar interaction interface. reset returns the initial observation of each agent. Then, at each step, all agents’ actions are submitted, and the environment returns new observations, rewards, termination flags, truncation flags, and additional info. These quantities are organized into dictionaries keyed by agent names, consistent with PettingZoo’s parallel API.
The following code relies only on the Python standard library and can run directly. For readability, observations are represented as dictionaries; during actual training, they typically need to be converted into arrays.
import randomMOVES = {0: (0, 1), 1: (0, -1), 2: (-1, 0), 3: (1, 0)} # Up, Down, Left, Rightclass GridWorldEnv:def __init__(self, width=8, height=8, n_agents=2, max_steps=100,obstacle_ratio=0.1, seed=None):self.width = widthself.height = heightself.n_agents = n_agentsself.max_steps = max_stepsself.obstacle_ratio = obstacle_ratioself.rng = random.Random(seed)self.agents = [f"agent_{i}" for i in range(n_agents)]self.obstacles = set()self.positions = []self.goals = []self.t = 0def _in_bounds(self, pos):x, y = posreturn 0 <= x < self.width and 0 <= y < self.heightdef _sample_free_cells(self, k, exclude=frozenset()):free = [(x, y)for x in range(self.width)for y in range(self.height)if (x, y) not in self.obstacles and (x, y) not in exclude]return self.rng.sample(free, k)def reset(self, seed=None):if seed is not None:self.rng.seed(seed)cells = [(x, y) for x in range(self.width) for y in range(self.height)]n_obs = int(len(cells) * self.obstacle_ratio)self.obstacles = set(self.rng.sample(cells, n_obs))self.positions = self._sample_free_cells(self.n_agents)self.goals = self._sample_free_cells(self.n_agents,exclude=set(self.positions))self.t = 0infos = {a: {} for a in self.agents}return self._get_obs(), infosdef _move(self, pos, action):dx, dy = MOVES[action]nxt = (pos[0] + dx, pos[1] + dy)if not self._in_bounds(nxt) or nxt in self.obstacles:return pos # Stay in place if out of bounds or hitting an obstaclereturn nxtdef _get_obs(self):return {a: {"pos": self.positions[i], "goal": self.goals[i]}for i, a in enumerate(self.agents)}def step(self, actions):self.t += 1# Process in index order. If the target cell is occupied, the agent stays in place.occupied = set(self.positions)new_pos = []for i, a in enumerate(self.agents):current = self.positions[i]target = self._move(current, actions[a])if target != current and target in occupied:target = currentoccupied.discard(current)occupied.add(target)new_pos.append(target)self.positions = new_posat_goal = [p == g for p, g in zip(self.positions, self.goals)]rewards = {a: (1.0 if at_goal[i] else 0.0) - 0.01for i, a in enumerate(self.agents)}all_done = all(at_goal)terminations = {a: all_done for a in self.agents}truncations = {a: self.t >= self.max_steps for a in self.agents}infos = {a: {"at_goal": at_goal[i]} for i, a in enumerate(self.agents)}return self._get_obs(), rewards, terminations, truncations, infosif __name__ == "__main__":env = GridWorldEnv(n_agents=2, seed=0)obs, infos = env.reset(seed=0)policy_rng = random.Random(1)done = Falsewhile not done:actions = {a: policy_rng.randrange(4) for a in env.agents}obs, rewards, terms, truncs, infos = env.step(actions)done = any(terms.values()) or any(truncs.values())print("Steps at the end of the episode:", env.t)
Three points to note during implementation:
First, collisions and out-of-bounds movements must be explicitly handled in the state transition. Otherwise, agents might pass through obstacles, or two agents might occupy the same cell. The code above processes movements sequentially by index number; if the target cell is already occupied, the agent stays in its original position.
