Help with Ogre Gorge Gouger


#1

This is my code:

function collectCoin(target) {
    hero.move(target.pos);
}
while(hero.time < 20) {
    // Collect coins
while(hero.gold < 60) {
// Will check every loop for the nearest coin...
 var nearest = hero.findNearest(hero.findItems());
 collectCoin(nearest);
    }
}

while(hero.pos.x > 16) {
    // Retreat behind the fence
    hero.move({'x': 15, 'y': 37});
}
// Build a fence to keep the ogres out.
hero.buildXY("fence", 20, 35);

It keeps giving me this error… I’m not really sure why.
He still goes and collects the coins though.
Also even after he builds the fence, it still says that he has to fortify the cabin and then he stands there till the time runs out.


#2

You need to check if there’s a nearest before giving the command to collectCoin(target).


#3

So I tried adding an if line, but this time it gives me the infinite loop error.

Removing the if again works but then he’s not able to collect 60 gold.
I thought that maybe it’s because I’m not going for the best coins, so i tried again with this code below.
But he won’t move anymore.


function collectCoin(target) {
    hero.move(target.pos);
}

 while(hero.time < 20) {
    while(hero.gold < 60) {
        var coins = hero.findNearest(hero.findItems());
        var coinIndex = 0;
        var bestValue = 0;
        var bestCoin = null;

         while(coinIndex < coins.length) {
            var coin = coins[coinIndex];
            var distance = hero.distanceTo(coin);
            var currentValue = coin.value/distance;
            if (currentvalue > bestValue) {
                bestValue = currentValue;
                bestCoin = coin;
                collectCoin(bestCoin);
            }
        coinIndex ++;
        }
    }
}

while(hero.pos.x > 16) {
    // Retreat behind the fence
    hero.move({'x': 15, 'y': 37});
}
// Build a fence to keep the ogres out.
hero.buildXY("fence", 20, 35);



#4

Oh, Ok sorry, keep you’re original code and get rid of

And just use

And I’m sure it works this time. :grin:


#5

function collectCoin(target) {
hero.move(target.pos.x, target.pos.y);
}


#6

You can just collect coins until there is an enemy then go back and build a fence


#7

like this

while(1){
var item = hero.findNearestItem();
var enemy = hero.findNearestEnemy();
if (enemy){
//Go into the cabin
moveXY(x, y);
//build in the enterance
buildXY(("fence") x, y);
}
else{
moveXY(item.pos.x, item.pos.y);
}

}