Drop the Flag Issue

I finally figured out what I’m doing wrong on this level, but now whenever I place a flag, instead of placing a trap at the flag, my character just drops it where she’s standing. Can anyone tell me what’s wrong with my code?

// Put flags where you want to build traps.
// When you’re not building traps, pick up coins!

loop {
var flag = this.findFlag();

if (flag) {
    // How do we get fx and fy from the flag's pos?
        var flagX = pos.x;
        var flagY = pos.y;   
    this.buildXY("fire-trap", flagX, flagY);
    this.pickUpFlag(flag);     
}
else {
    var item = this.findNearestItem();
    if (item) {
        var pos = item.pos;
        var itemX = pos.x;
        var itemY = pos.y;
        this.moveXY(itemX, itemY);
    }
}

}

I think “pos.x” is your position, not the flag’s position.

Yeah, I think maybe pos.x defaults to self.pos.x. You need the pos of the flag you found.

I’m really not understanding what to do here. I don’t think I’m really learning anything from this particular set of levels. I only know of .pos for position and if it only detects the position of my character, I don’t know what to default to to make it work. She either just stands there or stops collecting coins when I place a flag. Is there any possible way someone can walk me through this code?

Do you see how you get the position of the items at the end of your code? You need to to the same thing with the flag. If you can’t get it with this, I’ll help a little more on the next response.

“pos” represents the property of a position as it belongs to something.

In this particular case, the subtle Javascript behavior you are running into is since you haven’t added “.pos” to an existing thing, it assumes you mean “this”, which is representative of your character in the game.

Your item code is correctly grabbing the position property of the nearest Item you found. The part that can be really confusing is your line

var pos = item.pos;

WITH that line, you have changed what “pos” means. Now, it is no longer referencing the property of your character “this”, but the new assignment of “item.pos”.

It can be really confusing when a variable and a property on “this” share the same name. To avoid confusion in the future, I would recommend more descriptive variable names (the part after var), like:

if (item) {
    var itemPos = item.pos;
    var itemX = itemPos.x;
    var itemY = itemPos.y;
    this.moveXY(itemX, itemY);
}