我在做一个程序,你发射一个“爆炸机”,我有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.")
你需要跟踪外星人的健康状况。你现在所做的就是减少Alien.die函数中的“health”局部变量。
这里有一个小片段可以帮助你朝着正确的方向前进:
玩家的弹药也需要类似的追踪。
想想看:可用的弹药量是玩家状态的一部分。对象的状态最好表示为该对象的实例变量。所以你不应该把
ammo
作为blast
的参数——在这个方法中,它应该是self.ammo
,初始化为5或者你忘记编码的__init__
中的任何东西;-)。这不是一个寻找华丽的解决方案来隐藏和隐藏状态的问题——而是一个以最简单、最直接、最有效的方式做事的问题。你为什么不想这样?!
我只是修改了上面的程序,使两个属性命名为ammo和health。 我觉得他们让程序很简单。通过改变属性的初始值来尝试不同的结果。
相关问题 更多 >
编程相关推荐