@@ -23,13 +23,40 @@ let appleY = 5;
23
23
let xVelocity = 0 ;
24
24
let yVelocity = 0 ;
25
25
26
+ let inputXVelocity = 0 ;
27
+ let inputYVelocity = 0 ;
28
+
26
29
let score = 0 ;
27
30
const gulpSound = new Audio ( "gulp.mp3" ) ;
31
+
32
+ let previousXVelocity = 0 ;
33
+ let previousYVelocity = 0 ;
28
34
//game loop
29
35
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 ;
30
56
changeSnakePosition ( ) ;
31
57
let result = isGameOver ( ) ;
32
58
if ( result ) {
59
+ document . removeEventListener ( "keydown" , keydown ) ;
33
60
return ;
34
61
}
35
62
clearScreen ( ) ;
@@ -126,28 +153,24 @@ function checkAppleCollision() {
126
153
document . addEventListener ( "keydown" , keydown ) ;
127
154
function keydown ( event ) {
128
155
// 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 ;
133
159
}
134
160
// 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 ;
139
164
}
140
165
// 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 ;
145
169
}
146
170
// 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 ;
151
174
}
152
175
}
153
176
0 commit comments