Skip to main content

Class: Game

Implements

Constructors

new Game()

new Game(options): Game

The base class for all games. New games should extend this class.

Parameters

options: GameOptions

GameOptions

Returns

Game

Defined in

Game.ts:136

Properties

_canvasKit?

optional _canvasKit: CanvasKit

Defined in

Game.ts:95


additionalParameters?

optional additionalParameters: unknown

Additional activity parameters that were set.

Implementation of

Activity.additionalParameters

Defined in

Game.ts:119


beginIso8601Timestamp

beginIso8601Timestamp: string = ""

The value of new Date().toISOString() immediately before the activity begins

Implementation of

Activity.beginIso8601Timestamp

Defined in

Game.ts:107


beginTimestamp

beginTimestamp: number = NaN

The value of performance.now() immediately before the activity begins

Implementation of

Activity.beginTimestamp

Defined in

Game.ts:106


canvasCssHeight

canvasCssHeight: number = 0

Defined in

Game.ts:858


canvasCssWidth

canvasCssWidth: number = 0

Defined in

Game.ts:857


canvasKitWasmVersion

readonly canvasKitWasmVersion: "__CANVASKITWASM_VERSION__" = "__CANVASKITWASM_VERSION__"

Defined in

Game.ts:104


currentScene?

optional currentScene: Scene

Defined in

Game.ts:844


data

data: GameData

Defined in

Game.ts:834


entryScene?

optional entryScene: string | Scene

The scene, or its name as a string, to be presented when the game is started. If this is undefined, the game will start with the first scene that has been added

Defined in

Game.ts:833


eventStore

eventStore: EventStore

Defined in

Game.ts:125


freeNodesScene

freeNodesScene: Scene

Defined in

Game.ts:861


i18n?

optional i18n: I18n

Defined in

Game.ts:114


id

id: string

Short identifier of this activity

Implementation of

Activity.id

Defined in

Game.ts:99


manifest?

optional manifest: Manifest

Defined in

Game.ts:124


materializedNodes

materializedNodes: M2Node[]

Nodes created during event replay

Defined in

Game.ts:129


moduleMetadata

moduleMetadata: ModuleMetadata

Defined in

Game.ts:103


name

name: string

Human-friendly name of this activity

Implementation of

Activity.name

Defined in

Game.ts:98


options

options: GameOptions

Defined in

Game.ts:105


publishUuid

publishUuid: string = ""

Persistent unique identifier (UUID) of the activity. Required for games. Optional or empty string if a survey.

Implementation of

Activity.publishUuid

Defined in

Game.ts:100


scenes

scenes: Scene[]

Defined in

Game.ts:860


sessionUuid

sessionUuid: string = ""

The activity's parent session unique identifier. This is newly generated each session.

Implementation of

Activity.sessionUuid

Defined in

Game.ts:96


snapshots

snapshots: Image[]

Defined in

Game.ts:2515


staticTrialSchema

staticTrialSchema: object

Index Signature

[key: string]: JsonSchemaDataTypeScriptTypes

Defined in

Game.ts:120


studyId?

optional studyId: string

The ID of the study (protocol, experiment, or other aggregate) that contains the repeated administrations of this activity. The ID should be short, url-friendly, human-readable text (no spaces, special characters, or slashes), e.g., nyc-aging-cohort.

Implementation of

Activity.studyId

Defined in

Game.ts:101


studyUuid?

optional studyUuid: string

Unique identifier (UUID) of the study (protocol, experiment, or other aggregate) that contains the administration of this activity.

Implementation of

Activity.studyUuid

Defined in

Game.ts:102


surface?

optional surface: Surface

Defined in

Game.ts:840


trialIndex

trialIndex: number = 0

The 0-based index of the current trial

Defined in

Game.ts:838


type

readonly type: Game = ActivityType.Game

The type of activity: Game or Survey

Implementation of

Activity.type

Defined in

Game.ts:94


uuid

uuid: string

The activity's unique identifier. This is newly generated each session. The UUID for an activity will vary across sessions.

Implementation of

Activity.uuid

Defined in

Game.ts:97

Accessors

canvasKit

Get Signature

get canvasKit(): CanvasKit

Returns

CanvasKit

Set Signature

set canvasKit(canvasKit): void

Parameters

canvasKit: CanvasKit

Returns

void

Defined in

Game.ts:821


dataStores

Get Signature

get dataStores(): IDataStore[]

Optional stores to use for saving data. The implementation of the store is not provided by the @m2c2kit/core library.

Returns

IDataStore[]

Set Signature

set dataStores(dataStores): void

