-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobot.js
More file actions
63 lines (54 loc) · 1.57 KB
/
robot.js
File metadata and controls
63 lines (54 loc) · 1.57 KB
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
class Robot {
constructor(gridSize, initialColor) {
this.paintedPanels = new Set();
this.grid = initGrid(gridSize);
this.x = Math.floor(gridSize / 2);
this.y = Math.floor(gridSize / 2);
this.directionAngle = 90;
this.color = initialColor;
this.waitingColor = true;
this.processInput = function (input) {
if (this.waitingColor) {
this.color = input;
}
else {
this.move(input);
}
}
this.move = function (turnVal) {
this.directionAngle = ((turnVal === 0 ? this.directionAngle + 90 : this.directionAngle - 90) + 360) % 360;
switch (this.directionAngle) {
case 0:
this.x++;
break;
case 90:
this.y--;
break;
case 180:
this.x--;
break;
case 270:
this.y++;
break;
default: throw ('Incorrect angle');
}
this.waitingColor = true;
}
}
get color() {
return this.grid[this.y][this.x];
}
set color(color) {
if (this.color !== color) {
this.paintedPanels.add(`${this.x},${this.y}`);
}
this.grid[this.y][this.x] = color;
this.waitingColor = false;
}
}
function initGrid(size) {
return Array(size)
.fill(null)
.map(_ => Array(size).fill(0));
}
module.exports = Robot;