修改器处需注意无返回值,并使用self._hp接收,与访问器不同
from random import randint
class fight(object):
__slots__ = ('_name','_hp')
def __init__(self,name,hp):
self._name = name
self._hp = hp
@property
def name(self):
return self._name
@property
def hp(self):
return self._hp
@hp.setter
def hp(self,hp):
self._hp = hp if hp > 0 else 0 # 此处需要注意是用self._hp接收,而非直接return
def attack(self,other):
other.hp -= randint(1,15)
class man(fight):
__slots__ = ('_name','_hp','_mp')
def __init__(self,name,hp,mp):
super().__init__(name,hp)
self._mp = mp
@property
def mp(self):
return self._mp
@mp.setter
def mp(self,mp):
self._mp = mp if mp > 0 else 0
def big_attack(self,other):
self._mp -= 20
if other.hp > 50:
other.hp -= 50
else:
other.hp *= 1//4
class Monster(fight):
__slots__ = ('_name','_hp')
def exist(monsters):
for monster in monsters:
if monster.hp > 0:
return monster
return monsters[0]
def existnum(monsters):
num = 0
for monster in monsters:
if monster.hp > 0:
num += 1
return num
def main():
superman = man('雷欧',300,100)
m1 = Monster('1号',100)
m2 = Monster('2号',100)
m3 = Monster('3号',100)
m = [m1,m2,m3]
live = exist(m)
session = 1
while live.hp != 0 and superman.hp != 0:
print(f'---------第{session}局开始-------------')
if randint(1,10) < 8:
superman.attack(live)
print(f'{superman.name}使用普通攻击殴打了{live.name}')
print(f'-----{live.name}的生命值为{live.hp}')
else:
if superman.mp >= 20:
superman.big_attack(live)
print(f'{superman.name}使用大招殴打了{live.name}')
print(f'-----{live.name}的生命值为{live.hp}')
num = existnum(m)
live = exist(m)
t = m.copy()
while num != 0:
live.attack(superman)
num -= 1
print(f'{live.name}使用普通攻击击打了{superman.name}')
print(f'-----{superman.name}的生命值为{superman.hp}')
t.remove(live)
if t:
live = exist(t)
else:
num = 0
live = exist(m)
recover(superman)
session += 1
print('game over')
def recover(_man):
if _man.mp < 100:
_man.mp += 5
if __name__ == '__main__':
main()