-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathrobot.js
More file actions
120 lines (103 loc) · 2.46 KB
/
robot.js
File metadata and controls
120 lines (103 loc) · 2.46 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
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
(function () {
'use strict';
const board = [
['.', '.', '.', '.','.'],
['.', '.', '.', '.','.'],
['R', '.', '.', '.','F'],
['.', 'A', 'A', 'A','.'],
['.', '.', '.', '.','.']
];
const robot = {
x: 0,
y: 2,
dir: 'right',
};
let flagReached = false;
let appleEaten = false;
let applesEaten = 0;
let moves = 0;
board.reverse();
const trailIndicators = {
left: '←',
right: '→',
up: '↑',
down: '↓'
};
function render() {
console.log('\n ' + moves + ':');
for (let row = board.length - 1; row >= 0; row--) {
const cells = board[row];
let line = '';
for (let col = 0; col < cells.length; col++) {
line += ' ' + cells[col] + ' ';
}
console.log(line);
}
if (appleEaten) { console.log('YUM!');}
if (flagReached) {
console.log('\nHurray! Flag reached in ' + moves + ' steps!' + "I ate " + applesEaten +" apples");
}
}
function move() {
let x = robot.x;
let y = robot.y;
switch (robot.dir) {
case 'up':
y = y < board.length - 1 ? y + 1 : y;
break;
case 'down':
y = y > 0 ? y - 1 : y;
break;
case 'left':
x = x > 0 ? x - 1 : x;
break;
case 'right':
x = x < board[y].length - 1 ? x + 1 : x;
break;
}
const cellContents = board[y][x];
if (cellContents === '.' || cellContents === 'A' || cellContents === 'F') {
board[robot.y][robot.x] = trailIndicators[robot.dir];
robot.x = x;
robot.y = y;
board[y][x] = 'R';
if (cellContents === 'A') {
appleEaten = true;
applesEaten ++;}
if (cellContents === 'F') {
flagReached = true;
}
}
moves += 1;
render();
}
function turn(turnDirection) {
if (turnDirection !== 'left' && turnDirection !== 'right') {
console.log('ignoring invalid turn', turnDirection);
}
switch (robot.dir) {
case 'up':
robot.dir = turnDirection === 'left' ? 'left' : 'right';
break;
case 'down':
robot.dir = turnDirection === 'left' ? 'right' : 'left';
break;
case 'left':
robot.dir = turnDirection === 'left' ? 'down' : 'up';
break;
case 'right':
robot.dir = turnDirection === 'left' ? 'up' : 'down';
break;
}
}
render();
turn('right');
move();
turn("left");
move();
move();
move();
move();
turn('left');
move();
})();