[SOLVED] Cloudrip Treasure (JS)

Here’s some of my code:

let minX = [0, 0, 100, 100];
let maxX = [50, 50, 150, 150];
let minY = [0, 60, 0, 60];
let maxY = [60, 120, 60, 120];

function findBest(unit, moreX, lessX, moreY, lessY) {
    let best = 0;
    let item = null;
    for (let current of hero.findItems()) {
        let value = current.value / unit.distanceTo(current);
        let pos = current.pos
        if (value > best && pos.x >= moreX && pos.x < lessX && pos.y >= moreX && pos.y < lessY) {
            best = value;
            item = current;
        }
    }
    return item;
}

function command() {
    let peasants = hero.findByType("peasant");
    for (let i = 0; i < peasants.length; i ++) {
        let peasant = peasants[i]
        if (peasant && peasant.team == "ogres") {continue;}
        else {
            let item = findBest(peasant, minX[i], maxX[i], minY[i], maxY[i]);
            if (item) {hero.command(peasant, "move", item.pos);}
            else {hero.command(peasant, "move", {x: maxX[i] - 25, y: maxY[i] - 30})}
        }
    }
}

One of my peasants isn’t moving to get coins. It will move to the neutral location, it just won’t get the coins. I’m getting the error “Try hero.distanceTo(),” I have a unit with a distanceTo() feature specified, so that shouldn’t be an error like this. The rest of my units move properly. Is it a bug, or is there something I’m not seeing here?

I’m not good at JS but I think you should write else if (peasant){ instead of just else (because what will happen if your peasant is dead?)

Also, I don’t think you need to check y position in the findBest() function. Like this:

function findBest(unit, moreX, lessX, moreY, lessY) {
    let best = 0;
    let item = null;
    for (let current of hero.findItems()) {
        let value = current.value / unit.distanceTo(current);
        let pos = current.pos
        if (value > best && pos.x >= moreX && pos.x < lessX) {
            best = value;
            item = current;
        }
    }
    return item;
}

I had a problem keeping the peasants from going for the same coins. That’s why I used the moreY and lessY coordinates. As for the first question, would that matter? It’s in a for-loop, so I don’t think that it would. I guess I’m not positive, but I don’t think it would matter.

As it is though, I didn’t have a problem with either of those functions, I doesn’t seem like the peasant, I think his name is Duan, is able to do the unit.distanceTo() function like the other ones are, because that part of the findBest(...) function isn’t working for Duan. Again, it works for the other peasants just as intended, just not for Duan.

Actually, it was a simple problem. I meant to do moreY, not moreX. Thanks, Peter!

1 Like

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.