Skip to content

Instantly share code, notes, and snippets.

@bgerstle
Created October 5, 2013 16:05
Show Gist options
  • Save bgerstle/6842692 to your computer and use it in GitHub Desktop.
Save bgerstle/6842692 to your computer and use it in GitHub Desktop.
Beat JS Warrior!
var extensions = {
low_hp: 9,
check_actions: {
'enemy': 'attack',
'diamond': 'collect'
},
check_and_act: function (direction) {
var status = this.check(direction);
if(this.check_actions.hasOwnProperty(status)) {
var method = this.check_actions[status];
this[method](direction);
return status;
}
return false;
},
idle: function () {
if (this.should_retreat()) {
this.walk('backward');
} else if (this.should_rest()) {
this.rest();
} else if (this.facing_wall()) {
this.pivot();
} else {
this.walk();
}
},
facing_wall: function () {
return this.check('forward') == 'wall';
},
should_pursue: function () {
},
should_rest: function () {
// not full health and didn't take dmg
return this.getHealth() < 20 && this.last_health <= this.getHealth();
},
should_retreat: function () {
// below low_hp and taking damage
return this.last_health > this.getHealth() && this.getHealth() < this.low_hp;
}
};
function maybe_extend_warrior(warrior) {
for (var prop in extensions) {
if (!warrior[prop]) {
warrior[prop] = extensions[prop];
}
}
}
function reverse_until_diamond(warrior) {
if (warrior.found_diamond) {
return true;
} else if (warrior.check_and_act('backward') == 'diamond') {
warrior.found_diamond = true;
return true;
}
warrior.walk('backward');
return false;
}
jsWarrior.turn = function(warrior) {
maybe_extend_warrior(warrior);
if (!warrior.check_and_act('forward') && !warrior.check_and_act('backward')) {
warrior.idle();
}
warrior.last_health = warrior.getHealth();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment