Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
14,855 Points

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

2 Answers

Steven Parker
Steven Parker
216,014 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
216,014 Points

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