我刚开始学习 python,我希望你们能帮助我更好地理解事物。如果你曾经为 gameboy 玩过 pokemon 游戏,你会更了解我想要做什么。我从一个文字冒险开始,你可以做一些简单的事情,但现在我正处于口袋妖怪互相争斗的地步。所以这就是我想要实现的目标。
- 口袋妖怪对战开始
- 你攻击目标
- 目标失去 HP 并反击
- 第一个输掉 0 的 hp
当然所有这些都是打印出来的。
这是我到目前为止的战斗,我不确定我现在有多准确。只是想看看我离正确执行此操作还有多远。
class Pokemon(object):
sName = "pidgy"
nAttack = 5
nHealth = 10
nEvasion = 1
def __init__(self, name, atk, hp, evd):
self.sName = name
self.nAttack = atk
self.nHealth = hp
self.nEvasion = evd
def fight(target, self):
target.nHealth - self.nAttack
def battle():
print "A wild appeared"
#pikachu = Pokemon("Pikafaggot", 18, 80, 21)
pidgy = Pokemon("Pidgy", 18, 80, 21)
pidgy.fight(pikachu)
#pikachu.fight(pidgy)
完整代码在这里: http://pastebin.com/ikmRuE5z
我也在寻找有关如何管理变量的建议;我似乎在顶部有一个变量杂货 list ,我认为这不是好的做法,它们应该去哪里?
最佳答案
如果我要将 fight
作为实例方法(我不确定我会这样做),我可能会像这样编写代码:
class Pokemon(object):
def __init__(self,name,hp,damage):
self.name = name #pokemon name
self.hp = hp #hit-points of this particular pokemon
self.damage = damage #amount of damage this pokemon does every attack
def fight(self,other):
if(self.hp > 0):
print("%s did %d damage to %s"%(self.name,self.damage,other.name))
print("%s has %d hp left"%(other.name,other.hp))
other.hp -= self.damage
return other.fight(self) #Now the other pokemon fights back!
else:
print("%s wins! (%d hp left)"%(other.name,other.hp))
return other,self #return a tuple (winner,loser)
pikachu=Pokemon('pikachu', 100, 10)
pidgy=Pokemon('pidgy', 200, 12)
winner,loser = pidgy.fight(pikachu)
当然,这有点无聊,因为伤害量不取决于口袋妖怪的类型,也不是随机的......但希望它能说明这一点。
至于你的类结构:
class Foo(object):
attr1=1
attr2=2
def __init__(self,attr1,attr2):
self.attr1 = attr1
self.attr2 = attr2
如果保证在 __init__
中覆盖类属性,那么声明类属性(对我而言)就没有意义。只需使用实例属性,你应该没问题(即):
class Foo(object):
def __init__(self,attr1,attr2):
self.attr1 = attr1
self.attr2 = attr2v
关于Python: Sprite 宝可梦对战(类、函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11706505/