首页 > 解决方案 > 蟒蛇坦克游戏

问题描述

我正在尝试使用 Python 制作坦克游戏,但卡在某个地方。以下是游戏代码:

from tank import Tank
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol")}
alive_tanks = len(tanks)
while alive_tanks > 1:
    print()
    for tank_name in sorted(tanks.keys()):
        print(tank_name, tanks[tank_name])
    first = raw_input("Who fires?").lower()
    second = raw_input("At whom?").lower()
    try:
        first_tank = tanks[first]
        second_tank = tanks[second]
    except KeyError, name:
        print("No such tank!", name)
        continue
    
    if not first_tank.alive or not second_tank.alive:
        print("One of those tanks is dead!")
        continue
    print()
    print("*" * 30)
    first_tank.fire_at(second_tank)
    if not second_tank.alive:
        alive_tanks -= 1
    print()
    print("*" * 30)
for tank in tanks.values():
    if tank.alive:
        print(tank.name, "is the winner!")
        break
    

运行短程序时显示一些错误,如下所示:

SyntaxError:无效的语法和错误:

    try:
        first_tank = tanks[first]
        second_tank = tanks[second]
    except KeyError, name:
        print("No such tank!", name)
        continue

在以下位置用红色突出显示逗号:

except KeyError, name:

鉴于屏幕截图寻求帮助:

https://imgur.com/mSbqEJ6

由于这个令人困惑的错误,我无法继续。您的帮助将不胜感激和尊重。下面给出的是我用来定义Tank 类的代码:

class Tank(object):

def_init_(self, name):

    self.name = name
    self.alive = True
    self.ammo = 5
    self.armor = 60

my_tank = Tank("Bob")

def_str_(self):

    if self.alive:
        return "%s (%i armor, %i shells)" % (self.name, self.armor, self.ammo)
    else:
        return "%s (DEAD)" % self.name

def fire_at(self, enemy):

    if self.ammo >= 1:
        self.ammo -= 1
        print self.name, "fires on", enemy.name
        enemy.hit()
    else:
        print self.name, "has no shells!"

def hit(self):

    self.armor -= 20
    print self.name, "is hit!"
    if self.armor <= 0:
        self.explode()

def explode(self):

    self.alive = False
    print self.name, "explodes!"

非常感谢您;急切地想要答案。

标签: python

解决方案


推荐阅读