IT
games/rob-revisited / src / Revisited / Ui / SaveStore.php · commit f9a1307
<?phpnamespace App\Revisited\Ui;use App\Revisited\Land\Escape;use App\Revisited\Land\Game;use App\Revisited\Land\Quest;use JumPHP\Save\Storage;/** * The saved games of "Rob revisited" (docs/reborn.md "Saves"): 20 slots the player names, plus one "Sauvegarde automatique" * slot (every game hour, when the game is left), all in the engine's storage (var/ on a computer, IndexedDB in a browser): * *   revisited/index.json      the slots' metadata (the lists load at once, without reading the games) *   revisited/slot-01.json    a slot's game (compact JSON, ~20-90 KB) ... slot-20.json, auto.json *   revisited/slot-01.png     its preview (160 x 120 PNG: the 3D view read back at save time, else drawn from the map) * * The single save of older versions (revisited.json) becomes slot 1 once (migrate()). */final class SaveStore{    public const SLOTS = 20;    public const AUTO = 'auto';    public const AUTO_NAME = 'Sauvegarde automatique';    public const INDEX = 'revisited/index.json';    public const OLD = 'revisited.json';    public const NAME_MAX = 40;    private const MONTHS = ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'];    /** @var array<string, array<string, mixed>>|null slot key => metadata */    private ?array $index = null;    public function __construct(private Storage $storage)    {    }    public static function file(string $key, string $ext = 'json'): string    {        return $key === self::AUTO ? "revisited/auto.$ext" : sprintf('revisited/slot-%02d.%s', (int) $key, $ext);    }    /** @return list<string> every slot key: '1' .. '20', then 'auto' */    public static function keys(): array    {        $out = [];        for ($i = 1; $i <= self::SLOTS; $i++) {            $out[] = (string) $i;        }        $out[] = self::AUTO;        return $out;    }    /** The old single save (revisited.json) goes into slot 1 (or the first free one), once. */    public function migrate(): void    {        if (!$this->storage->exists(self::OLD)) {            return;        }        $a = $this->storage->readJson(self::OLD, null);        $key = $this->firstFree();        if (is_array($a) && isset($a['game']) && is_array($a['game']) && $key !== null) {            try {                $g = Game::fromArray($a['game']);                $at = strtotime((string) ($a['at'] ?? '')) ?: time();                $this->write($key, $a + ['played' => 0.0], self::meta($g, self::defaultName($g), (float) ($a['played'] ?? 0.0), $at));            } catch (\Throwable) {                return;           // unreadable: left where it is            }        }        $this->storage->delete(self::OLD);    }    /** @return array<string, array<string, mixed>> slot key => metadata, for the slots that hold a game */    public function index(): array    {        if ($this->index === null) {            $raw = $this->storage->readJson(self::INDEX, []);            $this->index = [];            foreach (is_array($raw) && is_array($raw['slots'] ?? null) ? $raw['slots'] : [] as $k => $m) {                $k = (string) $k;                if (is_array($m) && in_array($k, self::keys(), true) && $this->storage->exists(self::file($k))) {                    $this->index[$k] = $m;                }            }        }        return $this->index;    }    public function has(string $key): bool    {        return isset($this->index()[$key]);    }    public function any(): bool    {        return $this->index() !== [];    }    /** @return array<string, mixed>|null */    public function metaOf(string $key): ?array    {        return $this->index()[$key] ?? null;    }    /** @return list<string> the slots that hold a game, the most recent first */    public function recent(): array    {        $idx = $this->index();        $keys = array_map('strval', array_keys($idx));        usort($keys, static fn (string $a, string $b): int => ((int) ($idx[$b]['at'] ?? 0) <=> (int) ($idx[$a]['at'] ?? 0)) ?: strcmp($a, $b));        return $keys;    }    public function latest(): ?string    {        return $this->recent()[0] ?? null;    }    /** The first numbered slot without a game, null: all 20 are used. */    public function firstFree(): ?string    {        for ($i = 1; $i <= self::SLOTS; $i++) {            if (!$this->has((string) $i)) {                return (string) $i;            }        }        return null;    }    /**     * Writes a slot: its game (payload), its metadata, its preview (PNG bytes, null: keep none).     * @param array<string, mixed> $payload     * @param array<string, mixed> $meta     */    public function write(string $key, array $payload, array $meta, ?string $png = null): bool    {        $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION);        if ($json === false || !$this->storage->write(self::file($key), $json)) {            return false;        }        if ($png !== null && $png !== '') {            $this->storage->write(self::file($key, 'png'), $png);            $meta['preview'] = (int) ($meta['at'] ?? time()) . '-' . strlen($png);        } else {            $this->storage->delete(self::file($key, 'png'));            unset($meta['preview']);        }        $this->index();        $this->index[$key] = $meta;        return $this->flush();    }    /** A better preview for a slot already written (the 3D view read back a frame later). */    public function setPreview(string $key, string $png): void    {        if (!$this->has($key) || $png === '') {            return;        }        $this->storage->write(self::file($key, 'png'), $png);        $this->index[$key]['preview'] = (int) ($this->index[$key]['at'] ?? 0) . '-' . strlen($png) . '-gl';        $this->flush();    }    /** The preview's file on disk (Sdl::loadTexture() takes it), null: none. */    public function previewPath(string $key): ?string    {        if (!$this->has($key) || empty($this->index()[$key]['preview']) || !$this->storage->exists(self::file($key, 'png'))) {            return null;        }        return $this->storage->path(self::file($key, 'png'));    }    /** @return array<string, mixed>|null the slot's game payload ('game', 'slots', 'hints', 'played') */    public function read(string $key): ?array    {        if (!$this->has($key)) {            return null;        }        $a = $this->storage->readJson(self::file($key), null);        return is_array($a) && isset($a['game']) && is_array($a['game']) ? $a : null;    }    public function rename(string $key, string $name): bool    {        $name = self::cleanName($name);        if (!$this->has($key) || $name === '') {            return false;        }        $this->index[$key]['name'] = $name;        return $this->flush();    }    public function delete(string $key): void    {        $this->storage->delete(self::file($key));        $this->storage->delete(self::file($key, 'png'));        $this->index();        unset($this->index[$key]);        $this->flush();    }    private function flush(): bool    {        return $this->storage->write(self::INDEX, (string) json_encode(['v' => 1, 'slots' => $this->index ?? []], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));    }    public static function cleanName(string $name): string    {        $name = trim((string) preg_replace('/[\x00-\x1f\x7f]+/u', '', $name));        return mb_substr($name, 0, self::NAME_MAX);    }    /** "Rob — Forêt du Naufrage, jour 2" */    public static function defaultName(Game $g): string    {        return 'Rob — ' . $g->zone->name . ', jour ' . $g->day();    }    /** @return array<string, mixed> what the lists show of a game, without loading it */    public static function meta(Game $g, string $name, float $played, ?int $at = null): array    {        $q = Quest::state($g);        $v = $g->body->vitals();        return [            'name' => self::cleanName($name) ?: self::defaultName($g), 'at' => $at ?? time(), 'day' => $g->day(), 'clock' => $g->clock(),            'hour' => round($g->hour(), 2), 'zone' => $g->zone->id, 'zoneName' => $g->zone->name, 'cave' => $g->zone->cave,            'chapter' => (int) $q['chapter'], 'title' => (string) $q['title'], 'objective' => (string) $q['objective'],            'health' => (int) round($v['health']), 'hunger' => (int) round($v['hunger']), 'thirst' => (int) round($v['thirst']),            'temp' => round($v['temperature'], 1), 'fatigue' => (int) round($v['fatigue']), 'played' => (int) round($played),            'parts' => Escape::partsFitted($g), 'partsOf' => count(Escape::PARTS), 'seed' => $g->seed,        ];    }    /** "3 déc. 2026, 17:52" / "Dec 3, 2026, 17:52" (the computer's local time, the player's language) */    public static function dateText(int $at): string    {        if (\App\Revisited\I18n\Translator::lang() === 'en') {            return date('M j, Y, H:i', $at);        }        return (int) date('j', $at) . ' ' . self::MONTHS[(int) date('n', $at) - 1] . ' ' . date('Y, H:i', $at);    }    /** "1 h 12" / "8 min" */    public static function playedText(int $seconds): string    {        $m = intdiv(max(0, $seconds), 60);        return $m >= 60 ? sprintf('%d h %02d', intdiv($m, 60), $m % 60) : max(1, $m) . ' min';    }}