也许是这样的:
class NotEnoughMagic(Exception):
pass
class Character(object):
fire = 0
magic = 0
hp = 100
armor = 1
def take_damage(self, amount):
self.hp -= amount
if self.hp <= 0:
print '%s HAS DIED!' % type(self).__name__
def walk(self):
pass
def attack(self, target, attack_points):
target.take_damage(attack_points/target.armor)
class Monster(Character):
fire = 50
hp = 150
armor = 2
def punch(self, target):
self.attack(target, 25)
class Magician(Character):
magic = 10
def magic_armor(self):
self.hp += 20
self.magic -= 10
def sword_attack(self, target):
self.attack(target, 20)
def magic_attack(self, target):
"""Does tons of damage but uses all magic"""
if self.magic > 0:
self.attack(target, 100)
self.magic = 0
else:
raise NotEnoughMagic()
用法:
>>> monster = Monster()
>>> magician = Magician()
>>>
>>> print magician.hp
100
>>> print monster.hp
150
>>>
>>> monster.punch(magician)
>>> magician.sword_attack(monster)
>>>
>>> print magician.hp
75
>>> print monster.hp
140
>>>
>>> monster.punch(magician)
>>> magician.magic_attack(monster)
>>>
>>> print magician.hp
50
>>> print monster.hp
90
>>>
>>> monster.punch(magician)
>>> magician.magic_attack(monster)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 14, in magic_attack
__main__.NotEnoughMagic
>>>
>>> print magician.hp
25
>>> print monster.hp
90
>>>
>>> monster.punch(magician)
Magician HAS DIED!
>>> magician.sword_attack(monster)
>>>
>>> print magician.hp
0
>>> print monster.hp
80
一些潜在的游戏逻辑:
>>> # Gang of monsters
... monsters = [Monster() for x in range(10)]
>>> magician = Magician()
>>>
>>> # Prepare for battle
... while magician.magic > 0:
... magician.magic_armor()
...
... # Put on some chain mail
... magician.armor += 5
File "<stdin>", line 6
magician.armor += 5
^
SyntaxError: invalid syntax
>>>
>>>
>>> while magician.hp > 0:
... for m in monsters:
... m.punch(magician)
...
Magician HAS DIED!
Magician HAS DIED!
Magician HAS DIED!
Magician HAS DIED!
Magician HAS DIED!
Magician HAS DIED!
Magician HAS DIED!
>>>
更新:
此外,有一点需要注意的是mixins。例如,如果您想要将更多功能添加到一组广泛的类中,而不是在整个继承树下。
class TeleportAbilityMixin(object):
def teleport(self, destination):
cost = 20
if self.mp >= cost:
# Unpack the x, y coordinates
self.x, self.y = destination
self.mp -= cost
class TeleportingMagician(Magician, TeleportAbilityMixin):
pass
m = TeleportingMagician()
new_location = (10, 5)
m.teleport(new_location)
有许多的方式来解决这个问题。我发现最明显的是没有'class2'处理'method2';将逻辑移动到某个知道必要对象的地方,比如'class3'。 – user2357112
@ user2357112像我说的,我“认为”这是不可行的,但现在你提到它,“链接”它可能有效,尽管它会使代码更加复杂。 (例如声明一个变量,它在class2中使用class1,然后在class4中使用class2和class3,等等,而不是像我现在正在做的那样尝试合并class 4中的class 1,2和3) – Cestarian