<p>我只是修改了上面的程序,使两个属性命名为ammo和health。
我觉得他们让程序很简单。通过改变属性的初始值来尝试不同的结果。</p>
<pre><code>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)
</code></pre>