Last active
August 29, 2015 14:22
-
-
Save taddeimania/7b0512395f2e27b216e1 to your computer and use it in GitHub Desktop.
Bike Race OOP JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Bike = (function () { | |
var _bike; | |
_bike = function(opts) { | |
this.name = opts.name; | |
this.topSpeed = opts.topSpeed; | |
this.location = 0; | |
this.speed = 0; | |
}; | |
_bike.prototype.toString = function() { | |
return this.name + " - " + this.location + " - " + this.speed; | |
}; | |
_bike.prototype.accelerate = function() { | |
if (this.speed < this.topSpeed){ | |
this.speed = this.speed + 1; | |
} | |
}; | |
_bike.prototype.start = function() { | |
this.accelerate(); | |
}; | |
_bike.prototype.update = function() { | |
// something random? | |
this.location = this.location + (this.speed * Math.random()); | |
}; | |
return _bike; | |
})(); | |
var Race = (function () { | |
var _race; | |
_race = function(opts) { | |
this.racers = opts.racers; | |
this.start = 0; | |
this.finish = opts.finish || 100; | |
this.active = false; | |
this.winner = ""; | |
}; | |
_race.prototype.start = function() { | |
this.active = true; | |
for (var i = 0 ; i < this.racers.length ; i++){ | |
var currentRacer; | |
currentRacer = this.racers[i]; | |
currentRacer.start(); | |
currentRacer.update(); | |
} | |
}; | |
_race.prototype.beginRace = function() { | |
this.start(); | |
while (this.active){ | |
for (var i = 0 ; i < this.racers.length ; i++){ | |
var current_racer; | |
currentRacer = this.racers[i]; | |
if (currentRacer.location >= this.finish){ | |
this.winner = currentRacer; | |
this.stop(); | |
break; | |
} | |
currentRacer.update(); | |
} | |
} | |
}; | |
_race.prototype.stop = function() { | |
this.active = false; | |
console.log("STOP THE RACE! " + this.winner.name + " WON!!!") | |
for (var i = 0 ; i < this.racers.length ; i++){ | |
var current_racer; | |
currentRacer = this.racers[i]; | |
console.log(currentRacer); | |
} | |
}; | |
return _race; | |
})(); | |
var jeff = new Bike({name: "Jeff", topSpeed: 15}); | |
var joel = new Bike({name: "Joel", topSpeed: 12}); | |
var bekk = new Bike({name: "Bekk", topSpeed: 18}); | |
var race = new Race({racers: [jeff, joel, bekk], finish: 100}); | |
race.beginRace(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment