Table of Contents

Class Play

Namespace
Gym.Utils
Assembly
Gym.Rendering.dll

Gymnasium's gymnasium.utils.play: play an env from the keyboard (Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?), play, or RunAsync(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?, CancellationToken) to await a game), and show a frame on a surface (DisplayArr(Surface, NDArray, (int Width, int Height), bool?), display_arr). The window is a PygameContext's display, Default's (the static Display) unless a context is given, made by the viewer factory (DR-20); the keys come from it through the context's event queue, or from events a program posts there.

public static class Play
Inheritance
Play
Inherited Members

Remarks

To play for real, set a viewer that reports input (Gymnasium.HumanViewerFactory = AvaloniaEnvViewer.Factory, or pass viewerFactory), then Play.Run(Gymnasium.Make("CartPole-v1", new { render_mode = "rgb_array" }), keysToAction: new Dictionary<object, object?> { ["a"] = 0, ["d"] = 1 }). Headless, under NullEnvViewer, nothing reports keys, so the loop runs on the no-op until events are posted (a callback can post them, as Gymnasium's tests do).

Reference: gymnasium/utils/play.py.

Methods

DisplayArr(Surface, NDArray, (int Width, int Height), bool?)

Shows a frame on a surface (Gymnasium's display_arr): the frame, transposed or not, scaled to videoSize by nearest neighbour, centred on a black surface (cropped where it is larger).

public static void DisplayArr(Surface screen, NDArray arr, (int Width, int Height) videoSize, bool? transpose)

Parameters

screen Surface

The surface to draw on, opaque (the display's).

arr NDArray

The frame, uint8, (H, W, 3) (or (H, W), read through pygame's 8-bit palette, not as gray).

videoSize (int Width, int Height)

The size the frame is scaled to, (width, height).

transpose bool?

Whether the frame's first two axes are swapped first, as an (H, W, 3) frame needs to be shown upright; null is false.

Remarks

The offsets are (screen size - video size) / 2 truncated toward zero, as pygame's blit truncates a float position: a frame wider than the window is shifted left by half the excess, rounded toward zero. Reference: gymnasium/utils/play.py.

Exceptions

ArgumentNullException

Thrown when screen is null.

AssertionError

Thrown, with an empty message, when arr is null or not uint8.

ValueError

Thrown for a frame of another shape (pygame's must be a valid 2d or 3d array, newline-terminated), and for a negative size (Cannot scale to negative size).

AxisError

Thrown when a frame of fewer than two dimensions is transposed (NumPy's swapaxes error).

NotSupportedException

Thrown when screen has per-pixel alpha (not a display surface).

Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?)

Lets a person play env with the keyboard (Gymnasium's play): resets with seed, opens the display, then each frame steps with the action of the keys held (or noop), calls callback, shows the frame, reads the events and paces itself, resetting with the same seed whenever an episode ends, until Escape, the window's close button or a Quit event. Then it closes the display.

[PyName("play")]
public static void Run(IEnv env, bool? transpose = true, double? fps = null, double? zoom = null, PlayCallback? callback = null, object? keysToAction = null, BigInteger? seed = null, object? noop = null, bool waitOnPlayer = false, EnvViewerFactory? viewerFactory = null, PygameContext? context = null)

Parameters

env IEnv

The env, in render mode rgb_array or rgb_array_list; it is not closed.

transpose bool?

Whether frames are transposed for display (true, the default, shows an (H, W, 3) frame upright); null is false.

fps double?

The most steps per second; null reads metadata["render_fps"] (30 when absent), which must then be a Python int.

zoom double?

Scales the window; must be positive.

callback PlayCallback

Called after every step, with borrowed arguments (see PlayCallback).

keysToAction object

A dictionary from keys to actions, or null for the env's own (get_keys_to_action, through any wrapper). A key is a key code (KeyCode.Space, an int), a string whose characters are held together ("wa"), a KeyCombination, or a tuple of codes and one-character strings held together ((KeyCode.Left, KeyCode.Right), ValueTuple.Create("w")); every action must be in the action space. A given dictionary stays the caller's; the env's own is a new one play owns and releases (its actions included) when it returns or throws (DR-45).

seed BigInteger?

The seed of every reset; null does not reseed.

noop object

The action when no mapped combination is held; null is Gymnasium's default, the int 0.

waitOnPlayer bool

Step only while a mapped key is held (turn-based envs); otherwise the no-op plays on.

viewerFactory EnvViewerFactory

The window's factory; null takes the context's ViewerFactory, then Gymnasium.HumanViewerFactory.

context PygameContext

The display and event queue the game runs in (DR-41); null is Default, the static Display and EventQueue. Two games at once need two contexts.

Remarks

Gymnasium's own quirks are kept: the callback's first obs_t of an episode is the reset's (obs, info); every reset reuses seed, so a seeded game repeats its starting state; and an exception leaves the display open (call the context's Quit(), Quit() for the default one), as pygame stays initialized.

One game per context at a time; see PygameEventQueue. The game runs on the calling thread, which the frame clock blocks between frames, as pygame's loop does; RunAsync(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?, CancellationToken) runs the same loop without blocking the caller. The env is stepped through its StepAsync, which every built-in env completes on the calling thread; an env whose steps are genuinely asynchronous continues the game on a thread-pool thread after its first such step, while this call waits.

Exceptions

ArgumentNullException

Thrown when env is null.

Error

Thrown for a negative seed, by the first reset.

MissingKeysToAction

Thrown when no mapping is given and the env has none: CartPole-v1 does not have explicit key to action mapping, please specify one manually.

ValueError

Thrown, with Gymnasium's messages, when no mapping is given and the env has none and no spec, when the env's mapping is None, for an empty key tuple (MountainCar's own mapping has one), for an action outside the action space, for the wrong render mode, and for a zoom that is not positive.

TypeError

Thrown, with Gymnasium's messages, when the mapping is no dictionary, a key is neither an int, a string nor a tuple of them, a tuple element is a string of another length than one (ord()'s message), or render_fps is not an int.

AssertionError

Thrown, with an empty message, when a render is not a uint8 array.

DependencyNotInstalled

Thrown when no viewer factory is given or set.

RunAsync(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?, CancellationToken)

Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?) as a task that completes when the game ends (DR-44): the same loop, on a thread of its own when the game shows a real window, on the thread pool when it is headless, so the caller (a UI, a test, an agent) can await a game, or several in their own contexts, without blocking its thread.

public static Task RunAsync(IEnv env, bool? transpose = true, double? fps = null, double? zoom = null, PlayCallback? callback = null, object? keysToAction = null, BigInteger? seed = null, object? noop = null, bool waitOnPlayer = false, EnvViewerFactory? viewerFactory = null, PygameContext? context = null, CancellationToken cancellationToken = default)

Parameters

env IEnv

The env, in render mode rgb_array or rgb_array_list; it is not closed.

transpose bool?

Whether frames are transposed for display, as in Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?).

fps double?

The most steps per second, as in Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?).

zoom double?

Scales the window; must be positive.

callback PlayCallback

Called after every step, with borrowed arguments, on the game's thread (not the caller's synchronization context).

keysToAction object

A dictionary from keys to actions, or null for the env's own, as in Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?).

seed BigInteger?

The seed of every reset; null does not reseed.

noop object

The action when no mapped combination is held; null is the int 0.

waitOnPlayer bool

Step only while a mapped key is held (turn-based envs).

viewerFactory EnvViewerFactory

The window's factory; null takes the context's, then Gymnasium.HumanViewerFactory.

context PygameContext

The display and event queue the game runs in; null is Default.

cancellationToken CancellationToken

Ends the game as Escape or the window's close button does: the current frame finishes (a frame wait or an env's asynchronous step is cut short), the display closes and the task completes normally, not as canceled.

Returns

Task

A task that completes when the game ends, faulted with what Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?) would have thrown.

Remarks

Where it runs follows DR-22's rule for thread-bound envs: a game whose env renders into a window of its own (render_mode="human", which PlayableGame then refuses) or whose display is a real window (any viewer factory but Factory) runs on a dedicated background thread, paced by the blocking clock, as pygame's loop is; a headless game (Factory) runs on the thread pool with awaited pacing (TickAsync(double, CancellationToken)), holding no thread between frames. The dedicated thread is a background thread: the process does not wait for a game to end.

Every error Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?) throws surfaces through the task instead, Gymnasium's messages unchanged. Games that share a context steal each other's events, as in Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?); give each its own PygameContext.

Exceptions

ArgumentNullException

Thrown here, not through the task, when env is null.