GameInstanceApi.getCurrentTick()、getTickRate()

| Chrono Divide | 3 Reads

GameInstanceApi 定義

GameInstanceApi 位於套件 @chronodivide/game-api,其型別宣告顯示了 getCurrentTick()getTickRate() 等方法:

export declare class GameInstanceApi {
    #private;
    isFinished(): boolean;
    /** Advances the game turn in offline mode or waits for the next turn in online mode */
    update(): Promise<void>;
    getCurrentTick(): number;
    getTickRate(): number;
    getPlayerStats(): PlayerStats[];
    ...
}

在壓縮後的實作中,兩個方法僅將呼叫轉交給內部的遊戲物件:

getCurrentTick(){return Rm(this,Bm,"f").getCurrentTick()}
getTickRate(){return Rm(this,Bm,"f").getTickRate()}

其中 Rm(this,Bm,"f") 指向實際的 GameApi 實例,因此 GameInstanceApi 只是把目前的遊戲 tick 值與 tick 速率直接回傳。


使用方式

專案範例程式 exampleBot.ts 中,遊戲主迴圈會透過 getCurrentTick() 檢查是否超時:

const game = await cdapi.createGame(process.env.ONLINE_MATCH ? onlineSettings : offlineSettings1v1);
while (!game.isFinished()) {
    if (!!MAX_GAME_LENGTH_SECONDS && game.getCurrentTick() / 15 > MAX_GAME_LENGTH_SECONDS) {
        console.log(`Game forced to end due to timeout`);
        break;
    }
    await game.update();
}

而在 SupalosaBotonGameStart 中,getTickRate() 取得當前遊戲速度,以計算機器人行動頻率:

override onGameStart(game: GameApi) {
    const gameRate = game.getTickRate();
    const botApm = 300;
    const botRate = botApm / 60;
    this.tickRatio = Math.ceil(gameRate / botRate);
}

簡易示例

以下示例示範如何於離線模式下印出當前 tick 與 tick 速率:

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

class TickPrinter extends Bot {
    onGameTick(game: GameApi) {
        console.log(`Tick: ${game.getCurrentTick()}  (rate: ${game.getTickRate()} ticks/sec)`);
    }
}

async function main() {
    await cdapi.init(process.env.MIX_DIR!);
    const opts: CreateOfflineOpts = { online: false, agents: [new TickPrinter("Demo", "Americans")], mapName: "mp03t4.map", shortGame: true };
    const game = await cdapi.createGame(opts);
    while (!game.isFinished()) {
        await game.update();       // 每次 update 後 onGameTick 會被呼叫
    }
    game.saveReplay();
    game.dispose();
}
main().catch(console.error);

這段程式碼在每個遊戲更新後輸出目前的 tick 數與速度,可作為基礎的時序控管示例。透過 getCurrentTick()getTickRate(),AI 能夠精確掌握遊戲進度並根據實際速度調整行為。

 

→返回《@chronodivide/game-api 使用教學與完整 API 對照表》

This article was last edited at