模拟王者荣耀写一个游戏人物的类.
要求:
- 创建一个 Game_role的类.
- 构造方法中给对象封装name,ad(攻击力),hp(血量).三个属性.
- 创建一个attack方法,此方法是实例化两个对象,互相攻击的功能:
例: 实例化一个对象 李白,ad为30, hp为100
实例化另个一个对象 王昭君 ad为20, hp为150
李白通过attack方法攻击王昭君,此方法要完成 '谁攻击谁,谁掉了多少血, 还剩多少血’的提示功能.
class Game_role:
def __init__(self, name, ad, hp):
self.name = name
self.ad = ad
self.hp = hp
def attack(self, obj_role):
obj_role.hp -= self.ad
print(f'{self.name}攻击了{obj_role.name},{obj_role.name}掉了{self.ad}点血,{obj_role.name}还剩{obj_role.hp}点血')
libai_hero = Game_role('李白', 30, 100)
zhaojun_hero = Game_role('王昭君', 20, 150)
libai_hero.attack(zhaojun_hero)
libai_hero.attack(zhaojun_hero)
zhaojun_hero.attack(libai_hero)
zhaojun_hero.attack(libai_hero)
zhaojun_hero.attack(libai_hero)
对上面进行升级,人物使用武器进行攻击
class Game_role:
def __init__(self, name, ad, hp):
self.name = name
self.ad = ad
self.hp = hp
def attack(self, obj_role):
obj_role.hp -= self.ad
print(f'{self.name}攻击了{obj_role.name},{obj_role.name}掉了{self.ad}点血,{obj_role.name}还剩{obj_role.hp}点血')
def equipment_weapon(self, weap, role_obj):
# 给人物对象封装武器的属性(封装是另一类的对象,这样这个对象有许多方法和属性)
self.weapon = weap
self.weapon.weapon_attack(self, role_obj) # 这里传的self是libai_hero这个对象的空间地址
class Weapons:
def __init__(self, name, ad):
self.name = name
self.ad = ad
def weapon_attack(self, role1, role2):
print(f'{role1.name}用{self.name}攻击了{role2.name},{role2.name}掉了{self.ad}点血')
libai_hero = Game_role('李白', 30, 100)
zhaojun_hero = Game_role('王昭君', 20, 150)
sword = Weapons('剑', 50)
wand = Weapons('法杖', 40)
libai_hero.equipment_weapon(sword, zhaojun_hero)
# 或者这样
libai_hero.weapon.weapon_attack(libai_hero, zhaojun_hero)