GameInstanceApi.saveReplay()
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/1221
GameInstanceApi.saveReplay()
會把目前遊戲的回放檔寫入磁碟,並回傳檔案路徑。
在套件的型別宣告中可以看到此方法的註解與簽名:
/**
* @param targetDir - Where to save the replay file.
* @returns - The path where the replay file was saved to.
*/
saveReplay(targetDir?: string): string;
打包後的實作會在結束錄製後生成檔名,以地圖名稱加上目前時間戳再附上 .ra2cd
副檔名,最後寫入指定路徑(若未指定則寫到目前工作目錄)並在主控台輸出提示:
...))}saveReplay(e){let t=Rm(this,Em,"f");t.finish(Rm(this,Am,"f").currentTick);
var i=`${Rm(this,Am,"f").gameOpts.mapName}_${Date.now()}${um.extension}`,s=t.serialize(),
i=a.resolve(e??process.cwd(),i);return Im.writeFileSync(i,s,"utf-8"),
process.stdout.write(`Replay saved to "${i}"\n`),i}dispose(){...
專案中最簡單的用法是在遊戲迴圈結束後直接呼叫 saveReplay()
:
while (!game.isFinished()) {
await game.update();
}
game.saveReplay();
game.dispose();
範例:指定儲存目錄
import { cdapi, Bot, GameApi } from "@chronodivide/game-api";
import * as fs from "fs";
class ReplayBot extends Bot {
onGameStart(game: GameApi) {
console.log("Game started!");
}
onGameEnd(game: GameApi) {
// 確保自訂目錄存在
fs.mkdirSync("./replays", { recursive: true });
const path = game.saveReplay("./replays");
console.log("Replay stored at", path);
}
}
async function main() {
await cdapi.init(process.env.MIX_DIR!);
const game = await cdapi.createGame({
agents: [new ReplayBot("Recorder", "Americans")],
mapName: "mp03t4.map",
online: false,
});
while (!game.isFinished()) {
await game.update();
}
game.dispose();
}
main().catch(console.error);
此範例在比賽結束後於 ./replays
目錄中建立回放檔並輸出其路徑。
透過 saveReplay(targetDir?)
,可輕鬆記錄對戰實況,方便後續分析或分享。
→返回《@chronodivide/game-api 使用教學與完整 API 對照表》
This article was last edited at