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 trialRobin Nilsson
3,783 PointsWon't the while loop always drain the enemy's life completely?
In the method fireAtEnemy(), we have a while loop that decreases the life of the enemy by the strength of the tower in each iteration. Since the loop will continue till the enemy has no more health, is there really a purpose to this loop as currently written?
Won't the while loop always just drain the enemy's life completely? And in that case, wouldn't it make more sense to simply set enemy.life = 0 instead of bothering with the while loop at all?
2 Answers
Kelly Ford
Courses Plus Student 7,658 PointsAs I read it, the use of the while loop means that it will continue to decrease the enemy's life until it is 0. I think ideally it should be an "if"...
if enemy.life > 0 {
enemy.decreaseHealth(self.strength)
if enemy.life = 0 {
print("Enemy vanquished!")
}
...
Paul Ryan
4,584 PointsI am not familiar with the code you are referring to but I assume eventually there will be some conditions within the while loop that may break the loop before the enemy's life is completely drained.
Thomas Miele
18,388 PointsThomas Miele
18,388 PointsIt would be an "if" inside a loop iterating for movement, but there is no movement in this simplified example