We have learnt the concept of class and object-oriented programming in the previous article. Now, let us consider an interesting programmable concept to build the backend of a computer game where yourself and an enemy are in a sword fight. Each of them have an initial health of 5 units. Now, write a program using classes and object-oriented programming concepts in python to reduce the health of the victim by one unit each time it gets a hit. At every instance check their health, display their health if they are still alive, else declare dead.
class enemy: #class enemy created
life = 5
def attack(self): #when ever there is an attack on you, print "ouch!!!" and reduce the current health by 1 unit.
print( ' ouch!!! ')
def check_life(self): # check the present health, if health is 0 or less, then declare it as dead,
#else convert the present health into a printable string format to print the health remaining.
if self.life <=0:
print('I am dead')
# Here, in the above example, to use anything inside class we can create objects and use them whenever necessery.
enemy1 = enemy() # Here enemy1 is an object
enemy1.attack() # returns ouch and reduces life by one
enemy1.check_life() # returns dead or prints life=2 ( remaining points )