@@ -115,7 +115,9 @@ SNAKE.Snake = SNAKE.Snake || (function() {
115115 playingBoard = config . playingBoard ,
116116 myId = instanceNumber ++ ,
117117 growthIncr = 5 ,
118- lastMove = 1 ;
118+ lastMove = 1 ,
119+ preMove = - 1 ,
120+ isFirstMove = true ,
119121 currentDirection = - 1 , // 0: up, 1: left, 2: down, 3: right
120122 columnShift = [ 0 , 1 , 0 , - 1 ] ,
121123 rowShift = [ - 1 , 0 , 1 , 0 ] ,
@@ -233,32 +235,35 @@ SNAKE.Snake = SNAKE.Snake || (function() {
233235 //console.log("lastmove="+lastMove);
234236 //console.log("dir="+keyNum);
235237
238+ let directionFound = - 1 ;
239+
236240 switch ( keyNum ) {
237241 case 37 :
238242 case 65 :
239- if ( lastMove !== 1 || snakeLength === 1 ) {
240- currentDirection = 3 ;
241- }
243+ directionFound = 3 ;
242244 break ;
243245 case 38 :
244246 case 87 :
245- if ( lastMove !== 2 || snakeLength === 1 ) {
246- currentDirection = 0 ;
247- }
247+ directionFound = 0 ;
248248 break ;
249249 case 39 :
250250 case 68 :
251- if ( lastMove !== 3 || snakeLength === 1 ) {
252- currentDirection = 1 ;
253- }
251+ directionFound = 1 ;
254252 break ;
255253 case 40 :
256254 case 83 :
257- if ( lastMove !== 0 || snakeLength === 1 ) {
258- currentDirection = 2 ;
259- }
255+ directionFound = 2 ;
260256 break ;
261257 }
258+ if ( currentDirection !== lastMove ) // Allow a queue of 1 premove so you can turn again before the first turn registers
259+ {
260+ preMove = directionFound ;
261+ }
262+ if ( Math . abs ( directionFound - lastMove ) !== 2 && isFirstMove ) // Prevent snake from turning 180 degrees
263+ {
264+ currentDirection = directionFound ;
265+ isFirstMove = false ;
266+ }
262267 } ;
263268
264269 /**
@@ -286,7 +291,13 @@ SNAKE.Snake = SNAKE.Snake || (function() {
286291
287292 if ( currentDirection !== - 1 ) {
288293 lastMove = currentDirection ;
294+ if ( preMove !== - 1 ) // If the user queued up another move after the current one
295+ {
296+ currentDirection = preMove ; // Execute that move next time (unless overwritten)
297+ preMove = - 1 ;
298+ }
289299 }
300+ isFirstMove = true ;
290301
291302 newHead . col = oldHead . col + columnShift [ lastMove ] ;
292303 newHead . row = oldHead . row + rowShift [ lastMove ] ;
@@ -371,6 +382,8 @@ SNAKE.Snake = SNAKE.Snake || (function() {
371382 */
372383 me . rebirth = function ( ) {
373384 isDead = false ;
385+ isFirstMove = true ;
386+ preMove = - 1 ;
374387 } ;
375388
376389 /**
0 commit comments