GameInstanceApi.getPlayerStats()

| Chrono Divide | 3 Reads

GameInstanceApi.getPlayerStats() 是在遊戲進行中讀取所有非中立玩家的統計資料。型別宣告位於 @chronodivide/game-apiindex.d.ts

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;
393      dispose(): void;
394  }

PlayerStats 結構如下,表示每位玩家的資料:

export declare interface PlayerStats {
    name: string;
    country: Country;
    ai: boolean;
    defeated: boolean;
    credits: number;
    startLocation: number;
}

在打包後的程式碼中,getPlayerStats() 會遍歷所有非中立玩家(排除觀戰者),並組成上述資料:

...getCurrentTick(){return Rm(this,Bm,"f").getCurrentTick()}
getTickRate(){return Rm(this,Bm,"f").getTickRate()}
getPlayerStats(){return Rm(this,Am,"f").getNonNeutralPlayers()
    .filter(e=>!e.isObserver)
    .map(t=>({
        name:t.name,
        country:t.country,
        ai:t.isAi||Rm(this,Cm,"f").some(e=>e.name===t.name),
        defeated:t.defeated,
        credits:t.credits,
        startLocation:t.startLocation
    }))}...

如何使用

getPlayerStats() 常在遊戲進行中或結束後呼叫,以取得各玩家目前的狀態,例如剩餘金錢或是否已戰敗。以下是簡化的範例:

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

class StatsReporter extends Bot {
    onGameTick(game: GameApi) {
        const stats = game.getPlayerStats();
        stats.forEach((p) => {
            console.log(
                `${p.name} (${p.country.name}) – Credits: ${p.credits}, ` +
                `Defeated: ${p.defeated}, AI: ${p.ai}`
            );
        });
    }
}

async function main() {
    await cdapi.init(process.env.MIX_DIR!);
    const game = await cdapi.createGame({
        online: false,
        agents: [new StatsReporter("BotA", "Americans"),
                 new StatsReporter("BotB", "Russians")],
        mapName: "mp03t4.map",
        shortGame: true,
    });

    while (!game.isFinished()) {
        await game.update();     // 每次 update 後 onGameTick 會被呼叫
    }
    game.saveReplay();
    game.dispose();
}
main().catch(console.error);

此程式在每個 update() 後列出所有玩家的名稱、國家、剩餘資金以及是否被擊敗等資訊。透過 getPlayerStats()Bot 能即時取得整局遊戲的玩家狀態,對後續決策或紀錄戰局結果都相當有幫助。

 

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

This article was last edited at