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);