GameApi.getPlayers()
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/1205
GameApi
的宣告檔 (package/dist/index.d.ts
) 中可以看到 getPlayers
的介面定義,方法僅回傳一個字串陣列:
#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;
getPlayers(): string[];
getPlayerData(playerName: string): PlayerData;
getAllTerrainObjects(): number[];
在壓縮後的實作檔 index.js
中,getPlayers
會取得「非中立」玩家後,回傳它們的名稱:
...foundationCenter}}getPlayers(){return Mp(this,Lp,"f").getNonNeutralPlayers().map(e=>e.name)}getPlayerData(e){let t=Mp(this,Lp,"f").getPlayerByName(e)...
專案內的使用範例
在 src/bot/logic/building/common.ts
裡,AI 透過 game.getPlayers()
取得所有玩家,再排除同盟者來計算防禦建築面向的位置:
const allNames = game.getPlayers();
// Create a list of positions that point roughly towards hostile player start locatoins.
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);
});
同樣地,在 awareness.ts
中也會先取得所有玩家,再依敵我關係篩選敵方名單,用於威脅評估與集結點更新:
const hostilePlayerNames = game
.getPlayers()
.map((name) => game.getPlayerData(name))
.filter(
(other) =>
other.name !== playerData.name &&
other.isCombatant &&
!game.areAlliedPlayers(playerData.name, other.name),
)
.map((other) => other.name);
基本使用示例
下列範例顯示如何在自訂 Bot 中使用 getPlayers()
列出遊戲中所有玩家:
import { cdapi, Bot, GameApi } from "@chronodivide/game-api";
class PlayerListBot extends Bot {
onGameStart(game: GameApi) {
const names = game.getPlayers();
console.log("目前玩家:", names.join(", "));
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
await cdapi.createGame({
agents: [new PlayerListBot("BotA", "Americans"), new PlayerListBot("BotB", "French")],
mapName: "mp03t4.map",
shortGame: true,
online: false,
});
}
main().catch(console.error);
在 onGameStart
時呼叫 getPlayers()
,即可獲得本局所有非中立玩家的名稱,可用來後續判斷敵我關係或進行統計。此方法在許多邏輯中都扮演了取得玩家清單的角色,例如計算防禦位置、更新全局威脅資訊等。通过搭配 areAlliedPlayers
、getPlayerData
等方法,Bot 可以進一步分析敵方陣營並採取相應策略。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at