1

Initially the array holds the default values as 100. Once if the enemy looses its health then i want to set the default values from 100 to 0. When all the array elements gets a value of 0 then the message will trace as game win.

var enemyHealth:Array = new Array(100,100,100,100,0);

    for (var i = 0; i< enemyHealth.length; i++)
    {

        if (enemyHealth[i] == 0)
        {
            trace ("game win");
        }

    }

Actually the issue is if any one of the array element holds a value of 0 then it trace a massage as game win.

So can any one help me in this regard.

2
  • do you want an if statement for checking when ALL the elements are 0? Commented Feb 23, 2013 at 12:53
  • Yes mr sharma. like (0,0,0,0,0); //output game win Commented Feb 23, 2013 at 12:55

4 Answers 4

1

You need to check all elements, not just one:

var allZero:Boolean = true;
var enemyHealth:Array = new Array(100,100,100,100,0);

for (var i = 0; i< enemyHealth.length; i++)
{

    if (enemyHealth[i] != 0)
    {
        allZero = false;
        break; // We know it's not a win, so we can stop the loop early
    }

}
if (allZero) {
    trace ("game win");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mr dasblinkenlight its worth for me.
1

I would do something like this

var enemyHealth:Array = new Array(100,100,100,100,0);

var isDead:Boolean = true;
for (var i = 0; i< enemyHealth.length; i++)
{

   if (enemyHealth[i] != 0)
   {
        isDead = false;
        break;
   }
}

if(isDead)
{
    trace ("Game Win");
}

Comments

1

You can do what the other answerers have said or something like this which might help you more to get the exact amount of enemies dead.

var enemyHealth:Array = new Array(100,100,100,100,0);
var enemiesDead:int=0;

    for (var i = 0; i< enemyHealth.length; i++)
    {

        if (enemyHealth[i] == 0)
        {
            enemiesDead++;
        }

    }

if(enemiesDead==enemyHealth.length)
{
    trace("Game Over");
}

Comments

1

You can use the every method to check that every element of your array (or vector) meet a criterion.

const enemyHealth:Vector.<uint> = new <uint>[100,100,100,100,0];

const zeroHealth:Function = function(item:uint, index:int, vector:Vector.<uint>):Boolean {
   return item === 0;
}

if (enemyHealth.every(zeroHealth)) {
    trace("Game win")
}

I have changed the array to a Vector because they are more efficient, and you can specify the type of the elements, but it also works fine with array.

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.