Calculating the ratio distance To Item/worth Of Item

Hi again guys, i was curious to see if it’s possible to calculate the ratio of distance/worth of an item.

How would you write it?
I tried writing my own, but don’t know if it’s really working,
because my hero looks very indecisive while he’s running from coin to coin
(by that i mean that he keeps on turning and it seems like he’s running slower than he should)

so this is my code, I based it on the model of finding the closest coin not using the findNearest function

this.pickUpCoin = function(){
    items = this.findItems();
    maxRatio = 0;
    for(i=0;i<items.length;i++){
        item = items[i];
        ratio = item.value/this.distanceTo(item);
        if (ratio>maxRatio) maxRatio = ratio;
        items[i].ratio = ratio;
    }
    for(i=0;i<items.length;i++){
        if (items[i].ratio>=maxRatio){
            this.move(items[i].pos);
        }
    }
};

thanks a bunch!

1 Like

You’re probably having problems because items[i] is API-protected–writing to the coin itself is not allowed and probably doesn’t work very well. Try this more standard way of keeping track of both maxRatio and that item which it refers to, maxRatioCoin:

this.pickUpCoin = function(){
    var items = this.findItems();
    var maxRatio = 0;
    var maxRatioCoin = null;
    for (i=0; i<items.length; i++){
        var item = items[i];
        var ratio = item.value / this.distanceTo(item);
        if (ratio > maxRatio) {
            maxRatio = ratio;
            maxRatioCoin = item;
        }
    }
    if (maxRatioCoin) {
        this.move(maxRatioCoin.pos);
    }
};
2 Likes

Thank you very much! in the end it didn’t make a very big difference in effectiveness :blush: