Python Course Design Note 21 of 52

Namespaces - Reference Answers

Programming exercise:

Simple Honor of Kings
1. Design a hero class for Honor of Kings; each hero object can use skills on other hero objects
2. A hero has the following attributes: hero name, level, health, and three damage attributes Q_hurt, W_hurt, E_hurt, representing the damage of each skill
3. It has the following skills: Q, W, E; all three skills take an enemy hero as a parameter, and when the enemy's health is less than or equal to 0, output that the character has died
"""
Simple Honor of Kings
1. Design a hero class for Honor of Kings; each hero object can use skills on other hero objects
2. A hero has the following attributes: hero name, level, health, and three damage attributes Q_hurt, W_hurt, E_hurt, representing the damage of each skill
3. It has the following skills: Q, W, E; all three skills take an enemy hero as a parameter, and when the enemy's health is less than or equal to 0, output that the character has died
"""
import random

class Hero:
    def __init__(self, name, q_hurt=30, w_hurt=50, e_hurt=70, level=1, life=100):
        self.name = name
        self.level = level
        self.life = life
        self.is_alive = True
        self.Q_hurt = q_hurt
        self.W_hurt = w_hurt
        self.E_hurt = e_hurt
        self.kill_count = 0

    def attack(self, skill, enemy):
        if self.name == enemy.name:
            return
        if enemy.life >= 0:
            enemy.life -= skill
        if enemy.life <= 0:
            enemy.life = 0
            enemy.is_alive = False
            self.kill_count += 1
            print('{}杀死{},击杀数为{}'.format(self.name, enemy.name, self.kill_count))
            return enemy.is_alive, self.kill_count

    def elevate(self):
        if self.kill_count % 5 == 0 and self.kill_count != 0:
            self.level += 1
            self.Q_hurt += 10
            self.W_hurt += 10
            self.E_hurt += 10
            print('{} 等级提升为 {}'.format(self.name, self.level))
            return self.level

obj1 = Hero('小1')
obj2 = Hero('小2')
obj3 = Hero('小3')
obj4 = Hero('小4')
obj5 = Hero('小5')
skill_dict = {
    'q_hurt': 30,
    'w_hurt': 50,
    'e_hurt': 70
}

for i in range(1000):
    random_obj1 = random.choice([obj1, obj2, obj3, obj4, obj5])
    random_obj2 = random.choice([obj1, obj2, obj3, obj4, obj5])
    random_skill = random.choice([skill_dict['q_hurt'], skill_dict['w_hurt'], skill_dict['e_hurt']])
    random_obj1.attack(random_skill, random_obj2)
    random_obj1.elevate()