有没有一种方法可以在函数内重用python输入?

时间:2019-07-20 13:42:55

标签: python variables nameerror

我正在用Python编写冒险游戏,但在编写用于检查藏宝图中是否有藏宝的函数时遇到了麻烦。具体来说,似乎输入查询无法在函数的其他部分中重用。

我正在用Sublime Text 3,Python 3.7.3编写代码,并且正在通过Apple Terminal运行代码。我尝试过通过flake8和black重新格式化代码很多次,并大体上将其清理干净。

import random
import time
from time import sleep
import sys
import copy

player_inventory = []

class Sword:
    def __init__(self, name=None, weak=None, medium=None, 
strong=None, superstrong=None, description=None):
        self.name = name
        self.weak = weak
        self.medium = medium
        self.strong = strong
        self.superstrong = superstrong
        self.description = description

rusty_sword = Sword(name="rusty sword", weak=5, description="This is 
a rusty old sword that you found on the ground.")

gold_sword = Sword(name="gold sword", medium=15, description="This 
is a fine golden sword, with a crown engraved on the handle.")

diamond_sword = Sword(name="diamond sword", strong=45, 
description="This 100% pure diamond sword is of the finest quality. 
It reflects a prism of light when you turn it back and forth.")

plasma_sword = Sword(name="plasma sword", superstrong=135, 
description="This plasma sword can slay any opponent. With this, you 
are unstoppable.")

def printfast(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.04)

def findingtreasure0(p):
    global rusty_sword, gold_sword, diamond_sword, plasma_sword

    if p == "r" or p == "g":
        printfast("\nYou found treasure!\n")

    if p == "r":
        printfast(f"\n{rusty_sword.description}\n")
        p = rusty_sword  # maybe a problem here? 
        tstring = (f"Add {p.name} to inventory? Y/N:")
        treasurequery = input(f"{tstring}")

    elif p == "g":
        printfast(f"\n{gold_sword.description}\n")
        p = gold_sword
        tstring = (f"Add {p.name} to inventory? Y/N:")
        treasurequery = input(f"{tstring}")
    else:
        pass

    if treasurequery.lower() == "y":
        player_inventory.append(p)
        itemname.capitalize()
        print(f"The {itemname} was added to your inventory.")
        itemname.lower()
    elif treasurequery.lower() == "n":
        printfast(f"\nYou left the {itemname} alone and kept moving.\n\n")
    else:
        treasurequery

我遇到了错误:

Traceback (most recent call last):
  File "adventuregame.py", line 504, in <module>
    user_input1(firstinput)
  File "adventuregame.py", line 374, in user_input1
    findingtreasure0(tmat[x][y])
  File "adventuregame.py", line 255, in findingtreasure0
    if treasurequery.lower() == "y":
UnboundLocalError: local variable 'treasurequery' referenced before assignment

我希望宝藏查询仍然保留其先前的定义,但似乎没有。

0 个答案:

没有答案