GameInstanceApi.update()

| Chrono Divide | 3 Reads

GameInstanceApi.update()

GameInstanceApi 定義於套件 @chronodivide/game-api,其介面在型別宣告中如下:

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[];
}

實作中 update 會依照線上或離線模式執行不同邏輯:
若有線上用的 waitForTick 物件,則等待下一個伺服器回合;否則在本地執行一次 game turn。之後會將 onGameTick 通知給每個註冊的 Bot:

...nc.Ended || Rm(this, Pm, "f").getErrorState()}
async update() {
    if (Rm(this, Nm, "f"))
        await Rm(this, Nm, "f").waitForTick();
    else {
        if (!(Rm(this, Pm, "f") instanceof em))
            throw new Error("Missing animation loop or turn manager");
        Rm(this, Pm, "f").doGameTurn()
    }
    Rm(this, Cm, "f").forEach(e => e.onGameTick(Rm(this, Bm, "f")))
}

使用方式
官方範例與本專案的 exampleBot.ts 都以 update() 作為主迴圈核心:

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

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

@chronodivide/game-apiREADME 中也展示相同用法:

unitCount: 10
});

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

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

說明
update()非同步方法,必須 await

若在連線對戰模式,update() 會等待伺服器送來下一個 tick。
在離線模式則自行執行一次 doGameTurn()

完成後會觸發各 Bot 的 onGameTick,使 AI 得以根據最新狀態行動。

通常搭配 isFinished() 判斷遊戲是否結束,形成主迴圈。

透過 GameInstanceApi.update(),Bot 可以在離線或線上環境中持續推進遊戲並獲得即時回饋,是驅動整個 AI 流程的關鍵方法。

 

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

This article was last edited at