$(document).ready(function() { console.log("ready"); var fruit = $("#fruit"); function setFruitCooridnates(){ var xFruit = Math.floor((Math.random()*10)+1)*4; var yFruit = Math.floor((Math.random()*10)+1)*4; var positionFruit = [xFruit,yFruit]; return positionFruit; } function drawFruit(newPositionFruit){ fruit.css({ 'left': newPositionFruit[0] + 'rem', 'top': newPositionFruit[1] + 'rem', }) } function eatFruit(){ var snake = $("#snake"); var fruit = $("#fruit"); var positionFruit = fruit.position(); var positionSnake = snake.position(); console.log(positionFruit.top); console.log(positionFruit.top); if(positionFruit.top == positionSnake.top && positionFruit.left == positionSnake.left){ snake.css({"width": '+=1rem'}); drawFruit(setFruitCooridnates()); } } function startGame(){ var dir = 'bottom'; setInterval(move = function() { var snake = $("#snake"); var fruit = $("#fruit"); if(dir == 'top') { snake.css({"top": '-=1em'}); eatFruit(); } if(dir == 'bottom') { snake.css({"top": '+=1em'}); eatFruit(); } if(dir == 'left') { snake.css({"left": '-=1em'}); eatFruit(); } if(dir == 'right') { snake.css({"left": '+=1em'}); eatFruit(); } }, 150); $(document).keydown(function(event){ if(event.which == 38) { dir = 'top'; } else if(event.which == 37) { dir = 'left'; } else if(event.which == 39) { dir = 'right'; } else if(event.which == 40) { dir = 'bottom'; }; }); } startGame(); eatFruit(); // moveSnake(); })