ActionsApi.sellObject(objectId)方法說明與使用範例
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/1185
在 @chronodivide/game-api 的型別定義檔 (dist/index.d.ts) 中,sellObject 定義於 ActionsApi 類別:
export declare class ActionsApi {
placeBuilding(buildingName: string, rx: number, ry: number): void;
sellObject(objectId: number): void;
/** @deprecated use {@link ActionsApi.sellObject} instead */
sellBuilding(buildingId: number): void;
...
}
在對應的 JavaScript 檔(dist/index.js)中,sellObject 會發送 SellObject 指令給遊戲,將指定 ID 的物件賣掉:
sellObject(id) {
sendCommand(GameCommand.SellObject, payload => {
payload.objectId = id;
});
}
sellBuilding(id) {
this.sellObject(id); // 舊方法僅包裝 sellObject
}
方法用途
sellObject(objectId)
會把具有該 objectId 的建築或單位出售,效果與在遊戲中手動點擊「賣出」相同:
-
物件從地圖上移除。
-
玩家獲得相應的回收資金。
sellBuilding
只是 sellObject
的舊名,現在已標示為過時。
取得 objectId
物件 ID 可以透過 GameApi 的查詢函式取得,例如:
-
game.getVisibleUnits(playerName, "self", filter)
:列出可見的己方單位/建築 ID。 -
game.getGameObjectData(id)
:根據 ID 查詢該物件詳細資料。
使用範例
以下示例在遊戲開始時搜尋第一座己方電廠並將其賣掉。示例以 TypeScript 編寫並加入中文註解:
import { Bot, GameApi } from "@chronodivide/game-api";
class SellExampleBot extends Bot {
// 遊戲開始時觸發
override onGameStart(game: GameApi) {
// 取得己方所有電廠的物件 ID(以 Allied 電廠 GAPOWR 為例)
const powerPlants = game.getVisibleUnits(
this.name, // 玩家名稱
"self", // 只查詢己方
r => r.name === "GAPOWR" // 過濾條件:物件名稱
);
// 若找到電廠,賣掉第一座
if (powerPlants.length > 0) {
const plantId = powerPlants[0];
this.actionsApi.sellObject(plantId);
}
}
}
說明
-
getVisibleUnits
依條件找出所有可見且名稱為 GAPOWR 的建築,回傳的是物件 ID 清單。 -
sellObject(plantId)
立即把該 ID 的建築賣出,並返還一定的資金。 -
如果需要賣掉其他建築或單位,只需修改過濾條件或傳入不同的 ID。
-
透過這個方法,開發者可以在任何時機賣掉不再需要的建築或單位,例如轉型戰術或避免敵方佔領。只要取得正確的 objectId,即可呼叫
actionsApi.sellObject(objectId)
完成動作。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at