@chronodivide/game-api
TypeScript icon, indicating that this package has built-in type declarations

0.51.3 • Public • Published

Chrono Divide Game API

This is a TypeScript/JavaScript API and development sandbox for the Chrono Divide game engine. It can be used to develop and test AI bots by running the game headless, in an isolated command-line environment. The API can create offline games between computer-controlled agents, or even online games, played in real-time versus human opponents.

Prerequisites

  • NodeJS 14+
  • TypeScript 4.3.5+ (optional)
  • MIX files from an original RA2 installation

Installation

npm install @chronodivide/game-api

Basic Usage

The following code example creates an offline game, between two AI agents, runs the simulation until the game ends, then saves the game replay and exits.

The bot implementation is not provided.

import { cdapi, OrderType, ApiEventType, Bot, GameApi, ApiEvent } from "@chronodivide/game-api";

class ExampleBot extends Bot {}

async function main() {
    const mapName = "mp03t4.map";

    // Replace MIX_DIR with your original RA2 installation folder
    await cdapi.init(process.env.MIX_DIR || "./");

    const game = await cdapi.createGame({
        agents: [
            new ExampleBot("AgentRed", "Americans"),
            new ExampleBot("AgentBlue", "French")
        ],
        buildOffAlly: false,
        cratesAppear: false,
        credits: 10000,
        gameMode: cdapi.getAvailableGameModes(mapName)[0],
        gameSpeed: 5,
        mapName,
        mcvRepacks: true,
        shortGame: true,
        superWeapons: false,
        unitCount: 10
    });

    while (!game.isFinished()) {
        await game.update();
    }

    game.saveReplay();
    game.dispose();
}

main().catch(e => {
    console.error(e);
    process.exit(1);
});

Online Games

Online games between an AI and a human opponent are also possible, but require a Chrono Divide server URL to connect to and a bot account. Online games can be created with minimal changes to the createGame function from the previous example:

const game = await cdapi.createGame({
    online: true,
    serverUrl: process.env.SERVER_URL!,
    clientUrl: process.env.CLIENT_URL!,
    botPassword: process.env.BOT_PASSWORD!,
    agents: [
        new ExampleBot(`BotNickname`, "Americans"),
        { name: `PlayerNickname`, country: "French" }
    ],

    buildOffAlly: false,
    cratesAppear: false,
    credits: 10000,
    gameMode: cdapi.getAvailableGameModes(mapName)[0],
    gameSpeed: 5,
    mapName,
    mcvRepacks: true,
    shortGame: true,
    superWeapons: false,
    unitCount: 10
});

API Reference

Please refer to the TypeScript definitions.

Debugging

Application logging

Debug logging can be enabled by setting the DEBUG_LOGGING environment variable when running in the sandbox, or the r.debug_logging console variable in the game client. To enable, set this variable to a string containing a comma-delimited list of loggers.

For example, to print player actions as they are processed, you can set DEBUG_LOGGING=action.

Bot logger

The Bot class exposes its own logger, which allows more granular control and filtering, especially when there are multiple bots printing messages at the same time. Logged messages are also prefixed with the bot name and in-game timestamp.

By default, the logger prints only warnings and errors. Debug mode (see below) enables all log levels.

Debug mode

Bot debug mode is a flag set on the Bot class, which toggles certain debug features on or off, like logging or setting debug labels. Debug mode is generally controlled automatically by the game client, but it can also be enabled from the sandbox, by calling botInstance.setDebugMode(true).

IMPORTANT: setDebugMode() should never be called from within the bot implementation class itself.

Debug mode can be enabled within the game client by setting the value of the r.debug_bot console variable to the player index (0-based) of the bot that is being debugged.

E.g.: r.debug_bot=1 will debug the bot in player slot index 1 (the second slot) and r.debug_bot=0 will disable debugging.

Unit debug labels and global debug text

The game client offers the following features which can aid debugging bot code:

  • Displaying a multiline debug string attached to a unit or building. To use this feature, the bot implementation should call actionsApi.setUnitDebugText. Once set, this text is persistent, until overwritten by a new value.
  • Displaying a sticky always-on-top multiline text, at a fixed position on the screen, below the chat area. To use this, call actionsApi.setGlobalDebugText. This text is also persistent and offers no scrolling functionality. The value is simply overwritten. Use this feature to display relevant debug stats on the screen. Logging should be done using the bot logger instead.

In both cases, debug text will be printed in the game client only if the console variable r.debug_text=1 is set.

IMPORTANT: Both actionsApi.setUnitDebugText and actionsApi.setGlobalDebugText will generate a player action as workaround for not being able to directly remote control a game client. This is a consequence of the bot code running in its own sandbox and not being directly connected to a game client. As a result, this can generate considerable network noise, as well as increased replay file size. For this reason, both functions only work when bot debug mode is enabled and require an account with bot privileges in online mode.

Notes on deterministic code

The game loop must be guaranteed to give the exact same game simulation provided that the player inputs/commands and initial state are identical. This means that code must be deterministic, or, given the same input, it will always produce the same output. Otherwise, multiplayer games will often result in fatal desyncs, because each client will have its own slightly different version of reality. Singleplayer games will not crash, but loading replay files or save games will be unreliable for the same reason.

Even though a bot running in the sandbox doesn't necessarily need to be deterministic when fighting a real player over the network, it does however need to be once integrated in the game loop. Below is a non-exhaustive table of unsafe JavaScript built-in functions, and their safe version offered through the game API.

JavaScript built-in Game API equivalent Notes
Math.random gameApi.generateRandom and gameApi.generateRandomInt Uses a PRNG
Math.pow, ** operator GameMath.pow Only works with integer exponents; precision of 6 decimals
Math.sqrt GameMath.sqrt
Math.sin GameMath.sin Uses a LUT; resolution of ~0.006rad
Math.cos GameMath.cos Uses a LUT; resolution of ~0.006rad
Math.asin GameMath.asin Uses reverse LUT lookup
Math.acos GameMath.acos Uses reverse LUT lookup
Math.atan2 GameMath.atan2 Precision of 3 decimals
Math.acosh Unsupported
Math.asinh Unsupported
Math.atan Unsupported
Math.atanh Unsupported
Math.cbrt Unsupported
Math.cosh Unsupported
Math.exp Unsupported
Math.expm1 Unsupported
Math.hypot Unsupported
Math.log Unsupported
Math.log10 Unsupported
Math.log1p Unsupported
Math.log2 Unsupported
Math.sinh Unsupported
Math.tan Unsupported
Math.tanh Unsupported

Safe version of THREE.js geometry/math classes are also provided:

THREE.js class Game API equivalent
THREE.Vector2 Vector2
THREE.Vector3 Vector3
THREE.Box2 Box2
THREE.Euler Euler
THREE.Quaternion Quaternion
THREE.Matrix4 Matrix4

Readme

Keywords

none

Package Sidebar

Install

npm i @chronodivide/game-api

Weekly Downloads

1

Version

0.51.3

License

UNLICENSED

Unpacked Size

1.01 MB

Total Files

6

Last publish

Collaborators

  • usestrict