Skip to content

KernelAPI reference

Class Game

Namespace: MicroEngine.Core
Assembly: MicroEngine.dll
Guide: Game lifecycle and time

Base class for a game. Subclasses declare Settings, build content in Load and push the first scene. The runner owns the loop.

C#
public abstract class Game : IEngineModule, IStateHashed

Inheritance

object ← Game

Implements

IEngineModule, IStateHashed

Examples

C#
public sealed class MyGame : Game
{
public override GameSettings Settings { get; } = new("My Game", 320, 180);
protected override void Load() => Scenes.Push(new TitleScene());
}

Remarks

The engine services (Graphics, Audio, Input, Scenes, Font) exist from Load on; reading them in the constructor fails. The simulation advances in fixed steps of 1 / UpdateRate seconds; drawing happens once per frame.

A game is an engine module ([IEngineModule](/docs/api/microengine.kernel.ienginemodule/)): its services are registered in the engine's [Services](/docs/api/microengine.core.game/#MicroEngine_Core_Game_Services) and its per-frame work runs as named systems of the frame [Schedule](/docs/api/microengine.core.game/#MicroEngine_Core_Game_Schedule). Override [Configure](/docs/api/microengine.core.game/#MicroEngine_Core_Game_Configure_MicroEngine_Kernel_EngineBuilder_) to add systems, replace services or change the [TimeSettings](/docs/api/microengine.kernel.timesettings/).

Constructors

Game()

C#
protected Game()

Properties

Achievements

The game’s achievements; available after TrackAchievements.

C#
public AchievementTracker Achievements { get; }

Property Value

AchievementTracker

Assets

The game’s content files: textures, atlases and fonts loaded from Content/, shared and released by the engine (AssetCache). Created before Load; everything it loaded is disposed after Unload.

C#
public AssetCache Assets { get; }

Property Value

AssetCache

Audio

The mixer that loads and plays sound effects and music. Created before Load.

C#
public AudioMixer Audio { get; }

Property Value

AudioMixer

ContentRoot

A content folder of the game’s own for Assets, which then wins over the composition’s content. Null (the default) reads the content the composition names (Content: a macOS bundle’s resources, a phone’s unpacked files, a zip archive), or else the Content folder next to the executable (DefaultRoot). Tests override it to point at the game’s sources.

C#
protected virtual string? ContentRoot { get; }

Property Value

string?

DebugDraw

Lines, shapes, text and physics worlds any code can ask to see, drawn above the scenes at the end of the frame (DebugDraw). Calls do nothing until Enabled is set.

C#
public DebugDraw DebugDraw { get; }

Property Value

DebugDraw

Diagnostics

The live measurements of the run: the last frame’s times, allocations, graphics work and audio voices, and the time of each frame system. Off until Enabled is set or a tool listens to the engine’s meter.

C#
public GameDiagnostics Diagnostics { get; }

Property Value

GameDiagnostics

Font

The built-in pixel font, created before Load and disposed by the engine when the game shuts down.

C#
public BitmapFont Font { get; }

Property Value

BitmapFont

Frame

The time of the frame being run (FrameContext): its delta, the fixed step, the blend and the frame number.

C#
public FrameContext Frame { get; }

Property Value

FrameContext

FrameBlend

How far the frame being drawn is between the last update and the next one, from 0 to 1: the part of a step of real time that has passed but not been simulated yet. Updates run at a fixed rate and frames at the display’s, so on a display whose rate is not a multiple of UpdateRate (75, 100, 144 Hz…) some frames show no new update; drawing moving things at Vector2.Lerp(previousPosition, position, FrameBlend) makes their motion even (drawn up to one update behind, like every interpolating loop). Always 1 when time advances one step per frame (headless, scripted runs), so captures show exactly the last update.

C#
public float FrameBlend { get; }

Property Value

float

Graphics

Creates textures from images (PixelImage, atlases, fonts). Available from Load on; throws InvalidOperationException before.

C#
public IGraphicsDevice Graphics { get; }

Property Value

IGraphicsDevice

HasAchievements

Whether TrackAchievements was called, so Achievements can be read without throwing.

C#
public bool HasAchievements { get; }

Property Value

bool

Height

Height of the virtual canvas in pixels (VirtualHeight).

C#
public int Height { get; }

Property Value

int

Input

The input actions of player 1, built by CreateInput before Load and sampled once per update. With no setup player 1 owns every device, so a single-player game reads only this.

C#
public InputMap Input { get; }

