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.
public abstract class Game : IEngineModule, IStateHashedInheritance
Implements
Examples
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()
protected Game()Properties
Achievements
The game’s achievements; available after TrackAchievements.
public AchievementTracker Achievements { get; }Property Value
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.
public AssetCache Assets { get; }Property Value
Audio
The mixer that loads and plays sound effects and music. Created before Load.
public AudioMixer Audio { get; }Property Value
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.
protected virtual string? ContentRoot { get; }Property Value
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.
public DebugDraw DebugDraw { get; }Property Value
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.
public GameDiagnostics Diagnostics { get; }Property Value
Font
The built-in pixel font, created before Load and disposed by the engine when the game shuts down.
public BitmapFont Font { get; }Property Value
Frame
The time of the frame being run (FrameContext): its delta, the fixed step, the blend and the frame number.
public FrameContext Frame { get; }Property Value
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.
public float FrameBlend { get; }Property Value
Graphics
Creates textures from images (PixelImage, atlases, fonts). Available from Load on; throws InvalidOperationException before.
public IGraphicsDevice Graphics { get; }Property Value
HasAchievements
Whether TrackAchievements was called, so Achievements can be read without throwing.
public bool HasAchievements { get; }Property Value
Height
Height of the virtual canvas in pixels (VirtualHeight).
public int Height { get; }Property Value
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.
public InputMap Input { get; }Property Value
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.
public InputSystem InputSystem { get; }Property Value
Lifecycle
Engine events: suspension, resumption, quit requests (with veto) and, where the platform reports them, resizing and focus.
public IEngineLifecycle Lifecycle { get; }Property Value
Log
Where the engine’s diagnostics go (the ILog service; standard error by default).
public ILog Log { get; }Property Value
Platform
The platform running the game (window, audio, input). Throws InvalidOperationException before the game starts.
protected IPlatform Platform { get; }Property Value
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.
public ActionPrompts Prompts { get; }Property Value
QuitRequested
True after Quit; the loop stops at the end of the current frame.
public bool QuitRequested { get; }Property Value
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).
public Random Random { get; }Property Value
Scenes
The scene stack. Push the first scene from Load.
public SceneManager Scenes { get; }Property Value
Schedule
The frame’s systems by phase, the built-in ones named engine.*; fixed once the game starts.
public FrameSchedule Schedule { get; }Property Value
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.
public GameScreen Screen { get; }Property Value
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.
public ServiceRegistry Services { get; }Property Value
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.
public abstract GameSettings Settings { get; }Property Value
Time
Seconds of simulated time since start.
public float Time { get; }Property Value
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.
public TimeSettings TimeSettings { get; }Property Value
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.
public VirtualControls Touch { get; }Property Value
UpdateCount
Number of fixed updates simulated since start (0 during Load).
public long UpdateCount { get; }Property Value
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).
public GameViews Views { get; }Property Value
Width
Width of the virtual canvas in pixels (VirtualWidth).
public int Width { get; }Property Value
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.
public StepHash ComputeStateHash(bool sections = false)Parameters
sections bool
Whether the result carries each section’s hash, to name the state that differs.
Returns
Exceptions
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.
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.
public Camera2D CreateCamera()Returns
CreateInput()
Override to change bindings; the default suits most games.
protected virtual InputMap CreateInput()Returns
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).
protected virtual TouchLayout CreateTouchLayout()Returns
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.
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).
public virtual void HashState(StateHasher hash)Parameters
hash StateHasher
InitializeForTest(IPlatform, int)
Test hook: initializes against a platform without running the loop.
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.
protected abstract void Load()OnResumed()
Called when a suspended game comes back, before its next update.
protected virtual void OnResumed()OnSuspended()
Called when the platform suspends the game (sent to the background), after music paused and achievements were saved.
protected virtual void OnSuspended()Quit()
Asks the loop to stop. The current frame finishes, then every scene exits and Unload runs.
public void Quit()StepForTest()
Test hook: advances one fixed step after sampling input.
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.
protected AchievementTracker TrackAchievements(IEnumerable<Achievement> catalog, SaveStore store)Parameters
catalog IEnumerable<Achievement>
store SaveStore
Returns
Exceptions
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.
public bool TryGetCapability<T>(out T? capability) where T : classParameters
capability T?
Returns
Type Parameters
T
Unload()
Called once before the platform is disposed.
protected virtual void Unload()