有没有办法在函数中重用python输入?

2024-06-16 12:35:29 发布

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

我正在用Python编写一个冒险游戏,我在编写一个函数来检查藏宝图中是否有宝藏时遇到了问题。具体来说,输入查询似乎不能在函数的其他部分重用。你知道吗

我正在用Sublime Text 3、Python3.7.3编写代码,并通过Apple终端运行代码。我曾多次尝试通过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

我希望查询仍然保持它以前的定义,但它似乎没有这样做。你知道吗


Tags: nameimportselfnonedescriptionstrongmediuminventory