Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Loops and Final Touches Putting It All Together

Why remainingInvaders is reset to zero (remainingInvaders = 0;) and why add more remainingInvaders

if remainingInvaders is set to zero the foreach(Invader invader in _invaders) wont see more active invaders, and what about the addition of remainingInvaders that means that they are more invaders coming to score?

while(remainingInvaders > 0) {
foreach(Tower tower in Towers) { tower.FireOnInvaders(_invaders); }
//count and move the invaders that are still active. remainingInvaders = 0; foreach(Invader invader in _invaders) { if(invader.IsActive) { invader.Move();

          if(invader.HasScored)
              {
                return false;
              }              
          remainingInvaders++;
      }
  }

} return true; }

Kevin Gates
Kevin Gates
15,052 Points

Can you take a snapshot of your workspace? And/or paste all of your relevant code here?

2 Answers

Steven Parker
Steven Parker
229,004 Points

The code you are talking about is not removing or adding invader objects, it is just managing a count.

It sets the count to zero to begin, then checks each invader to see if it is still active. For each one that is, the count is incremented. Then, when the loop ends you have an accurate count of how many invaders are remaining. So you might think of this part of the code as just "taking inventory".

Hi Kevin sorry for late reply,here is the code i am talking about public bool Play() { //run until all invaders are neutralized or an invader reaches the end of the path int remainingInvaders = _invaders.Length;

  while(remainingInvaders > 0)
  {      
      foreach(Tower tower in Towers)
      {
        tower.FireOnInvaders(_invaders);
      }          
      //count and move the invaders that are still active.
      remainingInvaders = 0;
      foreach(Invader invader in _invaders)
      {
          if(invader.IsActive)
          {
              invader.Move();

              if(invader.HasScored)
                  {
                    return false;
                  }              
              remainingInvaders++;
          }
      }
  }
  return true;
}
Steven Parker
Steven Parker
229,004 Points

I had already seen the code in the video. See the answer I left on Friday.