GameApi.areAlliedPlayers(p1, p2)
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/1202
以下是 @chronodivide/game-api 中 GameApi
類別部分宣告,可以看到 areAlliedPlayers
的對外介面:
export declare class GameApi {
#private;
mapApi: MapApi;
rulesApi: RulesApi;
isPlayerDefeated(playerName: string): boolean;
areAlliedPlayers(p1Name: string, p2Name: string): boolean;
canPlaceBuilding(playerName: string, buildingName: string, tile: Tile): boolean;
getBuildingPlacementData(objName: string): BuildingPlacementData;
}
在打包後的 index.js
中可以看到 areAlliedPlayers
的實作核心:
areAlliedPlayers(e, t) {
var i = Mp(this, Lp, "f").getPlayerByName(e);
if (!i) throw new Error(`Player "${e}" doesn't exist`);
e = Mp(this, Lp, "f").getPlayerByName(t);
if (!e) throw new Error(`Player "${t}" doesn't exist`);
return Mp(this, Lp, "f").alliances.areAllied(i, e);
}
簡單來說,方法會:
-
依名稱取得兩位玩家的 Player 物件;若找不到則丟出錯誤。
-
透過內部的
alliances
結構判斷兩位玩家是否互為盟友。 -
回傳布林值表示結果。
原始碼中使用範例
在建造防禦建築時,程式會篩掉同盟玩家,只考慮敵方起始位置,以便決定建築朝向:
const candidates = allNames
.filter((otherName) => otherName !== currentName && !game.areAlliedPlayers(otherName, currentName))
.map((otherName) => {
const enemyPlayer = game.getPlayerData(otherName);
return getPointTowardsOtherPoint(game, startLocation, enemyPlayer.startLocation, 4, 16, 1.5);
});
簡易示例
以下 TypeScript 範例展示如何在自訂 bot 中使用 areAlliedPlayers
判斷各玩家的同盟狀態:
import { cdapi, Bot, GameApi } from "@chronodivide/game-api";
class DiplomacyBot extends Bot {
onGameStart(game: GameApi) {
const players = game.getPlayers();
for (let i = 0; i < players.length; i++) {
for (let j = i + 1; j < players.length; j++) {
const p1 = players[i];
const p2 = players[j];
const allied = game.areAlliedPlayers(p1, p2);
console.log(`${p1} 與 ${p2} 是否同盟:${allied}`);
}
}
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
await cdapi.createGame({
agents: [new DiplomacyBot("Bot1", "Americans"), new DiplomacyBot("Bot2", "French")],
mapName: "mp03t4.map",
shortGame: true,
online: false,
});
}
main().catch(console.error);
此範例在 onGameStart
中列出所有玩家彼此間是否為盟友;若要在遊戲中調整盟友關係,可以搭配 ActionsApi.toggleAlliance(toPlayer, enabled)
方法。
透過 areAlliedPlayers
,Bot 能夠隨時掌握玩家間的同盟狀態,進而影響偵查、進攻或支援的決策。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at