0

I am an AS3 novice and I am working on my first game.

So I have an Array of troops, that will be added when purchased from the store.

public var myTroops: Array = [{type: "lightInfantry", hp: "100", def: "10"},
{type: "lightInfantry", hp: "100", def: "10"},
{type: "heavyInfantry", hp: "100", def: "10"}];

I need to find how many times a certain type of infantry occurs and then trace it back, I have found other questions asking for help, but not for multi-arrays. How would I get this? Basically asking for some help in how to write the code for returning how many of each infantry the player already has.

Tips and answered are greatly appreciated. Thanks in advance.

2
  • did you get it figured out? Commented Dec 20, 2015 at 21:15
  • Thank you for your input, very helpful! Commented Dec 23, 2015 at 16:55

1 Answer 1

3

First, make your life easier and make some constants. This gives compile time checking against typos and makes it so you only have to type up the string once.

package {
   public class TROOP_TYPE {
       public const LIGHT_INFANTRY:String = "lightInfantry";
       public const HEAVY_INFANTRY:String = "heavyInfantry";
   }
}

Now, you could make a helper function to count certain types:

public function countTroops(type:String):int {
    var ctr:int = 0; 

    //loop through the troops array
    for(var i:int=0;i<myTroops.length;i++){
        //if the current troop matches the type passed, increment the counter
        if(myTroops[i].type == type) ctr++;
    }

    //return the value
    return ctr;
}

Then call it like so:

var lightCount:int = countTroops(TROOP_TYPE.LIGHT_INFANTRY);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.