Maze::isCompletedBy()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\Puzzle\Maze;
4
5
use function array_map;
6
use function implode;
7
use const PHP_EOL;
8
9
final class Maze
10
{
11
    /** @var Goal */
12
    private $exit;
13
    /** @var Wall[] */
14
    private $walls;
15
16
    public function __construct(Goal $exit, Wall ...$walls)
17
    {
18
        $this->exit = $exit;
19
        $this->walls = $walls;
20
    }
21
22
    public static function withGoalAndWalls(Goal $exit, Wall ...$walls): self
23
    {
24
        return new self($exit, ...$walls);
25
    }
26
27
    public function isValidPosition(Hero $hero): bool
28
    {
29
        foreach ($this->walls as $wall) {
30
            if ($wall->blocks($hero->x(), $hero->y())) {
31
                return false;
32
            }
33
        }
34
        return true;
35
    }
36
37
    public function isCompletedBy(Hero $hero): bool
38
    {
39
        return $this->exit->isAt($hero->x(), $hero->y());
40
    }
41
42
    public function __toString(): string
43
    {
44
        $maze = [];
45
        $maxX = 0;
46
        $maxY = 0;
47
        foreach ($this->walls as $wall) {
48
            if ($wall->x() > $maxX) {
49
                $maxX = $wall->x();
50
            }
51
            if ($wall->y() > $maxY) {
52
                $maxY = $wall->y();
53
            }
54
        }
55
        for ($x = 0; $x < $maxX; ++$x) {
56
            for ($y = 0; $y < $maxY; ++$y) {
57
                $maze[$y][$x] = ' ';
58
            }
59
        }
60
        foreach ($this->walls as $wall) {
61
            $maze[$wall->y()][$wall->x()] = '#';
62
        }
63
        $maze[$this->exit->y()][$this->exit->x()] = 'X';
64
        return implode(PHP_EOL, array_map('implode', $maze));
65
    }
66
}
67