1

I need to transfer for loop to recrusion function..

This is my fucntion:

public void AddEnemyToScreen(int enemy_count)
{
    for(int i=0 ; i<enemy_count;i++)
    {
        AddEnemey(new Enemy(r.nextInt(640), -10, textures,this,game));
    }
}

I have tried to do this:

public void AddEnemyToScreen(int enemy_count)
{
    if ( enemy_count == 1)
        AddEnemey(new Enemy(r.nextInt(640), -10, textures,this,game));
    else
    {
        AddEnemyToScreen(--enemy_count);
    }

}

but in some reason it dosent works..

0

1 Answer 1

3

Your condition in the recursive function is to add an enemy only when enemy_count is equal to 1, meaning you will only add one enemy.

public void AddEnemyToScreen(int enemy_count)
{

    // As long as enemy count is positive, keep adding enemies.
    if ( enemy_count > 0) {
             // Add new enemy to screen
            AddEnemey(new Enemy(r.nextInt(640), -10, textures,this,game));
            AddEnemyToScreen(enemy_count-1); // Add one more            
    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes it does, it will return when enemy_count is equal to 0, since then it wont call the recursive function :)
I tried this right now..even if I send to the function count of 0 the thread addes new enemies all the time
Sorry, my mistake. Bug fixed.

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.