Help with Ogre Gorge Gouger

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.

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

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);


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

And just use

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

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

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

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);
}

}

while hero.time < 20:
# Собирай монеты
item = hero.findNearestItem()
if item:
hero.moveXY(item.pos.x, item.pos.y)

while hero.pos.x > 16:
# Беги за ограду
hero.moveXY(16, 37)

Дострой стену, чтобы оставить огров снаружи.

hero.buildXY(“fence”, 21, 37)

hello welcome to the discourse and enjoy your stay
do you mind clicking the </> button and pasting your code inside of there, please?
it will format your code correctly and helps us read it thanks. and also what is the problem with your code?

1 Like