I just have a question with this level. I wrote the code two ways and failed once but passed the other time. I feel the code does the same thing both ways how ever I fail with the first code simply because it looks like my character does not move fast enough to get the coin since for w.e reason I stop moving at certain points with in the level.
Here is what the level asks you to do:
and here is what you are given at the start of the level to work with.
Here is my code from my first attempt:
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
if(enemy.type != "peon") {
hero.attack(enemy);
}
}
var item = hero.findNearestItem();
if(item) {
// Gather the item only if the type is NOT equal to "poison".
if(item.type != "poison") {
hero.moveXY(item.pos.x, item.pos.y);
}
}
}
Here is a gif of the level running.
and here is the code from my second attempt that actually solved the level for me:
while(true) {
var item = hero.findNearestItem();
if(item && item.type != "poison") {
hero.moveXY(item.pos.x, item.pos.y);
var enemy = hero.findNearestEnemy();
}
if (enemy && enemy.type != "peon") {
hero.attack(enemy);
}
}
Gif of the level with the passing code
If someone could please explain to me why one fails and why the other doesn’t that would be great. From what I understand in the second solution all I did was shorten up the code.
In the first solution the code is broken down like this if I am correct.
while(true) {
var enemy = hero.findNearestEnemy(); // Set enemy Variable to find nearest enemy
if(enemy) { // If there is an enemy
if(enemy.type != "peon") { // If the enemy type is not equal to peon
hero.attack(enemy); // Hero will attack the enemy
}
}
var item = hero.findNearestItem(); // Set item variable to find the nearest item
if(item) { // If there is an item
if(item.type != "poison") { // If the item type is not poison
hero.moveXY(item.pos.x, item.pos.y); // The hero will move to the items position
}
}
}
Then in my working solution the code broken down works like this
while(true) {
var item = hero.findNearestItem(); //I set the variable of item to find the nearest item
if(item && item.type != "poison") { //Then if there is an item and it is not poision
hero.moveXY(item.pos.x, item.pos.y); //Hero will move to that items position
var enemy = hero.findNearestEnemy(); // Set variable to find nearest enemy
}
if (enemy && enemy.type != "peon") { // If there is an enemy and the type isnt a peon
hero.attack(enemy); //The hero will attack the enemy
}
}