Need clarification please!


#1

Currently I am on level 48/125 on the Backwood Forest map. I read the “Goals” text and the example code:
(I cut and pasted it so I know its kind of a mess)

This function has 1 parameter: ‘target’:

def checkAndAttack(target):
# ‘target’ is a predefined variable.
if(target):
hero.attack(target)

enemy = hero.findNearestEnemy()

Below, ‘enemy’ is the argument. This becomes ‘target’ inside checkAndAttack.

checkAndAttack(enemy)

What I do Understand:

  1. The function is clearly stated as ‘checkAndAttack’
  2. ‘target’ becomes a predefined variable

What I do NOT understand:

  1. How and why does the ‘enemy’ variable substitute the ‘target’ variable?

#2

Parameter Passing


#3

Inside the brackets of a function you can put anything you like, as long as you keep that the same throughout the rest of the code. You can then put anything else in those brackets - for example, “enemy” - and all the targets in your function will be replaced with enemy.
Example:

def attackMyTarget(target):
    while target.health > 0:
        hero.attack(target)
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        attackMyTarget(enemy)


#4

I think I understand:

“attackMyTarget” is acting as the string while (target) is just a designated placeholder of sorts.
So as long as “attackMyTarget” stays the same then the designated placeholder can change randomly without effecting the rest of the code!?


#5

Yep, It’s pretty cool and really helpful for writing code as you could use the “attackMyTarget()” function on literally anything, here’s one more example just to show in how many ways it could be used:

def attackMyTarget(target):
    while target.health > 0:
        hero.attack(target)
while True:
    witch = hero.findNearest(hero.findByType("witch"))
    enemy = hero.findNearestEnemy()
    if witch:
        attackMyTarget(witch)
    elif enemy:
        attackMyTarget(enemy)

#6

Sweet, appreciate you clarifying that for me. By the way, thanks for using a few new commands. I haven’t learned the findByType command yet but I am excited to find out that that is actually an option. I think that made sense lol


#7

Umm, you can use hero.findByType() but you do need special glasses which unlock at level 26 / 27 not quite sure and you have to pay gems for them, they’re called the twilight glasses. But I’m afraid you can’t use the function unless you have the item, although you can use more advanced commands like continue and break and for loops and other stuff even if you don’t have the right prommaticon, not sure how that works. :man_shrugging: