1

I'm a jQuery/javascript beginner and for fun I'm trying to make a snake game. I think I'm pretty close to getting movement except when I change directions via keyboard arrows, it's not working how I'd expect. For example, the snake will automatically start moving right. If I hit down it will go down BUT still continue to go right. If I hit left, it'll go left but continue to go down.

This might be just a fundamental error in my code or something more obvious.

JSFiddle: http://jsfiddle.net/zgjg6914/

var direction = 'left';
var plusOrMinus = '+=25px';

// create the object literal
var aniArgs = {}; 

function myFunction(){
    aniArgs[direction] = plusOrMinus;
    var posTop = $('.snake_bit').position().top + 25;
    var posLeft = $('.snake_bit').position().left + 25;
    if (posTop > 500 || posLeft > 500 || posTop < 25 || posLeft < 25) {
        gameOver();
        return;
    }
    $('.snake_bit').animate(aniArgs, 0);
    console.log('top: ' + posTop + ' left: ' + posLeft);
}
function gameOver(){
    clearInterval(theInterval);
    console.log('game over');
}

$(document).keydown(function(e){
    if (e.keyCode == 38) {
      direction = 'top';
      plusOrMinus = '-=25px';
    } else if (e.keyCode == 40) {
      direction = 'top';
      plusOrMinus = '+=25px';
    } else if (e.keyCode == 37) {
      direction = 'left';
      plusOrMinus = '-=25px';
    } else if (e.keyCode == 39) {
      plusOrMinus = '+=25px';
      direction = 'left';
    }
});

var theInterval = setInterval(myFunction, 1000);

2 Answers 2

2

The problem is, when you set a new direction, you leave the previous one in aniArgs.

Quick fix: in your keydown handler, in all of the ifs, you need to reset aniArgs.

if (e.keyCode == 38) {
    aniArgs = {};  // clear previous movement
    direction = 'top';
    plusOrMinus = '-=25px';
}

I updated your fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't think if it's good idea to use time interval to check any behaviour inside game. Read sth about preparing games with html5 canvas element (jquery will be also useful there) - imho it's more proper way to create games inside browser

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.