UK
games/rob-revisited / tests / RevisitedOverflowTest.php · commit f9a1307
<?phpnamespace Tests;use App\Revisited\I18n\Translator;use App\Revisited\Land\Chests;use App\Revisited\Land\Game;use App\Revisited\Land\Npc;use App\Revisited\Land\People;use App\Revisited\Land\Talk;use App\Revisited\Sim\Crafting;use App\Revisited\Sim\Items;use App\Revisited\Ui\Canvas;use App\Revisited\Ui\ChestView;use App\Revisited\Ui\Hud;use App\Revisited\Ui\SaveScreen;use App\Revisited\Ui\Screens;use App\Revisited\Ui\VitalMenu;use App\Scene\RevisitedScene;use JumPHP\Testing\GameTestCase;/** * No text wider than its box (docs/i18n-plan.md "Text fitting", "Overflow test"): every screen of Rob revisited in French * and in English, at the desktop's scale and at a phone's (touch on, a small window), drawn one frame with Canvas::$record * on. Each text drawn must lie inside its box (Canvas fits it: smaller, then cut with "…"); a text that had to be CUT * is a failure too (a menu row, a button, a tab must say it all), and in English no French text may be left. */final class RevisitedOverflowTest extends GameTestCase{    /** @var list<string> */    private array $overflows = [];    /** @var array<string, string> text => where */    private array $cuts = [];    /** @var array<string, string> */    private array $french = [];    private int $records = 0;    private int $screens = 0;    private string $where = '';    protected function tearDown(): void    {        Canvas::$record = null;        Translator::setLang('fr');        parent::tearDown();    }    /** @return list<array{0: string, 1: bool, 2: ?float}> lang, touch, uiscale */    public static function layouts(): array    {        return [['fr', false, null], ['en', false, null], ['fr', true, 0.54], ['en', true, 0.54]];    }    public function testNoTextOverflowsItsBoxOnAnyScreenInBothLanguagesOnDesktopAndPhone(): void    {        $t0 = microtime(true);        foreach (self::layouts() as [$lang, $touch, $scale]) {            $this->walk($lang, $touch, $scale);        }        $report = sprintf("\n[overflow] %d screens, %d texts drawn, %d overflows, %d cut, %d French left in English (%.1f s)\n",            $this->screens, $this->records, count($this->overflows), count($this->cuts), count($this->french), microtime(true) - $t0);        foreach (array_slice($this->overflows, 0, 40) as $o) {            $report .= "  overflow  $o\n";        }        foreach (array_slice($this->cuts, 0, 300, true) as $t => $w) {            $report .= "  cut       $w  «{$t}»\n";        }        foreach (array_slice($this->french, 0, 300, true) as $t => $w) {            $report .= "  french    $w  «{$t}»\n";        }        fwrite(STDERR, $report);        self::assertGreaterThan(100, $this->screens);        self::assertSame([], $this->overflows, $report);        self::assertSame([], $this->cuts, $report);        self::assertSame([], $this->french, $report);    }    private function call(string $method, mixed ...$args): mixed    {        $scene = $this->game->scene();        $m = new \ReflectionMethod($scene, $method);        return $m->invoke($scene, ...$args);    }    private function set(string $field, mixed $value, ?object $on = null): void    {        $on ??= $this->game->scene();        $p = new \ReflectionProperty($on, $field);        $p->setValue($on, $value);    }    /** Draws one frame with the record on and checks every text of it. */    private function snap(string $screen, int $frames = 1): void    {        if ($frames > 1) {            $this->game->run($frames - 1);        }        Canvas::$record = [];        Canvas::$recordBoxes = [];        $this->game->run(1);        $records = Canvas::$record;        $boxes = Canvas::$recordBoxes;        Canvas::$record = null;        Canvas::$recordBoxes = [];        $this->screens++;        $where = $this->where . ' | ' . $screen;        // the boxes themselves (slots, rows): inside the panel they stand in        foreach ($boxes as $b) {            [$x, , $w] = $b['box'];            [$px, , $pw] = $b['parent'];            if ($x < $px - 0.5 || $x + $w > $px + $pw + 0.5) {                $this->overflows[] = sprintf('%s  box x %.0f..%.0f out of its panel %.0f..%.0f', $where, $x, $x + $w, $px, $px + $pw);            }        }        foreach ($records as $r) {            $this->records++;            [$bx, , $bw] = $r['box'];            if ($r['x'] < $bx - 0.5 || $r['x'] + $r['w'] > $bx + $bw + 0.5) {                $this->overflows[] = sprintf('%s  «%s» x %.0f w %.0f, box %.0f..%.0f', $where, $r['text'], $r['x'], $r['w'], $bx, $bx + $bw);            }            if ($r['cut']) {                $this->cuts[$r['full']] ??= $where;            }            if (Translator::lang() === 'en' && self::looksFrench($r['full'])) {                $this->french[$r['full']] ??= $where;            }        }    }    private static function looksFrench(string $text): bool    {        if (mb_strlen($text) < 3) {            return false;       // a key of the on-screen keyboard (é, à, ç)        }        if (!preg_match('/[àâçéèêëîïôûùœ]|\b(le|la|les|des|du|une|est|avec|pour|dans|sur|tu|ton|ta|tes)\b/iu', $text)) {            return false;        }        // names and places keep their accents (Maëva, Nadjé, Aïka), as the English dictionary does        $plain = preg_replace('/Maëva|Nadjé|Aïka|Iréna|Français|Expérience|Rôdeur|Mérid/u', '', $text) ?? $text;        if (!preg_match('/[àâçéèêëîïôûùœ]|\b(le|la|les|des|du|une|est|avec|pour|dans|tu|ton|ta|tes)\b/iu', $plain)) {            return false;        }        return !Translator::knows($text);    }    private function begin(string $lang, bool $touch, ?float $scale, array $more = []): Game    {        $params = ['seed' => 7, 'new' => true, 'help' => false, 'lang' => $lang, 'touch' => $touch] + $more;        if ($scale !== null) {            $params['uiscale'] = $scale;        }        $this->game->start(RevisitedScene::class, $params);        $this->game->run(4);        return $this->game->peek('game');    }    private function walk(string $lang, bool $touch, ?float $scale): void    {        $this->where = $lang . ' ' . ($touch ? 'phone' : 'desktop');        $g = $this->begin($lang, $touch, $scale);        self::assertSame($lang, Translator::lang());        // the HUD: wounds, conditions, a long log, a toast        $g->hitPlayer('rleg', 'bite', 0.6, \App\Revisited\Land\Wildlife::the('stalker', true));        $g->body->wound('larm', 'fracture', 0.5);        $g->body->poison(0.4);        $g->give('flint', 2);        $g->say('Tu te sens plus endurant : +5 %');        $this->snap('hud', 20);        // the combat mode: a crawler winding up its bite, the precision cursor, popups        $this->combatHud($g);        // menus        foreach ([['titleMenu', 'title'], ['pauseMenu', 'pause'], ['optionsMenu', 'options'], ['deathMenu', 'death'], ['victoryMenu', 'victory']] as [$m, $name]) {            $m === 'optionsMenu' ? $this->call($m, 'pause') : $this->call($m);            $this->snap($name, 2);        }        $this->call('askLeave', function (): void {        });        $this->snap('ask leave');        $this->call('optionsMenu', 'title');        $this->snap('options (title)');        foreach ([false, true] as $t) {            $this->call('setTouch', $t);            $this->call('openControls', 'pause');            $this->snap('controls ' . ($t ? 'touch' : 'keys'));        }        $this->call('setTouch', $touch);        // the screens        $this->set('mode', 'play');        $this->call('pauseMenu');        $this->set('mode', 'play');        $this->screensWalk($g, $touch);        // a chest's transfer screen: both sides, a message, an empty chest        $this->chestWalk($g);        // the gauges' menus and the sleep        $this->set('mode', 'play');        foreach (array_merge(array_map(fn ($k) => 'vital:' . $k, array_keys(Hud::VITALS)), array_keys(VitalMenu::COND_KEY)) as $hit) {            $this->call('openVitals', $g, $hit, 300.0);            $this->snap('vital ' . $hit);            $this->game->peek('vitals')->close();        }        $this->set('mode', 'play');        $this->call('openSleep', $g);        $this->snap('sleep choose');        $sv = $this->game->peek('sleepView');        $sv->phase = 'woke';        $sv->summary = 'Tu dors 7 h 30. Réveil : Jour 2, 06:30. Repos +62.';        $this->snap('sleep summary');        $this->set('mode', 'play');        // saves: load, save, rename, the questions        $this->set('demoSaves', 6);        $this->set('demoScreen', 'load');        $this->call('makeDemoSaves', $g);        $this->snap('saves load', 2);        /** @var SaveScreen $ss */        $ss = $this->game->peek('saveScreen');        $ss->sel = 1;        $this->snap('saves load row 2');        $this->call('openSaves', 'save', 'pause');        $this->snap('saves save', 2);        foreach (['overwrite', 'delete', 'leave'] as $kind) {            $ss->ask = ['kind' => $kind, 'key' => '2', 'yes' => false];            $this->snap('saves ask ' . $kind);        }        $ss->ask = null;        $ss->startRename('2');        $this->snap('saves rename');        $ss->edit = null;        $this->set('mode', 'play');        // a conversation with each of the people, every node reachable from its root        $this->dialogues($g);    }    private function screensWalk(Game $g, bool $touch): void    {        /** @var Screens $s */        $s = $this->game->peek('screens');        // one item of each kind, the longest names (both languages)        $byKind = [];        foreach (Items::all() as $id) {            $it = Items::get($id);            $len = max(mb_strlen((string) $it['name']), mb_strlen(Translator::t((string) $it['name'])));            $k = (string) $it['kind'];            $byKind[$k][] = [$len, $id];        }        foreach ($byKind as $k => $list) {            rsort($list);            foreach (array_slice($list, 0, 2) as [, $id]) {                $g->give($id);            }        }        $this->set('mode', 'screen');        $s->open('inventory');        $this->snap('inventory', 2);        $items = $this->game->peek('items', $s);        foreach ($items as $i => $id) {            if ($touch) {                $s->pDetail = $id;            } else {                $s->invSel = $i;            }            $this->snap('inventory ' . $id);        }        $s->pDetail = null;        $s->open('craft');        $this->snap('craft', 2);        foreach (array_keys(Crafting::recipes()) as $i) {            if ($touch) {                $s->pDetail = (string) $i;            } else {                $s->craftSel = $i;            }            $this->snap('craft ' . $i);        }        $s->pDetail = null;        $s->open('body');        foreach (['dressed', 'medical'] as $view) {            foreach (range(0, 5) as $part) {                $s->bodyView = $view;                $s->part = $part;                $this->snap("body $view $part");            }        }        if ($touch) {            foreach (['head', 'torso', 'larm', 'rarm', 'lleg', 'rleg'] as $p) {                $s->pDetail = $p;                $this->snap("body page $p");            }            $s->pDetail = null;        }        // the talents: points to spend, some ranks, every card / page        $g->talents->gain(\App\Revisited\Sim\Talents::total(6) - $g->talents->xp);        $g->talents->learn('power');        $g->talents->learn('footwork');        $g->talents->learn('footwork');        $s->open('talents');        $this->snap('talents', 2);        foreach (array_keys(\App\Revisited\Sim\Talents::TREE) as $id) {            if ($touch) {                $s->pDetail = $id;            } else {                foreach (\App\Revisited\Ui\TalentsView::columns() as $ci => $list) {                    if (in_array($id, $list, true)) {                        $s->talentsView->col = $ci;                        $s->talentsView->row = (int) array_search($id, $list, true);                    }                }            }            $this->snap('talent ' . $id);        }        $s->pDetail = null;        $g->talents->gain(\App\Revisited\Sim\Talents::total(20));        $s->open('talents');        $this->snap('talents max', 2);        $s->open('scanner');        foreach (['radar', 'gps'] as $page) {            $s->scanPage = $page;            $this->snap('scanner ' . $page, 2);        }        $s->open('map');        $this->snap('map', 2);        $s->open('journal');        $this->snap('journal', 2);        $this->set('mode', 'play');    }    private function combatHud(Game $g): void    {        $c = \App\Revisited\Land\Wildlife::make($g, 'glacier_brute', $g->x + sin($g->yaw) * 1.6, $g->z + cos($g->yaw) * 1.6);        $c->health = 900;        $c->cooldown = 999;        $g->creatures = [$c];        $g->combat->engage($g, $c);        $c->data['wu'] = 0.4;        $c->data['wuT'] = 0.85;        $g->combat->popup('CRITIQUE ×1,5', [255, 120, 90]);        $g->combat->popup('Esquivé !', [140, 220, 255]);        $g->give('club');        $g->useItem('club');        $g->attackCoolReset();        $g->swing();        $this->snap('combat hud');        foreach (['charge', 'keep', 'flee'] as $state) {            unset($c->data['wu']);            $c->state = $state === 'charge' ? 'hunt' : $state;            $c->x = $g->x + sin($g->yaw) * 6;            $c->z = $g->z + cos($g->yaw) * 6;            $this->snap('combat ' . $state);        }        $g->creatures = [];        $g->swing = null;        $g->combat->disengage();    }    private function chestWalk(Game $g): void    {        $this->set('mode', 'play');        $cap = $g->inv->capacity();        $g->inv->setCapacity(9999.0);        foreach (['chest_metal', 'basket'] as $kind) {            $g->give($kind);            $text = Chests::place($g, $kind);            $t = Chests::inZone($g)[count(Chests::inZone($g)) - 1] ?? null;            self::assertNotNull($t, $text);            Chests::open($g, $t);            $this->call('openChest', $g);            $this->snap($kind . ' empty');            // the longest names in it            $byLen = Items::all();            usort($byLen, static fn ($a, $b) => mb_strlen(Translator::t(Items::name($b))) <=> mb_strlen(Translator::t(Items::name($a))));            foreach (array_slice($byLen, 0, 14) as $id) {                $g->inv->add($id, 3);                Chests::put($g, $t, $id, 2);            }            /** @var ChestView $v */            $v = $this->game->peek('chestView');            $this->snap($kind . ' bag');            $v->side = 'box';            $this->snap($kind . ' box');            $this->game->press('rv_drop', 1);            $this->snap($kind . ' note');            $this->game->press('rv_prev', 1);            $this->snap($kind . ' full note');            Chests::close($g);            $this->set('mode', 'play');        }        $g->inv->setCapacity($cap);    }    private function dialogues(Game $g): void    {        $talk = new \ReflectionProperty($g, 'talk');        $id = 900;        foreach (array_keys(People::WHO) as $key) {            $npc = new Npc(++$id, People::name($key), People::group($key), $g->x + 1.5, $g->y, $g->z + 1.5);            $npc->data['key'] = $key;            $g->npcs[] = $npc;            $g->talkTo($npc);            $todo = ['root'];            $done = [];            while ($todo && count($done) < 40) {                $node = array_shift($todo);                if (isset($done[$node])) {                    continue;                }                $done[$node] = true;                $talk->setValue($g, ['id' => $npc->id, 'node' => $node, 'say' => null]);                $this->snap("talk $key $node");                foreach (Talk::node($g, $npc, $node, null)['choices'] as $c) {                    if (str_starts_with($c[1], 'node:')) {                        $todo[] = substr($c[1], 5);                    }                }            }            $talk->setValue($g, null);            array_pop($g->npcs);        }    }}