-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToyRobot.php
101 lines (88 loc) · 3.35 KB
/
ToyRobot.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
<?php
class ToyRobot
{
private $x;
private $y;
private $facing;
private $directions = ['NORTH', 'EAST', 'SOUTH', 'WEST'];
public const TABLE_WIDTH = 5;
public const TABLE_HEIGHT = 5;
public const NOT_PLACED = -1;
public function __construct() {
// Within the constructor, the robot has not been placed on the table yet.
$this->x = self::NOT_PLACED;
$this->y = self::NOT_PLACED;
$this->facing = '';
}
public function placeRobot($x, $y, $facing) {
if ($this->isValidPosition($x, $y) && in_array($facing, $this->directions)) {
$this->x = $x;
$this->y = $y;
$this->facing = $facing;
}
}
public function moveRobot() {
if (!$this->isPlaced()) {
return "Invalid Move. The Robot is not placed on the table.";
} else {
$newX = $this->x;
$newY = $this->y;
switch ($this->facing) {
case 'NORTH':
$newY++;
break;
case 'EAST':
$newX++;
break;
case 'SOUTH':
$newY--;
break;
case 'WEST':
$newX--;
break;
}
if (!$this->isValidPosition($newX, $newY)) {
return "Silly Robot..... You Are Going To Fall.";
} else {
$this->x = $newX;
$this->y = $newY;
}
}
}
public function leftTurnRobot() {
// turns the direction the robot is facing 90 degrees left.
if (!$this->isPlaced()) {
return "Invalid Turn. Robot is not placed on the table.";
} else {
$currentDirection = array_search($this->facing, $this->directions);
$newDirection = ($currentDirection + 3) % 4;
$this->facing = $this->directions[$newDirection];
}
}
public function rightTurnRobot() {
// turns the direction the robot is facing 90 degrees right.
if (!$this->isPlaced()) {
return "Invalid Turn. Robot is not placed on the table.";
} else {
$currentDirection = array_search($this->facing, $this->directions);
$newDirection = ($currentDirection + 1) % 4;
$this->facing = $this->directions[$newDirection];
}
}
public function report() {
// Output of where robot is sitting on the table when called.
if (!$this->isPlaced()) {
return "No Report Avaliable. Robot is not placed on the table.";
} else {
return "{$this->x},{$this->y},{$this->facing}";
}
}
private function isValidPosition($x, $y) {
// Checks if x & y are within the table width (less than 4 but greater than 0)
return $x >= 0 && $x < self::TABLE_WIDTH && $y >= 0 && $y < self::TABLE_HEIGHT;
}
private function isPlaced() {
// Checks if the robot has been placed on the table. Coordinates will be between 0-4)
return $this->x !== self::NOT_PLACED && $this->y !== self::NOT_PLACED;
}
}