Clash of Clones For Loop Help


#1

I’ll preface this by saying I know how to beat the level from reading other posts, but I’d still like to know what’s wrong with my initial code attempt.

I start by sorting the different enemy types into arrays so I can prioritize them later.

var enemies = this.findEnemies();
    var archers = [];
    var soldiers = [];
    var scouts = [];
    var shamans = [];
    var ogres = [];
    var evilAnya = [];
    for (var i = 0; i < enemies.length; i++){
        var enemy = enemies[i];
        if (enemy.type === "archer"){
            archers.push(enemy);
        }
        if (enemy.type === "soldier"){
            soldiers.push(enemy);
        }

Ect. Then my plan was to go Archers > Shamans > Ect, by doing the following:

if(archers){
        for(var a = 0; a < archers.length; a++){
            var target = archers[a];
            if (target){
                this.attack(target);
            }
        }
    }
    else if(shamans){
        for(var s = 0; s < shamans.length; s++){
            var target2 = shamans[s];
            if (target2){
                this.attack(target2);
            }
        }
    }

This works fine to kill all the archers, but then it gets stuck and won’t break out of my first for loop. What am I doing wrong?


#2

In CodeCombat (at least for Python, but probably also for JavaScript) an empty list is considered true.

Try to check for archers[0]or the length of archers and see if that solves the problem.


#3

Umm…
I don’t know to much about JS, but do you make arrays with var?(variable)
Also, I didn’t know there were shamans in clash of clones. ( JS version different from python?)
OH. Your else if isn’t on the same level of your if statement, so it doesn’t know what to else if.
Try:

if (archers){
    blahblahblah.
else if(shamans){
    blahblahblah.

not:

if (archers){
    blahblah.
    else if(shamans){
        blahblah.

That way, the Else If doesn’t belong to the if.


#4

Levels of indentation do not matter in JavaScript. They are merely more convenient to read.

As Hinkle says, the JavaScript processor on CodeCombat reads an empty list as true. It is more reliable to check the length of the list to see if it is empty.


#5

Snap. Don’t know too much of javascript, so I guess you’re right.
maybe check it using archers(len)? Probably should sort put some python related questions, but I just wanna help.


#6

Yes, CodeNinja could check the length of the list using list.length.