0.51.3 • Published 3 months ago

@chronodivide/game-api v0.51.3

Weekly downloads
-
License
UNLICENSED
Repository
-
Last release
3 months ago

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-inGame API equivalentNotes
Math.randomgameApi.generateRandom and gameApi.generateRandomIntUses a PRNG
Math.pow, ** operatorGameMath.powOnly works with integer exponents; precision of 6 decimals
Math.sqrtGameMath.sqrt
Math.sinGameMath.sinUses a LUT; resolution of ~0.006rad
Math.cosGameMath.cosUses a LUT; resolution of ~0.006rad
Math.asinGameMath.asinUses reverse LUT lookup
Math.acosGameMath.acosUses reverse LUT lookup
Math.atan2GameMath.atan2Precision of 3 decimals
Math.acoshUnsupported
Math.asinhUnsupported
Math.atanUnsupported
Math.atanhUnsupported
Math.cbrtUnsupported
Math.coshUnsupported
Math.expUnsupported
Math.expm1Unsupported
Math.hypotUnsupported
Math.logUnsupported
Math.log10Unsupported
Math.log1pUnsupported
Math.log2Unsupported
Math.sinhUnsupported
Math.tanUnsupported
Math.tanhUnsupported

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

THREE.js classGame API equivalent
THREE.Vector2Vector2
THREE.Vector3Vector3
THREE.Box2Box2
THREE.EulerEuler
THREE.QuaternionQuaternion
THREE.Matrix4Matrix4
0.51.3

3 months ago

0.51.2

3 months ago

0.51.1

3 months ago

0.51.0

4 months ago

0.50.1

4 months ago

0.50.0

5 months ago

0.42.0

8 months ago

0.43.0

8 months ago

0.40.0

10 months ago

0.41.0

9 months ago

0.48.0

6 months ago

0.49.0

6 months ago

0.46.0

7 months ago

0.47.0

6 months ago

0.44.0

8 months ago

0.45.0

8 months ago

0.39.0

12 months ago

0.38.0

1 year ago

0.37.0

1 year ago

0.36.0

1 year ago

0.35.1

1 year ago

0.35.0

1 year ago