Snake

by Trifan Alexandru

HTML

<div class="map">
    <div id="snake">
        <span class="trunk" data-id="0"></span>
    </div>
</div>

CSS

.map {
    position: relative;
    border: 1px solid;
    width: 300px;
    height: 300px;
}

#snake {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -4px;
    margin-top: -4px;
}

.trunk {
    position: absolute;
    background-color: black;
    width: 8px;
    height: 8px;
    display: inline-block;
}

JavaScript

function Snake() {
    this._snake = $('#snake');
    this._movement = [];
    this._timeout = [];
}

Snake.prototype._setup = function () {
    var self = this;
    $(document).keydown(function(ev) {
        var keyCode = ev.keyCode || ev.which,
        arrow = {left: 37, up: 38, right: 39, down: 40 };
        var destination = {
            direction: '',
            howMuch: ''
        };
        
        switch (keyCode) {
            case arrow.left:
                destination.direction = 'left';
                destination.howMuch = 8;
                break;
            case arrow.right:
                destination.direction = 'left';
                destination.howMuch = -8;
                break;
            case arrow.down:
                destination.direction = 'top';
                destination.howMuch = -8;
                break;
            case arrow.up:
                destination.direction = 'top';
                destination.howMuch = 8;
                break;
            default:
                destination.direction = 'top';
                destination.howMuch = 0;
                break;
        }
        self.move(ev, destination);
    });
}

Snake.prototype.move = function (ev, destination) {
    
    var lastChildIndex = this._snake.children().length;
    
    for(var i = lastChildIndex - 1; i >= 0; i--) {
        this._applyMovement(i, lastChildIndex, destination);
    }
        
}

Snake.prototype._applyMovement = function(bodyIndex, length, destination) {
    var self = this;
    var animationTimer = 40;
     var animation = {};
    console.log(bodyIndex);
    animation[destination.direction] = '-=' + destination.howMuch +  'px';
    this._timeout[bodyIndex] =  setTimeout(function () {
            if(self._movement[bodyIndex]) {
                clearInterval(self._movement[bodyIndex]);
            }
            self._movement[bodyIndex] = setInterval(
                function () {
                   ...