EN
games/rob-revisited / tests / RevisitedLandTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\Land\Creature;use App\Revisited\Land\Game;use App\Revisited\Land\Intent;use App\Revisited\Land\Npc;use App\Revisited\Land\Quest;use App\Revisited\Land\Thing;use App\Revisited\Land\Wildlife;use App\Revisited\Land\ZoneFactory;use App\Revisited\Sim\Body;use PHPUnit\Framework\TestCase;/** The world of "Experience - Rob revisited": zones, actions, creatures, people, quests, saves (pure logic). */final class RevisitedLandTest extends TestCase{    private const SEED = 7;    public function testEachZoneGeneratesTheSameWayFromItsSeedAndHasItsExits(): void    {        $arrivals = [];        foreach (ZoneFactory::IDS as $id) {            foreach (ZoneFactory::exits($id) as $e) {                $arrivals[$e['to']][] = [$e['toX'], $e['toZ']];            }        }        foreach (ZoneFactory::IDS as $id) {            $a = ZoneFactory::make($id, self::SEED);            $b = ZoneFactory::make($id, self::SEED);            self::assertSame($a->heights, $b->heights, "$id heights");            self::assertSame(count($a->things), count($b->things), "$id things");            self::assertSame($a->things[10]->x, $b->things[10]->x);            self::assertCount(($a->grid + 1) ** 2, $a->heights);            self::assertCount($a->grid ** 2, $a->solid);            self::assertGreaterThan(100, count($a->things), "$id has things on the ground");            self::assertNotEmpty($a->exits, "$id has exits");            self::assertNotSame($a->heights, ZoneFactory::make($id, self::SEED + 1)->heights, "$id depends on the seed");            foreach ($a->exits as $e) {                self::assertContains($e['to'], ZoneFactory::IDS);                self::assertFalse($a->solidAt($e['x'], $e['z']), "$id exit to {$e['to']} is not in a wall");                foreach ($arrivals[$id] as [$x, $z]) {                    self::assertFalse($a->solidAt($x, $z), "$id arrival point is free");                    self::assertTrue(ZoneFactory::reachable($a, $x, $z, $e['x'], $e['z']), "$id: the exit to {$e['to']} can be walked to");                }            }            if ($a->cave) {                self::assertNotEmpty($a->ceilings);                self::assertGreaterThan(10000, count(array_filter($a->solid)), "$id is mostly rock");            }        }        $kinds = static fn (string $id): array => array_count_values(array_map(static fn (Thing $t) => $t->kind, ZoneFactory::make($id, self::SEED)->things));        self::assertArrayHasKey('wreck_pod', $kinds('valley'));        self::assertArrayHasKey('wreck_colony', $kinds('caves2'));        self::assertSame(6, $kinds('canyon')['hut']);        self::assertArrayHasKey('relay_mast', $kinds('plateau'));        self::assertTrue(ZoneFactory::reachable(ZoneFactory::make('plateau', self::SEED), 40, 470, ZoneFactory::MAST[0], ZoneFactory::MAST[1] + 6));    }    public function testWalkingIntoACaveWallIsBlocked(): void    {        $g = Game::newGame(self::SEED);        $g->travel(ZoneFactory::exits('valley')[0]);        self::assertSame('caves1', $g->zone->id);        $g->creatures = [];        // walk north from the arrival point until the rock        $z = $g->zone;        $wall = $g->z;        while (!$z->solidAt($g->x, $wall)) {            $wall -= 0.5;        }        $g->z = $wall + 2.0;        $g->yaw = M_PI;   // forward = (0, -1)        $in = new Intent();        $in->forward = 1.0;        for ($i = 0; $i < 180; $i++) {            $g->update(1 / 30, $in);        }        self::assertFalse($z->solidAt($g->x, $g->z));        self::assertGreaterThan($wall, $g->z, 'Rob stopped at the wall');    }    public function testDrinkingAtTheLakeRaisesThirst(): void    {        $g = Game::newGame(self::SEED);        $g->body = Body::fromArray(array_merge($g->body->toArray(), ['thirst' => 40.0]));        // from the middle of the lake towards the start until the water is shallow        $x = 0.64 * 512;        $z = 0.62 * 512;        self::assertGreaterThan(0.5, $g->zone->waterDepth($x, $z), 'there is a lake');        while ($g->zone->waterDepth($x, $z) > 0.4) {            $x -= 0.5;        }        $g->x = $x;        $g->z = $z;        $g->yaw = M_PI / 2;   // facing the lake (+x)        $g->creatures = [];        self::assertContains('drink', array_column($g->actions(), 'id'));        $g->act('drink');        self::assertGreaterThan(70.0, $g->body->vitals()['thirst']);        self::assertTrue(Quest::done($g, 'drink'));    }    public function testCuttingATreeNeedsTheAxe(): void    {        $g = Game::newGame(self::SEED);        $tree = $this->nearest($g, 'tree_broad');        $this->face($g, $tree, 1.0);        $text = $g->act('chop');        self::assertStringContainsString('hache', (string) $text);        self::assertSame(0, $g->inv->count('wood'));        $g->inv->add('axe_stone');        $g->act('chop');        self::assertSame(2, $g->inv->count('wood'));    }    public function testAStalkerAttacksAtNightAndWounds(): void    {        $g = Game::newGame(self::SEED);        $g->minutes = (23 - 7) * 60;        self::assertTrue($g->isNight());        $g->creatures = [Wildlife::make($g, 'stalker', $g->x + sin($g->yaw) * 6, $g->z + cos($g->yaw) * 6)];        $wounded = false;        for ($i = 0; $i < 600 && !$wounded; $i++) {            $g->update(1 / 30, new Intent());            $wounded = $g->body->injuries() !== [];        }        self::assertTrue($wounded, 'the stalker bit Rob');        self::assertGreaterThan(0.0, $g->hurt);        self::assertStringContainsString('rôdeur de nuit', implode("\n", $g->messages()));    }    public function testKillingAGrazerGivesACarcassThatTheKnifeTurnsIntoMeat(): void    {        $g = Game::newGame(self::SEED);        $g->inv->add('knife_flint');        $g->inv->equip('knife_flint');        $g->creatures = [Wildlife::make($g, 'grazer', $g->x + sin($g->yaw) * 1.5, $g->z + cos($g->yaw) * 1.5)];        $prey = $g->creatures[0];        for ($i = 0; $i < 30 && in_array($prey, $g->creatures, true); $i++) {            $g->act('attack');            // the blow lands at its strike, a moment after the press (the grazer held in place meanwhile)            for ($f = 0; $f < 60 && $g->swing !== null; $f++) {                [$prey->x, $prey->z] = [$g->x + sin($g->yaw) * 1.5, $g->z + cos($g->yaw) * 1.5];                $g->update(1 / 60, new Intent());            }        }        self::assertNotContains($prey, $g->creatures, 'the grazer is dead');        $carcass = $this->nearest($g, 'carcass');        self::assertLessThan(2.0, hypot($carcass->x - $g->x, $carcass->z - $g->z));        $this->face($g, $carcass, 1.0);        $g->act('skin');        self::assertSame(3, $g->inv->count('meat_raw'));        self::assertSame(1, $g->inv->count('hide'));        self::assertSame('bones', $carcass->kind);    }    public function testTheHaldiTraderTrades(): void    {        $g = Game::newGame(self::SEED);        $g->travel(ZoneFactory::exits('caves2')[1]);        self::assertSame('canyon', $g->zone->id);        $oko = $this->npc($g, 'Oko');        $this->face($g, $oko, 1.5);        $g->act('talk');        self::assertSame('Oko', $g->dialogue()['npc'] ?? null);        $this->say($g, 'Faire du troc');        $g->inv->add('hide', 2);        $this->say($g, '2 Peau → 6 Flèche');        self::assertSame(6, $g->inv->count('arrow'));        self::assertSame(0, $g->inv->count('hide'));        $this->say($g, '2 Peau → 6 Flèche');        self::assertStringContainsString('manque', $g->dialogue()['text']);        $this->say($g, 'Retour');        $this->say($g, 'Au revoir');        self::assertNull($g->dialogue());    }    public function testGoingThroughTheCaveMouthLoadsCaves1(): void    {        $g = Game::newGame(self::SEED);        $e = ZoneFactory::exits('valley')[0];        $g->x = $e['x'];        $g->z = $e['z'] + 2;        self::assertSame('Entrer dans la grotte', $g->prompt() === $e['label'] ? $e['label'] : $this->labelOf($g, 'exit'));        $g->act('exit');        self::assertSame('caves1', $g->zone->id);        self::assertTrue($g->zone->cave);        self::assertTrue(Quest::done($g, 'enter_caves'));        self::assertFalse($g->zone->solidAt($g->x, $g->z));        self::assertNotNull($g->zone->ceilingAt($g->x, $g->z));        self::assertLessThan(0.1, $g->lightLevel());    }    public function testTheWholeStoryCanBePlayedToTheRescue(): void    {        $g = Game::newGame(self::SEED);        self::assertSame(1, $g->quest()['chapter']);        // 1. the first night        $g->creatures = [];        $g->drinkWater(true);        $g->useItem('ration');        $g->inv->add('fire_drill');        $g->useItem('fire_drill');        // the drill in hand: "Allumer un feu" needs it        for ($i = 0; $i < 6 && !Quest::done($g, 'fire'); $i++) {            $g->inv->add('wood');            $g->lightFire();        }        self::assertTrue(Quest::done($g, 'fire'));        $g->minutes = (22 - 7) * 60;        $g->creatures = [];        // a dry night (the weather follows the game's random draws, which every creature's choice changes)        $g->weather = ['kind' => 'clear', 'amount' => 0.0];        \Closure::bind(function (): void {            $this->weatherLeft = 900.0;            $this->weatherTarget = null;        }, $g, Game::class)();        $g->sleep();        self::assertTrue(Quest::done($g, 'sleep'), implode("\n", array_slice($g->messages(), -3)));        $g->act();        self::assertSame(2, $g->quest()['chapter']);        // 2. the trail        $pod = $this->nearest($g, 'wreck_pod');        $this->face($g, $pod, 2.5);        $g->act('read');        $g->act('search');        self::assertTrue($g->inv->has('pod_log'));        $g->travel(ZoneFactory::exits('valley')[0]);        self::assertSame(3, $g->quest()['chapter']);        // 3. the caves        $g->inv->add('torch');        $bones = null;        foreach ($g->zone->things as $t) {            if (($t->data['note'] ?? '') === 'colonist') {                $bones = $t;            }        }        self::assertNotNull($bones);        $this->face($g, $bones, 1.0);        $g->act('search');        self::assertTrue($g->inv->has('keycard'));        $g->travel(ZoneFactory::exits('caves1')[1]);        self::assertSame('caves2', $g->zone->id);        $base = $this->nearest($g, 'wreck_colony');        $this->face($g, $base, 3.0);        $g->act('open');        $g->act('search');        self::assertTrue($g->inv->has('power_cell'));        self::assertSame(4, $g->quest()['chapter']);        // 4. the Haldi        $g->travel(ZoneFactory::exits('caves2')[1]);        $maeva = $this->npc($g, 'Maëva');        $this->face($g, $maeva, 1.5);        $g->act('talk');        $this->say($g, 'quitter cette lune');        $this->say($g, 'Je vous rapporterai');        $this->say($g, 'Au revoir');        $chest = null;        foreach ($g->zone->things as $t) {            if (!empty($t->data['chest'])) {                $chest = $t;            }        }        self::assertNotNull($chest);        $this->face($g, $chest, 1.2);        $g->act('search');        self::assertTrue($g->inv->has('tuner'));        $this->face($g, $maeva, 1.5);        $g->act('talk');        $this->say($g, 'repris votre accordeur');        $this->say($g, 'Au revoir');        self::assertSame(2, $g->inv->count('antenna_part'));        self::assertSame(5, $g->quest()['chapter']);        // the mast (optional since the escape): it gives the Meridian's launch windows        $g->travel(ZoneFactory::exits('canyon')[1]);        self::assertSame('plateau', $g->zone->id);        $g->creatures = [];        $mast = $this->nearest($g, 'relay_mast');        $this->face($g, $mast, 3.0);        $g->act('fit_cell');        $g->act('fit_tuner');        $g->act('repair');        $g->minutes = 2 * 1440 + (12 - 7) * 60;        $g->act('transmit');        self::assertFalse($g->won(), 'at noon the station is not overhead');        $g->minutes = 2 * 1440 + (23 - 7) * 60;        $g->act('transmit');        self::assertFalse($g->won(), 'the Meridian cannot land: the colony\'s shuttle is the way out');        self::assertTrue(!empty($g->flags['orbit_data']), 'but it gives its launch windows');        self::assertNull($g->over());        self::assertSame(5, $g->quest()['chapter']);    }    public function testASavedGameComesBackTheSame(): void    {        $g = Game::newGame(self::SEED);        $stick = $this->nearest($g, 'stick');        $this->face($g, $stick, 0.8);        $g->act('pick');        self::assertSame(1, $g->inv->count('stick'));        $g->addThing('carcass', $g->x + 3, $g->z, ['species' => 'grazer', 'meat' => 3]);        $g->inv->add('fire_drill');        $g->useItem('fire_drill');        $g->inv->add('wood', 3);        for ($i = 0; $i < 6 && $g->fires === []; $i++) {            $g->lightFire();        }        $g->update(0.05, new Intent());        $data = json_decode((string) json_encode($g->toArray()), true);        $h = Game::fromArray($data);        self::assertSame('valley', $h->zone->id);        self::assertEqualsWithDelta($g->x, $h->x, 0.001);        self::assertEqualsWithDelta($g->minutes, $h->minutes, 0.001);        self::assertSame($g->inv->all(), $h->inv->all());        self::assertSame($g->flags, $h->flags);        self::assertNull($h->zone->thing($stick->id), 'the stick picked up stays picked up');        self::assertCount(count($g->zone->things), $h->zone->things);        self::assertCount(count($g->fires), $h->fires);        self::assertEqualsWithDelta($g->body->vitals()['thirst'], $h->body->vitals()['thirst'], 0.001);        // a zone left and came back to keeps its changes too        $h->travel(ZoneFactory::exits('valley')[0]);        $i = Game::fromArray(json_decode((string) json_encode($h->toArray()), true));        self::assertSame('caves1', $i->zone->id);        $i->travel(ZoneFactory::exits('caves1')[0]);        self::assertNull($i->zone->thing($stick->id));        self::assertCount(count($g->zone->things), $i->zone->things);    }    // ------------------------------------------------------------------------------------------ helpers    public function testTheValleyAndTheCanyonHaveAWaterfallWithCleanRunningWaterAndASecretBehindIt(): void    {        foreach (['valley', 'canyon'] as $zone) {            $z = ZoneFactory::make($zone, self::SEED);            $falls = array_values(array_filter($z->things, static fn (Thing $t) => $t->kind === 'waterfall'));            self::assertCount(1, $falls, "a waterfall in the $zone");            $f = $falls[0];            self::assertGreaterThan(8.0, $f->data['top'] - $f->data['bottom'], 'it falls from a cliff');            self::assertTrue($z->solidAt($f->x, $f->z + 2), 'the face behind the water is rock');            self::assertGreaterThan(0.3, $z->waterDepth($f->x, $f->z + 9), 'a pool at its foot');            self::assertTrue(ZoneFactory::reachable($z, $f->x, $f->z + 4.6, $f->x, $f->z + 24), 'the ledge behind the curtain can be walked to');        }        $g = Game::newGame(self::SEED);        $g->creatures = [];        $fall = $this->nearest($g, 'waterfall');        $cache = null;        foreach ($g->zone->things as $t) {            if (($t->data['label'] ?? '') === 'Cache derrière la cascade') {                $cache = $t;            }        }        self::assertNotNull($cache, 'something is hidden behind the valley waterfall');        // in front of the fall: its water is clean and can fill a gourd        $g->x = $fall->x;        $g->z = $fall->z + 9;        $g->y = $g->zone->heightAt($g->x, $g->z);        $g->yaw = M_PI;        $ids = array_column($g->actions(), 'label', 'id');        self::assertStringContainsString('cascade', $ids['drink']);        $g->body = Body::fromArray(array_merge($g->body->toArray(), ['thirst' => 30.0]));        $g->drinkWater(true, 0.04);        self::assertGreaterThan(60.0, $g->body->vitals()['thirst']);        $g->inv->add('gourd_empty');        $g->act('fill');        self::assertTrue($g->inv->has('gourd_clean'), 'a gourd of spring water');        // standing in the falling water soaks the clothes        $g->x = $fall->x;        $g->z = $fall->z + 5.4;        $g->inv->wet = 0.0;        $g->passTime(4);        self::assertGreaterThan(0.5, $g->inv->wet);        // the cache behind it        $g->x = $cache->x;        $g->z = $cache->z + 1.4;        $g->yaw = M_PI;        $text = (string) $g->act('search');        self::assertTrue($g->inv->has('antenna_part'), $text);    }    public function testEarthwormsComeUpAfterTheRainAndCanBeEatenCookedOrUsedAsBait(): void    {        $g = Game::newGame(self::SEED);        $g->creatures = [];        // a patch of mud or jungle        $spot = null;        for ($k = 0; $k < 4000 && $spot === null; $k++) {            $x = 20 + ($k * 37) % 470;            $z = 20 + (int) ($k * 53 / 7) % 470;            if ($g->zone->biomeAt($x, $z) === 'mud' && !$g->zone->solidAt($x, $z) && $g->zone->waterDepth($x, $z) < 0) {                $spot = [$x, $z];            }        }        self::assertNotNull($spot);        [$g->x, $g->z] = $spot;        $g->y = $g->zone->heightAt($g->x, $g->z);        self::assertContains('worms', array_column($g->actions(), 'id'), 'Fouiller la terre');        $g->setWeatherTarget('rain', 1.0, 300);        $g->passTime(30);        $g->inv->add('knife_flint');        for ($i = 0; $i < 8; $i++) {            $g->act('worms');        }        self::assertGreaterThanOrEqual(6, $g->inv->count('earthworm'), 'after the rain, with a knife, worms come up');        // raw: disgusting        $morale = $g->body->vitals()['morale'];        $g->body = Body::fromArray(array_merge($g->body->toArray(), ['hunger' => 40.0]));        $text = $g->useItem('earthworm');        self::assertLessThan($morale, $g->body->vitals()['morale'], $text);        self::assertStringContainsString('Pouah', $text);        // cooked on a fire        $g->fires[] = ['x' => $g->x + 1, 'z' => $g->z, 'minutes' => 100.0];        $g->inv->add('earthworm', 4);        $g->craft('worms_cooked');        self::assertTrue($g->inv->has('worms_cooked'));        // bait: the fish bite better, a worm is spent each time        $n = $g->inv->count('earthworm');        $g->inv->add('fishing_line');        $lake = null;        for ($r = 2.0; $r < 300 && $lake === null; $r += 3) {            for ($a = 0.0; $a < 6.28; $a += 0.3) {                $x = $g->x + sin($a) * $r;                $z = $g->z + cos($a) * $r;                if ($g->zone->waterDepth($x + sin($a) * 1.4, $z + cos($a) * 1.4) > 0.2 && $g->zone->waterDepth($x, $z) < 0.5 && !$g->zone->solidAt($x, $z)) {                    $lake = [$x, $z, $a];                    break;                }            }        }        self::assertNotNull($lake);        [$g->x, $g->z, $g->yaw] = $lake;        $text = (string) $g->act('fish');        self::assertSame($n - 1, $g->inv->count('earthworm'), $text);    }    public function testDirtyWaterCanBeBoiledFilteredOrPurified(): void    {        $g = Game::newGame(self::SEED);        $g->creatures = [];        $g->inv->add('gourd_dirty', 3);        $g->inv->add('stone');        self::assertStringContainsString('feu', $g->boilWater(), 'boiling needs a fire');        $g->fires[] = ['x' => $g->x + 1.2, 'z' => $g->z, 'minutes' => 300.0];        self::assertContains('boil', array_column($g->actions(), 'id'), 'near a fire with dirty water: Faire bouillir');        $text = (string) $g->act('boil');        self::assertTrue($g->inv->has('gourd_boiled'), 'hot stones boil it without a pot: ' . $text);        // the filter        $g->inv->add('water_filter');        $g->useItem('water_filter');        self::assertTrue($g->inv->has('gourd_filtered'));        // a tablet of the pod's kit        $g->inv->add('purification_tablets');        $g->useItem('purification_tablets');        self::assertTrue($g->inv->has('gourd_purified'));        self::assertFalse($g->inv->has('gourd_dirty'));        // safe water counts as clean water in a recipe        $g->inv->add('herb_fever', 2);        $g->inv->add('pot');        self::assertSame('Tu as fabriqué : 1 tisane de fièvre, 1 gourde vide.', str_replace(['Tisane', 'Gourde'], ['tisane', 'gourde'], $g->craft('tea_fever')));        // drinking: the filtered water still has a small risk, the boiled one none        self::assertArrayNotHasKey('risk', \App\Revisited\Sim\Items::get('gourd_boiled'));        self::assertLessThan(\App\Revisited\Sim\Items::get('gourd_dirty')['risk']['dirty'], \App\Revisited\Sim\Items::get('gourd_filtered')['risk']['dirty']);    }    public function testThePodLogsCoordinatesGoIntoTheGpsAndPointTheWayAcrossZones(): void    {        $g = Game::newGame(self::SEED);        $g->creatures = [];        $text = $g->logText('pod_log');        self::assertMatchesRegularExpression('/\d+\.\d{4} N \/ \d+\.\d{4} E/', $text, 'the log gives coordinates');        $g->inv->add('pod_log');        $said = $g->insertLog('pod_log');        self::assertArrayHasKey('halde_base', $g->waypoints, $said);        self::assertSame('halde_base', $g->activeWaypoint);        // the base is in the deep caves: from the valley, the compass shows the cave's mouth        $t = $g->waypointTarget();        self::assertNotNull($t);        self::assertFalse($t[4]);        self::assertEqualsWithDelta(256.0, $t[0], 0.1);        self::assertEqualsWithDelta(66.0, $t[1], 0.1);        // coordinates are one grid: the same place seen from two zones is at the same coordinates        self::assertSame(Game::coordText('valley', 256.0, 66.0), Game::coordText('caves1', 32.0, 128.0));        // north is up the grid: a point further north has a higher latitude        self::assertGreaterThan(Game::coords('valley', 100, 300)[0], Game::coords('valley', 100, 100)[0]);        $far = $g->waypointDistance('halde_base');        $g->travel($g->zone->exits[0]);        $g->travel($g->zone->exits[1]);        self::assertSame('caves2', $g->zone->id);        $t = $g->waypointTarget();        self::assertTrue($t[4], 'in its zone: the point itself');        self::assertLessThan($far, $g->waypointDistance('halde_base') + 1);        // Rob's own marks; the GPS is saved        $g->markHere();        $h = Game::fromArray(json_decode((string) json_encode($g->toArray()), true));        self::assertSame(array_keys($g->waypoints), array_keys($h->waypoints));        self::assertSame($g->activeWaypoint, $h->activeWaypoint);        // the colony's log has the refuge and the mast        self::assertCount(2, $g->logPlaces('colony_log'));    }    public function testSleepingRunsAtItsOwnPaceAndADangerWakesRobUp(): void    {        $g = Game::newGame(self::SEED);        $g->creatures = [];        $g->minutes = (21 - 7) * 60;        $info = $g->sleepInfo();        self::assertSame('ground', $info['place']);        self::assertNotEmpty(array_filter($info['risks'], static fn ($r) => str_contains($r[0], 'Prédateurs')), 'the open ground at night: beasts');        // by a fire: safer, better        $g->fires[] = ['x' => $g->x + 1.0, 'z' => $g->z, 'minutes' => 900.0];        self::assertSame('fire', $g->sleepInfo()['place']);        self::assertGreaterThan(0.75, $g->sleepComfort());        $f0 = $g->body->vitals()['fatigue'];        self::assertNull($g->startSleep('4h'));        $g->sleepStep(60);        self::assertEqualsWithDelta((21 - 7) * 60 + 60, $g->minutes, 0.01, 'an hour asleep');        self::assertFalse($g->sleeping['done']);        $g->sleepStep(1000);        self::assertTrue($g->sleeping['done']);        $text = $g->wake();        self::assertStringContainsString('Tu dors 4 h', $text);        self::assertGreaterThan($f0, $g->body->vitals()['fatigue']);        self::assertNull($g->sleeping);        // a beast close by wakes him up at once        $g->fires = [];        $g->body = Body::fromArray(array_merge($g->body->toArray(), ['fatigue' => 30.0]));        self::assertNull($g->startSleep('dawn'));        $g->creatures[] = Wildlife::make($g, 'stalker', $g->x + 15, $g->z);        $g->creatures[0]->state = 'stalk';        $g->sleepStep(10);        self::assertNotNull($g->sleeping['woken']);        self::assertTrue($g->sleeping['done']);        $g->wake();        self::assertStringContainsString('Impossible de dormir', (string) $g->startSleep('1h'), 'not with a beast around');        // the short rest: awake, sitting        $g->creatures = [];        self::assertNull($g->startSleep('rest'));        $g->sleepStep(30);        self::assertStringContainsString('reposes', $g->wake());    }    public function testNightfallWithRainNeverFreezesTheLogicAndNanTimeIsRefused(): void    {        $g = Game::newGame(self::SEED);        $g->minutes = 805.0;      // day 1, 20:25        $g->setWeatherTarget('storm', 1.0, 300);        $in = new Intent();        $in->forward = 1.0;        $t0 = microtime(true);        for ($f = 0; $f < 60 * 20; $f++) {            $g->update(1 / 60, $in);        }        self::assertLessThan(5.0, microtime(true) - $t0);        self::assertTrue($g->isNight());        $m = $g->minutes;        $g->update(NAN, $in);        $g->update(INF, $in);        $g->passTime(INF);        $g->passTime(NAN);        $g->body->tick(INF, $g->environment());        $g->sleepStep(INF);        self::assertSame($m, $g->minutes, 'NaN / INF time is ignored');        foreach ($g->body->vitals() as $k => $v) {            self::assertTrue(is_finite($v), $k);        }    }    public function testTheNewClothesKeepTheirPartsWarmAndBareHandsFreezeOnThePlateau(): void    {        $g = Game::newGame(self::SEED);        foreach (['helmet_pilot', 'gloves_hide', 'trousers_hide', 'undershirt'] as $id) {            $g->inv->add($id);            $g->useItem($id);        }        self::assertSame('helmet_pilot', $g->inv->head);        self::assertSame('gloves_hide', $g->inv->hands);        self::assertSame('trousers_hide', $g->inv->legs);        self::assertSame('undershirt', $g->inv->under);        self::assertSame('flight_suit_torn', $g->inv->worn, 'the suit stays over the undershirt');        self::assertGreaterThan(0.0, $g->inv->regionWarmth('hands'));        self::assertGreaterThan($g->inv->protection('torso'), $g->inv->protection('head') + 0.1, 'the helmet protects the head');        // the plateau at night: bare hands go numb, gloved hands much less        $cold = new \App\Revisited\Sim\Environment();        $cold->airTemp = -8.0;        $cold->clothing = 10.0;        $cold->regions = ['head' => 2.0, 'torso' => 6.0, 'arms' => 4.0, 'hands' => 0.0, 'legs' => 4.0, 'feet' => 2.0];        $bare = new Body();        $bare->tick(180, $cold);        $cold->regions['hands'] = 4.0;        $gloved = new Body();        $gloved->tick(180, $cold);        self::assertLessThan($gloved->extremityTemps()['hands'], $bare->extremityTemps()['hands'] - 3);        self::assertContains('cold_hands', array_column($bare->conditions(), 'id'));        self::assertLessThan($gloved->fightFactor() + 0.001, $bare->fightFactor());        // an older save (one "worn" slot for everything) puts each garment in its own slot        $old = Game::fromArray(['seed' => 7, 'zone' => 'valley', 'inv' => ['items' => ['boots' => 1, 'coat_fur' => 1], 'worn' => 'coat_fur', 'feet' => 'boots', 'cond' => []]]);        self::assertSame('coat_fur', $old->inv->worn);        self::assertSame('boots', $old->inv->feet);        self::assertNull($old->inv->head);    }    private function nearest(Game $g, string $kind): Thing    {        $best = null;        foreach ($g->zone->things as $t) {            if ($t->kind === $kind && ($best === null || hypot($t->x - $g->x, $t->z - $g->z) < hypot($best->x - $g->x, $best->z - $g->z))) {                $best = $t;            }        }        self::assertNotNull($best, "a $kind in {$g->zone->id}");        return $best;    }    private function npc(Game $g, string $name): Npc    {        foreach ($g->npcs as $n) {            if ($n->name === $name) {                return $n;            }        }        self::fail("$name is not in {$g->zone->id}");    }    /** Puts Rob at $dist metres of a thing / person, looking at it. */    private function face(Game $g, Thing|Npc|Creature $t, float $dist): void    {        for ($k = 0; $k < 16; $k++) {            $a = $k * M_PI / 8;            $x = $t->x - sin($a) * $dist;            $z = $t->z - cos($a) * $dist;            if (!$g->zone->solidAt($x, $z) && $g->zone->waterDepth($x, $z) < 0.3) {                $g->x = $x;                $g->z = $z;                $g->y = $g->zone->heightAt($x, $z);                $g->yaw = $a;                return;            }        }        self::fail('no room around the ' . ($t instanceof Thing ? $t->kind : $t->name));    }    /** Picks the dialogue choice whose text contains $part. */    private function say(Game $g, string $part): void    {        $d = $g->dialogue();        self::assertNotNull($d, 'a dialogue is open');        foreach ($d['choices'] as $i => $c) {            if (str_contains($c, $part)) {                $g->choose($i);                return;            }        }        self::fail("no choice '$part' in: " . implode(' | ', $d['choices']));    }    private function labelOf(Game $g, string $id): ?string    {        foreach ($g->actions() as $a) {            if ($a['id'] === $id) {                return $a['label'];            }        }        return null;    }    public function testAJumpGoesUpAndComesDownWithoutHarm(): void    {        $g = Game::newGame(7);        $in = new Intent();        $y0 = $g->y;        $in->jump = true;        $g->update(0.05, $in);        $in->jump = false;        $top = $g->y;        for ($k = 0; $k < 40; $k++) {            $g->update(0.02, $in);            $top = max($top, $g->y);        }        self::assertGreaterThan($y0 + 0.5, $top, 'about 0.8 m high');        self::assertTrue($g->onGround);        self::assertSame([], $g->body->injuries());        // crouched: no jump        $in->crouch = true;        $in->jump = true;        $g->update(0.05, $in);        self::assertTrue($g->onGround);    }    public function testAJumpIsASmoothArcThatEndsOnTheGround(): void    {        $g = Game::newGame(7);        $in = new Intent();        $ground = $g->zone->heightAt($g->x, $g->z);        $in->jump = true;        $g->update(1 / 60, $in);        $in->jump = false;        $heights = [];        for ($k = 0; $k < 120 && !$g->onGround; $k++) {            $g->update(1 / 60, $in);            $heights[] = $g->y - $g->zone->heightAt($g->x, $g->z);        }        self::assertTrue($g->onGround);        self::assertGreaterThan(0.85, max($heights), 'about 1 m high');        self::assertGreaterThan(30, count($heights), 'about half a second in the air');        // no jump to the ground on the way down: each frame falls a few centimetres at most        for ($k = 1; $k < count($heights); $k++) {            self::assertLessThan(0.25, abs($heights[$k] - $heights[$k - 1]), "frame $k");        }        self::assertEqualsWithDelta($ground, $g->y, 0.5);    }    public function testRunningKeptUpBecomesASprintThatTires(): void    {        $g = Game::newGame(7);        $g->creatures = [];        $g->yaw = self::clearHeading($g, 30.0);     // nothing solid in the way (rocks, trunks: Solids)        $in = new Intent();        $in->forward = 1.0;        $in->run = true;        $g->update(0.5, $in);        self::assertTrue($g->running);        self::assertFalse($g->sprinting, 'not at once');        $x = $g->x;        $z = $g->z;        for ($k = 0; $k < 60; $k++) {            $g->update(1 / 30, $in);        }        self::assertTrue($g->sprinting, 'after a while of running');        self::assertGreaterThan(Game::RUN * 2 * 0.9, hypot($g->x - $x, $g->z - $z), 'faster than running');        $in->run = false;        $g->update(1 / 30, $in);        self::assertFalse($g->sprinting);    }    public function testAFallFromHighHurtsTheLegs(): void    {        $g = Game::newGame(7);        $g->y += 9.0;        $g->onGround = false;        $in = new Intent();        for ($k = 0; $k < 120 && !$g->onGround; $k++) {            $g->update(0.02, $in);        }        $legs = array_filter($g->body->injuries(), static fn ($w) => in_array($w['part'], ['lleg', 'rleg'], true));        self::assertNotEmpty($legs);    }    public function testTheWeatherChangesLittleByLittle(): void    {        $g = Game::newGame(7);        $g->setWeatherTarget('storm', 1.0);        $in = new Intent();        $prev = 0.0;        $max = 0.0;        for ($k = 0; $k < 600; $k++) {            $g->update(0.05, $in);            $a = $g->weather['kind'] === 'storm' ? (float) $g->weather['amount'] : 0.0;            $max = max($max, abs($a - $prev));            $prev = $a;        }        self::assertSame('storm', $g->weather['kind']);        self::assertGreaterThan(0.9, $prev);        self::assertLessThan(0.02, $max, 'never a jump');    }    public function testRobCrashedDressedAndHisClothesWear(): void    {        $g = Game::newGame(7);        self::assertSame('flight_suit_torn', $g->inv->worn);        $c = $g->inv->condition('flight_suit_torn');        $warm = $g->inv->warmth();        $g->passTime(600);        self::assertLessThan($c, $g->inv->condition('flight_suit_torn'));        $g->inv->wet = 1.0;        self::assertLessThan($warm, $g->inv->warmth(), 'wet clothes warm less');        $old = Game::fromArray(['seed' => 7, 'zone' => 'valley', 'inv' => ['items' => ['ration' => 1]]]);        self::assertSame('flight_suit_torn', $old->inv->worn, 'an old save gets the crash clothes');        self::assertTrue($old->inv->has('scanner'));    }    /** A heading along which Rob can walk $len metres on flat enough ground without meeting a solid thing or a wall. */    private static function clearHeading(Game $g, float $len): float    {        for ($a = 0; $a < 64; $a++) {            $yaw = $a * 6.2832 / 64;            $ok = true;            for ($d = 0.5; $d <= $len && $ok; $d += 0.5) {                $x = $g->x + sin($yaw) * $d;                $z = $g->z + cos($yaw) * $d;                $px = $g->x + sin($yaw) * ($d - 0.5);                $pz = $g->z + cos($yaw) * ($d - 0.5);                $ok = \App\Revisited\Land\Solids::free($g->zone, $x, $z, 0.5) && $g->zone->waterDepth($x, $z) < 0.3                    && $g->zone->heightAt($x, $z) - $g->zone->heightAt($px, $pz) < 0.4;            }            if ($ok) {                return $yaw;            }        }        return $g->yaw;    }}