Small game battle code
Small game battle code:
- Before we start the battle
- Let's give our Enemies a special attack.
- If the Enemy does not have a special attack, we print "Enemy does not have a special attack."
- Add code into the:
- Enemy(Parent)
- Both Zombie and Ogre
Enemy class:
# Parent class Enemy is also known as super class or base class.
class Enemy:
def __init__(self, typeOfEnemy: str,
healthPoints: int = 10,
attack_damage: int = 1):
self.__typeOfEnemy = typeOfEnemy
self.healthPoints = healthPoints
self.attack_damage = attack_damage
def get_typeOfEnemy(self):
return self.__typeOfEnemy
def talk(self):
print(f"I am a {self.__typeOfEnemy}. Be prepared to fight!")
def walk_forward(self):
print(f"{self.__typeOfEnemy} moves closer to you!")
def attack(self):
print(f"{self.__typeOfEnemy} attacks you for {self.attack_damage} damage!")
def special_attack(self):
print(f"{self.__typeOfEnemy} has no special attack!")
Zombie class:
# Child class of Enemy Zombie
from Enemy import Enemy
import random
class Zombie(Enemy):
def __init__(self, healthPoints, attack_damage):
super().__init__(typeOfEnemy='Zombie', healthPoints=healthPoints,
attack_damage=attack_damage)
self.healthPoints = healthPoints
self.attack_damage = attack_damage
# method overriding
# This method is overriding the talk method of parent class Enemy
def talk(self):
print(f"Zombie: Braaaains!")
# new method specific to Zombie class
def spread_diesease(self):
print(f"Zombie: Spreading disease!")
def special_attack(self):
did_special_attack_work = random.random() < 0.5
if did_special_attack_work:
self.healthPoints += 2
print('Zombie regerated 2 HP!)')
Ogre class:
# Child class of Enemy Ogre
from Enemy import Enemy
import random
class Orge(Enemy):
def __init__(self, healthPoints, attack_damage):
super().__init__(typeOfEnemy='Ogre', healthPoints=healthPoints,
attack_damage=attack_damage)
self.healthPoints = healthPoints
self.attack_damage = attack_damage
# method overriding
# This method is overriding the talk method of parent class Enemy
def talk(self):
print(f"Ogre: Smash them!")
def special_attack(self):
did_special_attack_work = random.random() < 0.20
if did_special_attack_work:
self.attack_damage += 4
print('Ogre attack has increased by 4!)')
main.py
from Enemy import Enemy
from Zombie import Zombie
from Ogre import Orge
def battle(e1: Enemy, e2: Enemy): # We are passing parent object as parameter
e1.talk()
e2.talk()
while e1.healthPoints > 0 and e2.healthPoints > 0:
e1.special_attack()
e2.special_attack()
e2.attack()
e1.healthPoints -= e2.attack_damage
e1.attack()
e2.healthPoints -= e1.attack_damage
if e1.healthPoints > 0:
print("Enemy 1 wins!")
else:
print("Enemy 2 wins!")
zombie = Zombie(healthPoints=15, attack_damage=3)
ogre = Orge(healthPoints=25, attack_damage=7)
battle(zombie, ogre)
Comments
Post a Comment