Class Play
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
screenSurfaceThe surface to draw on, opaque (the display's).
arrNDArrayThe 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).transposebool?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
screenis null.- AssertionError
Thrown, with an empty message, when
arris 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
swapaxeserror).- NotSupportedException
Thrown when
screenhas 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
envIEnvThe env, in render mode
rgb_arrayorrgb_array_list; it is not closed.transposebool?Whether frames are transposed for display (true, the default, shows an
(H, W, 3)frame upright); null is false.fpsdouble?The most steps per second; null reads
metadata["render_fps"](30 when absent), which must then be a Python int.zoomdouble?Scales the window; must be positive.
callbackPlayCallbackCalled after every step, with borrowed arguments (see PlayCallback).
keysToActionobjectA 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 oneplayowns and releases (its actions included) when it returns or throws (DR-45).seedBigInteger?The seed of every reset; null does not reseed.
noopobjectThe action when no mapped combination is held; null is Gymnasium's default, the int 0.
waitOnPlayerboolStep only while a mapped key is held (turn-based envs); otherwise the no-op plays on.
viewerFactoryEnvViewerFactoryThe window's factory; null takes the context's ViewerFactory, then
Gymnasium.HumanViewerFactory.contextPygameContextThe 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
envis 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), orrender_fpsis 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
envIEnvThe env, in render mode
rgb_arrayorrgb_array_list; it is not closed.transposebool?Whether frames are transposed for display, as in Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?).
fpsdouble?The most steps per second, as in Run(IEnv, bool?, double?, double?, PlayCallback?, object?, BigInteger?, object?, bool, EnvViewerFactory?, PygameContext?).
zoomdouble?Scales the window; must be positive.
callbackPlayCallbackCalled after every step, with borrowed arguments, on the game's thread (not the caller's synchronization context).
keysToActionobjectA 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?).
seedBigInteger?The seed of every reset; null does not reseed.
noopobjectThe action when no mapped combination is held; null is the int 0.
waitOnPlayerboolStep only while a mapped key is held (turn-based envs).
viewerFactoryEnvViewerFactoryThe window's factory; null takes the context's, then
Gymnasium.HumanViewerFactory.contextPygameContextThe display and event queue the game runs in; null is Default.
cancellationTokenCancellationTokenEnds 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
envis null.