GameApi.getCurrentTick()、getCurrentTime()

| Chrono Divide | 5 Reads

以下摘錄自套件 @chronodivide/game-api 的型別宣告,可看到 getCurrentTick()getCurrentTime() 皆為 GameApi 的成員,並附有說明註解:

368  /** Current game speed in ticks per real-time second. IMPORTANT: The game speed can change during a game */
369  getTickRate(): number;
370  /** Game speed in ticks per in-game second (at game speed 4) */
371  getBaseTickRate(): number;
372  getCurrentTick(): number;
373  /**
374   * Current game time in game seconds.
375   * The get the time in real-time seconds, use {@link GameApi.getCurrentTick} / {@link GameApi.getTickRate} instead
376   */
377  getCurrentTime(): number;

壓縮後的實作則直接回傳內部狀態:
getCurrentTick() 讀取 currentTick,而 getCurrentTime() 則將毫秒值除以 1000 轉成秒數。

getCurrentTick() { return Mp(this, Lp, "f").currentTick }
getCurrentTime() { return Mp(this, Lp, "f").currentTime / 1e3 }

在專案中常透過 getCurrentTick() 進行計時,例如計算 60 秒內已更新區塊的比例:

sectorCache.updateSectors(game.getCurrentTick(), SECTORS_TO_UPDATE_PER_CYCLE, game.mapApi, playerData);
let updateRatio = sectorCache?.getSectorUpdateRatio(game.getCurrentTick() - game.getTickRate() * 60);

exampleBot.ts 也以 getCurrentTick() 配合基準常數判斷遊戲是否超時:

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();
}

簡易示例
下列程式展示如何讀取當前 tick 與遊戲時間,並定期輸出。

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

class TickLoggerBot extends Bot {
    onGameTick(game: GameApi) {
        const tick = game.getCurrentTick();
        const gameSeconds = game.getCurrentTime();
        console.log(`Tick ${tick}  (game time: ${gameSeconds.toFixed(2)}s)`);
    }
}

async function main() {
    await cdapi.init(process.env.MIX_DIR!);
    await cdapi.createGame({
        agents: [new TickLoggerBot("Timer", "Americans")],
        mapName: "mp03t4.map",
        shortGame: true,
        online: false,
    });
}
main().catch(console.error);

說明

  • getCurrentTick() 取得自遊戲開始以來的累計 tick 數,可直接用於判斷某事件是否應觸發或比較兩個時間點的間隔。

  • getCurrentTime() 取得的是「遊戲內秒數」,相當於 currentTick / getTickRate(),主要用於轉換成實際秒數或向玩家顯示經過時間。

  • 若需要真實秒,可以改用 getCurrentTick() 搭配 getTickRate()(或直接使用 getCurrentTime() 乘以 4 / getBaseTickRate() 以考慮遊戲速度)。

  • 透過這兩個方法,Bot 能精準地掌握遊戲進行的節奏,並以 tick 為基礎執行各式計時邏輯。

 

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

This article was last edited at