-
Notifications
You must be signed in to change notification settings - Fork 0
/
robot.js
89 lines (82 loc) · 1.77 KB
/
robot.js
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
'use strict';
function Robot() {
this.x = null;
this.y = null;
this.orientation = null;
this.maze = null;
}
Robot.prototype.setMaze = function (maze) {
this.maze = maze;
this.x = maze.startX;
this.y = maze.startY;
this.orientation = maze.startOrientation;
};
Robot.prototype.turnRight = function () {
if(!this.maze || !this.maze.isValidDirection(this.orientation)){
return false;
}
var rights = {
north: 'east',
east: 'south',
south: 'west',
west: 'north',
}
this.orientation = rights[this.orientation];
return true;
}
Robot.prototype.turnLeft = function () {
if(!this.maze || !this.maze.isValidDirection(this.orientation)){
return false;
}
var lefts = {
north: 'west',
east: 'north',
south: 'east',
west: 'south',
}
this.orientation = lefts[this.orientation];
return true;
}
Robot.prototype.moveForward = function () {
if(!this.canMoveForward()){
return false;
}
switch (this.orientation) {
case 'north':
this.y++;
break;
case 'east':
this.x++;
break;
case 'south':
this.y--;
break;
case 'west':
this.x--;
break;
}
return true;
}
Robot.prototype.canMoveForward = function (){
if(!this.maze){
return false;
}
return this.maze.canMove(this.x, this.y, this.orientation);
}
Robot.prototype.exitMaze = function (steps) {
if(this.maze){
while (steps != 0) {
steps--;
if (this.canMoveForward()) {
this.moveForward();
this.turnLeft();
}else {
this.turnRight();
}
if (this.x == this.maze.endX && this.y == this.maze.endY) {
return true;
}
}
return false;
}
}