1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Kata\Rover\Domain\Model; |
4
|
|
|
|
5
|
|
|
class Position |
6
|
|
|
{ |
7
|
|
|
private $col; |
8
|
|
|
private $row; |
9
|
|
|
|
10
|
3 |
|
public function __construct(int $a_col, int $a_row) |
11
|
|
|
{ |
12
|
3 |
|
$this->col = $a_col; |
13
|
3 |
|
$this->row = $a_row; |
14
|
3 |
|
} |
15
|
|
|
|
16
|
4 |
|
public static function create(int $a_col, int $a_row): Position |
17
|
|
|
{ |
18
|
4 |
|
self::validate($a_col, $a_row); |
19
|
|
|
|
20
|
3 |
|
return new self($a_col, $a_row); |
21
|
|
|
} |
22
|
|
|
|
23
|
4 |
|
private static function validate(int $x, int $y): void |
24
|
|
|
{ |
25
|
4 |
|
if ($x < 0 || $y < 0) |
26
|
|
|
{ |
27
|
1 |
|
throw new \InvalidArgumentException('Invalid coordinates'); |
28
|
|
|
} |
29
|
3 |
|
} |
30
|
|
|
|
31
|
3 |
|
public function col(): int |
32
|
|
|
{ |
33
|
3 |
|
return $this->col; |
34
|
|
|
} |
35
|
|
|
|
36
|
3 |
|
public function row(): int |
37
|
|
|
{ |
38
|
3 |
|
return $this->row; |
39
|
|
|
} |
40
|
|
|
|
41
|
2 |
|
public function equals(Position $a_position): bool |
42
|
|
|
{ |
43
|
2 |
|
return $this->col === $a_position->col && $this->row === $a_position->row; |
44
|
|
|
} |
45
|
|
|
|
46
|
2 |
|
public function moveForward(Orientation $orientation): Position |
47
|
|
|
{ |
48
|
2 |
|
if ($orientation->isNorth()) |
49
|
|
|
{ |
50
|
1 |
|
return self::create($this->col, $this->row + 1); |
51
|
|
|
} |
52
|
2 |
|
if ($orientation->isSouth()) |
53
|
|
|
{ |
54
|
|
|
return self::create($this->col, $this->row - 1); |
55
|
|
|
} |
56
|
2 |
|
if ($orientation->isEast()) |
57
|
|
|
{ |
58
|
2 |
|
return self::create($this->col + 1, $this->row); |
59
|
|
|
} |
60
|
|
|
if ($orientation->isWest()) |
61
|
|
|
{ |
62
|
|
|
return self::create($this->col - 1, $this->row); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
public function moveBackward(Orientation $orientation): Position |
67
|
|
|
{ |
68
|
|
|
if ($orientation->isNorth()) |
69
|
|
|
{ |
70
|
|
|
return self::create($this->col, $this->row - 1); |
71
|
|
|
} |
72
|
|
|
if ($orientation->isSouth()) |
73
|
|
|
{ |
74
|
|
|
return self::create($this->col, $this->row + 1); |
75
|
|
|
} |
76
|
|
|
if ($orientation->isEast()) |
77
|
|
|
{ |
78
|
|
|
return self::create($this->col - 1, $this->row); |
79
|
|
|
} |
80
|
|
|
if ($orientation->isWest()) |
81
|
|
|
{ |
82
|
|
|
return self::create($this->col + 1, $this->row); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
} |