Python 3中基于文本的冒险

时间:2014-10-20 11:27:54

标签: python python-3.x

我正在制作基于文字的角色扮演游戏,但我发现了很多问题,例如:

  • 进入商店后无法前往任何地方;
  • 我无法进入"酒馆"由于某些原因;和
  • 计算机只是说"buy is not defined in crossbow"

代码:

gold = int(100)
inventory = ["sword", "armor", "potion"]

print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity 
# player can spend and take points from any attribute

classic = {"Warrior",
         "Archer",
         "Mage",
         "Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)


# library contains attribute and points
attributes = {"strenght": int("0"),
             "health": "0",
             "wisdom": "0",
             "dexterity": "0"}

pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")

while choice != "0":
    # list of choices
    print(
    """
    Options: 

    0 - End
    1 - Add points to an attribute
    2 - remove points from an attribute
    3 - Show attributes
    """
    )
    choice = input("Choose option: ")
    if choice == "0":
        print("\nYour hero stats are:")
        print(attributes)
    elif choice == "1":
        print("\nADD POINTS TO AN ATTRIBUTE")
        print("You have", pool, "points to spend.")
        print(
        """
        Choose an attribute:
           strenght
           health
           wisdom
           dexterity
        """
        )
        at_choice = input("Your choice: ")
        if at_choice.lower() in attributes:
            points = int(input("How many points do you want to assign: "))
            if points <= pool:
                pool -= points
                result = int(attributes[at_choice]) + points
                attributes[at_choice] = result
                print("\nPoints have been added.")
            else:
                print("\nYou do not have that many points to spend")
        else:
            print("\nThat attribute does not exist.")
    elif choice == "2":
        print("\nREMOVE POINTS FROM AN ATTRIBUTE")
        print("You have", pool, "points to spend.")
        print(
        """
        Choose an attribute:
           strenght
           health
           wisdom
           dexterity
        """
        )
        at_choice = input("Your choice: ")
        if at_choice.lower() in attributes:
            points = int(input("How many points do you want to remove: "))
            if points <= int(attributes[at_choice]):
                pool += points
                result = int(attributes[at_choice]) - points
                attributes[at_choice] = result
                print("\nPoints have been removed.")
            else:
                print("\nThere are not that many points in that attribute")
        else:
            print("\nThat attribute does not exist.")

    elif choice == "3":
        print("\n", attributes)
        print("Pool: ", pool)
    else:
        print(choice, "is not a valid option.")






print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")

crossbow = int(50)
spell = int(35)
potion = int(35)


if choice == "shop":
      print("Welcome to the shop!")
      print("You have", gold,"gold")
      buy = input("What would you like to buy? A crossbow, a spell or a potion: ")


if buy == "crossbow":
         print("this costs 50 gold")
         answer = input("Do you want it: ")
         if answer == "yes":
             print("Thank you for coming!")
             inventory.append("crossbow")
             gold = gold - crossbow
             print("Your inventory is now:")
             print(inventory)
             print("Your gold store now is: ", gold)
         if answer == "no":
             print("Thank you for coming!")

if buy == "spell":
         print("this costs 35 gold")
         answear2 = input("Do you want it: ")
         if answear2 == "yes":
             print("Thank you for coming!")
             inventory.append("spell")
             gold = gold - spell
             print("Your inventory is now:")
             print(inventory)
         if answear2 == "no":
             print("Thank you for coming!")


if buy == "potion":
         print("this costs 35 gold")
         answear3 = input("Do you want it: ")
         if answear3 == "yes":
             print("Thank you for coming!")
             inventory.append("spell")
             gold = gold - potion
             print("Your inventory is now:")
             print(inventory)
         if answear3 == "no":
             print("Thank you for coming!")



choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
      print("Not acepted")
      print("What do you wish to do?")
      print("please input shop, tavern, forest.")
      choice = input("Go to the shop, go to the tavern, go to the forest: ")

if choice == "teavern":
    print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
    tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")

if tavernChoice == "drunken warriors":
    print("You approach the warriors to greet them.")
    print("They notice you as you get close and become weary of your presence.")
    print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
    if dexterity >= 5:
        print("You quickly dodge the mug and leave the warriors alone")
    else:
        print("You are caught off guard and take the mug to the face compleatly soaking you.")
        print("The dodgy figure leaves the tavern")

2 个答案:

答案 0 :(得分:0)

当您第一次询问用户在第111行的哪个位置时,如果他们输入的内容会发生什么?&#34; shop&#34;?那么第119行的if choice == "shop":条件将失败,buy = input("...")将永远不会执行。此时,buy不存在,因此当下一个条件执行时,它会崩溃,因为它无法评估if buy == "crossbow"buy没有任何价值,因此您无法将其与任何内容进行比较。

您需要缩进所有商店逻辑,使其位于if choice == "shop"块内。

if choice == "shop":
    print("Welcome to the shop!")
    print("You have", gold,"gold")
    buy = input("What would you like to buy? A crossbow, a spell or a potion: ")

    if buy == "crossbow":
        print("this costs 50 gold")
        #...etc
    if buy == "spell":
        print("this costs 35 gold")

您的酒馆代码也存在同样的问题。即使你不去酒馆,也要检查tavernChoice。这也需要缩进。

if choice == "teavern":
    print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
    tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")

    if tavernChoice == "drunken warriors":
        print("You approach the warriors to greet them.")

此时,您的计划将结束,但我猜您想继续探索区域。您可以将所有内容放在while循环中,从第一个input命令开始。

while True:
    print("Here is your inventory: ", inventory)
    print("What do you wish to do?")
    print("please input shop, tavern, forest.")
    choice = input("Go to the shop, go to the tavern, go to the forest: ")

    if choice == "shop":
        print("Welcome to the shop!")
        #...etc

    elif choice == "tavern":
        print("You enter the tavern...")
        #...etc

    elif choice == "forest":
        print("You enter the forest...")
        #etc

    else:
        print("Not acepted")
        print("What do you wish to do?")
        print("please input shop, tavern, forest.")

这也比您当前的方法更清晰,因为您只需要询问用户他们去过哪一次,而不是在第112,165和170行上三次。

答案 1 :(得分:0)

根据Kevin的回答,这里有一个冗余被挤出的版本,因此您只需在顶部附近添加一个新的def go_xyz(): ...即可添加新地点。

def go_shop():
    print("Welcome to the shop!")
    #...etc

def go_tavern():
    print("You enter the tavern...")
    #...etc

def go_forest():
    print("You enter the forest...")
    #etc

places = {name[3:]:globals()[name] for name in globals() if name.startswith('go_')}
placenames = ', '.join(places)

inventory = ['book']
retry = False

while True:
    if not retry:
        print("Here is your inventory: ", inventory)
    else:
        print("I do not know that place")
    print("Where do you wish to go?")
    print("Possible places: ", placenames, '.')
    choice = input("? ")
    try:
        places[choice]()
        retry = False
    except KeyError:
        retry = True
相关问题