ZH

教程 6 — 保存分数与选项

玩家的文件在桌面上存放在游戏的 var/ 文件夹中,在网页上则存放在浏览器的存储(IndexedDB)里:代码完全相同。

// 最高分
$best = $this->engine->storage->readJson('scores.json', ['best' => 0]);
if ($this->score > $best['best']) {
    $this->engine->storage->writeJson('scores.json', ['best' => $this->score]);
}

// 设置(立即保存)
$difficulty = $this->engine->options->get('difficulty', 'normal');
$this->engine->options->set('difficulty', 'hard');

当玩家离开页面或关闭窗口时,close 事件让你有机会保存状态:

$this->engine->lifecycle()->on('close', fn () => $this->engine->storage->writeJson('partie.json', $this->state()));

构建时千万不要读取玩家的文件:var/ 文件夹不会被发布。