-
Notifications
You must be signed in to change notification settings - Fork 0
/
Map.php
130 lines (107 loc) · 3 KB
/
Map.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
declare(strict_types=1);
class Map
{
private array $rows;
private Justin $justin;
public function __construct(array $rows) {
$yPos = 0;
foreach ($rows as $row) {
$yPos++;
$xPos = 0;
foreach ($row as $tile) {
$xPos++;
if (!isset($this->rows[$yPos])) {
$this->rows[$yPos] = [];
}
$this->rows[$yPos][$xPos] = $tile;
$tile->setPosition($xPos, $yPos);
if ($tile instanceof Justin) {
$this->justin = $tile;
}
}
}
if (!$this->justin) {
throw new RuntimeException('Justin not found on map?');
}
}
public static function createFromFile(string $filePath): self
{
$rows = [];
$text = file_get_contents($filePath);
$lines = explode("\n", $text);
$i = 0;
$rowCount = count($lines);
foreach ($lines as $line) {
$i++;
$rows[] = self::createRow(
str_split($line),
$i === 1 || $i === $rowCount
);
}
return new self($rows);
}
public function draw(?Path $path = null): string
{
$output = chr(27) . "[0G";
$output .= chr(27) . sprintf("[%dA", count($this->rows));
foreach ($this->rows as $row) {
foreach ($row as $tile) {
if ($path && $path->contains($tile)) {
$output .= $path->getChar($tile);
} else {
$output .= $tile->getChar();
}
}
$output .= PHP_EOL;
}
return $output;
}
private static function createRow(array $chars, bool $firstOrLast): array
{
$row = [];
$i = 0;
$charCount = count($chars);
foreach ($chars as $char) {
$i++;
$row[] = TileFactory::createFromChar(
$char,
$firstOrLast || $i === 1 || $i === $charCount
);
}
return $row;
}
public function getSurroundingTiles(int $xPos, int $yPos): array
{
return [
DirectionOfTravel::NORTH => $this->getTile(
$xPos,
$yPos - 1
),
DirectionOfTravel::EAST => $this->getTile(
$xPos + 1,
$yPos
),
DirectionOfTravel::SOUTH => $this->getTile(
$xPos,
$yPos + 1
),
DirectionOfTravel::WEST => $this->getTile(
$xPos - 1,
$yPos
),
];
}
private function getTile($xPos, int $yPos): ?TileInterface
{
if (!array_key_exists($yPos, $this->rows)) {
return null;
}
$row = $this->rows[$yPos];
return $row[$xPos] ?? null;
}
public function getJustin(): Justin
{
return $this->justin;
}
}