class MatchstickMan:
# 初始化函数,用于设置火柴人的初始值
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
# 定义一个函数,用于让火柴人攻击其他火柴人
def attack_other(self, other):
# 如果对方的血量大于攻击力,则扣除对方的血量,否则将对方的血量设为 0
if other.health >self.attack:
other.health -= self.attack
else:
other.health = 0
# 创建两个火柴人对象
player1 = MatchstickMan("player1", 10, 3)
player2 = MatchstickMan("player2", 10, 3)
# 让 player1 攻击 player2,打击 player2 的血量
player1.attack_other(player2)
# 打印 player2 的剩余血量
print(player2.health) # 输出:7
代码如下(缩进请参考截图):
from random import randint
me_hp = 300
enemy_hp = 300
while True:
m_hurt = randint(1, 100)
if enemy_hp - m_hurt >0:
enemy_hp -= m_hurt
print('造成 {:3} 点伤害,敌方HP为: {:3}'.format(m_hurt, enemy_hp))
else:
print('造成 {:3} 点伤害,Victory!'.format(m_hurt))
break
e_hurt = randint(1, 100)
if me_hp - e_hurt >0:
me_hp -= e_hurt
print('受到 {:3} 点伤害,当前HP为: {:3}'.format(e_hurt, me_hp))
else:
print('受到 {:3} 点伤害,Defeated!'.format(e_hurt))
break
输出如下: