python代码练习:人狗大战
作者:互联网
题目:
请写一个小游戏,人狗大战,2个角色,人和狗,游戏开始后,生成2个人,3条狗,互相混战,人被狗咬了会掉血(生命值减少),狗被人打了也掉血(生命值减少)。
注意,狗和人的攻击力及生命值都不一样。
基类Role定义如下:
class Role(object):
def __init__(self, name):
self.name = name
def attack(self, enemy): # 攻击敌人的方法
enemy.life_value -= self.agressivity
要求:
(1)请根据题意定义子类Dog和People。
(2)并编写测试代码,输出人狗混战后各自的生命值。
class Role(object):
def __init__(self, name):
self.name = name
def attack(self, enemy): # 攻击敌人的方法
enemy.life_value -= self.agressivity
class Dog(Role):
life_value = 50
agressivity = 10
class People(Role):
life_value = 100
agressivity = 5
if __name__ == '__main__':
people1 = People('people1')
people2 = People('people2')
dog1 = Dog('dog1')
dog2 = Dog('dog2')
dog3 = Dog('dog3')
# 混战开始
dog1.attack(people2)
people1.attack(dog3)
people2.attack(dog1)
dog1.attack(people2)
dog2.attack(people2)
dog2.attack(people1)
dog3.attack(people1)
# 输出各自的生命值
print('{}的生命值为:{}'.format(dog1.name,dog1.life_value))
print('{}的生命值为:{}'.format(dog2.name, dog2.life_value))
print('{}的生命值为:{}'.format(dog3.name, dog3.life_value))
print('{}的生命值为:{}'.format(people1.name, people1.life_value))
print('{}的生命值为:{}'.format(people2.name, people2.life_value))
输出结果:
dog1的生命值为:45
dog2的生命值为:50
dog3的生命值为:45
people1的生命值为:80
people2的生命值为:70
标签:life,name,python,练习,值为,value,attack,people2,人狗 来源: https://www.cnblogs.com/qtqsydmht/p/15509015.html