PublicApi.getAvailableGameModes(mapName)
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1240
以下程式碼片段節錄自套件 @chronodivide/game-api
的 dist/index.d.ts
,可以看到 getAvailableGameModes
是 PublicApi
類別的一個方法,回傳值為 number[]
:
export declare class PublicApi {
#private;
init(mixDir: string): Promise<void>;
getAvailableMaps(): string[];
getAvailableGameModes(mapName: string): number[];
/**
* Creates a new game
在編譯後的 index.js
中,方法實作如下,可看到其流程:
... API is not initialized. Call init() first.;
let t = Wm(this, Qm, "f").getByName(e);
if (!t) throw new Error(`Map "${e}" is not available`);
return t.gameModes.map(e => e.id)
依此可知,getAvailableGameModes(mapName)
的作用是:
-
確認 API 是否已初始化
若尚未呼叫cdapi.init()
,會拋出API is not initialized. Call init() first.
的錯誤。 -
檢查指定地圖是否存在
透過內部的地圖列表尋找名稱對應的地圖,找不到則丟出Map "<mapName>" is not available
。 -
回傳可用模式 ID 陣列
從地圖資訊裡的gameModes
屬性擷取其id
,形成number[]
傳回。
使用範例
本專案內的 exampleBot.ts
範例亦展示了此方法的典型用法。擷取部分程式如下:
const baseSettings: CreateBaseOpts = {
buildOffAlly: false,
cratesAppear: false,
credits: 10000,
gameMode: cdapi.getAvailableGameModes(mapName)[0],
gameSpeed: 6,
mapName,
mcvRepacks: true,
shortGame: true,
以下為一個更完整的示範,說明如何取得地圖的可用遊戲模式並建立遊戲:
import { cdapi, CreateOfflineOpts } from "@chronodivide/game-api";
async function run() {
// MIX_DIR 指向原始 RA2 安裝資料夾或 MIX 檔所在處
await cdapi.init(process.env.MIX_DIR || "./");
// 假設已知地圖名稱
const mapName = "CA_RealWorld";
// 取得此地圖支援的模式 ID
const gameModes = cdapi.getAvailableGameModes(mapName);
console.log(`${mapName} 可用模式:`, gameModes);
// 以第一個模式建立離線遊戲
const game = await cdapi.createGame({
online: false,
agents: [],
mapName,
gameMode: gameModes[0],
} as CreateOfflineOpts);
while (!game.isFinished()) {
await game.update();
}
game.dispose();
}
run().catch(console.error);
透過 getAvailableGameModes
,可以得知某張地圖支援哪些模式(以數字 ID 表示)。將其中一個模式值傳入 createGame
的 gameMode
欄位即可建立對應的遊戲。若要了解各 ID 所對應的實際模式名稱,可查閱遊戲文件或 ra2.mix
內的設定。此方法在載入地圖資訊後即可隨時呼叫,對建立離線或線上對戰都十分實用。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at