ActionsApi.toggleAlliance(toPlayer, enabled)方法說明與使用範例
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/1189
下列檔案的型別宣告可看到 ActionsApi.toggleAlliance 的定義:
export declare class ActionsApi {
...
toggleAlliance(toPlayer: string, enabled: boolean): void;
...
}
在實作檔 dist/index.js
中,方法會送出 ToggleAlliance
指令,告知遊戲是否與某玩家結盟:
toggleAlliance(t,i){np(this,pp,"m",mp).call(this,oc.ToggleAlliance,e=>{e.toPlayer=np(this,up,"f").getPlayerByName(t),e.toggle=i})}
專案中的實際用法位於 src/bot/bot.ts
;在遊戲開始時,bot 會自動嘗試與指定玩家結盟:
this.tryAllyWith.forEach((playerName) => this.actionsApi.toggleAlliance(playerName, true));
方法說明
toggleAlliance(toPlayer, enabled)
主要用於與其他玩家建立或解除同盟關係。
參數
-
toPlayer
:要結盟或解除結盟的目標玩家名稱。 -
enabled
:true
代表結盟,false
則代表解除。
行為
呼叫後會向遊戲送出 ToggleAlliance
指令,遊戲端依照布林值決定與指定玩家結盟或取消結盟。
使用範例
以下 TypeScript 程式碼示範如何在遊戲開始後與另一位玩家結盟,並在特定條件下解除:
import { Bot, GameApi } from "@chronodivide/game-api";
class AllianceBot extends Bot {
// 遊戲開始時與指定玩家結盟
override onGameStart(game: GameApi) {
const allyName = "Teammate";
this.actionsApi.toggleAlliance(allyName, true); // 建立同盟
}
// 每回合判斷是否維持同盟
override onGameTick(game: GameApi) {
const allyName = "Teammate";
const allyDefeated = game.isPlayerDefeated(allyName);
// 若盟友已被擊敗,就取消同盟
if (allyDefeated) {
this.actionsApi.toggleAlliance(allyName, false);
}
}
}
程式流程:
-
onGameStart
取得目標玩家名稱並呼叫toggleAlliance(allyName, true)
,與之結盟。 -
每次
onGameTick
檢查盟友是否被擊敗;若是,呼叫toggleAlliance(allyName, false)
解除同盟。
透過此方法,即可在遊戲進行中動態改變外交關係,例如與 AI 結盟或在合作戰略失敗時解除結盟。方法本身相當直接,只需提供對方名稱與布林值即可。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at