CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。
CheckiO 官网:https://checkio.org/
我的 CheckiO 主页:https://py.checkio.org/user/TRHX/
CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise
题目描述
【The Warriors】:这个题目的故事大概就是说有个车夫抢了个女孩,然后被一个爵士遇到了,爵士要救这个女孩,就要和车夫决斗,将爵士和车夫命名为 Warrior 和 Knight,两者的生命值(50点)相同但攻击力不相同,Warrior 攻击力为 5 点,Knight 攻击力为 7 点,他们之间不断来回攻击,每一个回合,被攻击者将减去相应的生命值,战斗以其中之一的死亡而告终。
我们需要创建一个 Warrior
类,这个类将具有 2 个参数:生命值(50点)和攻击力(5点),以及 1 个属性:is_alive
,如果战士的生命值大于0,其值为 True,否则为 False。另外,还需要创建一个 Knight
类,该类是 Warrior
的子类,其攻击力参数为 7。此外,还必须创建一个函数 fight()
,该函数的功能是判断谁是最强的,谁会活到最后。
【链接】:https://py.checkio.org/mission/the-warriors/
【输入】:两个人物赋予不同的角色
【输出】:决斗的结果以及判断是否活着(True or False)
【范例】:
chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
fight(chuck, bruce) == True
fight(dave, carl) == False
chuck.is_alive == True
bruce.is_alive == False
carl.is_alive == True
dave.is_alive == False
解题思路
题目已经告诉我们了,创建两个类:Warrior
和 Knight
,其中 Knight
是 Warrior
的子类,继承其生命值的参数和是否活着的属性,fight()
函数里面用于计算每次决斗两者的剩余生命值,判断其是否还活着。
代码实现
class Warrior:
health = 50
is_alive = True
attack = 5
class Knight(Warrior):
attack = 7
def fight(unit_1, unit_2):
while unit_1.health > 0:
unit_2.health -= unit_1.attack
unit_1.health -= unit_2.attack
if unit_2.health > unit_1.health:
unit_1.is_alive = False
return False
else:
unit_2.is_alive = False
return True
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
mark = Warrior()
assert fight(chuck, bruce) == True
assert fight(dave, carl) == False
assert chuck.is_alive == True
assert bruce.is_alive == False
assert carl.is_alive == True
assert dave.is_alive == False
assert fight(carl, mark) == False
assert carl.is_alive == False
print("Coding complete? Let's try tests!")
大神解答
大神解答 NO.1
class Warrior:
def __init__(self):
self.health = 50
self.attack = 5
@property
def is_alive(self) -> bool:
return self.health >= 0
class Knight(Warrior):
def __init__(self):
super().__init__()
self.attack = 7
def fight(unit_1, unit_2):
while unit_1.is_alive and unit_2.is_alive:
unit_2.health -= unit_1.attack
if unit_2.is_alive:
unit_1.health -= unit_2.attack
return unit_1.is_alive
大神解答 NO.2
class Warrior:
def __init__(self):
self.health = 50
self.attack_points = 5
def take_damage(self, damage):
self.health -= damage
def attack(self, enemy):
enemy.take_damage(self.attack_points)
@property
def is_alive(self):
return self.health > 0
class Knight(Warrior):
def __init__(self):
Warrior.__init__(self)
self.attack_points = 7
def fight(unit_1, unit_2):
while True:
unit_1.attack(unit_2)
if not unit_2.is_alive:
return True
unit_2.attack(unit_1)
if not unit_1.is_alive:
return False