Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

[SOLVED] Hit and freeze javascript help

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 the result stored in canAttack is true, then attack!
if (true) {
    hero.attack(enemy);
    }

}
what am i doing wrong i keep failing. after i kill 5 i die

2 Likes

You need to check if (canAttack == true) { - or at least that’s what I think the format is…I wouldn’t know since I only know Python :sweat_smile:

4 Likes

Nailed it :nut_and_bolt:

Another way to write it is like this:

if (canAttack){

In JS, this will check if canAttack is true, not empty, or not null / none

4 Likes

I tried it, and I keep taking damage, because the character is moving toward the munchkins. Is there a way to fix it?
Here’s my code(Javascript):
// 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
var canAttack = inAttackRange(enemy);
// and save the result in the variable canAttack.
if(canAttack){
}
// If the result stored in canAttack is true, then attack!
hero.attack(enemy);
}

Please properly format your code…[Essentials] How To Post/Format Your Code Correctly

What weapon are you using? If the enemy is out of attack range, the hero will attempt to move towards it, so that it comes in range.

Never mind, I managed to beat the level.