ActionsApi.sellBuilding(buildingId)方法說明與使用範例
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/1186
以下內容節錄自 @chronodivide/game-api
的型別定義檔,可看到 ActionsApi
的方法列表,其中 sellBuilding
已標註為過時,建議改用 sellObject
:
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;
...
}
在對應的 JavaScript 檔可以看到 sellBuilding
的實作只是呼叫 sellObject
,因此兩者效果完全相同:
sellBuilding(e){this.sellObject(e)}
方法說明
ActionsApi.sellBuilding(buildingId)
用來「出售」擁有指定 ID 的建築。這個 ID 需先透過 GameApi
相關查詢取得,例如:
-
game.getVisibleUnits(playerName, "self", filter)
-
game.getGameObjectData(id)
呼叫後,該建築會立即被賣掉,與遊戲中手動點擊「賣出」的效果一致:建築消失並返還一定金額。
由於 sellBuilding
只是 sellObject
的舊名稱,建議直接使用 sellObject
,但 sellBuilding
仍然可正常運作。
簡易示例
以下程式片段展示如何在遊戲開始後賣掉第一座己方電廠。示例以 TypeScript 撰寫並附上繁體中文註解:
import { Bot, GameApi } from "@chronodivide/game-api";
class SellPowerPlantBot extends Bot {
// 遊戲開始後自動尋找並賣掉電廠
override onGameStart(game: GameApi) {
// 取得所有己方電廠的 ID(以盟軍電廠 GAPOWR 為例)
const powerPlants = game.getVisibleUnits(
this.name, // 玩家名稱
"self", // 只搜尋己方單位
r => r.name === "GAPOWR" // 過濾條件:物件名稱
);
// 若找到至少一座電廠,將其賣掉
if (powerPlants.length > 0) {
const plantId = powerPlants[0];
// 雖然 sellBuilding 已過時,但仍可使用
this.actionsApi.sellBuilding(plantId);
// 建議做法:this.actionsApi.sellObject(plantId);
}
}
}
程式說明
-
getVisibleUnits
用來列出所有可見且名稱為GAPOWR
的建築,回傳值是一個物件 ID 陣列。 -
取得 ID 後,呼叫
actionsApi.sellBuilding(plantId)
立即將該建築出售,返還資金。 -
由於
sellBuilding
內部其實是呼叫sellObject
,因此兩個方法行為等同,但官方建議改用sellObject
。 -
透過上述方式即可在 AI 內部控制何時賣掉不再需要的建築,例如戰術轉換或避免遭敵方佔領。
-
由於
sellBuilding
已標示為過時,若在新程式中使用,可直接替換成sellObject
以保持相容性。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at