-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
201 lines (177 loc) · 6.79 KB
/
index.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
const main = () => {
const sideLength = +(localStorage.getItem('side-length') ?? 8);
const initialMoveDelay = +(localStorage.getItem('initial-delay') ?? 500);
const minMoveDelay = +(localStorage.getItem('min-delay') ?? 200);
// handle initial values change
const minSideLength = 2;
const maxSideLength = 30;
const sideLengthEl = document.getElementById('side');
sideLengthEl.innerText = sideLength;
const initialMoveDelayEl = document.getElementById('initial-delay');
initialMoveDelayEl.innerText = initialMoveDelay;
const minMoveDelayEl = document.getElementById('min-delay');
minMoveDelayEl.innerText = minMoveDelay;
sideLengthEl.onblur = evt => {
const value = +evt.target.innerText;
if (
Number.isNaN(value) ||
value < minSideLength ||
value > maxSideLength
) {
sideLengthEl.innerHTML = sideLength;
return;
}
if (value !== sideLength) {
localStorage.setItem('side-length', value);
window.location.reload();
}
};
initialMoveDelayEl.onblur = evt => {
const value = +evt.target.innerText;
if (Number.isNaN(value) || value < 50 || value > 1000) {
initialMoveDelayEl.innerHTML = initialMoveDelay;
return;
}
if (value !== initialMoveDelay) {
if (minMoveDelay > value) localStorage.setItem('min-delay', value);
localStorage.setItem('initial-delay', value);
window.location.reload();
}
};
minMoveDelayEl.onblur = evt => {
const value = +evt.target.innerText;
if (Number.isNaN(value) || value < 50 || value > initialMoveDelay) {
minMoveDelayEl.innerHTML = minMoveDelay;
return;
}
if (value !== minMoveDelay) {
localStorage.setItem('min-delay', value);
window.location.reload();
}
};
const LEFT = 'LEFT';
const TOP = 'TOP';
const RIGHT = 'RIGHT';
const BOTTOM = 'BOTTOM';
const moveDelayDelta = initialMoveDelay - minMoveDelay;
const emptyField = Array(sideLength)
.fill(null)
.map(_ => Array(sideLength).fill(null));
const getCurrentMoveDelay = score =>
initialMoveDelay - moveDelayDelta * (score / (sideLength ** 2 - 1));
const getNewHead = ([curRow, curCell], direction) => {
if (direction === RIGHT) {
let newCell = curCell + 1;
if (newCell === emptyField[0].length) newCell = 0;
return [curRow, newCell];
} else if (direction === LEFT) {
let newCell = curCell - 1;
if (newCell < 0) newCell = emptyField[0].length - 1;
return [curRow, newCell];
} else if (direction === BOTTOM) {
let newRow = curRow + 1;
if (newRow === emptyField.length) newRow = 0;
return [newRow, curCell];
} else if (direction === TOP) {
let newRow = curRow - 1;
if (newRow < 0) newRow = emptyField.length - 1;
return [newRow, curCell];
} else {
throw new Error(`Unknown direction ${direction}`);
}
};
const isValidDirection = (...directions) => {
return !(
directions[0] === directions[1] ||
directions.every(d => [LEFT, RIGHT].includes(d)) ||
directions.every(d => [TOP, BOTTOM].includes(d))
);
};
const copyField = field => [...field.map(arr => [...arr])];
const renderField = field => {
const fieldString = field
.map(arr => arr.map(val => (val === null ? '.' : val)).join(' '))
.join('\n');
document.getElementById('field').textContent = fieldString;
};
const renderScore = score =>
(document.getElementById('score').textContent = score);
const randomUpTo = max => Math.floor(Math.random() * max);
const getUnoccupiedCell = fieldWithSnake => {
const options = [];
for (let rowI = 0; rowI < fieldWithSnake.length; rowI++) {
for (let cellI = 0; cellI < fieldWithSnake[0].length; cellI++) {
if (fieldWithSnake[rowI][cellI]) continue;
options.push([rowI, cellI]);
}
}
return options[randomUpTo(options.length)];
};
const fruits = 'YOUAREAMAZINGSTRONGBRAVEANDWONDERFULREMEMBERTHATTODAY';
const getRandomFruit = score => fruits[score % fruits.length];
let score = 0;
let timeoutId;
let direction = RIGHT;
let fieldWithoutSnake = copyField(emptyField);
const snake = [getUnoccupiedCell(fieldWithoutSnake)];
document.body.onkeydown = ev => {
if (timeoutId) {
if (ev.key === ' ') {
clearTimeout(timeoutId);
timeoutId = undefined;
return;
}
const newDirection = {
ArrowRight: RIGHT,
ArrowLeft: LEFT,
ArrowUp: TOP,
ArrowDown: BOTTOM
}[ev.key];
if (newDirection && isValidDirection(direction, newDirection))
direction = newDirection;
return;
}
if (ev.key === ' ')
timeoutId = setTimeout(makeMove, getCurrentMoveDelay(score));
};
const makeMove = (forceCreateFruit = false) => {
const fieldWithSnake = copyField(fieldWithoutSnake);
const [headRow, headCell] = getNewHead(snake[0], direction);
const newHead = fieldWithoutSnake[headRow][headCell];
let ateFruit = false;
if (newHead) {
ateFruit = true;
score++;
renderScore(score);
fieldWithoutSnake[headRow][headCell] = null;
}
if (!ateFruit) snake.pop();
snake.unshift([headRow, headCell]);
let isFirst = true;
for (const [blockRow, blockCell] of snake) {
if (fieldWithSnake[blockRow][blockCell] === '@') {
if (confirm(`Game over. Score: ${score}! Try again?`))
window.location.reload();
return;
}
fieldWithSnake[blockRow][blockCell] = isFirst ? '@' : '#';
isFirst = false;
}
if (forceCreateFruit || ateFruit) {
const fruitLocation = getUnoccupiedCell(fieldWithSnake);
if (!fruitLocation) {
if (confirm(`You won. Score: ${score}! Try again?`))
window.location.reload();
return;
}
const [rowI, cellI] = fruitLocation;
const fruit = getRandomFruit(score);
fieldWithoutSnake[rowI][cellI] = fruit;
fieldWithSnake[rowI][cellI] = fruit;
}
renderField(fieldWithSnake);
timeoutId = setTimeout(makeMove, getCurrentMoveDelay(score));
};
makeMove(true);
};
main();