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 trialRicardo Ponce
1,705 PointsWhy 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; }
2 Answers
Steven Parker
231,269 PointsThe 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".
Ricardo Ponce
1,705 PointsHi 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
231,269 PointsI had already seen the code in the video. See the answer I left on Friday.
Kevin Gates
15,053 PointsKevin Gates
15,053 PointsCan you take a snapshot of your workspace? And/or paste all of your relevant code here?