NL
games/rob-revisited / tests / RevisitedEscapeTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\Land\Companions;use App\Revisited\Land\Creature;use App\Revisited\Land\Escape;use App\Revisited\Land\Folk;use App\Revisited\Land\Game;use App\Revisited\Land\Intent;use App\Revisited\Land\Npc;use App\Revisited\Land\People;use App\Revisited\Land\Quest;use App\Revisited\Land\Raft;use App\Revisited\Land\Talk;use App\Revisited\Land\Thing;use App\Revisited\Land\Wildfire;use App\Revisited\Land\Wildlife;use App\Revisited\Land\ZoneFactory;use App\Revisited\Sim\Catalog2;use App\Revisited\Sim\Crafting;use App\Revisited\Sim\Inventory;use App\Revisited\Sim\Items;use App\Revisited\Sim\Weapons;use PHPUnit\Framework\TestCase;/** * Wave 2 of "Experience - Rob revisited" (docs/reborn.md "Wave 2"): the new zones, the people and their talks, money, * weapons, fire and lightning, the raft, the companions, spoilage, old saves, and the whole escape played to the launch. */final class RevisitedEscapeTest extends TestCase{    private const SEED = 7;    // ------------------------------------------------------------------------------------------ the world    public function testTheNineZonesAreBuiltQuicklyAndEveryDoorLeadsSomewhereReachable(): void    {        foreach (ZoneFactory::IDS as $id) {            $t = microtime(true);            $z = ZoneFactory::make($id, self::SEED);            $ms = (microtime(true) - $t) * 1000;            self::assertLessThan(200.0, $ms, "$id is built in under 200 ms");            self::assertNotEmpty($z->exits, "$id has doors");            foreach ($z->exits as $e) {                self::assertContains($e['to'], ZoneFactory::IDS);                $back = array_filter(ZoneFactory::exits($e['to']), fn (array $b) => $b['to'] === $id);                self::assertNotEmpty($back, "the door $id → {$e['to']} has a way back");            }        }        // every outdoor zone can be reached from the crash site, the caves are the junctions        foreach (ZoneFactory::OUTDOOR as $id) {            self::assertTrue($id === 'valley' || \App\Revisited\Ui\Guide::nextZone('valley', $id) !== null, "$id is on the map");        }        self::assertSame('caves3', \App\Revisited\Ui\Guide::nextZone('jungle', 'coast'));        self::assertSame('caves3', \App\Revisited\Ui\Guide::nextZone('marsh', 'coast'));    }    public function testTheOlderZonesKeepTheirThingsAndGetTheNewDoorsAfterThem(): void    {        $v = ZoneFactory::make('valley', self::SEED);        self::assertSame('signpost', end($v->things)->kind, 'the valley\'s new things come last: an older save\'s ids stay the same');        self::assertCount(2, $v->exits);        $c = ZoneFactory::make('canyon', self::SEED);        $kinds = array_map(fn (Thing $t) => $t->kind, array_slice($c->things, -6));        self::assertSame(['terminal', 'weapon_rack', 'forge', 'totem', 'market_stall', 'crate'], $kinds, 'the mesa cache (climbing) comes after them');    }    public function testTheJungleRiverCannotBeSwumButItsIslandsAreDryLand(): void    {        $g = $this->at('jungle');        $z = $g->zone;        $n = ZoneFactory::noiseOf('jungle', self::SEED);        foreach ([0.15, 0.4, 0.62, 0.9] as $v) {            $rx = ZoneFactory::riverX($v, $n) * 512;            self::assertGreaterThan(1.0, $z->waterDepth($rx + ZoneFactory::riverHalf($v, $n) * 0.3, $v * 512), "deep water mid-river at v=$v");            self::assertTrue(Raft::forbidden($g, $rx, $v * 512));        }        foreach (ZoneFactory::islands(self::SEED) as [$x, $zz, $r]) {            self::assertLessThan(0.0, $z->waterDepth($x, $zz), 'an island is above the water');            $wet = 0;            for ($a = 0; $a < 6.28; $a += 0.785) {                $wet += $z->waterDepth($x + sin($a) * ($r + 4), $zz + cos($a) * ($r + 4)) > 1.0 ? 1 : 0;            }            self::assertGreaterThanOrEqual(6, $wet, 'deep water all around: only a raft reaches it');        }        // walking into the river: refused        $rx = ZoneFactory::riverX(0.4, $n) * 512;        $half = ZoneFactory::riverHalf(0.4, $n);        $g->x = $rx - $half - 4;        $g->z = 0.4 * 512;        $g->y = $z->heightAt($g->x, $g->z);        $g->yaw = 1.5708;        $g->creatures = [];        $in = new Intent();        $in->forward = 1.0;        for ($k = 0; $k < 200; $k++) {            $g->update(0.05, $in);        }        self::assertLessThan($rx - $half * 0.4, $g->x, 'Rob stops at the river');        self::assertStringContainsString('radeau', implode(' ', $g->messages()));    }    public function testTheNewZonesHaveTheirPlacesAndPeople(): void    {        $g = $this->at('jungle');        self::assertNotNull($this->npc($g, 'Aïka'));        self::assertNotEmpty($this->things($g, 'totem'));        self::assertNotEmpty($this->things($g, 'giant_tree'));        self::assertNotEmpty($this->things($g, 'drone_wreck'));        $cub = Companions::pet($g);        self::assertNotNull($cub, 'the wounded cub waits in its den');        self::assertSame('wounded', $cub->state);        $boss = array_values(array_filter($g->creatures, fn (Creature $c) => !empty($c->data['boss'])));        self::assertCount(1, $boss, 'the Old Jaw lives in the river');        $g = $this->at('marsh');        self::assertNotNull($this->npc($g, 'Orsolo'));        self::assertNotNull($this->npc($g, 'Kessa'));        self::assertNotEmpty($this->things($g, 'stilt_hut'));        $g = $this->at('coast');        self::assertNotEmpty($this->things($g, 'shuttle'));        self::assertNotEmpty($this->things($g, 'fumarole'));        self::assertSame('beach', $g->zone->biomeAt(470, 256));        $g = $this->at('caves3');        self::assertNotNull($this->npc($g, 'Jonas Merle'));        self::assertCount(13, People::WHO, 'thirteen named people');    }    // ------------------------------------------------------------------------------------------ people    public function testAnswersChangeWhatPeopleThinkByTheirPersonalityAndTheGroupHearsOfIt(): void    {        $g = Game::newGame(self::SEED);        $maeva0 = People::trust($g, 'maeva');        $sela0 = People::trust($g, 'sela');        People::react($g, 'maeva', 'lie');        self::assertLessThan($maeva0 - 10, People::trust($g, 'maeva'), 'the wise one catches the lie');        self::assertLessThan($sela0, People::trust($g, 'sela'), 'gossip: the healer heard of it');        self::assertTrue(People::recalls($g, 'maeva', 'lie'), 'and she remembers');        $oko0 = People::trust($g, 'oko');        People::react($g, 'oko', 'gift');        self::assertGreaterThan($oko0 + 10, People::trust($g, 'oko'), 'the greedy one loves a present');        $koru0 = People::trust($g, 'koru');        People::react($g, 'koru', 'threat');        self::assertLessThan($koru0 - 15, People::trust($g, 'koru'), 'the proud one hates a threat');        $grell0 = People::trust($g, 'grell');        People::react($g, 'grell', 'threat');        self::assertGreaterThan($grell0, People::trust($g, 'grell'), 'the coward gives way to one');        // helping the Rôdeurs cools the Haldi        $m = People::trust($g, 'maeva');        People::change($g, 'vask', 40);        self::assertLessThan($m, People::trust($g, 'maeva'));        self::assertContains(People::attitude($g, 'mira'), ['hostile', 'méfiant']);        $personalities = array_unique(array_map(fn (array $w) => $w[2], People::WHO));        self::assertGreaterThanOrEqual(7, count($personalities), 'mad, paranoid, empathic, greedy, proud, coward, wise');    }    public function testEveryNamedPersonHasAConversationWithChoices(): void    {        $zones = ['canyon' => ['maeva', 'oko', 'sela', 'koru', 'grell', 'mira', 'vask'], 'jungle' => ['aika', 'tamu', 'nadje'], 'marsh' => ['orsolo', 'kessa'], 'caves3' => ['jonas']];        foreach ($zones as $zone => $keys) {            $g = $this->at($zone);            $g->flags['rodeur_truce'] = true;            $g->people['vask'] = ['trust' => 0.0];            Folk::populate($g);            foreach ($keys as $key) {                $n = $this->byKey($g, $key);                $g->talkTo($n);                $d = $g->dialogue();                self::assertNotNull($d, "$key talks");                self::assertNotSame('', $d['text']);                self::assertGreaterThanOrEqual(2, count($d['choices']), "$key offers choices");                self::assertCount(count($d['choices']), $d['tones']);                self::assertArrayHasKey('attitude', $d);                $g->closeDialogue();            }        }    }    public function testMerchantsTakeCreditsAtPricesThatFollowTheirTrust(): void    {        $g = $this->at('canyon');        $g->inv->add('credit', 100);        $cheap = Talk::buyPrice($g, 'oko', 'coat_fur');        People::change($g, 'oko', -60);        self::assertGreaterThan($cheap, Talk::buyPrice($g, 'oko', 'coat_fur'), 'a merchant who dislikes Rob asks more');        People::change($g, 'oko', 60);        $before = $g->inv->count('credit');        $price = Talk::buyPrice($g, 'oko', 'rope');        self::assertStringContainsString('achètes', Talk::buy($g, 'oko', 'rope'));        self::assertSame($before - $price, $g->inv->count('credit'));        self::assertTrue($g->inv->has('rope'));        $g->inv->add('fur', 1);        $c = $g->inv->count('credit');        Talk::sell($g, 'oko', 'fur');        self::assertGreaterThan($c, $g->inv->count('credit'));        // the colony's money is found in the canyon: the old counter        $h = $this->at('canyon');        $counter = $this->things($h, 'terminal')[0];        $this->face($h, $counter, 1.5);        $h->act('search');        self::assertSame(40, $h->inv->count('credit'));        self::assertTrue(!empty($h->flags['credits_known']));    }    // ------------------------------------------------------------------------------------------ weapons    public function testWeaponsFireTheirAmmunitionWearAndCanBeRepaired(): void    {        $g = Game::newGame(self::SEED);        $g->creatures = [];        $prey = Wildlife::make($g, 'grazer', $g->x + sin($g->yaw) * 20, $g->z + cos($g->yaw) * 20);        $prey->y = $g->zone->heightAt($prey->x, $prey->z);        $g->creatures[] = $prey;        foreach (['bow' => 'arrow_metal', 'crossbow' => 'bolt', 'sling' => 'stone'] as $weapon => $ammo) {            $g->inv->add($weapon);            $g->inv->add($ammo, 2);            $g->useItem($weapon);            self::assertSame($weapon, $g->inv->hand);            $n = $g->inv->count($ammo);            $this->fire($g);            self::assertLessThanOrEqual($n, $g->inv->count($ammo), "$weapon spends $ammo (an arrow may be pulled back)");            self::assertLessThan(100.0, $g->inv->condition($weapon), "$weapon wears");        }        // the pulse rifle: six shots a cell        $g->inv->add('pulse_rifle');        $g->inv->add('energy_cell', 1);        $g->useItem('pulse_rifle');        for ($k = 0; $k < 6; $k++) {            $this->fire($g);        }        self::assertSame(0, $g->inv->count('energy_cell'));        self::assertStringContainsString('munitions', (string) $this->fire($g));        // a club worn out breaks; repaired before, it lasts        $g->inv->add('club');        $g->useItem('club');        $g->inv->cond['club'] = 50.0;        $g->inv->add('wood');        $g->inv->add('vine');        self::assertStringContainsString('répares', $g->repairWeapon());        self::assertGreaterThan(100.0 - 1, $g->inv->condition('club'));        $g->inv->cond['club'] = 0.5;        $prey->x = $g->x + sin($g->yaw) * 1.5;      // something to hit        $prey->z = $g->z + cos($g->yaw) * 1.5;        $prey->y = $g->zone->heightAt($prey->x, $prey->z);        $prey->health = 500;        $prey->state = 'idle';        $g->creatures = [$prey];        $g->attackCoolReset();        $said = (string) $g->attack();        self::assertFalse($g->inv->has('club'), 'the club broke: ' . $said . ' / hand ' . $g->inv->hand);        self::assertGreaterThanOrEqual(14, count(Weapons::all()), 'from the stick to the plasma gun');        self::assertNotNull(Crafting::recipe('crossbow'));        self::assertSame('blueprint_crossbow', Crafting::recipe('crossbow')['tool'], 'the crossbow needs the colony\'s plan');    }    public function testACounterRightAfterABeastLungesHitsHarder(): void    {        $g = $this->at('valley');        $g->creatures = [];        $c = Wildlife::make($g, 'stalker', $g->x + sin($g->yaw) * 1.5, $g->z + cos($g->yaw) * 1.5);        $c->y = $g->zone->heightAt($c->x, $c->z);        $c->health = 1000;        $g->creatures[] = $c;        $g->inv->add('spear');        $g->useItem('spear');        $g->attackCoolReset();        $g->attack();        $plain = 1000 - $c->health;        $c->health = 1000;        $g->lunged();        $g->attackCoolReset();        self::assertStringContainsString('Contre', (string) $g->attack());        self::assertGreaterThan($plain * 1.2, 1000 - $c->health);    }    // ------------------------------------------------------------------------------------------ fire and lightning    public function testAFireSpreadsOnDryGrassLeavesAshAndRainPutsItOut(): void    {        $g = $this->at('canyon');        $g->flags['rain_at'] = $g->minutes - 72 * 60;        $g->weather = ['kind' => 'clear', 'amount' => 0.0];        [$x, $z] = $this->biomeSpot($g, 'grass');        self::assertTrue(Wildfire::ignite($g, $x, $z, 1.5), 'dry grass catches');        $g->wind = [1.0, 0.0, 0.9];        $r0 = $g->blazes[0]['r'];        for ($k = 0; $k < 400; $k++) {            Wildfire::update($g, 0.1);        }        self::assertTrue($g->blazes === [] || $g->blazes[0]['r'] > $r0, 'it grows');        // rain: it dies and leaves burnt ground        $g->weather = ['kind' => 'storm', 'amount' => 1.0];        $g->lightningTimer = 999;        for ($k = 0; $k < 600 && $g->blazes !== []; $k++) {            Wildfire::update($g, 0.1);        }        self::assertSame([], $g->blazes, 'the rain puts it out');        self::assertNotEmpty($g->burnt['canyon'] ?? [], 'ash where it burnt');        self::assertTrue(Wildfire::burntAt($g, $x, $z));        self::assertSame(0.0, Wildfire::burnable($g, $x, $z), 'burnt ground does not burn twice');        // the marsh does not burn        $m = $this->at('marsh');        [$mx, $mz] = $this->biomeSpot($m, 'marsh');        self::assertFalse(Wildfire::ignite($m, $mx, $mz, 1.0));    }    public function testAFireNearbyBurnsTreesScaresAnimalsAndHurtsRob(): void    {        $g = $this->at('valley');        $g->flags['rain_at'] = $g->minutes - 72 * 60;        $tree = $this->things($g, 'tree_broad')[0];        $g->creatures = [];        $grazer = Wildlife::make($g, 'grazer', $tree->x + 10, $tree->z);        $g->creatures[] = $grazer;        $g->blazes = [['x' => $tree->x, 'z' => $tree->z, 'r' => 4.0, 'fuel' => 20.0, 'age' => 0.0]];        $g->x = $tree->x + 1;        $g->z = $tree->z;        $g->y = $g->zone->heightAt($g->x, $g->z);        Wildfire::update($g, 0.5);        self::assertSame('burnt_tree', $tree->kind);        self::assertSame('flee', $grazer->state);        self::assertGreaterThan(0.0, $g->hurt);        $burns = array_filter($g->body->injuries(), fn (array $w) => $w['kind'] === 'burn');        self::assertNotEmpty($burns);    }    public function testLightningStrikesTallTreesSetsFiresAndHitsRobOnASummit(): void    {        $g = $this->at('valley');        $g->weather = ['kind' => 'storm', 'amount' => 1.0];        $at = Wildfire::strike($g, [$g->x + 343, $g->z]);        self::assertNotNull($g->lightning);        $thunder = array_values(array_filter($g->takeEvents(), fn (array $e) => $e[0] === 'thunder'));        self::assertEqualsWithDelta(1.0, $thunder[0][1], 0.01, 'the thunder comes a second after a flash 343 m away');        // Rob on the plateau's summit, metal in hand: struck        $p = $this->at('plateau');        $p->x = ZoneFactory::MAST[0] + 3;        $p->z = ZoneFactory::MAST[1] + 2;        $p->y = $p->zone->heightAt($p->x, $p->z);        $p->weather = ['kind' => 'storm', 'amount' => 1.0];        self::assertGreaterThan(0.5, Wildfire::exposure($p), 'a summit is exposed');        Wildfire::strike($p, [$p->x, $p->z]);        self::assertSame(1, (int) ($p->flags['struck'] ?? 0));        self::assertNotEmpty(array_filter($p->body->injuries(), fn (array $w) => $w['kind'] === 'burn'));        // a strike on a tree with dry weather sets it on fire        $g->flags['rain_at'] = $g->minutes - 200 * 60;        $g->weather = ['kind' => 'storm', 'amount' => 0.4];        $tree = $this->things($g, 'tree_dead')[0] ?? $this->things($g, 'tree_broad')[0];        Wildfire::strike($g, [$tree->x, $tree->z]);        self::assertSame('burnt_tree', $tree->kind);    }    // ------------------------------------------------------------------------------------------ the raft    public function testARaftIsBuiltBoardedCarriedByTheCurrentAndLeftOnTheShore(): void    {        $g = $this->at('jungle');        $g->creatures = [];        $n = ZoneFactory::noiseOf('jungle', self::SEED);        $v = 0.36;        $rx = ZoneFactory::riverX($v, $n) * 512;        $half = ZoneFactory::riverHalf($v, $n);        $g->x = $rx - $half - 1.5;        $g->z = $v * 512;        $g->y = $g->zone->heightAt($g->x, $g->z);        $g->yaw = 1.5708;        self::assertStringContainsString('rondins', Raft::build($g));        $g->inv->add('log', 4);        $g->inv->add('rope', 3);        $g->inv->add('raft_pole');        self::assertStringContainsString('flotte', $g->act('raft'));        self::assertTrue(!empty($g->flags['q_raft']));        $raft = $this->things($g, 'raft')[0];        $this->face($g, $raft, 2.0, true);        $g->act('board');        self::assertNotNull($g->raft);        $z0 = $g->z;        $in = new Intent();        $in->forward = 1.0;        $g->yaw = 1.5708;     // east, across the river        for ($k = 0; $k < 900 && !Raft::canLand($g) || $k < 60; $k++) {            $g->update(0.05, $in);        }        self::assertGreaterThan($z0 + 2, $g->z, 'the current carried the raft south');        self::assertGreaterThan($rx, $g->x, 'the pole pushed it across');        $g->act('land');        self::assertNull($g->raft);        self::assertGreaterThan($rx + $half * 0.5, $g->x, 'on the east bank');        self::assertCount(1, $this->things($g, 'raft'), 'the raft waits at the shore');        // the river is gone in a save and back        $h = Game::fromArray(json_decode((string) json_encode($g->toArray()), true));        self::assertCount(1, $this->things($h, 'raft'));    }    // ------------------------------------------------------------------------------------------ companions    public function testTheWoundedCubIsHealedFedTamedFollowsAndLeavesIfNeglected(): void    {        $g = $this->at('jungle');        $cub = Companions::pet($g);        $this->face($g, $cub, 1.5);        $g->inv->add('bandage');        $g->inv->add('meat_raw', 3);        $g->act('pet_heal');        self::assertTrue(!empty($g->pet['healed']));        $g->act('pet_feed');        self::assertSame('wild', $g->pet['state'] ?? 'wild', 'one meal is not enough');        $g->minutes += 200;        $g->act('pet_feed');        $g->minutes += 200;        $g->act('pet_feed');        self::assertSame('tame', $g->pet['state']);        self::assertTrue(!empty(Companions::pet($g)?->data['companion']));        // it follows through a door        $g->travel(ZoneFactory::exits('jungle')[0]);        self::assertNotNull(Companions::pet($g), 'the cub came along');        // orders        $g->talkToPet();        self::assertSame('Le petit', $g->dialogue()['npc']);        $g->choose(2);        self::assertSame('hunt', $g->pet['mode']);        // it warns of danger        $g->creatures[] = Wildlife::make($g, 'stalker', $g->x + 15, $g->z);        $in = new Intent();        $g->update(0.05, $in);        self::assertStringContainsString('gronde', implode(' ', $g->messages()));        // forgotten for days: gone        $g->pet['hunger'] = 100.0;        for ($k = 0; $k < 30; $k++) {            Companions::update($g, 60.0);        }        self::assertSame('gone', $g->pet['state']);    }    public function testAHumanCompanionCarriesFightsKeepsWatchAndEatsFromTheBag(): void    {        $g = $this->at('jungle');        People::change($g, 'tamu', 60, false);        $tamu = $this->byKey($g, 'tamu');        $g->talkTo($tamu);        $this->say($g, 'Viens avec moi');        self::assertSame('tamu', $g->companion);        self::assertSame(Inventory::DEFAULT_CAPACITY + Companions::CARRY, $g->inv->capacity());        self::assertTrue(Companions::watch($g));        $g->travel(ZoneFactory::exits('jungle')[0]);        $here = array_filter($g->npcs, fn (Npc $n) => !empty($n->data['companion']));        self::assertCount(1, $here, 'Tamu came through the door');        $g->inv->add('smoked_fish', 1);        $g->minutes += 25 * 60;        Companions::update($g, 0.05);        self::assertSame(0, $g->inv->count('smoked_fish'), 'he ate his share');        $g->minutes += 50 * 60;        Companions::update($g, 0.05);        self::assertNull($g->companion, 'two days without food: he leaves');    }    // ------------------------------------------------------------------------------------------ survival    public function testFoodSpoilsUnlessSmokedOrDriedAndColdKeepsItLonger(): void    {        $inv = new Inventory();        $inv->add('meat_raw', 2);        $inv->add('smoked_meat', 2);        self::assertSame([], $inv->spoil(20));        self::assertLessThan(0.3, $inv->freshness('meat_raw'));        self::assertSame(['meat_raw' => 2], $inv->spoil(5));        self::assertSame(2, $inv->count('food_rotten'));        self::assertSame(2, $inv->count('smoked_meat'), 'smoked meat keeps');        $cold = new Inventory();        $cold->add('fish_raw');        self::assertSame([], $cold->spoil(20, 0.5), 'the cold keeps fish longer');        // a fresh piece makes the stack younger        $mix = new Inventory();        $mix->add('meat_raw');        $mix->spoil(20);        $mix->add('meat_raw');        self::assertEqualsWithDelta(10.0, $mix->age['meat_raw'], 0.01);        $back = Inventory::fromArray($mix->toArray());        self::assertEqualsWithDelta(10.0, $back->age['meat_raw'], 0.01);    }    public function testEveryAnimalIsButcheredForWhatItGivesAndFishCanBeHarpooned(): void    {        $g = $this->at('jungle');        $g->creatures = [];        $g->inv->add('knife_flint');        $croc = Wildlife::make($g, 'river_croc', $g->x + 2, $g->z);        $g->creatures[] = $croc;        Wildlife::kill($g, $croc);        $carcass = $this->things($g, 'carcass')[0];        $this->face($g, $carcass, 1.2);        $g->act('skin');        self::assertTrue($g->inv->has('meat_raw') && $g->inv->has('fat') && $g->inv->has('scale_hide') && $g->inv->has('bone'));        $c = $this->at('coast');        $c->creatures = [];        $c->inv->add('knife_flint');        $crab = Wildlife::make($c, 'lava_crab', $c->x + 2, $c->z);        $c->creatures[] = $crab;        Wildlife::kill($c, $crab);        $this->face($c, $this->things($c, 'carcass')[0], 1.2);        $c->act('skin');        self::assertTrue($c->inv->has('crab_meat') && $c->inv->has('shell'));        foreach (['smoked_meat', 'smoked_fish', 'crab_cooked', 'ferment', 'fuel_canister', 'salve_burn', 'jacket_scale', 'machete', 'arrows_bone'] as $r) {            self::assertNotNull(Crafting::recipe($r === 'jacket_scale' ? 'armor_scale' : $r), "a recipe for $r");        }    }    // ------------------------------------------------------------------------------------------ the Rôdeurs' key    public function testVasksKeyCanBeStolenAtNightOrBoughtFromMiraOrTradedForTheTuner(): void    {        // theft: Vask sleeps by his fire        $g = $this->at('canyon');        $vask = $this->byKey($g, 'vask');        $vask->state = 'sleep';        $this->face($g, $vask, 1.2);        $g->crouching = true;        for ($k = 0; $k < 10 && !$g->inv->has('ignition_key'); $k++) {            $vask->state = 'sleep';            $g->act('steal');        }        self::assertTrue($g->inv->has('ignition_key'));        self::assertSame('theft', $g->flags['key_taken']);        // Mira sells him out        $m = $this->at('canyon');        $m->flags['rodeur_truce'] = true;        People::change($m, 'mira', 70, false);        $m->inv->add('credit', 60);        $mira = $this->byKey($m, 'mira');        $m->talkTo($mira);        $this->say($m, 'Tu n\'aimes pas Vask');        $this->say($m, 'Marché conclu');        self::assertTrue($m->inv->has('ignition_key'));        // the tuner: the Haldi never forgive it        $t = $this->at('canyon');        $t->flags['rodeur_truce'] = true;        $t->people['vask'] = ['trust' => 0.0];        $t->inv->add('tuner');        $before = People::trust($t, 'maeva');        $v = $this->byKey($t, 'vask');        $t->talkTo($v);        $this->say($t, 'Je veux la clé');        $this->say($t, 'accordeur des Haldi');        self::assertTrue($t->inv->has('ignition_key'));        self::assertLessThan($before - 30, People::trust($t, 'maeva'));        // a parley stops the fight        $p = $this->at('canyon');        $vask = $this->byKey($p, 'vask');        $vask->state = 'alert';        $p->x = $vask->x + 20;        $p->z = $vask->z;        $p->act('parley');        self::assertGreaterThan($p->minutes, $p->flags['parley_until']);    }    public function testOrsoloGivesTheCodesToWhoAnswersRightOrShowsHimTheColonysLog(): void    {        $g = $this->at('marsh');        $o = $this->byKey($g, 'orsolo');        $g->talkTo($o);        self::assertStringContainsString('Va-t\'en', $g->dialogue()['text'], 'the first day he chases Rob off');        $this->say($g, 'Je reviendrai demain');        $g->minutes += 1440;        $g->talkTo($o);        $this->say($g, 'codes de lancement');        $this->say($g, 'Quarante-deux');        $this->say($g, 'La Halde');        $this->say($g, 'Iréna');        self::assertTrue($g->inv->has('launch_codes'));        self::assertSame('riddles', $g->flags['codes_given']);        // a wrong answer sends Rob away        $h = $this->at('marsh');        $h->minutes += 1440;        People::visit($h, 'orsolo');        $o = $this->byKey($h, 'orsolo');        $h->minutes += 1440;        $h->talkTo($o);        $this->say($h, 'codes de lancement');        $this->say($h, 'Trente');        self::assertNull($h->dialogue());        self::assertFalse($h->inv->has('launch_codes'));        // the colony's log moves him to tears        $h->inv->add('colony_log');        $h->talkTo($o);        $this->say($h, 'dernier journal');        self::assertTrue($h->inv->has('launch_codes'));    }    // ------------------------------------------------------------------------------------------ saves, the whole escape    public function testAnOlderSaveLoadsAndItsMastCallBecomesTheLaunchWindows(): void    {        $g = Game::newGame(self::SEED);        $a = $g->toArray();        foreach (['v2', 'people', 'raft', 'blazes', 'blazeStore', 'burnt', 'wind', 'companion', 'companionFed', 'pet', 'cellShots'] as $k) {            unset($a[$k]);        }        $a['flags'] = ['q_drink' => true, 'q_eat' => true, 'q_fire' => true, 'q_sleep' => true, 'q_pod_log' => true, 'q_enter_caves' => true, 'q_torch' => true,            'q_keycard' => true, 'q_reach_caves2' => true, 'q_colony_log' => true, 'q_power_cell' => true, 'q_reach_canyon' => true, 'q_meet_elder' => true,            'q_tuner' => true, 'q_return_tuner' => true, 'q_reach_plateau' => true, 'q_reach_mast' => true, 'q_transmit' => true, 'chapter_told' => 6];        $h = Game::fromArray(json_decode((string) json_encode($a), true));        self::assertTrue(!empty($h->flags['orbit_data']), 'the old call to the Meridian gave its windows');        self::assertFalse($h->won());        self::assertSame(5, $h->quest()['chapter'], 'the story goes on: the Haldi\'s secret');        self::assertGreaterThan(30.0, People::trust($h, 'maeva'), 'the returned tuner is remembered');    }    public function testTheWholeEscapeCanBePlayedFromTheCanyonToTheLaunch(): void    {        $g = Game::newGame(self::SEED);        foreach (['drink', 'eat', 'fire', 'sleep', 'pod_log', 'enter_caves', 'torch', 'keycard', 'reach_caves2', 'colony_log', 'power_cell'] as $q) {            $g->flags['q_' . $q] = true;        }        $g->inv->add('colony_log');        $g->travel(ZoneFactory::exits('valley')[0]);        $g->travel(ZoneFactory::exits('caves1')[1]);        $g->travel(ZoneFactory::exits('caves2')[1]);        self::assertSame('canyon', $g->zone->id);        $g->creatures = [];        // the Haldi: the tuner, then the navigation core        $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 = array_values(array_filter($g->zone->things, fn (Thing $t) => !empty($t->data['chest'])))[0];        $this->face($g, $chest, 1.2);        $g->act('search');        $this->face($g, $maeva, 1.5);        $g->act('talk');        $this->say($g, 'repris votre accordeur');        $this->say($g, 'quitter cette lune');        $this->say($g, 'Confie-moi le cœur');        self::assertTrue($g->inv->has('nav_core'));        $this->say($g, 'Au revoir');        // the colony's money, the Rôdeurs' rack        $this->face($g, $this->things($g, 'terminal')[0], 1.5);        $g->act('search');        $this->face($g, $this->things($g, 'weapon_rack')[0], 1.5);        $g->act('search');        self::assertSame(65, $g->inv->count('credit'));        self::assertTrue($g->inv->has('pulse_rifle_broken'));        // Vask: a parley, a truce, then the ransom        $g->inv->add('credit', 200);       // sold furs and wrecks' finds along the way        $vask = $this->byKey($g, 'vask');        $vask->state = 'alert';        $g->x = $vask->x + 10;        $g->z = $vask->z;        $g->act('parley');        Folk::update($g, 0.05);        $this->face($g, $vask, 1.5);        $g->act('talk');        $this->say($g, 'Je veux la clé');        $this->say($g, 'Je paie');        self::assertTrue($g->inv->has('ignition_key'));        self::assertSame('ransom', $g->flags['key_taken']);        // east to the jungle        $g->travel(ZoneFactory::exits('canyon')[0]);        $g->travel(ZoneFactory::exits('caves2')[0]);        $g->travel(ZoneFactory::exits('caves1')[0]);        $g->travel(ZoneFactory::exits('valley')[1]);        self::assertSame('jungle', $g->zone->id);        self::assertSame(6, $g->quest()['chapter']);        // the Ouvi: the Old Jaw, then the plates        $aika = $this->byKey($g, 'aika');        $this->face($g, $aika, 1.5);        $g->act('talk');        $this->say($g, 'écailles du ciel');        $this->say($g, 'Que dois-je faire');        $this->say($g, 'Je te laisse');        $boss = array_values(array_filter($g->creatures, fn (Creature $c) => !empty($c->data['boss'])))[0];        Wildlife::hurt($g, $boss, 400);        self::assertTrue(!empty($g->flags['croc_dead']));        $this->face($g, $aika, 1.5);        $g->act('talk');        $this->say($g, 'Vieille Mâchoire est morte');        $this->say($g, 'écailles du ciel');        $this->say($g, 'Je les porterai');        self::assertTrue($g->inv->has('heat_plates'));        $g->closeDialogue();        // a raft across the river (the logs from the valley's trees)        $n = ZoneFactory::noiseOf('jungle', self::SEED);        $v = 0.36;        $rx = ZoneFactory::riverX($v, $n) * 512;        $half = ZoneFactory::riverHalf($v, $n);        $g->creatures = [];        $g->x = $rx - $half - 1.5;        $g->z = $v * 512;        $g->y = $g->zone->heightAt($g->x, $g->z);        $g->yaw = 1.5708;        $g->inv->setCapacity(60.0);       // the logs are cut at the shore, one trip at a time        $g->inv->add('log', 4);        $g->inv->add('rope', 3);        $g->inv->add('raft_pole');        self::assertStringContainsString('flotte', (string) $g->act('raft'));        $this->face($g, $this->things($g, 'raft')[0], 2.0, true);        $g->act('board');        $in = new Intent();        $in->forward = 1.0;        $g->yaw = 1.5708;        for ($k = 0; $k < 900 && (!Raft::canLand($g) || $g->x < $rx); $k++) {            $g->creatures = [];            $g->update(0.05, $in);        }        $g->act('land');        self::assertGreaterThan($rx, $g->x, 'across the river');        self::assertSame(7, $g->quest()['chapter']);        // the junction caves: Jonas        $g->travel(ZoneFactory::exits('jungle')[1]);        $jonas = $this->byKey($g, 'jonas');        $g->inv->add('splint');        $g->inv->add('ration');        $this->face($g, $jonas, 1.3);        $g->act('talk');        $this->say($g, 'soigner ta jambe');        $this->say($g, 'Mange, puis viens');        self::assertTrue(!empty($g->flags['jonas_free']));        // the marsh: Orsolo, two days running        $g->travel(ZoneFactory::exits('caves3')[1]);        $o = $this->byKey($g, 'orsolo');        $this->face($g, $o, 1.3);        $g->act('talk');        $this->say($g, 'Je reviendrai demain');        $g->minutes += 1440;        $g->act('talk');        $this->say($g, 'dernier journal');        self::assertTrue($g->inv->has('launch_codes'));        self::assertSame(9, $g->quest()['chapter']);        // the coast: Jonas repairs, the parts go in, the fuel        $g->travel(ZoneFactory::exits('marsh')[0]);        $g->travel(ZoneFactory::exits('caves3')[2]);        self::assertSame('coast', $g->zone->id);        $g->creatures = [];        $jonas = $this->byKey($g, 'jonas');        $g->inv->add('metal_scrap', 4);        $g->inv->add('wire', 3);        $this->face($g, $jonas, 1.3);        $g->act('talk');        $this->say($g, 'de quoi réparer');        self::assertTrue(!empty($g->flags['shuttle_repaired']));        $g->closeDialogue();        $this->face($g, array_values(array_filter($g->zone->things, fn (Thing $t) => ($t->data['label'] ?? '') === 'Soute éventrée'))[0], 1.3);        $g->act('search');        self::assertTrue($g->inv->has('plasma_gun'), 'the late weapon');        // two more cans distilled from the Ouvi's ferment        $g->inv->add('ferment', 6);        $g->inv->add('pot');        $g->inv->add('metal_scrap', 2);        $g->fires[] = ['x' => $g->x, 'z' => $g->z, 'minutes' => 999.0];        $g->craft('fuel_canister');        $g->craft('fuel_canister');        self::assertSame(3, $g->inv->count('fuel_canister'));        $shuttle = $this->things($g, 'shuttle')[0];        $this->face($g, $shuttle, 5.0);        foreach (Escape::PARTS as $p) {            $g->act('fit_' . $p);        }        for ($k = 0; $k < 3; $k++) {            $g->act('refuel');        }        self::assertTrue(Escape::ready($g));        // noon: the sky is closed; dawn: it opens        $g->minutes = (int) ($g->minutes / 1440 + 1) * 1440 + (12 - 7) * 60;        $g->weather = ['kind' => 'clear', 'amount' => 0.0];        $g->act('launch');        self::assertFalse($g->won());        $g->minutes = (int) ($g->minutes / 1440 + 1) * 1440 + (29 - 7) * 60;    // 05:00 the next morning        $g->act('launch');        self::assertTrue($g->won(), 'Rob escapes Ysor');        self::assertNull($g->over());        $ending = Escape::ending($g);        self::assertGreaterThanOrEqual(5, count($ending));        self::assertStringContainsString('Jonas', implode(' ', $ending));        self::assertNotEmpty(Escape::credits());        self::assertTrue(Quest::done($g, 'launch'));    }    // ------------------------------------------------------------------------------------------ helpers    private function at(string $zone): Game    {        $g = Game::fromArray(['seed' => self::SEED, 'zone' => $zone, 'v2' => 1]);        $e = $g->zone->exits[0];        $g->x = $e['x'] + ($e['x'] < $g->zone->size / 2 ? 8 : -8);        $g->z = $e['z'] + ($e['z'] > $g->zone->size - 40 ? -8 : 0);        $g->y = $g->zone->heightAt($g->x, $g->z);        return $g;    }    /** @return list<Thing> */    private function things(Game $g, string $kind): array    {        return array_values(array_filter($g->zone->things, fn (Thing $t) => $t->kind === $kind));    }    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}");    }    private function byKey(Game $g, string $key): Npc    {        foreach ($g->npcs as $n) {            if (People::keyOf($n) === $key) {                return $n;            }        }        self::fail("$key is not in {$g->zone->id}");    }    private function face(Game $g, Thing|Npc|Creature $t, float $dist, bool $wet = false): void    {        for ($k = 0; $k < 32; $k++) {            $a = $k * M_PI / 16;            $x = $t->x - sin($a) * $dist;            $z = $t->z - cos($a) * $dist;            if (!$g->zone->solidAt($x, $z) && ($wet || $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 instanceof Npc ? $t->name : $t->species)));    }    private function say(Game $g, string $part): void    {        $d = $g->dialogue();        self::assertNotNull($d, "a dialogue is open (for '$part')");        foreach ($d['choices'] as $i => $c) {            if (str_contains($c, $part)) {                $g->choose($i);                return;            }        }        self::fail("no choice '$part' in: " . $d['text'] . ' → ' . implode(' | ', $d['choices']));    }    private function fire(Game $g): ?string    {        $g->attackCoolReset();        return $g->attack();    }    /** @return array{0: float, 1: float} a dry spot of that biome away from water */    private function biomeSpot(Game $g, string $biome): array    {        for ($k = 0; $k < 4000; $k++) {            $x = 40 + ($k * 37) % 430;            $z = 40 + intdiv($k * 37, 430) * 11 % 430;            if ($g->zone->biomeAt($x, $z) === $biome && !$g->zone->solidAt($x, $z)) {                return [(float) $x, (float) $z];            }        }        self::fail("no $biome in {$g->zone->id}");    }}