RU
games/rob-revisited / tests / RevisitedSavesTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\Land\Game;use App\Revisited\Ui\SaveScreen;use App\Revisited\Ui\SaveStore;use App\Revisited\Ui\Screens;use App\Scene\RevisitedScene;use JumPHP\Save\Storage;use JumPHP\Testing\GameTestCase;/** * "Experience - Rob revisited": the saved games (Ui\SaveStore, Ui\SaveScreen): 20 named slots + the autosave, their * metadata and previews, the screens from the title and the pause, the old single save moved into slot 1; and the * crafting screen kept up to date with the bag. */final class RevisitedSavesTest extends GameTestCase{    /** Starts the scene on empty saves (the scene left by the previous test writes its autosave when it exits). */    private function fresh(array $params): void    {        $this->game->start(RevisitedScene::class, $params + ['help' => false]);        $this->wipe();    }    private function wipe(): void    {        $st = $this->game->engine->storage;        foreach (SaveStore::keys() as $k) {            $st->delete(SaveStore::file($k));            $st->delete(SaveStore::file($k, 'png'));        }        $st->delete(SaveStore::INDEX);        $st->delete(SaveStore::OLD);    }    private function begin(array $params = ['seed' => 7, 'new' => true]): Game    {        $this->fresh($params);        $this->game->run(4);        self::assertSame('play', $this->game->peek('mode'));        return $this->game->peek('game');    }    /** @return list<string> */    private function rows(): array    {        return array_map(static fn (array $r): string => $r[0], $this->game->peek('menu')->rows);    }    private function choose(string $label): void    {        $menu = $this->game->peek('menu');        $i = array_search($label, $this->rows(), true);        self::assertNotFalse($i, "the row $label");        $menu->sel = (int) $i;        $this->game->press('rv_act', 2);    }    private function spot(string $id): array    {        $canvas = $this->game->peek('canvas');        foreach ($this->game->peek('lastHits', $canvas) as [$x, $y, $w, $h, $hid]) {            if ($hid === $id) {                [, , $lw, $lh] = $this->game->engine->sdl->getRenderer()->letterbox();                $vw = $this->game->engine->config->width();                $vh = $this->game->engine->config->height();                return [($x + $w / 2) * $canvas->s * $vw / $lw, ($y + $h / 2) * $canvas->s * $vh / $lh];            }        }        self::fail("no region $id drawn");    }    private function clickAt(string $id): void    {        $mouse = $this->game->engine->input->getMouse();        $mouse->move(...$this->spot($id));        $this->game->run(1);        $mouse->down(1);        $this->game->run(1);        $mouse->up(1);        $this->game->run(1);    }    private function screen(): SaveScreen    {        return $this->game->peek('saveScreen');    }    /** Types a name with the letters drawn under the field (the mouse; the pad does the same with its arrows). */    private function typeName(string $text): void    {        $screen = $this->screen();        $keys = (new \ReflectionClassConstant(SaveScreen::class, 'KEYS'))->getValue();        $flat = [];        foreach ($keys as $row) {            foreach ($row as [$label, $value]) {                $flat[] = $value;            }        }        // clear the name proposed        while (($screen->edit['text'] ?? '') !== '') {            $this->clickAt('sv:key:' . array_search('#del', $flat, true));        }        foreach (mb_str_split($text) as $ch) {            $this->clickAt('sv:key:' . array_search($ch === ' ' ? ' ' : $ch, $flat, true));        }    }    // ------------------------------------------------------------------------------------------ the store    public function testTwentySlotsHoldTheirGamesWithTheirMetadataAndCanBeRenamedAndDeleted(): void    {        $store = new SaveStore(new Storage(sys_get_temp_dir() . '/rv-saves-' . getmypid() . '-' . mt_rand()));        $g = Game::newGame(7);        $g->minutes = 26 * 60 + 30;      // day 2        for ($i = 1; $i <= SaveStore::SLOTS; $i++) {            self::assertSame((string) $i, $store->firstFree());            $store->write((string) $i, ['game' => $g->toArray()], SaveStore::meta($g, "Partie $i", 3700, 1_700_000_000 + $i));        }        self::assertNull($store->firstFree(), 'the 20 slots are used');        $store->write(SaveStore::AUTO, ['game' => $g->toArray()], SaveStore::meta($g, SaveStore::AUTO_NAME, 10, 1_600_000_000));        self::assertCount(21, $store->index(), '20 slots + the autosave');        self::assertSame('20', $store->latest(), 'the most recent first');        $m = $store->metaOf('5');        self::assertSame('Partie 5', $m['name']);        self::assertSame(2, $m['day']);        self::assertSame('Jour 2, 09:30', $m['clock']);        self::assertSame('valley', $m['zone']);        self::assertSame('Forêt du Naufrage', $m['zoneName']);        self::assertSame(1, $m['chapter']);        self::assertNotSame('', $m['title']);        self::assertSame(3700, $m['played']);        self::assertSame(0, $m['parts']);        foreach (['health', 'hunger', 'thirst', 'temp'] as $k) {            self::assertArrayHasKey($k, $m);        }        self::assertSame('1 h 01', SaveStore::playedText(3700));        self::assertTrue($store->rename('5', '  Le camp du lac  '));        self::assertSame('Le camp du lac', (new SaveStore(new Storage($this->dirOf($store))))->metaOf('5')['name'], 'kept on disk');        $store->delete('5');        self::assertFalse($store->has('5'));        self::assertSame('5', $store->firstFree(), 'the slot is free again');        self::assertNotNull($store->read('6'));        self::assertSame('Rob — Forêt du Naufrage, jour 2', SaveStore::defaultName($g));    }    private function dirOf(SaveStore $store): string    {        $st = (new \ReflectionProperty(SaveStore::class, 'storage'))->getValue($store);        return dirname($st->path('x'));    }    public function testTheOldSingleSaveBecomesSlotOneOnce(): void    {        $this->fresh(['seed' => 7]);        $st = $this->game->engine->storage;        $g = Game::newGame(7);        $g->x += 5;        $st->writeJson(SaveStore::OLD, ['v' => 1, 'game' => $g->toArray(), 'slots' => [1 => 'spear'], 'hints' => [], 'at' => '2026-11-20T10:00:00+00:00']);        $store = new SaveStore($st);        $store->migrate();        self::assertFalse($st->exists(SaveStore::OLD), 'moved');        self::assertTrue($store->has('1'));        self::assertSame('Rob — Forêt du Naufrage, jour 1', $store->metaOf('1')['name']);        self::assertEqualsWithDelta($g->x, $store->read('1')['game']['x'], 0.001);        $store->migrate();        self::assertCount(1, $store->index(), 'once');    }    // ------------------------------------------------------------------------------------------ the screens    public function testTheTitleOffersNewGameWithoutSaveAndReprendreSelectedWhenOneExists(): void    {        $this->fresh(['seed' => 7]);        $this->game->run(4);        self::assertSame('title', $this->game->peek('mode'));        $menu = $this->game->peek('menu');        self::assertSame('Nouvelle partie', $this->rows()[$menu->sel], 'no save: a new game is the choice');        $g = $this->begin();        $this->game->hold('up', 40);        $x = $g->x;        $z = $g->z;        $g->inv->add('flint', 3);        $count = $g->inv->count('flint');        $this->game->press('pause', 2);        $this->choose('Sauvegarder…');        self::assertSame('saves', $this->game->peek('mode'));        $this->game->press('rv_act', 2);           // "Sauvegarder ici" on the first free slot        self::assertTrue($this->screen()->editing(), 'a new save asks its name');        $this->game->press('rv_act', 2);           // the pad's A on OK: the name proposed        self::assertFalse($this->screen()->editing());        $this->game->start(RevisitedScene::class, ['seed' => 9, 'help' => false]);        $store = $this->game->peek('saves');        self::assertTrue($store->has('1'), 'the slot');        self::assertTrue($store->has(SaveStore::AUTO), 'leaving the game wrote the autosave, beside it');        self::assertSame(['1', SaveStore::AUTO], array_values(array_map('strval', array_keys($store->index()))) === ['1', SaveStore::AUTO]            ? ['1', SaveStore::AUTO] : [SaveStore::AUTO, '1'], 'nothing else');        self::assertCount(2, $store->index());        $this->game->run(4);        self::assertSame('title', $this->game->peek('mode'));        $menu = $this->game->peek('menu');        self::assertSame('Reprendre', $this->rows()[$menu->sel], 'a save exists: Reprendre is selected');        $this->game->shot('revisited-title-reprendre');        $this->game->press('rv_act', 4);        self::assertSame('play', $this->game->peek('mode'));        $h = $this->game->peek('game');        self::assertNotSame($g, $h);        self::assertEqualsWithDelta($x, $h->x, 0.01, 'the position');        self::assertEqualsWithDelta($z, $h->z, 0.01);        self::assertSame('valley', $h->zone->id, 'the zone');        self::assertSame($count, $h->inv->count('flint'), 'the bag');    }    public function testSavingInANamedSlotWithAPreviewThenLoadingItFromThePauseAsksAboutTheUnsavedProgress(): void    {        $g = $this->begin();        $this->game->hold('up', 30);        $x = $g->x;        $z = $g->z;        $this->game->press('pause', 2);        self::assertContains('Charger une partie…', $this->rows(), 'the pause can load a game');        $this->choose('Sauvegarder…');        $this->game->run(1);        $this->game->shot('revisited-save-screen');        $this->clickAt('sv:btn:0:0');                // "Sauvegarder ici"        self::assertTrue($this->screen()->editing());        $this->typeName('mon camp');        $this->game->run(1);        $this->game->shot('revisited-save-name');        $flat = [];        foreach ((new \ReflectionClassConstant(SaveScreen::class, 'KEYS'))->getValue() as $row) {            foreach ($row as [, $value]) {                $flat[] = $value;            }        }        $this->clickAt('sv:key:' . array_search('#ok', $flat, true));        $store = $this->game->peek('saves');        $key = $store->latest();        self::assertSame('1', $key);        self::assertSame('mon camp', $store->metaOf($key)['name'], 'named');        $this->game->run(3);        $path = $store->previewPath($key);        self::assertNotNull($path, 'a preview picture');        $img = imagecreatefrompng($path);        self::assertSame([160, 120], [imagesx($img), imagesy($img)]);        self::assertLessThan(150_000, filesize($path));        self::assertLessThan(150_000, strlen((string) $this->game->engine->storage->read(SaveStore::file($key))), 'a slot stays small');        $sum = 0;        for ($i = 0; $i < 160; $i += 8) {            for ($j = 0; $j < 120; $j += 8) {                $sum += imagecolorat($img, $i, $j) & 0xFF;            }        }        self::assertGreaterThan(0, $sum, 'not a black picture');        $this->game->shot('revisited-save-list');        // more play, then load "mon camp" from the pause: the progress since is lost, so it asks        $this->game->press('rv_close', 2);        $this->game->press('rv_close', 2);        self::assertSame('play', $this->game->peek('mode'));        $this->game->hold('up', 60);        self::assertGreaterThan(1.0, hypot($g->x - $x, $g->z - $z));        $this->game->press('pause', 2);        $this->choose('Charger une partie…');        self::assertSame('load', $this->screen()->mode);        $this->game->press('rv_act', 2);            // "Charger" on the first row        self::assertSame('leave', $this->screen()->ask['kind'] ?? null, 'Quitter la partie en cours sans sauvegarder ?');        $this->game->run(1);        $this->game->shot('revisited-load-ask');        $this->clickAt('sv:yes');        $this->game->run(4);        self::assertSame('play', $this->game->peek('mode'));        $h = $this->game->peek('game');        self::assertNotSame($g, $h);        self::assertEqualsWithDelta($x, $h->x, 0.01);        self::assertEqualsWithDelta($z, $h->z, 0.01);    }    public function testOverwritingAndDeletingAskFirst(): void    {        $this->begin();        $this->game->press('pause', 2);        $this->choose('Sauvegarder…');        $this->game->press('rv_act', 2);        $this->game->press('rv_act', 2);           // named as proposed        $store = $this->game->peek('saves');        $at = $store->metaOf('1')['at'];        $screen = $this->screen();        // the rows: the next free slot, then slot 1        self::assertSame('new', $screen->rows[0]['type']);        $screen->sel = 1;        $screen->btn = 0;                           // "Écraser"        $this->game->press('rv_act', 2);        self::assertSame('overwrite', $screen->ask['kind'] ?? null);        $this->game->run(1);        $this->game->shot('revisited-save-overwrite');        $this->game->press('rv_close', 2);          // no        self::assertNull($screen->ask);        self::assertSame($at, $store->metaOf('1')['at'], 'not overwritten');        $this->game->press('rv_drop', 2);           // Suppr        self::assertSame('delete', $screen->ask['kind'] ?? null);        $this->game->press('left', 1);              // Oui        $this->game->press('rv_act', 2);        self::assertFalse($store->has('1'), 'deleted');    }    public function testRenamingFromTheLoadListWithTheKeyboard(): void    {        $this->begin();        $this->game->press('pause', 2);        $this->choose('Sauvegarder…');        $this->game->press('rv_act', 2);        $this->game->press('rv_act', 2);        $this->game->press('rv_close', 2);          // back to the pause        self::assertSame('pause', $this->game->peek('mode'));        $this->choose('Charger une partie…');        $this->game->press('rv_rest', 2);           // R: rename        $screen = $this->screen();        self::assertTrue($screen->editing());        $screen->edit['text'] = '';        $kb = $this->game->engine->input->getKeyboard();        // the system's text input (accents as typed), then Return        $scene = $this->game->scene();        \Closure::bind(function () use ($kb): void {            $kb->addText('Près du lac');            $this->saveScreen->update($this->ui, $kb, false, 0.016);        }, $scene, RevisitedScene::class)();        $kb->down(13);        $this->game->run(1);        $kb->up(13);        $this->game->run(1);        self::assertFalse($screen->editing());        self::assertSame('Près du lac', $this->game->peek('saves')->metaOf('1')['name']);    }    public function testOnAPhoneTheListIsOneColumnOfBigRows(): void    {        $this->begin(['seed' => 7, 'new' => true, 'touch' => true, 'uiscale' => 0.54]);        $this->game->press('pause', 2);        $this->choose('Sauvegarder…');        $this->game->press('rv_act', 2);        $this->game->press('rv_act', 2);        $this->game->run(2);        $this->game->shot('revisited-save-phone');        $screen = $this->screen();        self::assertTrue($screen->touch);        $canvas = $this->game->peek('canvas');        $rows = [];        foreach ($this->game->peek('lastHits', $canvas) as [$x, $y, $w, $h, $id]) {            if (str_starts_with($id, 'sv:row:')) {                $rows[] = [$x, $w, $h];            }        }        self::assertNotEmpty($rows);        foreach ($rows as [$x, $w, $h]) {            self::assertGreaterThan(900, $w, 'the whole width');            self::assertGreaterThan(140, $h, 'tall rows for a finger');        }        $this->clickAt('sv:btn:1:1');               // Renommer, with a finger        self::assertTrue($screen->editing());        $this->game->run(1);        $this->game->shot('revisited-save-phone-name');    }    // ------------------------------------------------------------------------------------------ crafting    public function testCraftingUpdatesTheRecipesAndTheBagAtOnce(): void    {        $g = $this->begin();        foreach (array_keys($g->inv->all()) as $id) {            if ($id === 'fiber' || $id === 'rope') {                $g->inv->remove($id, $g->inv->count($id));            }        }        $g->inv->add('fiber', 3);        $this->game->press('rv_craft', 2);        /** @var Screens $s */        $s = $this->game->peek('screens');        $find = function () use ($s): int {            foreach ($this->game->peek('recipes', $s) as $i => $r) {                if ($r['id'] === 'rope_fiber') {                    return $i;                }            }            self::fail('no rope recipe');        };        $s->craftSel = $find();        $this->game->run(1);        $can = new \ReflectionMethod(Screens::class, 'can');        self::assertTrue($can->invoke(null, $this->game->peek('recipes', $s)[$find()], $g, false), 'possible before');        $this->game->press('rv_act', 2);        self::assertTrue($g->inv->has('rope'), 'the rope is in the bag');        self::assertFalse($g->inv->has('fiber'));        $this->game->run(1);        $recipes = $this->game->peek('recipes', $s);        self::assertSame('rope_fiber', $recipes[$s->craftSel]['id'], 'the same recipe stays selected');        self::assertFalse($can->invoke(null, $recipes[$s->craftSel], $g, false), 'locked at once');        $this->game->shot('revisited-craft-after');        $this->game->press('rv_inventory', 2);        self::assertContains('rope', $this->game->peek('items', $s), 'the bag shows it');    }    public function testTheAutosaveOnlyEverWritesItsOwnSlotAndComesFirstInTheLoadList(): void    {        $g = $this->begin();        $this->game->press('pause', 2);        $this->choose('Sauvegarder…');        $this->game->press('rv_act', 2);        $this->game->press('rv_act', 2);        $this->game->press('rv_close', 2);        $this->game->press('rv_close', 2);        $store = $this->game->peek('saves');        $slot = $this->game->engine->storage->read(SaveStore::file('1'));        // two game hours of play: the autosave, never slot 1        $g->minutes += 59.5;        $this->game->run(40);        $g->minutes += 60.0;        $this->game->run(40);        self::assertTrue($store->has(SaveStore::AUTO));        self::assertSame($slot, $this->game->engine->storage->read(SaveStore::file('1')), 'the player\'s slot untouched');        self::assertSame(['1', SaveStore::AUTO], array_values(array_intersect(SaveStore::keys(), array_map('strval', array_keys($store->index())))));        // the quit question: progress since the player's save (the autosave does not count)        $this->game->press('pause', 2);        $this->choose('Charger une partie…');        $screen = $this->screen();        self::assertSame(SaveStore::AUTO, $screen->rows[0]['key'], 'the autosave first');        self::assertCount(2, (new \ReflectionMethod(SaveScreen::class, 'buttons'))->invoke($screen, 0), 'load, delete: no rename');        $this->game->run(1);        $this->game->shot('revisited-load-list');        $this->game->press('rv_close', 2);        $rows = $this->rows();        $quit = array_search('Quitter le jeu', $rows, true);        $this->game->peek('menu')->sel = (int) $quit;        $engine = $this->game->engine;        $quits = 0;        $count = function () use (&$quits): void {            $quits++;        };        $engine->on('quit', $count);        $this->game->press('rv_act', 2);        self::assertSame('askleave', $this->game->peek('mode'), 'Sauvegarder avant de quitter ?');        $this->game->run(1);        $this->game->shot('revisited-ask-leave');        self::assertSame(0, $quits);        $this->choose('Annuler');        self::assertSame('pause', $this->game->peek('mode'));        $engine->removeListener('quit', $count);    }    public function testDyingWritesNoSave(): void    {        $g = $this->begin();        $g->body = \App\Revisited\Sim\Body::fromArray(array_merge($g->body->toArray(), ['health' => 0.2, 'thirst' => 0.0]));        $this->game->run(240);        self::assertSame('dead', $this->game->peek('mode'));        self::assertSame([], $this->game->peek('saves')->index(), 'no save on death');    }}