Problem with .pos on Gold Rush


#1

I was having a problem with my code:

var items = this.getItems();
var currentShortOfArray = 1;
for(var i=0;i-1<items.length;++i){
    var iPos = items[i];
    var iClose = this.distance(iPos.pos);
    var curClose = this.distance(items[currentShortOfArray].pos);
    if(iClose<curClose){
     currentShortOfArray = i;
    }
}

When I press Run, I get an error that says:

Line 16, time 0.0: Cannot read property ‘pos’ of undefined

Does anyone by chance know what I’m doing wrong?


#2

PS
I am using JavaScript. Forgot to mention that.


#3

I think I see the problem. Your for-loop will iterate past the end of the array because of the i-1 you have. Try just using i with no -1 there. So if items.length is, say, 3, then you will want to access indices 0, 1, and 2, but not 3 (because there’s nothing in index 3–that would be the fourth element).

What are you trying to do with the currentShortOfArray variable, by the way?


#4

Ok. the currentShortOfArray tells the program which of the objects on the array is the closest. It just holds the number of it. Thanks!


#5

@nick
Oh, I forgot to include this in the code. The above mention variable is used for this line of code I left out:
this.move(items[currentShortOfArray].pos);
Now this is the only problem I have. Its same as before. Sorry, I forgot :frowning:


#6

You should check out what’s happening to currentShortOfArray, then. You set it to 1 in the beginning, but there may not be two items in the array. You should initialize it to, say, -1, and then only move if you found something:

if (currentShortOfArray !== -1)
    this.move(items[currentShortOfArray].pos);

#7

@nick Thanks. I’ll try that. Thanks again.


#8

Same error on the this.move(items[currentShortOfArray].pos);
I checked the variables, and all the ones in the for loop are undefined.
currentShortOfArray is some how -1, even though thats not in the code…


#9

@nick YES IT WORKS THANK YOU NICK!!! I changed curClose into two lines like the iPos and iClose, and changed the line var currentShortOfArray = 1; to var currentShortOfArray = 0;. Programming… It perplexes the mind, and the logical system… … . . …


#10

I just have one last question… how would you find the gold amount of the other player?


#11

this.getNearestEnemy().gold


#12

Thank you! That helps