Skip to content

Instantly share code, notes, and snippets.

@gkdp
Last active June 1, 2018 13:41
Show Gist options
  • Save gkdp/e9e287f6db13a6b8987c95cc15c174ff to your computer and use it in GitHub Desktop.
Save gkdp/e9e287f6db13a6b8987c95cc15c174ff to your computer and use it in GitHub Desktop.
Solution for beginner mode in warrior js
class Player {
constructor() {
this.health = 20;
}
playTurn(warrior) {
if (this.hasCaptiveBehind(warrior)) {
if (warrior.feel('backward').isEmpty()) {
return warrior.walk('backward');
} else {
return warrior.rescue('backward');
}
}
if (this.seesWall(warrior)) {
return this.tapHealth(warrior, () => {
warrior.pivot();
});
}
if (!warrior.feel().isEmpty()) {
if (warrior.feel().getUnit().isBound()) {
return this.tapHealth(warrior, () => {
warrior.rescue();
});
}
return this.tapHealth(warrior, () => {
warrior.attack();
});
}
if (this.hasBeenAttacked(warrior)) {
return this.tapHealth(warrior, () => {
warrior.walk(warrior.health() < 9 ? 'backward' : undefined);
});
}
if (this.enemyIsWithinThreeTiles(warrior)) {
return this.tapHealth(warrior, () => {
warrior.shoot();
});
}
if (warrior.health() < 17 && !this.stairsNearby(warrior)) {
return this.tapHealth(warrior, () => {
warrior.rest();
});
}
warrior.walk();
}
/**
* Check if there is a captive behind.
* @param {*} warrior
*/
hasCaptiveBehind(warrior) {
const tile = warrior.look('backward').find((tile) => {
return tile.isUnit();
});
return tile ? tile.getUnit().isBound() : false;
}
/**
* Check if the warrior has been attacked.
* @param {Warrior} warrior
*/
hasBeenAttacked(warrior) {
return warrior.health() < this.health;
}
/**
* Check if an enemy is within 3 tiles.
* @param {*} warrior
*/
enemyIsWithinThreeTiles(warrior) {
const tile = warrior.look().find((tile) => {
return tile.isUnit();
});
return tile ? tile.getUnit().isEnemy() : false;
}
/**
* Check if a wall is near.
* @param {*} warrior
*/
seesWall(warrior) {
const tile = warrior.look().find((tile) => {
return !tile.isEmpty() || tile.isStairs();
});
return tile ? tile.isWall() : false;
}
/**
* Check if the stairs are nearby.
* @param {*} warrior
*/
stairsNearby(warrior) {
const tile = warrior.look().find((tile) => {
return (tile.isUnit() && !tile.getUnit().isEnemy()) || tile.isStairs();
});
return tile ? tile.isStairs() || !tile.getUnit().isEnemy() : false;
}
/**
* Return a response and update the health.
* @param {Warropr} warrior
* @param {*} callback
*/
tapHealth(warrior, callback) {
callback(warrior);
this.health = warrior.health();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment