-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnimation.js
50 lines (43 loc) · 864 Bytes
/
Animation.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
document.addEventListener("keydown", handleKeyPressed);
var previousCommandTime = new Date();
function loop() {
drawCanvas();
drawFruit();
animateSnake();
eatFruit();
var detected = detectSnakeCollision();
if (detected) {
return;
} else {
requestAnimationFrame(loop);
}
}
function handleKeyPressed(e) {
if (e.defaultPrevented) {
return; // Do nothing if event already handled
}
currentClick = new Date();
if (currentClick.getTime() - previousCommandTime.getTime() < 10) {
return;
}
previousCommandTime = new Date();
switch (e.code) {
case "KeyS":
case "ArrowDown":
commandQueue.push('D');
break;
case "KeyW":
case "ArrowUp":
commandQueue.push('U');
break;
case "KeyA":
case "ArrowLeft":
commandQueue.push('L');
break;
case "KeyD":
case "ArrowRight":
commandQueue.push('R');
break;
}
}
loop();