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 trialAnjali Pasupathy
2,017 PointsWhy isn't print("Enemy vanquished!") outside the while loop?
Doesn't putting print("Enemy vanquished!") inside the while loop cause that line to be printed every time the tower fires, rather than at the moment the enemy's life becomes nonpositive?
3 Answers
Jerzy Mirecki
6,799 PointsYou are absolutely right, the print statement should be put outside the loop with a proper check for remaining life of the enemy, triggering only when it is less than or equal to 0.
Jason Bock
1,924 PointsAgreed - I found these minor tweaks helpful, particularly when playing with tower strength / enemy life #s <blockquote>
func fireAtEnemy(enemy:Enemy) {
if inRange(self.position, range: self.range, target: enemy.position) {
print("Enemy in range with \(enemy.life) HP")
while enemy.life > 0 {
enemy.decreaseHealth(self.strength)
print("Enemy attacked for \(self.strength) damage.")
if enemy.life > 0 {
print("Enemy has \(enemy.life) HP left")
}
else {
}
}
if enemy.life == 0 {
print("Enemy vanquished.")
}
}
else {
print("Darn, the enemy is out of range!")
}
}
</blockquote>
Daniel Cohen
5,785 PointsI like your changes, Jason.
James Estrada
Full Stack JavaScript Techdegree Student 25,866 PointsExactly. You should move the print statement outside the while loop, like this:
func fireAtEnemy(enemy: Enemy){
if inRange(self.position, range: self.range, target: enemy.position){
while enemy.life > 0 {
enemy.decreaseHealth(self.strength)
}
print("Enemy vanquished!")
} else {
print("Darn! The enemy is out of range!")
}
}