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 startupcollection_added- When a new collection is addedcollection_removed- When a collection is removedfunctions_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 gameplugins(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 topicsession- Session management topiclevel- 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 configurationplugins- Plugin configurationslevels- Level definitionssessions- Active sessionslisteners- 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
appin 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:
addTopic(topic, name, route)
Registers a new API topic with the game.
Parameters:
topic(Topic) - Topic instance to registername(string) - Name to identify the topicroute(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://orhttps://) - Returns unchanged - Absolute paths - Returns unchanged
- Relative paths - Joins with
game.filesdirectory
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/functionsdirectory
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 collectiondb_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 operationsgame.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
- As
Returns: Promise<string> - Result message indicating number of sessions canceled
Description:
Cancels sessions matching the query:
- Calls
quit()on each session instance - Cancels all active listeners
- Removes sessions from active session list
- Decrements level instance count
- Moves sessions to archive collection
- 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 ascancelSession)
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 parameterslevel(Object | string) - Level query or namename(string, optional) - Session name (must be unique)arguments(Object, optional) - Initial session arguments/referencescontent(string, optional) - Content type (e.g., language: 'en', 'de')
user(Object) - User informationlogin(string) - Username of creator
Returns: Promise<Session> - The created session instance
Throws:
adaptor.DuplicateError- If session name already existsadaptor.NotFoundError- If level not found
Description:
Creates a new session based on a level:
- Validates level exists
- Creates session database document
- Instantiates Session class
- Sets up session with optional arguments
- Dispatches START state
- Increments level instance count
- 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 byproperty(*) - 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
urlfield
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 byvalue(*) - 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: