-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
344 lines (311 loc) · 9.96 KB
/
script.js
File metadata and controls
344 lines (311 loc) · 9.96 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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
const maxX = 40;
const maxY = 40;
class Pair {
constructor(x, y) {
this.x = x;
this.y = y;
}
asText()
{
return JSON.stringify(this)
}
}
function modulo(a,b)
{
return (a+b) % b
}
function getPositionAfterDirection(pair, direction)
{
switch(direction)
{
case 0: return new Pair(modulo(pair.x+1, maxX), modulo(pair.y, maxY)) //right
case 1: return new Pair(modulo(pair.x, maxX), modulo(pair.y+1, maxY)) //down
case 2: return new Pair(modulo(pair.x-1, maxX), modulo(pair.y, maxY)) //left
case 3: return new Pair(modulo(pair.x, maxX), modulo(pair.y-1, maxY)) //up
default: throw new Error("Direction unknown! " + direction)
}
}
function getDirection(pair1, pair2)
{
for(let i=0;i<4;i++)
{
const newPair = getPositionAfterDirection(pair1, i);
if(pair2.asText() === newPair.asText())
return i;
}
throw new Error("Direction unknown!")
}
function initDisplay(maxX, maxY)
{
let display = []
for(let i=0;i<maxY;i++)
{
let line = []
for(let j=0;j<maxX;j++)
{
line.push(" ")
}
display.push(line)
}
return display
}
function getFruitPair(freeSpaces)
{
//run if this is efficient
if(freeSpaces.size > maxX * maxY / 40)
{
while(true)
{
const newFruitPair = new Pair(Math.floor(Math.random() * maxX), Math.floor(Math.random() * maxY))
if(freeSpaces.has(newFruitPair.asText()))
{
return newFruitPair
}
}
}
if(freeSpaces.size === 0)
return null
const freeSpacesEntries = Array.from(freeSpaces)
const randomPick = Math.floor(Math.random() * freeSpaces.size)
const pair = JSON.parse(freeSpacesEntries[randomPick])
return new Pair(pair.x, pair.y)
}
function getBlock(previousDirection, nextDirection)
{
const value = `${previousDirection}, ${nextDirection}`
switch (value)
{
case '0, 0': return '═'
case '2, 2': return '═'
case '1, 1': return '║'
case '3, 3': return '║'
case '0, 1': return '╗'
case '3, 2': return '╗'
case '0, 3': return '╝'
case '1, 2': return '╝'
case '2, 1': return '╔'
case '3, 0': return '╔'
case '1, 0': return '╚'
case '2, 3': return '╚'
default: throw new Error(`Cannot get block element ${value}`)
}
}
let toggle = 0
function getFruitCharacter()
{
toggle = modulo(toggle+1, 20)
return toggle >= 10 ? '▚' : '▞'
}
function getDisplayString(snakeBody, fruitPair)
{
const display = initDisplay(maxX, maxY)
for(let i=0;i<snakeBody.length;i++){
const piece = snakeBody[i]
if(i===snakeBody.length-1)
{
display[piece.y][piece.x] = '█'
}
else {
const lastPiece = (i!==0) ? snakeBody[i-1] : null
const nextPiece = snakeBody[i+1]
const nextDirection = getDirection(piece, nextPiece)
const previousDirection = lastPiece !== null ? getDirection(lastPiece,piece) : nextDirection
display[piece.y][piece.x] = getBlock(previousDirection, nextDirection)
}
}
if(fruitPair !== null)
display[fruitPair.y][fruitPair.x] = getFruitCharacter()
return display.map(x => x.join('')).join('\n')
}
function initStyles(gamebody)
{
const width = gamebody.getBoundingClientRect().width
const height = gamebody.getBoundingClientRect().height
const ratio = width / height
const scaleUp = 1
gamebody.style.transform = `scale(${scaleUp}, ${ratio * scaleUp})`
}
function init()
{
const snakeSize = 10;
const direction = Math.floor(Math.random() * 4)
const snakeOriginX = Math.floor(Math.random() * maxX)
const snakeOriginY = Math.floor(Math.random() * maxY)
const snakeBody = []
let pair = new Pair(snakeOriginX, snakeOriginY)
for(let i=0;i<snakeSize;i++)
{
snakeBody.push(pair)
pair = getPositionAfterDirection(pair, direction)
}
const snakeBodySet = new Set(snakeBody.map(x => x.asText()))
const freeSpaces = new Set()
for(let i=0;i<maxX;i++)
{
for(let j=0;j<maxY;j++)
{
const newPair = new Pair(i,j)
if(!snakeBodySet.has(newPair.asText()))
freeSpaces.add(newPair.asText())
}
}
let fruitPair = getFruitPair(freeSpaces)
const gamebody = document.getElementById("gamebody")
gamebody.innerHTML = getDisplayString(snakeBody, fruitPair)
initStyles(gamebody)
let gameOver = false
let leftPressed = false
let rightPressed = false
let downPressed = false
let upPressed = false
window.addEventListener("keydown", (event) => {
if (event.isComposing || event.keyCode === 229) {
return;
}
//event.preventDefault()
if(event.keyCode === 37) // left
leftPressed = true
if(event.keyCode === 38) // up
upPressed = true
if(event.keyCode === 39) // right
rightPressed = true
if(event.keyCode === 40) // down
downPressed = true
},{
capture: true,
});
window.addEventListener("keyup", (event) => {
if (event.isComposing || event.keyCode === 229) {
return;
}
if(event.keyCode === 37) // left
leftPressed = false
if(event.keyCode === 38) // up
upPressed = false
if(event.keyCode === 39) // right
rightPressed = false
if(event.keyCode === 40) // down
downPressed = false
});
// Swipe Handling for Mobile
let touchStartX = 0;
let touchStartY = 0;
let touchEndX = 0;
let touchEndY = 0;
window.addEventListener("touchstart", (event) => {
touchStartX = event.touches[0].clientX;
touchStartY = event.touches[0].clientY;
}, { passive: true });
window.addEventListener("touchend", (event) => {
touchEndX = event.changedTouches[0].clientX;
touchEndY = event.changedTouches[0].clientY;
handleSwipe();
}, { passive: true });
function handleSwipe() {
const deltaX = touchEndX - touchStartX;
const deltaY = touchEndY - touchStartY;
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
if (absDeltaX > absDeltaY) {
if (deltaX > 50) {
rightPressed = true;
setTimeout(() => rightPressed = false, 100); // reset
} else if (deltaX < -50) {
leftPressed = true;
setTimeout(() => leftPressed = false, 100);
}
} else {
if (deltaY > 50) {
downPressed = true;
setTimeout(() => downPressed = false, 100);
} else if (deltaY < -50) {
upPressed = true;
setTimeout(() => upPressed = false, 100);
}
}
}
let nextDirection = direction
let nextDirections = []
setInterval(() =>{
if(gameOver)
return
const lastDirection = nextDirection
//get next directions
if(nextDirections.length === 0)
{
nextDirections = []
if(leftPressed)
nextDirections.push(2)
if(upPressed)
nextDirections.push(3)
if(rightPressed)
nextDirections.push(0)
if(downPressed)
nextDirections.push(1)
if(nextDirections.length > 2)
nextDirections = []
}
//process directions
if(nextDirections.length > 0)
{
if(nextDirections.length === 1)
{
nextDirection = nextDirections.shift()
if(modulo(lastDirection - nextDirection, 4) === 2){
nextDirection = lastDirection
}
}
else if(nextDirections.length === 2 && nextDirections[0] === nextDirection)
{
nextDirection = nextDirections.pop()
if(modulo(lastDirection - nextDirection, 4) === 2){
nextDirection = lastDirection
}
}
else if(nextDirections.length === 2 && nextDirections[1] === nextDirection)
{
nextDirection = nextDirections.shift()
if(modulo(lastDirection - nextDirection, 4) === 2){
nextDirection = lastDirection
}
}
else if(nextDirections.length === 2)
{
const direction1 = nextDirections.shift()
const direction2 = nextDirections.pop()
if(modulo(lastDirection - direction1, 4) === 2){
nextDirection = direction2
nextDirections = [direction1]
}
if(modulo(lastDirection - direction2, 4) === 2){
nextDirection = direction1
nextDirections = [direction2]
}
}
}
const nextPair = getPositionAfterDirection(snakeBody[snakeBody.length - 1], nextDirection)
const nextPairString = nextPair.asText()
let foundSnack = false
if((fruitPair!== null) && (nextPairString === fruitPair.asText()))
{
foundSnack = true
}
else{
const firstPairOfSnakeBody = snakeBody.shift().asText()
snakeBodySet.delete(firstPairOfSnakeBody)
freeSpaces.add(firstPairOfSnakeBody)
}
if(snakeBodySet.has(nextPairString))
{
gameOver = true
}
snakeBody.push(nextPair)
snakeBodySet.add(nextPairString)
freeSpaces.delete(nextPairString)
if(foundSnack)
{
fruitPair = getFruitPair(freeSpaces)
}
gamebody.innerHTML = getDisplayString(snakeBody, fruitPair)
}, 30);
}