Property Value

InputMap

InputSystem

The engine’s input (InputSystem): the local players (Players; player 1’s map is Input), the devices and their events, the input layers events pass through before gameplay (Layers; the on-screen controls are one), this update’s events no layer took (Events) and the text channel (Text). Created before Load.

C#
public InputSystem InputSystem { get; }

Property Value

InputSystem

Lifecycle

Engine events: suspension, resumption, quit requests (with veto) and, where the platform reports them, resizing and focus.

C#
public IEngineLifecycle Lifecycle { get; }

Property Value

IEngineLifecycle

Log

Where the engine’s diagnostics go (the ILog service; standard error by default).

C#
public ILog Log { get; }

Property Value

ILog

Platform

The platform running the game (window, audio, input). Throws InvalidOperationException before the game starts.

C#
protected IPlatform Platform { get; }

Property Value

IPlatform

Prompts

How to name each action to the player on the device in use (Prompts.Format(“Press {confirm}”)), from the bindings of Input and the controls of Touch. Created with them, before Load.

C#
public ActionPrompts Prompts { get; }

Property Value

ActionPrompts

QuitRequested

True after Quit; the loop stops at the end of the current frame.

C#
public bool QuitRequested { get; }

Property Value

bool

Random

Deterministic per-run randomness, seeded by the launcher (Seed): a SeededRandom, which draws exactly what new Random(seed) draws and whose state is part of the per-step state hash (ComputeStateHash).

C#
public Random Random { get; }

Property Value

Random

Scenes

The scene stack. Push the first scene from Load.

C#
public SceneManager Scenes { get; }

Property Value

SceneManager

Schedule

The frame’s systems by phase, the built-in ones named engine.*; fixed once the game starts.

C#
public FrameSchedule Schedule { get; }

Property Value

FrameSchedule

Screen

The screen while the game runs: displays, VSync, frame limit, window mode, and the graphics API and GPU in use (GraphicsSettings for the options it starts with). Available from Load.

C#
public GameScreen Screen { get; }

Property Value

GameScreen

Services

The engine’s services: every built-in service (InputMap, AudioMixer, SceneManager, AssetCache, VirtualControls, ActionPrompts, BitmapFont, GameScreen, IPlatform, Random, this game) and those the game’s Configure registered, found by the type they were registered as. Available from Load on.

C#
public ServiceRegistry Services { get; }

Property Value

ServiceRegistry

Settings

The title, virtual canvas size, window scale, update rate and background colour of the game. Read once when the game starts; keep it constant.

C#
public abstract GameSettings Settings { get; }

Property Value

GameSettings

Time

Seconds of simulated time since start.

C#
public float Time { get; }

Property Value

float

TimeSettings

The time policy of the run: fixed rate, catch-up limits and whether time follows the wall clock or advances one step per frame.

C#
public TimeSettings TimeSettings { get; }

Property Value

TimeSettings

Touch

The on-screen touch controls (CreateTouchLayout), available from Configure on. They are an opt-in module: active, drawn and read on a touch-first screen (TouchFirst: phones, tablets, touch-only browsers) or once the game sets their Layout (in Configure, Load or a scene), on any platform with a touch screen; otherwise inactive, with no frame system, input layer, action source or overlay (IsActive). Controls activated after the engine was built join the game at the start of the next frame.

C#
public VirtualControls Touch { get; }

Property Value

VirtualControls

UpdateCount

Number of fixed updates simulated since start (0 during Load).

C#
public long UpdateCount { get; }

Property Value

long

Views

The world view and the UI view, and the mapping between window pixels, canvas pixels and UI units, with the pointer in each (GameViews).

C#
public GameViews Views { get; }

Property Value

GameViews

Width

Width of the virtual canvas in pixels (VirtualWidth).

C#
public int Width { get; }

Property Value

int

Methods

ComputeStateHash(bool)

Hashes the simulation state now (StateHasher), in sections: engine.time (update count and time), engine.random (Random), engine.input (Input after sampling, then the other players and the pairings when there are any), engine.audio (the music playing or paused and the volumes), engine.assets (how many assets are loaded), engine.achievements (when on), engine.scenes (the stack and the transition), one scene[i]:Type per scene from the bottom (its age, coroutines and tweens, then HashState) and game (HashState). The loop records it after every fixed step of a run given a StateTrace; drawing never changes it.

C#
public StepHash ComputeStateHash(bool sections = false)

Parameters

sections bool

Whether the result carries each section’s hash, to name the state that differs.

