function findBestItem(items) {
var bestItem = null;
var bestValue = 0;
var itemsIndex = 0;
// Loop over the items array.
// Find the item with the highest valueOverDistance()
return bestItem;
}
using
function valueOverDistance(item) {
return item.value / hero.distanceTo(item);
}
find valueOverDistance() for given item compare to bestValue( Over distance )
Use as a sample for other parts
function findMostHealth(enemies) {
var target = null;
var targetHealth = 0;
var enemyIndex = 0;
while(enemyIndex < enemies.length) {
var enemy = enemies[enemyIndex];
if(enemy.health > targetHealth) {
target = enemy;
targetHealth = enemy.health;
}
enemyIndex += 1;
}
return target;
}
function findBestItem(items) {
var bestItem = null;
var bestValue = 0;
var itemsIndex = 0;
// Loop over the items array.
// Find the item with the highest valueOverDistance()
while (itemsIndex < items.length){
var item = items[itemsIndex];
if (item.value / hero.distanceTo(item) < valueOverDistance(item)){
bestItem = item;
bestValue = item.value;
}
itemsIndex += 1;
}
return bestItem;
}
I see some problems here
First one
if (item.value / hero.distanceTo(item) < valueOverDistance(item))
This line of symbols
valueOverDistance(item)
redirect to this function
function valueOverDistance(item) {
return item.value / hero.distanceTo(item);
}
As you can see this this expression
item.value / hero.distanceTo(item)
and function valueOverDistance(item) do the same.
They get Item value for example 3 and divide it on the distance from the hero to an item for example 10 meters
3g / 10m = 0.3
This index shows you how much gold you will get per 1 meter of the way
3g / 15m = 0.2 gold per meter of the way.
3g / 5m = 0.6 gold per meter of the way.
So the closer item to you and the higher the value of the item the more appealing it is for you.
With numbers your code looks like this:
If ( 0.3 < 0.3 )
{
}
Second one
var bestValue = 0;
It is really confusing but
In fact it is bestValueOverDistance
Instead of the current best value over distance for a given item ( use valueOverDistance(item) function for this )
you assign item.value:
It seems like you completely overlooked the second one
Second one
bestValue
It is really confusing but
In fact it is bestValueOverDistance
Instead of the current best value over distance for a given item ( use valueOverDistance(item) function for this )
you assign item.value:
again bestValue is the highest valueOverDistance what you encountered up until the current moment
it is 0 at the start
var bestValue = 0;
As the items appear you start to check them
you check first item - it is gem with value 5 and within 10 meters of you --> 5 / 10 --> 0.5
0 < 0.5
so for now
bestItem becomes that gem
bestValue becomes 0.5
then you check second item
It is gold coin - value 3 distance 2 --> 3 / 2 --> 1.5
0.5 < 1.5
So for now
bestItem becomes that gold coin
bestValue becomes 1.5