更改def函数中的变量

2024-10-02 14:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,奇怪的问题。所以我正在为一个学校项目制作一个文本冒险游戏,我正在制作一个商店系统。它应该只允许你购买每件物品中的一件,除了药剂

schoice = str(input("> "))
def shopresults(item, itemvar, price):
  if schoice == str(item):
    if itemvar == 0 and gold >= price:
      print("Here ya go! One " + str(item) + " coming  right up!")
      # itemvar = 1 this should change the variable determining the status of the item, e.g. swordfire1 or swordfire2  
      gold == gold - price
      if item == "fire sword" or itemvar == "water sword" or itemvar == "thunder sword":
         freesword = 0
         elif itemvar == 1 and (item != potion1 or item != potion2 or item != potion3):
            print("You already have that, kiddo!")
         elif gold < price:
            print("You're a little short on gold there, bud...")
shopresults("fire sword", swordfire1, (100 - (100 * freesword)))
shopresults("flame sword", swordfire2, 500)

在进入shopresults程序之前,如何更改调用的变量(在本例中为Swardifre1),而不是itemvar本身?剑术1决定你是否拥有第一把火剑,每种武器都有这样的变量。忽略freesword变量,你基本上可以在游戏中得到一把免费的剑,据我所知,这不是问题所在。我知道这让人困惑,但如果可以的话请帮忙


Tags: orandtheifitempriceprintstr
2条回答

我想我想知道swordfire1swordfire2的值是多少-它们看起来像整数?我的想法是,你应该考虑创建武器对象并维护武器登记册。根据状态,调用注册表并将武器对象返回到该变量。当我说注册表时,你可以使用一个简单的dict,或者你可以设计一个类似工厂的模式

变量赋值是用=而不是==完成的。您需要将条件与括号结合起来:

schoice = str(input("> "))
def shopresults(item, itemvar, price):
  if schoice == str(item):
    if (itemvar == 0) and (gold >= price):
      print("Here ya go! One " + str(item) + " coming  right up!")
      # itemvar = 1 this should change the variable determining the status of the item, e.g. swordfire1 or swordfire2  
      gold = gold - price
      if (item == "fire sword") or (itemvar == "water sword") or (itemvar == "thunder sword"):
         freesword = 0
         elif (itemvar == 1) and (item != potion1) or (item != potion2) or (item != potion3):
            print("You already have that, kiddo!")
         elif gold < price:
            print("You're a little short on gold there, bud...")

shopresults("fire sword", swordfire1, (100 - (100 * freesword)))
shopresults("flame sword", swordfire2, 500)

相关问题 更多 >