ActionsApi.placeBuilding(buildingName, rx, ry) 方法說明與使用範例
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/1184
以下程式碼片段來自 node_modules/@chronodivide/game-api/dist/index.d.ts
,可看到 ActionsApi
的方法定義,其中 placeBuilding
負責在指定座標放置建築:
export declare class ActionsApi {
#private;
placeBuilding(buildingName: string, rx: number, ry: number): void;
sellObject(objectId: number): void;
/** @deprecated use {@link ActionsApi.sellObject} instead */
sellBuilding(buildingId: number): void;
...
}
在專案中,放置建築的實際範例如下(位於 queueController.ts
)。當建築生產完成並找到合適位置後,便呼叫 actionsApi.placeBuilding
:
let location: { rx: number; ry: number } | undefined =
this.getBestLocationForStructure(game, playerData, objectReady);
if (location !== undefined) {
logger(
`Completed: ${queueTypeToName(queueType)}: ${objectReady.name}, placing at ${location.rx},${location.ry}`,
);
actionsApi.placeBuilding(objectReady.name, location.rx, location.ry);
} else {
logger(`Completed: ${queueTypeToName(queueType)}: ${objectReady.name} but nowhere to place it`);
}
getBestLocationForStructure
會根據建築類型呼叫對應的尋點邏輯,通常最終會使用 getDefaultPlacementLocation
。該函式會搜尋靠近理想起始點的格子,確認 game.canPlaceBuilding
為真後才回傳座標:
const tiles = getAdjacencyTiles(game, playerData, technoRules, onWater, minSpace);
const tileDistances = getTileDistances(idealPoint, tiles);
for (let tileDistance of tileDistances) {
if (tileDistance.tile && game.canPlaceBuilding(playerData.name, technoRules.name, tileDistance.tile)) {
return tileDistance.tile;
}
}
return undefined;
placeBuilding 方法解析
參數
-
buildingName:建築在
rules.ini
中的名稱,例如"GAPOWR"
代表盟軍電廠。 -
rx, ry:地圖格子的 X、Y 座標。這裡使用的是建築左上角(normalized)的格子,不是中心點。
使用時機
-
必須先把建築加入生產佇列 (
queueForProduction
) 並等待建造完成。 -
建造完成 (
QueueStatus.Ready
) 後,先透過game.canPlaceBuilding
或getDefaultPlacementLocation
等函式找到可放置的格子。 -
取得位置後立即呼叫
actionsApi.placeBuilding(buildingName, rx, ry)
,遊戲便會在該格子放置建築。
注意事項
-
如果傳入無法放置的位置,或建築物尚未建造完成,動作會失敗。
-
版本變更後座標必須是「建築左上角」的格子,因此尋找位置時要特別注意。
簡易示例
下面是一個簡化示例,展示在建造完成時呼叫 placeBuilding
:
// 假設 queue 已經建造完成一座電廠 (GAPOWR)
const rules = BUILDING_NAME_TO_RULES.get("GAPOWR")!;
const location = getDefaultPlacementLocation(game, playerData, playerData.startLocation, rules);
if (location) {
actionsApi.placeBuilding("GAPOWR", location.rx, location.ry);
}
此範例利用 getDefaultPlacementLocation
自動尋找靠近起始位置的可建造格,並在找到後呼叫 placeBuilding
放下建築。
透過上述流程即可控制建築的自動放置;若要指定固定座標,只需直接提供 rx
、ry
兩個值即可。這是整個 bot 建造邏輯中最常用的指令之一。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at