我在python中制作游戏。我遇到了一些代码问题。我将我的怪物定义为不同的类,以便以后编辑。我遇到的问题是我不能要求健康对其造成损害。
class spaceStalker(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
mobList = [spaceStalker]
mob = random.choice(mobList)
killList = ["not killed the beast!", "killed the beast!"]
kill = random.choice(killList)
def game():
if mob == spaceStalker:
fleeAtt = input("A Space Stalker has appeared! Attack or flee? ")
if fleeAtt == "Attack":
hitPass = input("Attack or Pass? ")
if hitPass == "Attack":
spaceStalker.hp -= 50
print(spaceStalker.hp)
else:
print("1")```
使用该类的实例
mobList = [SpaceStalker('some name', 54)]
当你进行暴徒检查时,你可以用isinstance(object, classname)
来做:
而不是:
if mob == spaceStalker:
#dosomething
使用:
if isinstance(mob, SpaceStalker):
#dosomething
我还建议你为你的班级使用getter和setter:
class SpaceStalker(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
@property
def hp(self):
return self.__hp
@hp.setter
def hp(self, hp):
#some validation here
self.__hp = hp
另外,也许你想使用classname约定(camelcase)所以我把它写成SpaceStalker