GameInstanceApi.isFinished()

| Chrono Divide | 4 Reads

GameInstanceApi.isFinished() 用於判斷目前的遊戲是否已經結束。
在 type 定義檔可看到 GameInstanceApi 的介面,其中 isFinished 為一個回傳布林值的方法:

380  export declare class GameInstanceApi {
381      #private;
382      isFinished(): boolean;
383      /** Advances the game turn in offline mode or waits for the next turn in online mode */
384      update(): Promise<void>;
385      getCurrentTick(): number;
386      getTickRate(): number;
387      getPlayerStats(): PlayerStats[];
388      /**
389       * @param targetDir - Where to save the replay file.
390       * @returns - The path where the replay file was saved to.
391       */
392      saveReplay(targetDir?: string): string;

在壓縮後的實作中,isFinished 會檢查內部狀態是否等於 Ended,或是遊戲迴圈(turn manager)是否進入錯誤狀態:

...})}isFinished(){return Rm(this,Am,"f").status===nc.Ended||Rm(this,Pm,"f").getErrorState()}...

其中 nc 為一列舉型別,包含 NotStartedStartedEnded 三種值:

...(r=nc=nc||{})[r.NotStarted=0]="NotStarted",r[r.Started=1]="Started",r[r.Ended=2]="Ended";

使用方式

官方 README 範例展示了最基本的流程:建立遊戲後,不斷呼叫 update(),直到 isFinished() 為 true 才結束迴圈並儲存重播檔案。

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

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

專案中的 exampleBot.ts 亦採用相同邏輯,並在迴圈中額外判斷是否超時:

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

說明

isFinished() 會在遊戲正常結束(所有玩家獲勝/失敗)或偵測到錯誤狀態時回傳 true。

若回傳 false,則需呼叫 update() 前進一個遊戲迴圈或等待下一回合(線上模式)。

常見用法是在主迴圈中持續檢查 isFinished(),直到比賽結束後再儲存重播檔並釋放資源。

透過 isFinished(),Bot 便能掌握整局比賽是否已結束或發生異常,從而決定何時停止更新及進行收尾動作。

This method is essential to drive the simulation loop both for offline AI 對戰與線上模式。

 

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

This article was last edited at