So, I’m fairly new to CodeCombat as well as Python, just started yesterday and am doing well, but I encountered a problem when trying to tackle the Backwoods Treasure level. Could you guys help me out by any chance?
here is my code:
loop:
enemy = hero.findNearestEnemy()
if enemy:
if hero.isReady("cleave"):
hero.cleave(enemy)
else:
hero.attack(enemy)
loop:
item = hero.findNearestItem()
if item.type == "coin":
hero.moveXY(item.pos.x, item.pos.y)
Have you passed the first level of Backwoods Treasure? Your code is too complicated and moveXY has also a hidden loop inside it. rewrote a simplified version of your idea :
startPos = {'x': hero.pos.x, 'y': hero.pos.y}
def findAndPickUpItems():
enemy = hero.findNearestEnemy()
item = hero.findNearestItem()
if item:
iDistance = hero.distanceTo(item)
if enemy:
eDistance = hero.distanceTo(enemy)
if item and enemy:
if iDistance - eDistance > hero.attackRange :
hero.move(item.pos)
else:
hero.attack(enemy)
elif item:
hero.move(item.pos)
elif enemy and eDistance <= hero.attackRange :
hero.attack(enemy)
else:
hero.move(startPos)
@MunkeyShynes Is there a better way to implement this structure:
if item and enemy:
#code1
elif item:
#code2
elif enemy:
#code3
else:
#code4
You can put loops inside function though, as condition as there is a break somewhere in it. sometime I just make a function when I must repeat myself too much like that:
@Gabriel_Dupuis But if you use an explicit or hidden ( as moveXY ) loop inside the main loop all your other troops freeze ( soldiers, peasants …) , is that right?
yes while loop will prevent any other code outside the loop to execute.
so for example if you want the minions to act, well you’ll have to put that inside the loop too.