Skip to content

Commit 51cac32

Browse files
committedMar 11, 2024·
Debugged an issue
1 parent 4a43905 commit 51cac32

File tree

1 file changed

+39
-16
lines changed

1 file changed

+39
-16
lines changed
 

‎index.js

+39-16
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,40 @@ let appleY = 5;
2323
let xVelocity = 0;
2424
let yVelocity = 0;
2525

26+
let inputXVelocity = 0;
27+
let inputYVelocity = 0;
28+
2629
let score = 0;
2730
const gulpSound = new Audio("gulp.mp3");
31+
32+
let previousXVelocity = 0;
33+
let previousYVelocity = 0;
2834
//game loop
2935
function drawGame() {
36+
xVelocity = inputXVelocity;
37+
yVelocity = inputYVelocity;
38+
// was moving right and try to move left
39+
if (previousXVelocity === 1 && xVelocity === -1) {
40+
xVelocity = previousXVelocity;
41+
}
42+
// was moving left and try to move right
43+
if (previousXVelocity === -1 && xVelocity === 1) {
44+
xVelocity = previousXVelocity;
45+
}
46+
// was moving up and try to move down
47+
if (previousYVelocity === 1 && yVelocity === -1) {
48+
yVelocity = previousYVelocity;
49+
}
50+
// was moving down and try to move up
51+
if (previousYVelocity === -1 && yVelocity === 1) {
52+
yVelocity = previousYVelocity;
53+
}
54+
previousXVelocity = xVelocity;
55+
previousYVelocity = yVelocity;
3056
changeSnakePosition();
3157
let result = isGameOver();
3258
if (result) {
59+
document.removeEventListener("keydown", keydown);
3360
return;
3461
}
3562
clearScreen();
@@ -126,28 +153,24 @@ function checkAppleCollision() {
126153
document.addEventListener("keydown", keydown);
127154
function keydown(event) {
128155
// up
129-
if (event.keyCode == 38) {
130-
if (yVelocity == 1) return;
131-
yVelocity = -1;
132-
xVelocity = 0;
156+
if (event.keyCode == 38 || event.keyCode == 87) {
157+
inputYVelocity = -1;
158+
inputXVelocity = 0;
133159
}
134160
// down
135-
if (event.keyCode == 40) {
136-
if (yVelocity == -1) return;
137-
yVelocity = 1;
138-
xVelocity = 0;
161+
if (event.keyCode == 40 || event.keyCode == 83) {
162+
inputYVelocity = 1;
163+
inputXVelocity = 0;
139164
}
140165
// left
141-
if (event.keyCode == 37) {
142-
if (xVelocity == 1) return;
143-
yVelocity = 0;
144-
xVelocity = -1;
166+
if (event.keyCode == 37 || event.keyCode == 65) {
167+
inputYVelocity = 0;
168+
inputXVelocity = -1;
145169
}
146170
// right
147-
if (event.keyCode == 39) {
148-
if (xVelocity == -1) return;
149-
yVelocity = 0;
150-
xVelocity = 1;
171+
if (event.keyCode == 39 || event.keyCode == 68) {
172+
inputYVelocity = 0;
173+
inputXVelocity = 1;
151174
}
152175
}
153176

0 commit comments

Comments
 (0)
Please sign in to comment.