[SOLVED]Code error? on hit and freeze... JavaScript


function inAttackRange(enemy) {
    var distance = hero.distanceTo(enemy);
  
    if (distance <= 3) {
        return true;
    } else {
        return false;
    }
}


while (true) {
    var enemy = hero.findNearestEnemy();
   
    var canAttack = inAttackRange(enemy)
     if canAttack = True: {
   
    hero.attack(enemy);
     }
}

could someone tell me what is wrong with my if can attack loop?
Thanks!

the error it is giving me is
Screenshot 2022-04-11 11.33.20 AM

I believe this needs parenthesis like the first if-statement you made for the distance, and you should remove the colon at the end

yeah that’s not working same error

Can you post your new code please?

   var canAttack = inAttackRange(enemy)
     if (canAttack) = True {
     
    // If the result stored in canAttack is true, then attack!
    hero.attack(enemy);
     }
1 Like

I meant you got to put the whole thing in the parentheses.

How it should look like:

if (condition) {
    #The code in here
}

There shouldn’t be anything outside the parentheses other than the word “if”

ohhhhhhhh, ok total missunderstanding

that fixed that part technicly but wait theres more

// You are trapped. Don't move, it'll be painful.

// This function checks if the enemy is in your attack range.
function inAttackRange(enemy) {
    var distance = hero.distanceTo(enemy);
    // Almost all swords have attack range of 3.
    if (distance <= 3) {
        return true;
    } else {
        return false;
    }
}

// Attack ogres only when they're within reach.
while (true) {
    // Find the nearest enemy and store it in a variable.
    var enemy = hero.findNearestEnemy();
    // Call inAttackRange(enemy), with the enemy as the argument
    // and save the result in the variable canAttack.
    var canAttack = inAttackRange(enemy);
     if (canAttack = True) {
     
    // If the result stored in canAttack is true, then attack!
    hero.attack(enemy);
     }
}

error is
image

Unlike in Python where True is the representation, in Java and in many other languages, it’s true

1 Like

i never knew that thank you

And wait, one more thing, in most languages, if you want to check if 2 things are equivalent to each other, you need to use == and not =

2 Likes

Congrats on solving it, but please remove the solution as posting solutions is prohibited on the discourse because it will ruin the purpose of learning, thanks

1 Like

i was unaware but thank you for telling me

1 Like

It only needed == not ===, CodeCombat just wanted === because it’s better practice :] (and wait, ANOTHER thing, if you just wrote if (canAttack) { it would’ve also been fine)
Also, just a side note, this is JavaScript and not Java, please be clear next time

1 Like

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.