GameApi.getAllUnits(filter?) / getNeutralUnits(filter?)

| Chrono Divide | 5 Reads

GameApi 在型別宣告中提供 getAllUnitsgetNeutralUnits 方法,分別用於查詢地圖上所有單位以及中立方單位。其介面如下:

getPlayerData(playerName: string): PlayerData;
getAllTerrainObjects(): number[];

/** Queries all units and buildings on the map, regardless of owner */
getAllUnits(filter?: (r: TechnoRules) => boolean): number[];

/** Queries neutral units and buildings on the map */
getNeutralUnits(filter?: (r: TechnoRules) => boolean): number[];

/** Queries units in a given area of tiles. Uses a quadtree and is more efficient than scanning tile by tile. */
getUnitsInArea(tileRange: Box2): number[];

壓縮後的實作顯示兩個方法都會遍歷內部儲存的物件,再以可選的篩選函式過濾:

...getAllUnits(t = () => !0) {
    return Mp(this, Lp, "f").getWorld()
        .getAllObjects()
        .filter(e => e.isTechno() && t(e.rules))
        .map(e => e.id)
}

getNeutralUnits(t = () => !0) {
    return Mp(this, Lp, "f").getCivilianPlayer()
        .getOwnedObjects()
        .filter(e => t(e.rules))
        .map(e => e.id)
}

getAllUnits 回傳地圖上所有單位或建築的 ID;getNeutralUnits 則只回傳中立陣營所擁有的單位或建築。兩者皆可接受 (rules: TechnoRules) => boolean 的函式,用以依據單位的規則資料進一步篩選。


使用範例

以下範例在 bot 啟動時列出場上所有單位的名稱與坐標,並額外列出所有中立單位:

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

class UnitScannerBot extends Bot {
    onGameStart(game: GameApi) {
        const allIds = game.getAllUnits();
        console.log(`Total units/buildings: ${allIds.length}`);
        allIds.forEach((id) => {
            const data = game.getGameObjectData(id);
            if (data) {
                console.log(`${data.name} at (${data.tile.rx}, ${data.tile.ry})`);
            }
        });

        const neutralIds = game.getNeutralUnits();
        console.log(`Neutral objects: ${neutralIds.length}`);
    }
}

async function main() {
    await cdapi.init(process.env.MIX_DIR!);
    await cdapi.createGame({
        agents: [new UnitScannerBot("Scanner", "Americans")],
        mapName: "mp03t4.map",
        shortGame: true,
        online: false,
    });
}
main().catch(console.error);

onGameStart 中,getAllUnits() 取得地圖上每個單位(包含敵我與中立),透過 getGameObjectData 可進一步查詢其位置與名稱;getNeutralUnits() 則僅列出中立單位,常用於尋找可佔領的建築或中立目標。这样便能完整掌握目前地圖上所有活動物件的分佈情形。

 

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

This article was last edited at