MapApi.getTile(rx, ry)
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/1226
MapApi.getTile(rx, ry)
依照傳入的地圖座標尋找對應的 Tile
物件,若座標超出地圖範圍則回傳 undefined
。
在套件的型別宣告中,MapApi
的相關介面如下:
685 /** Tile coordinates for each player starting position */
686 getStartingLocations(): Vector2[];
687 getTheaterType(): TheaterType;
688 getTile(rx: number, ry: number): Tile | undefined;
689 getTilesInRect(rectangle: Rectangle): Tile[];
690 getTilesInRect(baseTile: Tile, size: Size): Tile[];
文件前面也說明若要確認座標是否落在地圖內,應呼叫 getTile
。
壓縮後的實作會先透過 tiles.getByMapCoords(rx, ry)
取得對應格子,再檢查是否在 mapBounds
內,僅在有效範圍內才傳回 Tile
物件:
class _p {
...
getTile(e,t){ t = Op(this,Cp,"f").tiles.getByMapCoords(e,t);
if (t && Op(this,Cp,"f").mapBounds.isWithinBounds(t)) return t
}
getTilesInRect(e,t){ ... }
...
}
專案中的應用
在 scout.ts
中,機器人會遍歷所有可能的敵方出生點,先以 getTile
確認該位置確實存在,再檢查能否看見:
const unseenStartingLocations = gameApi.mapApi
.getStartingLocations()
.filter((startingLocation) => {
if (startingLocation == playerData.startLocation) {
return false;
}
let tile = gameApi.mapApi.getTile(startingLocation.x, startingLocation.y);
return tile ? !gameApi.mapApi.isVisibleTile(tile, playerData.name) : false;
});
在計算某區域的可見度時,也會使用 getTile
逐格取回 Tile
再進行判斷:
for (let xx = startPoint.x; xx < endPoint.x; ++xx) {
for (let yy = startPoint.y; yy < endPoint.y; ++yy) {
let tile = mapApi.getTile(xx, yy);
if (tile) {
++validTiles;
if (mapApi.isVisibleTile(tile, playerData.name)) {
++visibleTiles;
}
}
}
}
在地圖區塊初始化時亦透過 getTile
建立每個 sector
的入口資訊:
for (let yy = 0; yy < this.sectorsY; ++yy) {
const tileX = xx * SECTOR_SIZE;
const tileY = yy * SECTOR_SIZE;
this.sectors[xx][yy] = new Sector(
new Vector2(tileX, tileY),
mapApi.getTile(tileX, tileY),
undefined,
undefined,
);
}
簡易示例
下例示範如何取得 (50,50)
位置的 Tile
並檢查其通行性:
import { cdapi, Bot, GameApi, SpeedType } from "@chronodivide/game-api";
class TileCheckBot extends Bot {
onGameStart(game: GameApi) {
const tile = game.mapApi.getTile(50, 50);
if (!tile) {
console.log("Tile (50,50) 不存在於此地圖");
return;
}
const passable = game.mapApi.isPassableTile(
tile,
SpeedType.Walk,
tile.onBridgeLandType !== undefined,
false
);
console.log(`Tile (50,50) passable: ${passable}`);
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
await cdapi.createGame({
agents: [new TileCheckBot("Inspector", "Americans")],
mapName: "mp03t4.map",
shortGame: true,
online: false,
});
}
main().catch(console.error);
getTile
在此用於確保座標有效並取得 Tile
物件;之後可以進一步查詢地形、判斷是否可通行或檢測可見度。由於它會在超出範圍時回傳 undefined
,因此於搜尋地圖位置或規劃路徑時,可先透過此方法過濾非法座標,避免後續操作失敗。通過搭配其他 MapApi
的函式,如 isVisibleTile
、isPassableTile
等,即能完整掌握地圖格子的狀態與特性。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at