Snake Game Right Position For Tail

Someone can explain to me how I can do to create new tail parts near the head of the snake, because new parts appear at 0/0

var makeAStep = function() {
if (snake.detectCollision(snake.velocity) === true) {
    alert("You Loose, what a pity!");
    clearInterval(intervalHandler);
    return;
}

var lastItemPosition = snake.body[snake.body.length - 1].position.copy();

snake.move();

if (snake.getHead().isOnPosition(food.position)) {
    food.updateScore();
    generateFood();
    snake.body.push(new snakeItem(lastItemPosition));
}

snake.screenUpdate();

violin with all the code.

I think I need to edit something here:

screenUpdate: function() {
    var offset = 0;
    var currentNode = null;
    for (i in this.body) {
        offset = 3 + parseInt(i);
        currentNode = $('#box :nth-child(' + offset + ')');

        if (currentNode.size() == 0)
            $('#box').append($('<div class="snakeItem"></div>'));

        currentNode.animate({top: $('#head').height() * this.body[i].position.y + "px"}, duration / 3);
        currentNode.animate({left: $('#head').width() * this.body[i].position.x + "px"}, duration / 3);
    }
+4
source share
2 answers

Your problem is the features .animate()you use in snake.screenUpdate(). For example, if you change them to .css(), you will see new items right in place. This, of course, would ruin the smooth movement of the rest of the snake, so you might want to treat things differently, for example:

for (i in this.body) {
    offset = 3 + parseInt(i);
    currentNode = $('#box :nth-child(' + offset + ')');

    if (currentNode.size() == 0) {
        $('#box').append($('<div class="snakeItem"></div>'));
        currentNode = $('#box :nth-child(' + offset + ')');
        currentNode.css({top: $('#head').height() * this.body[i].position.y + "px"}, duration / 3);
        currentNode.css({left: $('#head').width() * this.body[i].position.x + "px"}, duration / 3);
    } else {
        currentNode.animate({top: $('#head').height() * this.body[i].position.y + "px"}, duration / 3);
        currentNode.animate({left: $('#head').width() * this.body[i].position.x + "px"}, duration / 3);
    }
}

This should work if I understood your violin correctly.

+3
$('#box').append($('<div class="snakeItem"></div>'));

Replace above code with following code.

var element = $('#box').find(".snakeItem").last();
var elementtop= $(testelement).css( "top");
var elementleft= $(testelement).css( "left");

$("<div>", {
'class': "snakeItem",
css: {
    "top": elementtop,
    "left":elementleft
}
}).appendTo($('#box'));
+1

Source: https://habr.com/ru/post/1535712/


All Articles