简单的方法减少值而不创建新属性?
我正在制作一个程序,在这个程序里你可以发射一个“激光枪”,而我有5发子弹。我正在攻击一个有5点生命值的外星人。最后,我创建了一个玩家,让他发射6次,以检查程序是否正常工作。但是我现在的做法导致子弹数量不会减少。有没有简单的方法解决这个问题,还是说我必须为子弹和生命值分别创建新的属性?这是我现在的代码:
class Player(object):
""" A player in a shooter game. """
def blast(self, enemy, ammo=5):
if ammo>=1:
ammo-=1
print "You have blasted the alien."
print "You have", ammo, "ammunition left."
enemy.die(5)
else:
print "You are out of ammunition!"
class Alien(object):
""" An alien in a shooter game. """
def die(self, health=5):
if health>=1:
health-=1
print "The alien is wounded. He now has", health, "health left."
elif health==0:
health-=1
print "The alien gasps and says, 'Oh, this is it. This is the big one. \n" \
"Yes, it's getting dark now. Tell my 1.6 million larvae that I loved them... \n" \
"Good-bye, cruel universe.'"
else:
print "The alien's corpse sits up momentarily and says, 'No need to blast me, I'm dead already!"
# main
print "\t\tDeath of an Alien\n"
hero = Player()
invader = Alien()
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
hero.blast(invader)
raw_input("\n\nPress the enter key to exit.")
5 个回答
1
我刚刚修改了上面的程序,增加了两个属性,分别叫做弹药(ammo)和生命值(health)。我觉得这样让程序变得简单多了。你可以试着改变这两个属性的初始值,看看会有什么不同的结果。
class Player(object):
""" A player in a shooter game. """
def __init__(self, ammo):
self.ammo = ammo
def blast(self, enemy):
if enemy.health > 0:
if self.ammo > 0:
print "The player has blasted the alien.\n"
print "The player has", self.ammo, "ammunition left."
enemy.die()
elif self.ammo == 0:
print "The player can't blast the alien because he is out of ammunition.\n"
self.ammo -= 1
class Alien(object):
""" An alien in a shooter game. """
def __init__(self, health):
self.health = health
def die(self):
if self.health > 0:
self.health -= 1
print "The alien is wounded. He now has", self.health, "health left.\n"
if self.health == 0:
self.health -= 1
print "The alien gasps and says, 'Oh, this is it. This is the big one. \n"\
"Yes, it's getting dark now. Tell my 1.6 million larvae that I "\
"loved them...\nGood-bye, cruel universe.'\n"
elif self.health < 0:
print "The alien's corpse sits up momentarily and says, 'No need to blast me, I'm dead already!"
print "\t\tDeath of an Alien\n"
hero = Player(6)
invader = Alien(3)
blast = int(raw_input("How many times do you want to blast the alien? "))
for cnt in range(blast - 1):
hero.blast(invader)
6
想一想:可用的弹药数量是玩家状态的一部分。一个对象的状态最好用这个对象的实例变量来表示。所以你不应该把ammo
作为blast
的参数——在这个方法里应该用self.ammo
,而这个值应该在你忘记写的__init__
里初始化为5或者其他值;-)。
这并不是在寻找复杂的变通方法来隐藏和存储状态,而是要以最简单、最直接、最有效的方式来处理事情。你为什么会想要其他任何方式呢?!
3
你需要记录外星人的生命值。现在你做的只是让Alien.die函数里的“生命值”这个局部变量减少。
这里有一段小代码,可以帮助你朝正确的方向前进:
class Alien(object):
def __init__(self):
self.health = 5
def do_damage(self, amount):
self.health -= amount
玩家的弹药也需要类似的记录。