SOLVED: Problems with commands item.pos and enemy.type

Hm. I don’t see any more problems…well, when in doubt, call @Nick!

You want to put enemyIndex = 0 inside the loop loop, or else the hero logic will be some thing like this.

  1. Okay, found enemies. enemyIndex is 0.
  2. Kill enemies that are not sand yaks. Increment after killing or ignoring a sand yak.
  3. enemyIndex is now 2 or 3 (or some number of enemies).
  4. Found more enemies. There are two of them. enemyIndex is 2 or 3 (or whatever from last iteration).
  5. enemyIndex < len(enemies) is False , so hero ignores that loop.
  6. Hero doesn’t fight until there are more enemies than the stored enemyIndex.
  7. If that happens, hero only kills enemies 2 through len(enemies) - 1
  8. enemyIndex < len(enemies) is False…etc

Generally you don’t want to nest while loops like that, because (IMO) things get a little bit weird.

Instead you might want to try something like this:

# i do javascript, so this might be wrong
loop:
    enemies = self.findEnemies()
    ogres = [enemy for enemy in enemies if enemy.type is not 'sand-yak'] # list comprehensions, a bit advanced
    enemy = self.findNearest(ogres)
    if not enemy: continue
    # attack logic below
3 Likes

You want to put enemyIndex = 0 inside the loop loop, or else the hero logic will be some thing like this.

Thanks, trotod! Problem solved!

I have a problem with my item.pos. It keeps telling me to try this.pos even though I defined item. Please help!!!

Here’s my code (It’s Java):

loop {
var item = this.findNearestItem();
var x = item
var y = item.pos.y;
var enemy = this.findNearestEnemy();
var flag = this.findFlag(“green”);

if (enemy) {
   if (this.isReady("power-up")) {
       this.powerUp();  
   }
   else {
       this.attack(enemy);
   }  

}
else if (item) {
this.moveXY(x, y);
}
else if (flag) {
this.pickUpFlag(flag);
}
}

Hello, John, and welcome. Please format your code as per the FAQ.

First off, you don’t check if there is an item in the first place. That could possibly break your code.

Second, x is the item itself, not the x-coordinate of the item.

Fix these things, then come back if you still have problems.

First thing I had a typo. I meant:

var x = item.pos.x;

Second I am doing the level Backwoods Treasure, so there are coins that need to be picked up. I still get the same message.

Yes, but at the start of the level, for example, there will be a very small time in which the findNearestItem() command is executed and there is no coins to be picked up. Therefore, findNearestItem() will return null, and trying to find the pos of null throws an error. Move the defining of the item’s coordinates inside the if (item) { block.

1 Like

It works! Thank you very much. You’re a genius!

Please do not post correct code. It gives out an easy answer to people who don’t bother to learn.