I have this code in Toil and Trouble. However, I still fail. Does anyone have any ideas why?
Edit 1: Posted updated code, still doesn’t work. What is wrong?
// Ogre Witches have some unpleasant surprises ready for you.
// Define a chooseTarget function which takes a friend argument
// Returns the a target to attack, depending on the type of friend.
// Soldiers should attack the witches, archers should attack nearest enemy.
this.chooseTarget = function(friend){
if(friend.type=="archer"){
var enemy = friend.findNearest(this.findEnemies());
return enemy;
}else{
var witches = this.findByType("witch");
enemy = friend.findNearest(witches);
return enemy;
}
};
loop {
var friends = this.findFriends();
for(var i=0; i < friends.length; i++) {
var friend = friends[i];
// Use your chooseTarget function to decide what to attack.
var target = this.chooseTarget(friend);
if(target){
this.command(friend, "attack", target);
}
}
}
Your problem is that all your soldiers got to attack one witch. This shouldn’t happen. Instead, They should attack the nearest witch, while your archers attack the nearest enemy.
No, that would be your soldiers wouldn’t move until the nearest enemy is a witch. I was thinking more along the lines of this.findByType("witch"). This method returns all units of the type inputted. Do you have that method yet? If not, I strongly suggest you get at least the Hardened Steel Glasses.
Implementing it should be easy (but apologies, I’ve been on Python, not javascript, so some of the following may be a bit tricky):
Create a distance variable in your chooseTarget function - like dToWitch. Set the initial distance to 9999 or so. [dToWitch = 99999 ] before you go looping through the enemies.
As you loop through all enemies (like you’re doing already, actually), test 2 things prior to updating enemy (i.e. add an additional condition to your existing if statement): (a) if enemies[i] is a witch [you do this already] and (b) if friend.distanceTo(enemies[i]) < dToWitch. When you update enemy, also update dToWitch. dToWitch = friend.distanceTo(enemies[i])
Next, only “return enemy” after you’ve looped through all enemies. (i.e. return enemy should no longer be in the for statement).
It runs fine, my soldiers walk towards the witches, and the bottom one always dies, but the top one doesn’t, and then my soldiers and archers all die from various causes.
For your archer targets, change var enemy = friend.findNearest(this.findEnemies()); to var enemy = friend.findNearest(friend.findEnemies());. I’ll also make it so that the hero can always see the bottom ogres.