Table of Contents

Class CarRacingEnv

Namespace
Gym.Environments.Envs.Box2D
Assembly
Gym.Environments.dll

CarRacing-v3: a top-down race on a random closed track, learned from pixels. The observation is a 96×96 RGB image of the car and the track around it (with the speed, ABS, steering and gyro indicators and the score at the bottom); the reward is -0.1 per frame plus 1000/N for each of the track's N tiles first touched, and -100 when the car leaves the playfield. Continuous actions are Box([-1, 0, 0], [1, 1, 1], float32) (steer, gas, brake); discrete ones Discrete(5) (nothing, right, left, gas, brake). Step for step and frame for frame what Gymnasium's CarRacing computes on Box2D 2.3.

[PyName("CarRacing")]
public class CarRacingEnv : Env<NDArray, NDArray>, IEnv, IDisposable, IDynamicAttributes
Inheritance
CarRacingEnv
Implements
Inherited Members
Extension Methods

Remarks

The physics runs on b2World, Gym.NET's managed Box2D 2.3.0 (D5), with no gravity and Gymnasium's Car; one world serves the env's whole life, as in Gymnasium, so (as for BipedalWalker) an episode after other episodes can differ from a fresh env's after the same reset(seed). The track is 12 random checkpoints joined by a turning path of 21/6 m steps, regenerated until it closes; each step of it is a sensor tile the FrictionDetector watches, recolouring touched tiles and paying for first visits.

Every step renders the observation, as Gymnasium does: a 1000×800 frame of the road and grass (anti-aliased and filled polygons), the car, the indicators and the score, shrunk with pygame's smoothscale. The score is pygame's default font at size 42 laid out as SDL_ttf lays it out, from glyph data recorded from pygame and embedded in this package (DR-27, DR-48), for every text f"{reward:04.0f}" can show (NaN and the infinities included). Python's attributes are properties under their names (tile_visited_count is TileVisitedCount); the tiles' attributes live in CarRacingEnv.RoadTile. The class prints as Gymnasium's CarRacing (DR-32).

Not thread-safe; each env owns its world. Reference: gymnasium/envs/box2d/car_racing.py.

Its info reads typed (DR-91): CarRacingInfo info = step.Info; (CarRacingInfo), with the dict's own values still behind the indexer.

Constructors

CarRacingEnv(CarRacingEnvOptions)

Builds the instance from its options record: the properties set, the constructor's defaults for the rest.

public CarRacingEnv(CarRacingEnvOptions options)

Parameters

options CarRacingEnvOptions

The options.

Exceptions

ArgumentNullException

Thrown when options is null.

CarRacingEnv(RenderMode, bool, double, bool, bool, EnvViewerFactory?)

Builds the env with the render mode given as the RenderMode enum (DR-84, DR-93), as CarRacingEnv(string?, bool, double, bool, bool, EnvViewerFactory?) builds it from the mode's string: new CarRacingEnv(RenderMode.RgbArray) builds what new CarRacingEnv(renderMode: "rgb_array") builds, the member reaching the env as Gymnasium's string (Name(RenderMode)), which its RenderMode property then holds.

public CarRacingEnv(RenderMode renderMode, bool verbose = false, double lapCompletePercent = 0.95, bool domainRandomize = false, bool continuous = true, EnvViewerFactory? viewerFactory = null)

Parameters

renderMode RenderMode

The render mode, which the env must list in its metadata["render_modes"] as for the string; it behaves exactly as its Gymnasium string does in the other constructor.

verbose bool

Gymnasium's verbose: print the track generation's progress.

lapCompletePercent double

Gymnasium's lap_complete_percent: the share of tiles visited that, back at the start tile, completes the lap.

domainRandomize bool

Gymnasium's domain_randomize: random road, background and grass colours, drawn now and at resets.

continuous bool

Gymnasium's continuous: three continuous controls instead of five discrete actions.

viewerFactory EnvViewerFactory

Gym.NET's viewer_factory (DR-20) for human mode; null uses Gymnasium.HumanViewerFactory.

Remarks

The mode is required and comes first, so new CarRacingEnv() keeps meaning the other constructor, without a mode; leave the mode out there for no rendering. Every other parameter means what it means there.

Exceptions

ArgumentOutOfRangeException

Thrown for a value RenderMode does not declare (a cast integer such as (RenderMode)99).

CarRacingEnv(string?, bool, double, bool, bool, EnvViewerFactory?)

Creates the env.

public CarRacingEnv(string? renderMode = null, bool verbose = false, double lapCompletePercent = 0.95, bool domainRandomize = false, bool continuous = true, EnvViewerFactory? viewerFactory = null)

Parameters

renderMode string

Gymnasium's render_mode: null, "human", "rgb_array" or "state_pixels".

verbose bool

Gymnasium's verbose: print the track generation's progress.

lapCompletePercent double

Gymnasium's lap_complete_percent: the share of tiles visited that, back at the start tile, completes the lap.

domainRandomize bool

Gymnasium's domain_randomize: random road, background and grass colours, drawn now and at resets.

continuous bool

Gymnasium's continuous: three continuous controls instead of five discrete actions.

viewerFactory EnvViewerFactory

Gym.NET's viewer_factory (DR-20) for human mode; null uses Gymnasium.HumanViewerFactory.

Remarks

With domainRandomize the constructor draws the colours from the env's generator, which no seed has reached yet (it is entropy-seeded), as Gymnasium's does; a reset draws them again unless told not to.

Fields

Border

Gymnasium's BORDER: the red-white kerb's width on hard turns, in metres.

public const double Border = 1.3333333333333333

Field Value

double

BorderMinCount

Gymnasium's BORDER_MIN_COUNT: the consecutive sharp steps that make a kerb.

public const int BorderMinCount = 4

Field Value

int

Fps

Gymnasium's FPS: steps per simulated second and the human frame rate.

public const int Fps = 50

Field Value

int

GrassDim

Gymnasium's GRASS_DIM: a grass patch's side, in metres.

public const double GrassDim = 16.666666666666664

Field Value

double

MaxShapeDim

Gymnasium's MAX_SHAPE_DIM: the largest object's diagonal on screen, the margin of the off-screen test that skips drawing far polygons.

public static readonly double MaxShapeDim

Field Value

double

Playfield

Gymnasium's PLAYFIELD: the game-over boundary, in metres from the origin on either axis.

public const double Playfield = 333.3333333333333

Field Value

double

Scale

Gymnasium's SCALE: the track's scale.

public const double Scale = 6

Field Value

double

StateH

Gymnasium's STATE_H: the observation's height in pixels.

public const int StateH = 96

Field Value

int

StateW

Gymnasium's STATE_W: the observation's width in pixels.

public const int StateW = 96

Field Value

int

TrackDetailStep

Gymnasium's TRACK_DETAIL_STEP: the length of one track step, in metres.

public const double TrackDetailStep = 3.5

Field Value

double

TrackRad

Gymnasium's TRACK_RAD: the morphed circle's radius the checkpoints scatter around, in metres.

public const double TrackRad = 150

Field Value

double

TrackTurnRate

Gymnasium's TRACK_TURN_RATE: the most the path turns per step, in radians.

public const double TrackTurnRate = 0.31

Field Value

double

TrackWidth

Gymnasium's TRACK_WIDTH: the road's half-width, in metres.

public const double TrackWidth = 6.666666666666667

Field Value

double

VideoH

Gymnasium's VIDEO_H: the rgb_array frame's height.

public const int VideoH = 400

Field Value

int

VideoW

Gymnasium's VIDEO_W: the rgb_array frame's width.

public const int VideoW = 600

Field Value

int

WindowH

Gymnasium's WINDOW_H.

public const int WindowH = 800

Field Value

int

WindowW

Gymnasium's WINDOW_W: the frame every mode draws first, and the human window, in pixels.

public const int WindowW = 1000

Field Value

int

Zoom

Gymnasium's ZOOM: the camera's zoom after its first second.

public const double Zoom = 2.7

Field Value

double

ZoomFollow

Gymnasium's ZOOM_FOLLOW: kept for its name; Gymnasium's renderer always follows.

public const bool ZoomFollow = true

Field Value

bool

Properties

BgColor

Gymnasium's bg_color: the background's colour, as RoadColor.

public NDArray BgColor { get; }

Property Value

NDArray

Car

Gymnasium's car: the car, null before the first reset; stepping requires it.

public Car? Car { get; }

Property Value

Car

ClassMetadata

Gymnasium's class attribute metadata: {"render_modes": ["human", "rgb_array", "state_pixels"], "render_fps": 50}.

public static Metadata ClassMetadata { get; }

Property Value

Metadata

Remarks

A new dict on every read, so editing one env's metadata never reaches another.

Clock

Gymnasium's clock: paces human rendering, created by the first render.

public Clock? Clock { get; }

Property Value

Clock

ContactListenerKeepref

Gymnasium's contactListener_keepref: the constructor's contact listener, replaced in the world by each reset's.

public FrictionDetector ContactListenerKeepref { get; }

Property Value

FrictionDetector

Continuous

Gymnasium's continuous, fixed at construction.

public bool Continuous { get; }

Property Value

bool

DomainRandomize

Gymnasium's domain_randomize: whether resets draw new colours.

public bool DomainRandomize { get; set; }

Property Value

bool

FdTile

Gymnasium's fd_tile: the tiles' fixture definition, whose polygon each tile overwrites before its body is made.

public b2FixtureDef FdTile { get; }

Property Value

b2FixtureDef

GrassColor

Gymnasium's grass_color: the grass patches' colour, as RoadColor.

public NDArray GrassColor { get; }

Property Value

NDArray

InvisibleStateWindow

Gymnasium's invisible_state_window: always null (Python's None, never used).

public object? InvisibleStateWindow { get; }

Property Value

object

InvisibleVideoWindow

Gymnasium's invisible_video_window: always null.

public object? InvisibleVideoWindow { get; }

Property Value

object

IsOpen

Gymnasium's isopen: true until Close() shuts a human window down.

[PyName("isopen")]
public bool IsOpen { get; set; }

Property Value

bool

LapCompletePercent

Gymnasium's lap_complete_percent, which the next reset's contact listener takes.

public double LapCompletePercent { get; set; }

Property Value

double

NewLap

Gymnasium's new_lap: set by the contact listener when the start tile is reached with enough of the track visited.

public bool NewLap { get; set; }

Property Value

bool

PrevReward

Gymnasium's prev_reward: the score at the last step, whose difference is the step's reward.

public double PrevReward { get; set; }

Property Value

double

PythonClassName

The Python class this instance stands for: Gymnasium's CarRacing (DR-32).

protected override string PythonClassName { get; }

Property Value

string

Reward

Gymnasium's reward: the episode's running score (the text the frames show), which the contact listener raises.

public double Reward { get; set; }

Property Value

double

Road

Gymnasium's road: the track's tiles in order; null before the first reset.

public IReadOnlyList<CarRacingEnv.RoadTile>? Road { get; }

Property Value

IReadOnlyList<CarRacingEnv.RoadTile>

RoadColor

Gymnasium's road_color: an int64 array by default, float64 when randomized; a new array on each read.

public NDArray RoadColor { get; }

Property Value

NDArray

RoadPoly

Gymnasium's road_poly: each tile's polygon (in metres) with its colour, followed by a kerb's where the tile has one. A tile's colour is the tile's own array, which the contact listener overwrites, so touched tiles lose their shade.

public IReadOnlyList<(IReadOnlyList<(double X, double Y)> Poly, IReadOnlyList<double> Color)> RoadPoly { get; }

Property Value

IReadOnlyList<(IReadOnlyList<(double X, double Y)> Poly, IReadOnlyList<double> Color)>

Screen

Gymnasium's screen: the human window's surface, created by the first human render.

public Surface? Screen { get; }

Property Value

Surface

StartAlpha

Gymnasium's start_alpha: the angle the track's closing is cut at, set by the first track generation.

public double StartAlpha { get; }

Property Value

double

State

Gymnasium's state: the last observation, a new copy on each read.

public NDArray State { get; }

Property Value

NDArray

Exceptions

AttributeError

Thrown before the first step, as Python's attribute does not exist yet.

Surf

Gymnasium's surf: the last 1000×800 frame drawn (by any mode, the observation's included).

public Surface? Surf { get; }

Property Value

Surface

T

Gymnasium's t: the episode's simulated time in seconds, which drives the first second's zoom.

public double T { get; set; }

Property Value

double

Exceptions

AttributeError

Thrown before the first reset.

TileVisitedCount

Gymnasium's tile_visited_count: tiles visited this episode.

public long TileVisitedCount { get; set; }

Property Value

long

Track

Gymnasium's track: the closed path's steps (alpha, beta, x, y), the first being the start.

public IReadOnlyList<(double Alpha, double Beta, double X, double Y)> Track { get; }

Property Value

IReadOnlyList<(double Alpha, double Beta, double X, double Y)>

Exceptions

AttributeError

Thrown before the first reset, as Python's attribute does not exist yet.

Verbose

Gymnasium's verbose.

public bool Verbose { get; set; }

Property Value

bool

World

Gymnasium's world: the Box2D world without gravity, one for the env's life.

public b2World World { get; }

Property Value

b2World

Methods

Close()

Shuts the human window down once one was opened, and marks the env closed (IsOpen).

public override void Close()

Remarks

Dispose(bool)

Releases the kept observation along with the env's spaces.

protected override void Dispose(bool disposing)

Parameters

disposing bool

Whether managed resources are released.

RegisterInput(NDArray, ref bool, ref bool)

Gymnasium's demo keyboard handler (register_input): reads the pending window events and sets the demo's controls from the arrow keys (left/right steer -1/+1, up gas 1, down brake 0.8, cleared on release), and requests a restart on Return and quitting on Escape or the window's close button.

public static void RegisterInput(NDArray a, ref bool quit, ref bool restart)

Parameters

a NDArray

The demo's action, three float64 controls, written in place.

quit bool

Set when the demo should end; never cleared here.

restart bool

Set when the episode should restart; never cleared here.

Remarks

Python's function writes the module's globals a, quit and restart; here they are the caller's. Events come from EventQueue, the queue the interactive viewers fill (DR-41). Reference: gymnasium/envs/box2d/car_racing.py.

Exceptions

ArgumentNullException

Thrown when a is null.

ArgumentException

Thrown when a is not a float64 array of at least three elements.

Render()

Renders the current mode's frame (Gymnasium's render()): nothing and a warning without a render mode; the frame of RenderMode otherwise.

public override RenderResult Render()

Returns

RenderResult

rgb_array: the (400, 600, 3) frame; state_pixels: the (96, 96, 3) observation's frame; otherwise nothing.

Remarks

Exceptions

AssertionError

Thrown without a render mode when the env has no spec, or for a mode the metadata does not list.

DependencyNotInstalled

Thrown on the first human render when no viewer factory is set (DR-20).

Reset(BigInteger?, IReadOnlyDictionary<string, object?>?)

Starts an episode, as Gymnasium's does in its order: reseeds the generator when a seed is given, destroys the last episode's tiles and car (the old listener sees their contacts end), installs a new FrictionDetector, redraws the colours when randomizing, generates tracks until one closes, builds the car on the first step, renders in human mode, and returns the observation of a step without an action.

public override ResetResult<NDArray> Reset(BigInteger? seed = null, IReadOnlyDictionary<string, object?>? options = null)

Parameters

seed BigInteger?

The seed of a fresh Generator(PCG64(SeedSequence(seed))), or null to keep the generator.

options IReadOnlyDictionary<string, object>

Gymnasium's options: with domain_randomize, {"randomize": False} keeps the current colours (any value is read by Python's truth value); without it they are ignored.

Returns

ResetResult<NDArray>

The first observation and an empty info.

Remarks

Exceptions

Error

Thrown for a negative seed, with Gymnasium's message.

DependencyNotInstalled

Thrown in human mode by the first render when no viewer factory is set (DR-20).

Step(NDArray)

One step, in Gymnasium's order: the action's controls (continuous: steer by -action[0], gas, brake; discrete: checked against Discrete(5), then fixed controls), the car's wheel physics, one 1/50 s world step (180 and 60 iterations, the contact listener paying for new tiles), the observation's frame, then -0.1 on the score, the step's reward, and the lap's or the playfield's end. Renders in human mode.

public override StepResult<NDArray> Step(NDArray action)

Parameters

action NDArray

Continuous: three controls (read as float64, unclipped except the gas); discrete: an element of Discrete(5) (a 0-d integer array; the untyped step also takes a .NET integer). Read, never kept.

Returns

StepResult<NDArray>

The 96×96 RGB observation, the reward (the score's change, or -100 off the playfield), whether the episode ended, truncated=False, and the info (lap_finished when it ended).

Remarks

Exceptions

ArgumentNullException

Thrown when action is null (only the reset's own step goes without one).

AssertionError

Thrown before the first reset (Python's bare assert, with its empty message).

InvalidAction

Thrown in discrete mode for an action outside Discrete(5), with Gymnasium's message.

IndexError

Thrown in continuous mode for a 0-d action or one of fewer than three elements, with NumPy's message, after the controls before the missing one were applied.

NotSupportedException

Thrown in continuous mode for an action of more than one dimension (NumPy's array arithmetic on the wheels is not modelled).

DependencyNotInstalled

Thrown in human mode by the first render when no viewer factory is set (DR-20).