ClearCode

Scope

Apr 27th, 2022
895
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. # scope problem
  2. def update_health(amount):
  3.     monster.health += amount
  4.  
  5. # health = 10
  6. # print(health)
  7. # update_health(20)
  8. # print(health)
  9.  
  10. class Monster:
  11.     def __init__(self,health,energy):
  12.         self.health = health
  13.         self.energy = energy
  14.  
  15.     def update_energy(self,amount):
  16.         self.energy += amount
  17.  
  18.     # 2. the monster class should have a method that lowers the health -> get_damage(amount)
  19.     def get_damage(self,amount):
  20.         self.health -= amount
  21.  
  22. # exercise
  23. # 1. create a hero class with 2 parameters: damage, monster
  24. class Hero:
  25.     def __init__(self,damage,monster):
  26.         self.damage = damage
  27.         self.monster = monster
  28.  
  29. # 3. the hero class should have an attack method that calls the get_damage method from the monster
  30. # the amount of damage is hero.damage
  31.     def attack(self):
  32.         self.monster.get_damage(self.damage)
  33.  
  34. monster = Monster(health = 100, energy = 50)
  35.  
  36. hero = Hero(damage = 15, monster = monster)
  37. print(monster.health)
  38. hero.attack()
  39. print(monster.health)
Advertisement
Add Comment
Please, Sign In to add comment