GameApi.getAllTerrainObjects()
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/1207
GameApi
類(屬於 @chronodivide/game-api
套件的一部分)公開了一系列查詢輔助功能。其中之一是 getAllTerrainObjects()
,它提供對所有被歸類為地形的地圖物件的存取。
這個方法的簽名出現在函式庫的型別宣告中如下:
export declare class GameApi {
#private;
mapApi: MapApi;
rulesApi: RulesApi;
isPlayerDefeated(playerName: string): boolean;
areAlliedPlayers(p1Name: string, p2Name: string): boolean;
canPlaceBuilding(playerName: string, buildingName: string, tile: Tile): boolean;
getBuildingPlacementData(objName: string): BuildingPlacementData;
getPlayers(): string[];
getPlayerData(playerName: string): PlayerData;
getAllTerrainObjects(): number[];
/** Queries all units and buildings on the map, regardless of owner */
getAllUnits(filter?: (r: TechnoRules) => boolean): number[];
}
它在已編譯的 JavaScript 中的實作,單純是從所有世界物件中取出,依據地形類型進行篩選,然後回傳它們的 ID:
...getAllTerrainObjects(){return Mp(this,Lp,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}...
getAllTerrainObjects()
方法會回傳什麼?
getAllTerrainObjects()
會回傳一個數值 ID 的陣列。每個 ID 對應到目前地圖上的一個被視為地形的物件(例如岩石、懸崖、樹木等)。這些 ID 可以作為輸入傳入其它 API 呼叫,例如 getGameObjectData(objId)
,以檢查它們的屬性。
使用範例
以下是一個簡化的 bot,展示如何在遊戲開始時列出一些地形特徵:
import { cdapi, Bot, GameApi } from "@chronodivide/game-api";
class TerrainScannerBot extends Bot {
onGameStart(game: GameApi) {
const terrainIds = game.getAllTerrainObjects();
console.log(`地圖上的地形物件數量:${terrainIds.length}`);
// 顯示部分項目
terrainIds.slice(0, 5).forEach((id) => {
const data = game.getGameObjectData(id);
if (data) {
console.log(`ID ${id}:${data.name} 位置在 (${data.tile.rx}, ${data.tile.ry})`);
}
});
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
await cdapi.createGame({
agents: [new TerrainScannerBot("BotA", "Americans")],
mapName: "mp03t4.map",
shortGame: true,
online: false,
});
}
main().catch(console.error);
說明
- 這個 bot 會呼叫
game.getAllTerrainObjects()
來取得所有地形物件的 ID。 - 每個 ID 接著會被傳入
game.getGameObjectData(id)
,以取得詳細資訊,例如其規則、擁有者(如果有的話)以及在地圖上的位置。 - 這些資訊可以被用於路徑搜尋啟發式(pathfinding heuristics)或估算地圖上有多少障礙物。
由於這些 ID 僅指涉地形類型的物件,此清單會排除一般單位、建築物或覆蓋物(overlay)。
這個方法特別適合 AI 想要快速擷取靜態障礙物快照,而不需要掃描整個圖格網(tile grid)時使用。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at