Optional stores to use for saving data. The implementation of the store is not provided by the @m2c2kit/core library.

Parameters

dataStores: IDataStore[]

Returns

void

Optional stores to use for saving data. The implementation of the store is not provided by the @m2c2kit/core library.

Implementation of

Activity.dataStores

Defined in

Game.ts:674


entities

Get Signature

get entities(): M2Node[]

Deprecated

use Game.nodes instead

Returns

M2Node[]

Defined in

Game.ts:3116


eventMaterializer

Get Signature

get eventMaterializer(): EventMaterializer

Returns

EventMaterializer

Set Signature

set eventMaterializer(eventMaterializer): void

Parameters

eventMaterializer: EventMaterializer

Returns

void

Defined in

Game.ts:503


fontManager

Get Signature

get fontManager(): FontManager

Returns

FontManager

Set Signature

set fontManager(fontManager): void

Parameters

fontManager: FontManager

Returns

void

Defined in

Game.ts:470


freeEntities

Get Signature

get freeEntities(): M2Node[]

Deprecated

Use Game.freeEntities instead

Returns

M2Node[]

Defined in

Game.ts:953


freeNodes

Get Signature

get freeNodes(): M2Node[]

Returns array of free nodes that have been added to the game.

Returns

M2Node[]

array of free nodes

Defined in

Game.ts:946


imageManager

Get Signature

get imageManager(): ImageManager

Returns

ImageManager

Set Signature

set imageManager(imageManager): void

Parameters

imageManager: ImageManager

Returns

void

Defined in

Game.ts:481


nodes

Get Signature

get nodes(): M2Node[]

Returns array of all nodes that have been added to the game object.

Returns

M2Node[]

Defined in

Game.ts:3100


soundManager

Get Signature

get soundManager(): SoundManager

Returns

SoundManager

Set Signature

set soundManager(soundManager): void

Parameters

soundManager: SoundManager

Returns

void

Defined in

Game.ts:492

Methods

addFreeEntity()

addFreeEntity(node): void

Parameters

node: M2Node

Returns

void

Deprecated

Use addFreeNode() instead

Defined in

Game.ts:890


addFreeNode()

addFreeNode(node): void

Adds a node as a free node (a node that is not part of a scene) to the game.

Parameters

node: M2Node

node to add as a free node

Returns

void

Remarks

Once added to the game, a free node will always be drawn, and it will not be part of any scene transitions. This is useful if a node must persistently be drawn and not move with scene transitions. The appearance of the free node must be managed by the programmer. Note: internally, the free nodes are part of a special scene (named "__freeNodesScene"), but this scene is handled apart from regular scenes in order to achieve the free node behavior.

Defined in

Game.ts:883


addScene()

addScene(scene): void

Adds a scene to the game.

Parameters

scene: Scene

Returns

void

Remarks

A scene, and its children nodes, cannot be presented unless it has been added to the game object.

Defined in

Game.ts:964


addScenes()

addScenes(scenes): void

Adds multiple scenes to the game.

Parameters

scenes: Scene[]

Returns

void

Defined in

Game.ts:996


addStaticTrialData()

addStaticTrialData(variableName, value): void

Sets the value of a variable that will be the same for all trials.

Parameters

variableName: string

variable to be set

value: JsonSchemaDataTypeScriptTypes

value of the variable to set

Returns

void

Remarks

This sets the value of a variable that is the same across all trials ("static"). This is useful for variables that are not part of the trial schema, but that you want to save for each trial in your use case. For example, you might want to save the subject's participant ID for each trial, but this is not part of the trial schema. Rather than modify the source code for the game, you can do the following to ensure that the participant ID is saved for each trial:

game.addTrialSchema(&#123 participant_id: &#123 type: "string", description: "ID of the participant", } }); game.addStaticTrialData("participant_id", "12345");

When Game.trialComplete() is called, the participant_id variable will be saved for the trial with the value "12345".

Defined in

Game.ts:1867


addTrialData()

addTrialData(variableName, value): void

Adds data to the game's TrialData object.

Parameters

variableName: string

variable to be set

value: JsonSchemaDataTypeScriptTypes

value of the variable to set

Returns

void

Remarks

The variableName must be previously defined in the trialSchema object passed in during game initialization through GameInitOptions.trialSchema. The type of the value must match what was defined in the trialSchema, otherwise an error is thrown.

Defined in

Game.ts:1748


addTrialSchema()

addTrialSchema(schema): void

Adds custom trial schema to the game's trialSchema object.

Parameters

schema: TrialSchema

Trial schema to add

Returns

void

Remarks

This is useful if you want to add custom trial variables. This must be done before Session.start() is called, because Session.start() will call Game.start(), which will initialize the trial schema.

Defined in

Game.ts:1832


cancel()

cancel(): void

Should be called when current game has been canceled by a user action.

Returns

void

Remarks

This will send an ActivityCancel event to any listeners, such as a function provided to Game.onCancel() or a callback defined in SessionOptions.activityCallbacks.onActivityLifecycle. This is how the game can communicate changes in activity state to the parent session. It is the responsibility of the the game programmer to call this at the appropriate time. It is not triggered automatically.

Defined in

Game.ts:2153


createEventListener()

createEventListener(type, nodeName, callback, callbackOptions?): void

Creates an event listener for a node based on the node name

Parameters

type: M2EventType

the type of event to listen for, e.g., "tapDown"

nodeName: string

the node name for which an event will be listened

callback

the callback to be invoked when the event occurs

callbackOptions?: CallbackOptions

Returns

void

Remarks

Typically, event listeners will be created using a method specific to the event, such as onTapDown(). This alternative allows creation with node name.

Defined in

Game.ts:3070


dispose()

dispose(): void

Frees up resources that were allocated to run the game.

Returns

void

Remarks

This will be done automatically by the m2c2kit library; the end-user must not call this. FOR INTERNAL USE ONLY.

Defined in

Game.ts:1642


end()

end(): void

Should be called when current game has ended successfully.

Returns

void

Remarks

This will send an ActivityEnd event to any listeners, such as a function provided to Game.onEnd() or a callback defined in SessionOptions.activityCallbacks.onActivityLifecycle. This is how the game can communicate changes in activity state to the parent session. It is the responsibility of the the game programmer to call this at the appropriate time. It is not triggered automatically.

Defined in

Game.ts:2122


getParameter()

getParameter<T>(parameterName): T

Gets the value of the game parameter. If parameterName is not found, then throw exception.

Type Parameters

T

Parameters

parameterName: string

the name of the game parameter whose value is requested

Returns

T

Defined in

Game.ts:1102


getParameterOrFallback()

getParameterOrFallback<T, U>(parameterName, fallbackValue): T | U

Gets the value of the game parameter. If parameterName is not found, then return fallback value

Type Parameters

T

U

Parameters

parameterName: string

the name of the game parameter whose value is requested

fallbackValue: U

the value to return if parameterName is not found

Returns

T | U

Defined in

Game.ts:1121


hasDataStores()

hasDataStores(): boolean

Returns

boolean

Defined in

Game.ts:685


hasParameter()

hasParameter(parameterName): boolean

Returns true if a game parameter exists for the given string.

Parameters

parameterName: string

the name of the game parameter whose existence is queried

Returns

boolean

Defined in

Game.ts:1138


init()

init(): Promise<void>

Initializes the activity.

Returns

Promise<void>

Remarks

All code to create the activity's appearance and behavior must be placed in this method. This method is asynchronous, and must be awaited. When writing a new game by extending the Game class, this method will be overridden, but the base method must still be called with await super.init().

Deprecated

use Game.initialize() instead.

Implementation of

Activity.init

Defined in

Game.ts:232


initialize()

initialize(): Promise<void>

Initializes the activity.

Returns

Promise<void>

Remarks

All code to create the activity's appearance and behavior must be placed in this method. This method is asynchronous, and must be awaited. When writing a new game by extending the Game class, this method will be overridden, but the base method must still be called with await super.initialize().

Implementation of

Activity.initialize

Defined in

Game.ts:370


loadCanvasKit()

loadCanvasKit(canvasKitWasmUrl): Promise<CanvasKit>

Internal

Loads the canvaskit wasm binary.

For m2c2kit library use only

Parameters

canvasKitWasmUrl: string

URL to the canvaskit wasm binary

Returns

Promise<CanvasKit>

a promise that resolves to a CanvasKit object

Remarks

The CanvasKit object is initialized with this method, rather than calling CanvasKitInit() directly, so that this method can be easily mocked in tests.

Defined in

Game.ts:248


loadManifest()

loadManifest(manifestJsonUrl): Promise<Manifest>

Internal

Returns the manifest, if manifest.json was created during the build.

For m2c2kit library use only

Parameters

manifestJsonUrl: string = "__NO_M2C2KIT_MANIFEST_JSON_URL__"

Do not use this parameter. Allow the default.

Returns

Promise<Manifest>

a promise that resolves to the manifest object, or an empty object if there is no manifest

Remarks

This should be called without any parameters. The manifestJsonUrl parameter's default value will be modified during the build step, if the build was configured to include the manifest.json

Defined in

Game.ts:441


onCancel()

onCancel(callback, options?): void

Executes a callback when the game is canceled.

Parameters

callback

function to execute.

options?: CallbackOptions

options for the callback.

Returns

void

Implementation of

Activity.onCancel

Defined in

Game.ts:3775


onData()

onData(callback, options?): void

Executes a callback when the game generates data.

Parameters

callback

function to execute.

options?: CallbackOptions

options for the callback.

Returns

void

Implementation of

Activity.onData

Defined in

Game.ts:3801


onEnd()

onEnd(callback, options?): void

Executes a callback when the game ends.

Parameters

callback

function to execute.

options?: CallbackOptions

options for the callback.

Returns

void

Implementation of

Activity.onEnd

Defined in

Game.ts:3788


onStart()

onStart(callback, options?): void

Executes a callback when the game starts.

Parameters

callback

function to execute.

options?: CallbackOptions

options for the callback.

Returns

void

Implementation of

Activity.onStart

Defined in

Game.ts:3762


onWarmupEnd()

onWarmupEnd(callback, options?): void

Internal

Executes a callback when the game ends its warmup.

For m2c2kit library use only

Parameters

callback

function to execute.

options?: CallbackOptions

options for the callback.

Returns

void

Defined in

Game.ts:3831


onWarmupStart()

onWarmupStart(callback, options?): void

Internal

Executes a callback when the game begins its warmup.

For m2c2kit library use only

Parameters

callback

function to execute.

options?: CallbackOptions

options for the callback.

Returns

void

Defined in

Game.ts:3816


playEventsHandler()

playEventsHandler(mouseEvent): void

Parameters

mouseEvent: MouseEvent

Returns

void

Defined in

Game.ts:1256


presentScene()

presentScene(scene, transition?): void

Specifies the scene that will be presented upon the next frame draw.

Parameters

scene: string | Scene

the scene, its string name, or UUID

transition?: Transition

Returns

void

Defined in

Game.ts:1033


registerPlugin()

registerPlugin(plugin): Promise<void>

Registers a plugin with the game.

Parameters

plugin: Plugin

Plugin to register

Returns

Promise<void>

Remarks

Upon registration, the plugin's optional asynchronous initialize() method will be called.

Defined in

Game.ts:2645


removeAllFreeEntities()

removeAllFreeEntities(): void

Returns

void

Deprecated

Use removeAllFreeNodes() instead

Defined in

Game.ts:937


removeAllFreeNodes()

removeAllFreeNodes(): void

Removes all free nodes from the game.

Returns

void

Defined in

Game.ts:928


removeFreeEntity()

removeFreeEntity(node): void

Parameters

node: string | M2Node

Returns

void

Deprecated

Use removeFreeNode() instead

Defined in

Game.ts:921


removeFreeNode()

removeFreeNode(node): void

Removes a free node from the game.

Parameters

node: string | M2Node

the free node to remove or its name as a string

Returns

void

Remarks

Throws exception if the node to remove is not currently added to the game as a free node

Defined in

Game.ts:902


removeScene()

removeScene(scene): void

Removes a scene from the game.

Parameters

scene: string | Scene

the scene to remove or its name as a string

Returns

void

Defined in

Game.ts:1007


resolveGameBaseUrls()

resolveGameBaseUrls(game): Promise<GameBaseUrls>

Internal

Resolves base URL locations for game assets and CanvasKit wasm binary.

For m2c2kit library use only

Parameters

game: Game

game to resolve base URLs for

Returns

Promise<GameBaseUrls>

base URLs for game assets and CanvasKit wasm binary

Defined in

Game.ts:260


setParameters()

setParameters(additionalParameters): void

Sets additional activity parameters if defaults are not sufficient.

Parameters

additionalParameters: unknown

Returns

void

Implementation of

Activity.setParameters

Defined in

Game.ts:743


start()

start(entryScene?): Promise<void>

Starts the game loop.

Parameters

entryScene?: string | Scene

The scene (Scene object or its string name) to display when the game starts

Returns

Promise<void>

Remarks

If entryScene is undefined, the game will start with scene defined in the game object's entryScene property. If that is undefined, the game will start with the first scene in the game object's scenes. If there are no scenes in the game object's scenes, it will throw an error. Although the method has no awaitable calls, we will likely do so in the future. Thus this method is async.

Implementation of

Activity.start

Defined in

Game.ts:1162


stop()

stop(): void

Stops the activity

Returns

void

Implementation of

Activity.stop

Defined in

Game.ts:1627


storeClearItems()

storeClearItems(): Promise<void>

Deletes all items from the activity's key-value store.

Returns

Promise<void>

Remarks

The underlying persistence provider of the key-value store must have been previously provided in SessionOptions.

Example

import { LocalDatabase } from "@m2c2kit/db";
const session = new Session({
dataStores: [new LocalDatabase()]
...
});

Defined in

Game.ts:627


storeDeleteItem()

storeDeleteItem(key, globalStore): Promise<void>

Deletes an item value from the activity's key-value store.

Parameters

key: string

item key

globalStore: boolean = false

if true, treat the item as "global" and not associated with a specific activity; global items can be accessed by any activity. Default is false.

Returns

Promise<void>

Remarks

The underlying persistence provider of the key-value store must have been previously provided in SessionOptions.

Example

import { LocalDatabase } from "@m2c2kit/db";
const session = new Session({
dataStores: [new LocalDatabase()]
...
});

Defined in

Game.ts:610


storeGetItem()

storeGetItem<T>(key, globalStore): Promise<T>

Gets an item value from the activity's key-value store.

Type Parameters

T extends undefined | null | string | number | boolean | object

Parameters

key: string

item key

globalStore: boolean = false

if true, treat the item as "global" and not associated with a specific activity; global items can be accessed by any activity. Default is false.

Returns

Promise<T>

value of the item

Remarks

The underlying persistence provider of the key-value store must have been previously provided in SessionOptions.

Example

import { LocalDatabase } from "@m2c2kit/db";
const session = new Session({
dataStores: [new LocalDatabase()]
...
});

Defined in

Game.ts:586


storeItemExists()

storeItemExists(key, globalStore): Promise<boolean>

Determines if a key exists in the activity's key-value store.

Parameters

key: string

item key

globalStore: boolean = false

if true, treat the item as "global" and not associated with a specific activity; global items can be accessed by any activity. Default is false.

Returns

Promise<boolean>

true if the key exists, false otherwise

Remarks

The underlying persistence provider of the key-value store must have been previously provided in SessionOptions.

Example

import { LocalDatabase } from "@m2c2kit/db";
const session = new Session({
dataStores: [new LocalDatabase()]
...
});

Defined in

Game.ts:669


storeItemsKeys()

storeItemsKeys(globalStore): Promise<string[]>

Returns keys of all items in the activity's key-value store.

Parameters

globalStore: boolean = false

if true, treat the item as "global" and not associated with a specific activity; global items can be accessed by any activity. Default is false.

Returns

Promise<string[]>

Remarks

The underlying persistence provider of the key-value store must have been previously provided in SessionOptions.

Example

import { LocalDatabase } from "@m2c2kit/db";
const session = new Session({
dataStores: [new LocalDatabase()]
...
});

Defined in

Game.ts:646


storeSetItem()

storeSetItem(key, value, globalStore): Promise<string>

Saves an item to the activity's key-value store.

Parameters

key: string

item key

value: undefined | null | string | number | boolean | object

item value

globalStore: boolean = false

if true, treat the item as "global" and not associated with a specific activity; global items can be accessed by any activity. Default is false.

Returns

Promise<string>

key

Remarks

The underlying persistence provider of the key-value store must have been previously provided in SessionOptions.

Example

import { LocalDatabase } from "@m2c2kit/db";
const session = new Session({
dataStores: [new LocalDatabase()]
...
});

Defined in

Game.ts:556


takeScreenshot()

takeScreenshot(sx?, sy?, sw?, sh?): Promise<null | Uint8Array>

Takes screenshot of canvas

Parameters

sx?: number

Upper left coordinate of screenshot

sy?: number

Upper right coordinate of screenshot

sw?: number

width of area to screenshot

sh?: number

height of area to screenshot

Returns

Promise<null | Uint8Array>

Promise of Uint8Array of image data

Remarks

Coordinates should be provided unscaled; that is, the method will handle any scaling that happened due to device pixel ratios not equal to 1. This returns a promise because the screenshot request must be queued and completed once a draw cycle has completed. See the loop() method.

Defined in

Game.ts:2797


trialComplete()

trialComplete(): void

Should be called when the current trial has completed. It will also increment the trial index.

Returns

void

Remarks

Calling will trigger the onActivityResults callback function, if one was provided in SessionOptions. This is how the game communicates trial data to the parent session, which can then save or process the data. It is the responsibility of the the game programmer to call this at the appropriate time. It is not triggered automatically.

Defined in

Game.ts:1890