Returns

StepHash

Exceptions

InvalidOperationException

The game has not started.

Configure(EngineBuilder)

Called once when the game starts, after the built-in services and systems were registered and before Load: add frame systems (builder.Schedule.Add), register or replace services (builder.Services), edit settings such as TimeSettings (builder.Configure) and subscribe to builder.Lifecycle. A run’s own choices (TimeMode) are applied after it. The default does nothing.

C#
public virtual void Configure(EngineBuilder builder)

Parameters

builder EngineBuilder

CreateCamera()

A camera the size of the canvas whose defaults follow the game’s presentation (Presentation): snapped to whole pixels for pixel art, smooth for high-resolution 2D.

C#
public Camera2D CreateCamera()

Returns

Camera2D

CreateInput()

Override to change bindings; the default suits most games.

C#
protected virtual InputMap CreateInput()

Returns

InputMap

CreateTouchLayout()

Override to choose the on-screen controls for touch screens: which d-pad, joystick and buttons press which actions, and where. The default (CreateDefault) matches CreateDefault and is used on touch-first screens only. A layout of the game’s own, returned without calling the base method, is the game setting a layout: it activates the controls on any platform with a touch screen (Touch).

C#
protected virtual TouchLayout CreateTouchLayout()

Returns

TouchLayout

DrawAboveScenes(IRenderer)

Draws above every scene, in the canvas, once the scenes and their transition are drawn and before the scenes’ interfaces: what belongs to the game rather than to one scene, such as an unlock banner or a notice that stays while scenes change. Advance what it shows from a frame system (builder.Schedule.Add in Configure). The default draws nothing.

C#
protected virtual void DrawAboveScenes(IRenderer canvas)

Parameters

canvas IRenderer

The canvas renderer, in the game’s virtual pixels.

HashState(StateHasher)

Adds the game’s own simulation state to the per-step state hash (ComputeStateHash), after the engine’s sections, in a section named game: the fields of this class that decide what happens next (progress, a session’s lives and score…). Leave out what only drawing or the platform uses (caches written while drawing, textures, save locations). The default adds nothing; scenes add their own state (HashState).

C#
public virtual void HashState(StateHasher hash)

Parameters

hash StateHasher

InitializeForTest(IPlatform, int)

Test hook: initializes against a platform without running the loop.

C#
public void InitializeForTest(IPlatform platform, int seed = 1)

Parameters

platform IPlatform

seed int

Load()

Called once after the platform exists. Create atlases, sounds and push the first scene.

C#
protected abstract void Load()

OnResumed()

Called when a suspended game comes back, before its next update.

C#
protected virtual void OnResumed()

OnSuspended()

Called when the platform suspends the game (sent to the background), after music paused and achievements were saved.

C#
protected virtual void OnSuspended()

Quit()

Asks the loop to stop. The current frame finishes, then every scene exits and Unload runs.

C#
public void Quit()

StepForTest()

Test hook: advances one fixed step after sampling input.

C#
public void StepForTest()

Remarks

Runs the phases that come before drawing for one fixed step, with a frame that stands for exactly one step: BeginFrame, Input, the four fixed phases, Update and LateUpdate. The loop’s clock does not move.

TrackAchievements(IEnumerable<Achievement>, SaveStore)

Turns achievements on: call it from the game’s constructor or from Configure, before the engine is composed. It adds the achievements module (an AchievementTracker service over catalog and the engine.achievements system that writes progress) and the saves module when the game has none. Progress persists in the “achievements” slot of store. Report progress through Achievements. The game shows unlocks its own way: subscribe to Unlocked on Achievements, and draw a banner above every scene from DrawAboveScenes. A game that never calls it has no achievement service, system or file.

C#
protected AchievementTracker TrackAchievements(IEnumerable<Achievement> catalog, SaveStore store)

Parameters

catalog IEnumerable<Achievement>

store SaveStore

Returns

AchievementTracker

Exceptions

InvalidOperationException

The engine was already composed (called from Load or later).

TryGetCapability<T>(out T?)

An optional feature, if there is one: one the engine declared (Capabilities), else one the platform offers (TryGetCapability``1: its ITouchScreen, its IDisplayControl, its IPlatformDiagnostics…). False before the game starts.

C#
public bool TryGetCapability<T>(out T? capability) where T : class

Parameters

capability T?

Returns

bool

Type Parameters

T

Unload()

Called once before the platform is disposed.

C#
protected virtual void Unload()