PublicApi.createGame(opts)

| Chrono Divide | 3 Reads

以下程式片段引自 @chronodivide/game-api 的型別宣告檔 index.d.tscreateGamePublicApi 類別的方法,其完整註解如下:

1054  export declare class PublicApi {
1055      #private;
1056      init(mixDir: string): Promise<void>;
1057      getAvailableMaps(): string[];
1058      getAvailableGameModes(mapName: string): number[];
1059      /**
1060       * Creates a new game
1061       *
1062       * If {@link CreateOfflineOpts.online} is false, an offline game is created, in which multiple AI agents can battle
1063       * each other in a sandboxed environment. The game simulation runs programatically at the fastest possible speed.
1064       *
1065       * If {@link CreateOnlineOpts.online} is true, an online game is created, in which human players can fight
1066       * in real time against the AI.
1067       *
1068       * In online mode, the {@link CreateOnlineOpts.agents} array specifies both human and AI agents. In this case,
1069       * there can be only one AI agent (the game host) and it must be the first item in the array.
1070       */
1071      createGame(opts: CreateOpts): Promise<GameInstanceApi>;

CreateOpts 可為線下或線上模式的設定物件,其結構定義如下:

226  export declare interface CreateBaseOpts {
227      mapName: string;
228      gameMode: number;
229      shortGame: boolean;
230      mcvRepacks: boolean;
231      cratesAppear: boolean;
232      superWeapons: boolean;
233      gameSpeed: number;
234      credits: number;
235      unitCount: number;
236      buildOffAlly: boolean;
237      destroyableBridges?: boolean;
238      multiEngineer?: boolean;
239      noDogEngiKills?: boolean;
240  }

242  export declare interface CreateOfflineOpts extends CreateBaseOpts {
243      online?: false;
244      agents: Bot[];
245  }

247  export declare interface CreateOnlineOpts extends CreateBaseOpts {
248      online: true;
249      serverUrl: string;
250      clientUrl: string;
251      botPassword: string;
252      agents: [Bot, ...Agent[]];
253      /** If specified, process will not wait for player input before creating the game. */
254      nonInteractive?: boolean;
255      /**
256       * Called when the game is created.
257       *
258       * @param joinUrls - The URLs that each player agent can use to join the game.
259       */
260      onGameCreate?(joinUrls: Map<Agent, string>): unknown;
261  }

263  export declare type CreateOpts = CreateOfflineOpts | CreateOnlineOpts;

createGame 執行後,會回傳 GameInstanceApi 物件,用於後續更新或結束遊戲:

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  }

專案中 src/exampleBot.ts 展示了 createGame 的實際使用方式。以下摘錄部分程式碼:

72      const offlineSettings1v1: CreateOfflineOpts = {
73          ...baseSettings,
74          online: false,
75          agents: [
76              new SupalosaBot(firstBotName, Countries.FRANCE, [], false),
77              new SupalosaBot(secondBotName, Countries.RUSSIA, [], true).setDebugMode(true),
78          ],
79      };

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

104     game.saveReplay();
105     game.dispose();

在上述範例中,程式先透過 cdapi.init() 載入 MIX 資料,接著依線上或線下模式建立 CreateOpts,再呼叫 createGame
取得的 GameInstanceApi 物件可反覆 update() 推進遊戲迴圈,並在結束後儲存回放或釋放資源。


總結來說,createGame(opts) 用來啟動一局新遊戲:

線下模式 (online: false 或未指定)

適合多個 AI 在最快速度下交戰。
遊戲迴圈必須自行呼叫 update() 推進。

線上模式 (online: true)

需提供伺服器與客戶端 URL、機器人密碼等資訊,同時在 agents 陣列中將 AI 放在第一位。
人類玩家可透過 onGameCreate 取得連線 URL 進入對戰。


方法回傳的 GameInstanceApi 提供更新、判斷遊戲結束、儲存回放等功能,是控制比賽流程的核心介面。
透過正確組合 CreateOptsagents,便能靈活地建立線下測試戰局或真正的線上對戰。

 

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

This article was last edited at