-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
124 lines (107 loc) · 3.19 KB
/
script.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
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
121
122
123
124
class RobotGridState {
constructor() {
let gridElement = document.querySelector('.grid');
let grid = [];
for(let i=0; i < 5; i++) {
let row = [];
for(let j=0; j < 5; j++) {
let square = document.createElement('div');
square.classList.add('grid__square');
gridElement.appendChild(square);
row.push(square);
}
grid.push(row);
}
this.UP = 'UP';
this.DOWN = 'DOWN';
this.LEFT = 'LEFT';
this.RIGHT = 'RIGHT';
this.state = {
grid: grid,
x: 2,
y: 2,
rotation: this.DOWN
};
this.state.grid[2][2].classList.add('robot');
}
move() {
let newX = this.state.x;
let newY = this.state.y;
switch(this.state.rotation) {
case this.UP:
if(this.state.y - 1 >= 0) {
newY -= 1;
}
break;
case this.DOWN:
if(this.state.y + 1 < 5) {
newY += 1;
}
break;
case this.LEFT:
if(this.state.x - 1 >= 0) {
newX -= 1;
}
break;
case this.RIGHT:
if(this.state.x + 1 < 5) {
newX += 1;
}
break;
}
Object.assign(this.state, {x: newX, y: newY});
this.updateGrid();
}
rotateLeft() {
let newRotation = this.state.rotation;
switch(this.state.rotation) {
case this.UP:
newRotation = this.LEFT;
break;
case this.DOWN:
newRotation = this.RIGHT;
break;
case this.LEFT:
newRotation = this.DOWN;
break;
case this.RIGHT:
newRotation = this.UP;
break;
};
Object.assign(this.state, {rotation: newRotation});
this.updateGrid();
}
rotateRight() {
let newRotation = this.state.rotation;
switch(this.state.rotation) {
case this.UP:
newRotation = this.RIGHT;
break;
case this.DOWN:
newRotation = this.LEFT;
break;
case this.LEFT:
newRotation = this.UP;
break;
case this.RIGHT:
newRotation = this.DOWN;
break;
};
Object.assign(this.state, {rotation: newRotation});
this.updateGrid();
}
updateGrid() {
document.querySelector('.robot').classList.remove('robot','up','down','left','right');
this.state.grid[this.state.y][this.state.x].classList.add('robot',this.state.rotation.toLowerCase());
}
}
let state = new RobotGridState();
document.getElementById('move').onclick = () => {
state.move();
};
document.getElementById('rotateLeft').onclick = () => {
state.rotateLeft();
};
document.getElementById('rotateRight').onclick = () => {
state.rotateRight();
};