GameInstanceApi.dispose()
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/1222
以下為 GameInstanceApi
介面中對 dispose()
的宣告,可看到此方法沒有傳入參數,僅單純清理資源:
380 export declare class GameInstanceApi {
...
392 saveReplay(targetDir?: string): string;
393 dispose(): void;
394 }
在壓縮後的實作裡,dispose()
主要會釋放內部動畫迴圈與 bot 列表,最後觸發可能註冊的回呼:
dispose(){Rm(this,xm,"f").dispose(),Rm(this,Cm,"f").length=0,Rm(this,Dm,"f")?.call(this)}
官方套件的 README 也示範了標準流程:遊戲結束後先儲存重播,再呼叫 dispose()
釋放資源。
48 unitCount: 10
49 });
50 while (!game.isFinished()) {
51 await game.update();
52 }
53 game.saveReplay();
54 game.dispose();
55 }
本專案 exampleBot.ts
中亦採用相同模式:
96 while (!game.isFinished()) {
...
101 await game.update();
102 }
103
104 game.saveReplay();
105 game.dispose();
106 }
如何使用 dispose()
dispose()
應在遊戲完全結束、且不再需要更新或查詢任何狀態後呼叫,以確保底層的資源(動畫迴圈、Bot 清單等)能正確釋放。通常配合 saveReplay()
一同在主迴圈後執行。
簡易範例
import { cdapi, Bot, GameApi } from "@chronodivide/game-api";
class SimpleBot extends Bot {
onGameStart(game: GameApi) {
console.log("Match started!");
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
const game = await cdapi.createGame({
agents: [new SimpleBot("Demo", "Americans")],
mapName: "mp03t4.map",
online: false,
});
while (!game.isFinished()) {
await game.update();
}
game.saveReplay(); // 儲存重播
game.dispose(); // 釋放所有與這場比賽相關的資源
}
main().catch(console.error);
在這段程式中,game.dispose()
於比賽結束後被呼叫,以停止背景動畫/迴圈並清空內部資料,避免資源佔用或記憶體洩漏。這也是官方文件與範例所推薦的標準做法。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at