Big piece of code looked scary at first glance, but was pretty simple to figure after review of a few minutes. Two simple inherit edits, then a couple elif’s in the while loop to call the proper object’s hit method depending on weapon type. Note commented lines, Monster sub class weapon type is gun, Alien sub class is laser, so we are matching object instances to weapon types from an input. Sounded more confusing that it actually is, but you have to practice the previous lessons (or go beyond like I do) to get it.
This project is at the end of the SoloLearn Intermediate Python OOP lessons.
class Enemy:
name = ""
lives = 0
def __init__(self, name, lives):
self.name = name
self.lives = lives
def hit(self):
self.lives -= 1
if self.lives <= 0:
print(self.name + ' killed')
else:
print(self.name + ' has '+ str(self.lives) + ' lives')
# Inherit Enemy
class Monster(Enemy):
def __init__(self):
super().__init__('Monster', 3)
# Inherit Enemy
class Alien(Enemy):
def __init__(self):
super().__init__('Alien', 5)
m = Monster() # gun
a = Alien() # laser
while True:
x = input()
if x == 'exit':
break
# elif for weapon type and then call correct object hit method
elif x == 'gun':
m.hit()
elif x == 'laser':
a.hit()
Sample Input
laser
laser
gun
exit
Sample Output
Alien has 4 lives
Alien has 3 lives
Monster has 2 lives