Avoid Obstacles Game

by Trifan Alexandru

HTML

<div class="road">
    <div class="car">
    </div>
</div>

CSS

.road {
    width: 400px;
    height: 450px;
    margin-left: auto;
    margin-right: auto;
    background-image: url(http://images.all-free-download.com/images/graphiclarge/passing_zone_117259.jpg);
    position: relative;
    overflow: hidden;
}
.car {
    width: 120px;
    height: 40px;
    position: absolute;
    bottom: 10px;
    left: 50%;
    margin-left: -60px;
    background-color: red;
}

.block {
    width: 30px;
    height: 30px;
    position: absolute;
    background-color: yellow;
    margin-left: -15px;
}
}

JavaScript

function Car() {
    this._car = $('.car');
}

Car._instance = null;

Car.get = function () {
    return Car._instance ||
        (Car._instance = new Car());
};

Car.prototype.changeCarPosition = function (event, destination) {
    
    var roadScreenXPosition = Road.get().getRoadScreenPosition().left,
        carDestinationX;
    if(!destination) {
        var screenOffsetX = event.pageX,
            clickLocation = screenOffsetX - roadScreenXPosition,
            carDestinationX;
        
        if(clickLocation > this.getCarPosition().left) {
            carDestinationX = clickLocation - this.getCarSize().width/2;
        } else {
            carDestinationX = clickLocation + this.getCarSize().width/2;    
        }
        
        this._car.animate({
            left: carDestinationX + 'px'
        },100);
    } else {
        this._car.animate({
        left: '-=' + destination +  'px'
    }, 0);
    }           
    
};

Car.prototype.getCarPosition = function () {
    return this._car.position();
};

Car.prototype.getCarSize = function () {
    var size = {
        width: this._car.width(),
        height: this._car.height()
    };
    
    return size;
};

function Road() {
    this._road = $('.road');
    this._setup();
}

Road._instance = null;

Road.get = function () {
    return Road._instance ||
        (Road._instance = new Road());
};

Road.prototype._setup = function () {
    var carInstance = Car.get();
    this._road.on('click', carInstance.changeCarPosition.
                  bind(carInstance));
    $(document).keydown(function(ev) {
        var keyCode = ev.keyCode || ev.which,
        arrow = {left: 37, up: 38, right: 39, down: 40 };
        
        switch (keyCode) {
            case arrow.left:
                Car.get().changeCarPosition(ev, 8);
                break;
            case arrow.right:
                Car.get().changeCarPosition(ev, -8);
                break;
        }
    });
}

Road.prototype.generateBlocks = function...