python宠物类的实现_Python:口袋妖怪战斗(类,功能)

I just started learning python and I am hoping you guys can help me comprehend things a little better. If you have ever played a pokemon game for the gameboy you'll understand more as to what I am trying to do. I started off with a text adventure where you do simple stuff, but now I am at the point of pokemon battling eachother. So this is what I am trying to achieve.

Pokemon battle starts

You attack target

Target loses HP and attacks back

First one to 0 hp loses

Of course all of this is printed out.

This is what I have for the battle so far, I am not sure how accurate I am right now. Just really looking to see how close I am to doing this correctly.

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)

I am also looking for advice on how to manage variables; I seem to be having a grocery list of variables at the top and I assume that is not good practice, where should they go?

解决方案

If I was to have fight as a instance method (which I'm not sure I would), I would probably code it up something like this:

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)

Of course, this is somewhat boring since the amount of damage does not depend on type of pokemon and isn't randomized in any way ... but hopefully it illustrates the point.

As for your class structure:

class Foo(object):

attr1=1

attr2=2

def __init__(self,attr1,attr2):

self.attr1 = attr1

self.attr2 = attr2

It doesn't really make sense (to me) to declare the class attributes if you're guaranteed to overwrite them in __init__. Just use instance attributes and you should be fine (i.e.):

class Foo(object):

def __init__(self,attr1,attr2):

self.attr1 = attr1

self.attr2 = attr2v

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值