Last active
August 29, 2015 13:57
-
-
Save EdCharbeneau/9623348 to your computer and use it in GitHub Desktop.
js Warrior
This file contains 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
jsWarrior.turn = function(warrior) { | |
updateStatus(warrior); | |
executeFirstAvailableCommand( | |
warrior, | |
[ | |
findDirection, | |
attack, | |
retreat, | |
heal, | |
collectTreasure, | |
walk | |
]); | |
warrior.lastHealth = warrior.getHealth(); | |
} | |
function updateStatus(warrior) { | |
warrior.lastHealth = warrior.lastHealth || 20; | |
warrior.isBlockedByWall = warrior.check() == "wall"; | |
warrior.canAttack = warrior.check() == "enemy"; | |
warrior.canCollectTreasure = warrior.check() == "diamond"; | |
warrior.hasLowHealth = warrior.getHealth() < 19; | |
warrior.hasCriticalHealth = warrior.getHealth() < 10; | |
warrior.isUnderAttack = warrior.getHealth() < warrior.lastHealth; | |
} | |
function executeFirstAvailableCommand(warrior, commands) { | |
executeableCommands = commands.filter(whereCanExecute(warrior)); | |
executeableCommands[0].execute(warrior); | |
} | |
function whereCanExecute(warrior) { | |
return function(cmd) { | |
return cmd.canExecute(warrior); | |
} | |
} | |
findDirection = { | |
canExecute: function(warrior) { return warrior.isBlockedByWall }, | |
execute: function(warrior) { | |
warrior.pivot(); | |
} | |
} | |
attack = { | |
canExecute: function(warrior) { return warrior.canAttack }, | |
execute: function(warrior) { warrior.attack(); } | |
}; | |
retreat = { | |
canExecute: function(warrior) { return warrior.isUnderAttack && warrior.hasCriticalHealth; }, | |
execute: function(warrior) { warrior.walk("backward"); } | |
} | |
heal = { | |
canExecute: function(warrior) { return warrior.hasLowHealth && !warrior.isUnderAttack; }, | |
execute: function(warrior) { warrior.rest(); } | |
} | |
collectTreasure = { | |
canExecute: function(warrior) { return warrior.canCollectTreasure; }, | |
execute: function(warrior) { warrior.collect(); } | |
} | |
walk = { | |
canExecute: function(_warrior) { return true; }, | |
execute: function(warrior) { warrior.walk(); } | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment