Backend of a Computer game using Python

05 min read

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.

Solution:

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!!! ')

                          self.life -=1                              

          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')

                          else:

                                       print(str(self.life))

# 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 )
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error