I am getting an infinite loop in cloudtrip treasure. I know that while true loops can sometimes cause problems so I have while(hero.time <30). Is there anything in the code that can loop infinitly because I cannot tell.
var friends = hero.findFriends();
function compare(num){
return num == Math.min(distances)
}
for(var i = 0; i < friends.length; i++){
var friend = friends[i]
while(hero.time < 30){
var items = hero.findItems();
var distances = []
while(distances.length < 10 || items.length == distances.length||hero.time < 30) {
for(var j = 0; j < items.length || j < 10; i++){
var item = items[j]
distances.push(Math.pow((friend.pos.x-item.pos.x),2)+Math.pow((friend.pos.y-item.pos.y),2))
}
}
var find = items[distances.findIndex(compare)];
hero.command(friend, "move", find.pos);
}
}
The hero doesn’t do any actions in the 2nd while loop but calculations are still being made and the 2nd while loop is supposed to break out either after the length of “distances” (an array) reaches a certain size
I just tried declaring the variable before the function and it still infinitely loops. I thought that JS functions only needed you to define the variables when the function is actually run? I also tried substituting Math.min(distances) with just a plain number, both when the function declaration was at the top and the bottom of my code and that also did not work. Sorry for the late reply.
Update: I have almost completely revamped my code but now the peasant is stuck trying to move to a place after he has already gotten there
Here’s my code now:
function goCoin(fNum){
var friends = hero.findFriends();
var friend = friends[fNum]
var distances = []
var items = hero.findByType("coin", hero.findItems());
for(var j = 0; j < 10; j++){
var item = items[j]
distances.push(Math.sqrt((Math.pow((friend.pos.x-item.pos.x),2)+Math.pow((friend.pos.y-item.pos.y),2))).toPrecision(4))
}
var cTarget
for(var k =0; k<distances.length; k++){
if(distances[k]==Math.min(...distances)){
cTarget =items[k]
}
}
hero.command(friend, "move", {x:cTarget.pos.x, y:cTarget.pos.y});
hero.command(friend, "move", {x:28, y:52});
}
goCoin(0)
goCoin(0)