0

我在输入问题时遇到了一些问题,该问题应该允许玩家选择 5 场比赛之一。我使用了以下代码。

def racechoice():
    players.race = input('After you get a chance to think, you choose to be...') #Here race is chosen
    if players.race == "dwarf" or "Dwarf": #Race starting stats
        players.race = "Dwarf"
        players.level = 1
        players.strength = 12
        players.agility = 6
        players.inteligence = 8
        players.vitality = 14
    elif players.race == "Orc" or "orc":
        players.race = "Orc"
        players.level = 1
        players.strength = 14
        players.agility = 10
        players.inteligence = 4
        players.vitality = 12
    elif players.race == "elf" or "Elf":
        players.level = 1
        players.race = "Elf"
        players.strength = 8
        players.agility = 13
        players.inteligence = 12
        players.vitality = 7
    elif players.race == "Human" or "human":
        players.level = 1
        players.race = "Human"
        players.strength = 10
        players.agility = 10
        players.inteligence = 10
        players.vitality = 10
    elif players.race == "gnome" or "Gnome":
        players.race = "Gnome"
        players.strength = 5
        players.agility = 11
        players.intelligence = 17
        players.vitality = 7

当调用显示玩家的统计数据时:

def stats():
    print(players.name)
    print(players.race)
    print("Level: "+ str(players.level) +" Strength: "+ str(players.strength) +" Agility: " + str(players.agility) +" Inteligence: "+ str(players.inteligence) +" Vitality: "+ str(players.vitality))

无论玩家选择什么,它都会以具有 Dwarf 属性的 Dwarf 形式返回。我是 Python 新手,我想知道,我没有正确使用 if/elif 语句吗?ex) 在你有机会思考之后,你选择成为……兽人 Ecep 矮人等级:1 力量:12 敏捷:6 智力:8 活力:14

4

2 回答 2

0

有问题,你应该这样做:

if players.race == "dwarf" or "players.race == Dwarf":

但更好的是,将您的条件更改为:

elif players.race.lower() == "orc":

还建议您使用类来封装功能,例如:

class Player(object):
    def __init__(self, race, level, strength, agility, inteligence, vitality):
        self.race = race
        self.level = level
        self.strength = strength
        self.agility = agility
        self.inteligence = inteligence
        self.vitality = vitality

player = Player('Dwarf', 1, 12, 6, 8, 14)

那么您的racechoice功能将如下所示:

def racechoice():
    race = input('After you get a chance to think, you choose to be...')
    if race.lower() == 'dwarf':
        player = Player('Dwarf', 1, 12, 6, 8, 14)
    elif race.lower() == 'orc':
        player = Player('Orc', 1, 14, 10, 4, 12)
    ...
    return player
于 2013-09-08T02:23:23.097 回答
0

你不能这样使用or。您的所有if/elif陈述应采用以下形式:

if players.race == "dwarf" or players.race == "Dwarf":

"Dwarf"all 本身由 Python 考虑并考虑True空字符串,所以你的第一个总是成功的。""Falseif

于 2013-09-08T02:27:48.690 回答