Skip to content

Instantly share code, notes, and snippets.

@martypdx
Last active August 29, 2015 14:16
Show Gist options
  • Save martypdx/9f8420483ad3b089ea40 to your computer and use it in GitHub Desktop.
Save martypdx/9f8420483ad3b089ea40 to your computer and use it in GitHub Desktop.
animal race
<script>
function run(){
var adjustedSpeed = this.speed * Math.max( .5, Math.random() );
this.position += Math.floor( adjustedSpeed );
}
function fullName(){
return this.name + ' the ' + this.type;
}
function Animal(type, name, speed){
this.type = type;
this.name = name;
this.speed = speed;
this.position = 0;
this.run = run;
this.fullName = fullName;
}
var lizard = new Animal('lizard', 'leroy', 5);
var cat = new Animal('cat', 'cathy', 8);
var beetle = new Animal('beetle', 'bob', 2);
race([lizard, cat, beetle], 100);
function race(animals, distance){
function run(){
var animal, position, winner;
document.open();
for(var i = 0; i < animals.length; i++){
animal = animals[i];
animal.run();
if( animal.position >= distance ) {
winner = animal;
}
position = new Array(animal.position).join('-');
document.write('<p>' + position + animal.fullName() + '</p>');
}
document.close();
return winner;
}
var interval = setInterval(function(){
var animal = run();
if( animal ) {
clearInterval(interval);
alert('The winner of the ' + distance + ' unit dash is ' + animal.fullName());
}
}, 250);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment