Skip to content

Game Context

This document describes the public Game API available to plugins and functions through the game context object.

The game context is created by the Game.getAPI() method and provides both read-only properties and function references for game-wide operations.

Properties

name

  • Type: string
  • Description: Unique name of the game instance
  • Read-only: Yes
  • Usage: Identifies which game this plugin is running in

event

  • Type: events.EventEmitter
  • Description: Event emitter for game-wide custom events that can be used for inter-session and inter-plugin communication
  • Read-only: Reference is read-only, but you can use .emit() and .on() methods
  • Usage:
  • Emit custom events that other plugins or sessions can listen to
  • Listen to events from other parts of the game

Example:

// Emit a custom event
game.event.emit('player_joined', { playerId: 123 });

// Listen to events
game.event.on('player_joined', (data) => {
  console.log('Player joined:', data.playerId);
});

changes

  • Type: Object
  • Description: Dictionary of database change stream listeners. Each collection's stream listener is stored under its respective name
  • Read-only: Yes
  • Usage: Access to MongoDB change streams (or NeDB adaptor custom events)for real-time database monitoring

status

  • Type: events.EventEmitter
  • Description: Event emitter for game-level status changes and incidents
  • Read-only: Reference is read-only, but you can use .emit() and .on() methods
  • Events emitted:
    • plugins_loaded - When all plugins are loaded after startup
    • collection_added - When a new collection is added
    • collection_removed - When a collection is removed
    • functions_update - When custom functions are reloaded

Example:

game.status.on('collection_added', (data) => {
  console.log('New collection:', data.name);
});

game.status.on('functions_update', (functions) => {
  console.log('Functions reloaded:', Object.keys(functions));
});

data

  • Type: string
  • Description: Absolute path to the game's data directory
  • Read-only: Yes
  • Usage: Base path for accessing game-specific data files and functions

files

  • Type: string
  • Description: Absolute path to the game's assets directory
  • Read-only: Yes
  • Usage: Base path for accessing game media files (images, audio, video, etc.)

url

  • Type: string
  • Description: Base URL for accessing the game's web interface
  • Read-only: Yes

files_url

  • Type: string
  • Description: Base URL for accessing the game's files/media over HTTP
  • Read-only: Yes
  • Usage: Construct URLs for serving media files to clients

setup

  • Type: Object
  • Description: Game setup configuration
  • Properties:
  • collections (Array<string>) - List of collection names added to the game
  • plugins (Array<string>) - List of plugin names added to the game
  • Read-only: Yes

Example:

console.log('Available collections:', game.setup.collections);
console.log('Active plugins:', game.setup.plugins);

topics

  • Type: Object<string, Topic>
  • Description: Dictionary of game topics (API endpoints for different resources)
  • Available topics:
    • plugin - Plugin management topic
    • session - Session management topic
    • level - Level management topic
    • Plus any data or plugin item collection topics
  • Usage: Access topics for interacting with game resources. Adds a layer on top of the database
  • Read-only: Yes
// Query all items in the game
const items_with_rope = await this.game.topics.items.getMany({"inventory":"rope"}, {})

// Add a value to a list in an item of my collection
await this.game.topics.my_collection.editOne("my_document_id","add",{ "inventory": "rope" },{ user: { login: this.name }})

db

  • Type: Database
  • Description: Direct access to the game's database connection
  • Collections available:
    • setup - Game setup configuration
    • plugins - Plugin configurations
    • levels - Level definitions
    • sessions - Active sessions
    • listeners - Active listeners
    • Plus any data or plugin item collection
  • Usage: Perform database operations directly
  • Note: Prefer using topics whenever possible.

Example:

// Find all active sessions
const sessions = await game.db.sessions.find({});

// Query custom collection
const players = await game.db.players.find({ online: true });

app

  • Type: express.Router
  • Description: Express router for adding custom web routes to the game
  • Routes to: /{game}
  • Usage: Add custom HTTP endpoints for your plugin. Prefer using app in config parameter of setup function.

Methods

ready()

Returns the game's ready state.

Parameters: None

Returns: boolean - true if the game has finished loading, false otherwise

Description: Indicates whether the game has completed initialization. The game is ready when all topics have been created, plugins loaded, and sessions restored.

Example:

if (game.ready()) {
  console.log('Game is ready');
}

addTopic(topic, name, route)

Registers a new API topic with the game.

Parameters:

  • topic (Topic) - Topic instance to register
  • name (string) - Name to identify the topic
  • route (string) - API route path for the topic

Returns: void

Description:

Adds a new topic to the game's API. Topics provide RESTful API endpoints and internal CRUD operations for managing specific types of resources. The topic's router is mounted at the specified route, and the topic is stored in game.topics[name].

Use Cases:

  • Creating custom API endpoints for plugin-specific resources
  • Registering new data collection topics
  • Adding specialized management interfaces

Example:

const myTopic = new Topic({
  name: 'custom',
  coll_name: 'custom_data',
  schema: { /* ... */ },
  methods: ['GET', 'POST']
}, game);

game.addTopic(myTopic, 'custom', '/custom');
// Topic now accessible at /api/game/{game}/custom

getFilePath(file)

Resolves a file path relative to the game's files directory.

Parameters:

  • file (string) - File name or relative path

Returns: string - Absolute file path or URL

Description:

Converts a relative file path to an absolute path in the game's files directory. If the input is already an absolute path or URL, it returns it unchanged.

Behavior:

  • Web URLs (http:// or https://) - Returns unchanged
  • Absolute paths - Returns unchanged
  • Relative paths - Joins with game.files directory

Example:

// Relative path
const imagePath = game.getFilePath('images/logo.png');
// Returns: '/path/to/game/files/images/logo.png'

// URL (unchanged)
const url = game.getFilePath('https://example.com/image.png');
// Returns: 'https://example.com/image.png'

// Absolute path (unchanged)
const abs = game.getFilePath('/tmp/file.txt');
// Returns: '/tmp/file.txt'

getFileURL(file)

Generates a publicly accessible URL for a game file.

Parameters:

  • file (string) - File name or relative path (relative to game files directory)

Returns: string - Public URL for the file

Throws: adaptor.InvalidError - If file is an absolute path

Description:

Creates a URL that can be used to access a file over HTTP. The file must be located in the game's files directory. If the input is already a web URL, it returns it unchanged.

Use Cases:

  • Generating URLs for media files to send to clients
  • Creating download links
  • Embedding images/audio/video in web interfaces

Example:

// Generate URL for an image
const imageUrl = game.getFileURL('images/logo.png');
// Returns: 'https://yourdomain.com/game/mygame/files/images/logo.png'

// URL (unchanged)
const url = game.getFileURL('https://example.com/image.png');
// Returns: 'https://example.com/image.png'

// Absolute path throws error
try {
  game.getFileURL('/tmp/file.txt');
} catch (error) {
  // Error: Can not get file URL with absolute path
}

getFunctions()

Retrieves all available functions for the game.

Parameters: None

Returns: Object<string, Function> - Dictionary of function names to function objects

Description: Returns all functions available to the game, including:

  • Built-in adaptor functions
  • Custom functions from the game's data/functions directory

Functions can be used in variable resolution and custom logic within levels.

Example:

const functions = game.getFunctions();
console.log('Available functions:', Object.keys(functions));

// Use a function
if (functions.myCustomFunction) {
  const result = functions.myCustomFunction(arg1, arg2);
}


addDataCollection(name)

Creates a new data collection in the game.

Parameters:

  • name (string) - Name for the new collection

Returns: Promise<Object> - Creation result

  • created_id (string) - Name of the created collection
  • db_collection_created (boolean) - Whether a new database collection was created

Throws:

  • adaptor.ForbiddenError - If name is reserved (e.g., 'plugins', 'sessions', 'levels')
  • adaptor.DuplicateError - If collection already exists

Description:

Creates a new data collection with:

  • Database collection (if it doesn't exist)
  • API topic for CRUD operations
  • Change stream listener
  • Registration in game setup

The collection becomes accessible through:

  • game.db[name] - Database operations
  • game.topics[name] - API topic
  • /api/game/{game}/collection/{name} - REST API

Use Cases:

  • Storing plugin-specific data
  • Creating custom data models
  • Managing game state in structured collections

Example:

async function setup(config, game) {
  // Create a custom collection for player stats
  await game.addDataCollection('player_stats');

  // Now you can use it
  await game.db.player_stats.insert({
    player_id: '123',
    score: 1000,
    level: 5
  })
}

listPluginCollections()

Lists all plugin-specific collections.

Parameters: None

Returns: Array<Object> - Array of plugin collection information

Description:

Returns information about all collections that have been registered as plugin collections (not general data collections).

Example:

const pluginCollections = game.listPluginCollections();
console.log('Plugin collections:', pluginCollections);

cancelSession(query)

Cancels (stops) one or more sessions.

Parameters:

  • query (Object | string) - Query to find sessions
    • As Object: MongoDB-style query (e.g., { name: 'session1' })
    • As string: Session name

Returns: Promise<string> - Result message indicating number of sessions canceled

Description:

Cancels sessions matching the query:

  1. Calls quit() on each session instance
  2. Cancels all active listeners
  3. Removes sessions from active session list
  4. Decrements level instance count
  5. Moves sessions to archive collection
  6. Emits socket notifications

Sessions are gracefully shut down, allowing cleanup operations to complete.

Example:

// Cancel by name
await game.cancelSession('player_session_123');

// Cancel by query
await game.cancelSession({ created_by: 'user123' });

// Cancel all sessions for a level
await game.cancelSession({ level_name: 'tutorial' });

deleteSession(query)

Permanently deletes one or more sessions.

Parameters:

  • query (Object | string) - Query to find sessions (same format as cancelSession)

Returns: Promise<string> - Result message indicating number of sessions deleted

Description:

Permanently deletes sessions:

  • If session is archived: Deletes from archive
  • If session is active: Cancels session then deletes (no archiving)

Warning: This is a destructive operation. Sessions cannot be recovered after deletion.

Example:

// Delete archived sessions
await game.deleteSession('old_session');

// Delete by query
await game.deleteSession({ created_at: { $lt: oldDate } });

createSession(args, user)

Creates and starts a new session instance.

Parameters:

  • args (Object) - Session creation parameters
    • level (Object | string) - Level query or name
    • name (string, optional) - Session name (must be unique)
    • arguments (Object, optional) - Initial session arguments/references
    • content (string, optional) - Content type (e.g., language: 'en', 'de')
  • user (Object) - User information
    • login (string) - Username of creator

Returns: Promise<Session> - The created session instance

Throws:

  • adaptor.DuplicateError - If session name already exists
  • adaptor.NotFoundError - If level not found

Description:

Creates a new session based on a level:

  1. Validates level exists
  2. Creates session database document
  3. Instantiates Session class
  4. Sets up session with optional arguments
  5. Dispatches START state
  6. Increments level instance count
  7. Returns session instance

Use Cases:

  • Starting new game sessions
  • Creating test sessions
  • Spawning sessions programmatically
  • Multiplayer session management

Example:

  const newSession = await game.createSession(
    {
      level: 'tutorial',
      name: `player_${playerId}_tutorial`,
      arguments: {
        player_ref: { 
          collection: 'players', 
          query: { _id: playerId },
          reference: 'Player'
        }
      },
      content: 'en'
    },
    { login: 'my-plugin'}
  )

  console.log('Created session:', newSession._id)

getSession(id)

Retrieves a session instance by ID.

Parameters:

  • id (string | ObjectID) - Session ID to find

Returns: Session | undefined - Session instance if found, undefined otherwise

Description:

Searches the active sessions list for a session with matching _id. This only finds active sessions, not archived ones.

Example:

const session = game.getSession(sessionId)
if (session) {
  console.log('Found session:', session.name)
} else {
  console.log('Session not found')
}

findSession(key, property)

Finds a session by any property.

Parameters:

  • key (string) - Property name to search by
  • property (*) - Value to match

Returns: Session | undefined - First matching session instance, or undefined

Description:

Searches active sessions for the first one where session[key] == property.

Example:

// Find by name
const session = game.findSession('name', 'tutorial_session')

// Find by level
const session = game.findSession('level_name', 'boss_fight')

getWebhookURLs(append_path)

Generates webhook URLs for all configured webhook endpoints.

Parameters:

  • append_path (string) - Path to append to each webhook URL

Returns: Array<Object> - Array of webhook objects with extended URLs

  • Each object contains the original webhook properties plus an extended url field

Description:

Takes the global webhook configurations and generates game-specific URLs by appending the game name and the provided path. Useful for creating webhook endpoints that are specific to this game.

Example:

// Get webhook URLs for player events
const webhooks = game.getWebhookURLs('/player/joined')
// Returns: [
//   { local: 'http://localhost:8081/mygame/player/joined', ... },
//   { remote: 'https://my-adaptor-url.com/mygame/player/joined', ... }
// ]

webhooks.forEach(webhook => {
  console.log('Webhook Local:', webhook.local);
})

findPlugin(key, value)

Finds a plugin by any property.

Parameters:

  • key (string) - Property name to search by
  • value (*) - Value to match

Returns: Plugin | undefined - First matching plugin instance, or undefined

Description:

Searches active plugins for the first one where plugin[key] == value.

Example:

// Find by name
const plugin = game.findPlugin('name', 'data')

// Find by version
const plugin = game.findPlugin('version', '1.2.0')

// Find by custom property
const plugin = game.findPlugin('enabled', true)


getPlugin(name)

Retrieves a plugin instance by name.

Parameters:

  • name (string) - Plugin name

Returns: Plugin | undefined - Plugin instance if found, undefined otherwise

Description:

Gets a plugin by its registered name.

Use Cases:

  • Accessing other plugin functionality
  • Checking if optional plugins are available
  • Coordinating between plugins

Example:

// Check if MQTT plugin is available
const mqttPlugin = game.getPlugin('mqtt');
if (mqttPlugin) {
  // Use MQTT plugin methods
  const files = await mqttPlugin.sendMQTTMessage(data, session);
}