#python #traceback #shelve
Вопрос:
любая помощь будет признательна! Я скопировал и вставил код из другого приложения, которое я создал. проблема возникает при запуске функций входа в систему или регистрации пользователей
import shelve
import time
import colorama
from colorama import init, Fore, Back, Style
init()
FORES = [ Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE ]
BACKS = [ Back.BLACK, Back.RED, Back.GREEN, Back.YELLOW, Back.BLUE, Back.MAGENTA, Back.CYAN, Back.WHITE ]
BRIGHTNESS = [ Style.DIM, Style.NORMAL, Style.BRIGHT ]
item_rarity = {
'Legendary' : 'YELLOW',
'Uncommon' : 'GREEN',
'Common' : 'WHITE',
'Rare' : 'BLUE',
'Exotic' : 'RED',
'Unique' : 'CYAN',
}
Weapons = {'Excalibur': {'rarity': 'Legendary', 'damage': '100',},
'Dragonblade': {'rarity': 'Exotic', 'damage': '120', },
'woodensword': {'rarity': 'Common', 'damage': '11', },
'ironsword': {'rarity': 'Uncommon', 'damage': '39', }}
Armour = {'peasentwear': {'rarity': 'Common', 'defence': '17',},
'Dragonclothing': {'rarity': 'Exotic', 'defence': '89', },
'chainmail': {'rarity': 'Common', 'defence': '32', },
'ironarmour': {'rarity': 'Uncommon', 'defence': '39', }}
Enemies = {'Giant': {'health': '100', 'damage': '10',},
'Basilisk': {'health': '250', 'damage': '31', },
'Troll': {'health': '35', 'damage': '8', },
'Chad': {'health': '50', 'damage': '13', }}
def viewinventory():
print("work in progress")
def viewloadout():
username2gold = shelve.open('username2gold')
username2armour = shelve.open("username2armour")
username2weapon = shelve.open("username2weapon")
user_weapon = username2weapon[user_username]
gold_balance = username2gold[user_username]
user_armour = username2armour[user_username]
user_weapon_rarity = Weapons[user_weapon]['rarity']
user_armour_rarity = Armour[user_armour]['rarity']
user_armour_rarity_colour = item_rarity[user_armour_rarity]
user_weapon_rarity_colour = item_rarity[user_weapon_rarity]
print("Your loadout is as follows:")
print(f"You currently have {gold_balance} gold")
print("Your weapon is:")
print(Fore.BLUE Back.YELLOW "Hi My name is Aman Kharwal")
def adventurebegin():
print("work in progress")
def Adventure_minimum_balance():
global gold_balance
if gold_balance >= 100:
print("You have enough funds to play!")
gold_balance = gold_balance - 100
username2gold = shelve.open("username2gold")
username2gold[user_username] = gold_balance
print(f"Your new gold balance is {gold_balance}, we hope you enjoy your adventure!")
adventurebegin()
else:
gold_deficit = 100 - gold_balance
print("You have insufficient gold")
print(f"You need {gold_deficit} more gold to advance")
print("You are being returned to the mainmenu")
print("Come back when you have more gold!")
mainmenu()
def play():
print("The adventure continues...")
request_to_play = input("Would you like to go to the next stage, costing 100 gold? (y/n)")
while request_to_play != 'y' or 'n':
request_to_play = input("Invalid input, please try again")
if request_to_play == 'y':
Adventure_minimum_balance()
else:
print("We are redirecting you back to the mainmenu!")
time.sleep(1)
mainmenu()
def mainmenu():
print("Welcome to the main interface, here you can select what to do next")
print("1) Continue your Dawsgeon adventure")
print("2) View your inventory")
print("3) View your loadout")
global main_option
main_option = input("enter the number of what activity you would like to complete:")
def usereg():
print("Welcome new user to Dawsgeon, here you can register an account!")
desired_username = str(input("please enter your desired username: "))
username2password = shelve.open("username2password")
username2gold = shelve.open("username2gold")
username2armour = shelve.open("username2armour")
username2weapon = shelve.open("username2weapon")
while desired_username in (username2password.keys()):
print("An adventurer on the Dawsgeon network has already claimed that username")
desired_username = str(input("please input another username: "))
else:
print(f"this username is unique, welcome to Dawsgeon {desired_username}!")
print("next you need a strong yet memorable password")
desired_password = str(input("please enter the password you want to use: "))
print("creating your account... ")
time.sleep(1)
username2password[desired_username] = desired_password
username2gold[desired_username] = 1000
username2armour[desired_username] = 'peasentwear'
username2weapon[desired_username] = 'woodensword'
print(f"account created, your username is {desired_username} and your password is {desired_password}")
global user_password
global user_username
user_username = desired_username
user_password = desired_password
global gold_balance
gold_balance = username2gold[user_password]
username2password.close()
username2gold.close()
mainmenu()
def userlogin():
global user_username
global user_password
user_username = str(input("Please enter your username adventurer: "))
username2password = shelve.open("username2password")
while user_username not in (username2password.keys()):
print("The username you have inputted cannot be recognised")
user_username = str(input("please try again: "))
print(f"welcome back {user_username}!")
user_password = str(input("please input your password: "))
real_password = (username2password[user_username])
username2gold = shelve.open("username2gold")
n = 3
while user_password != real_password and 0 < n:
n = n - 1
n_str = str(n)
print(f"the password you inputted was incorrect, you have {n_str} attempts left")
user_password = str(input("please retry entering your password: "))
if n == 0:
print("You have been locked out")
quit()
else:
print(f"Ah yes, it really is you {user_password}!")
global gold_balance
gold_balance = username2gold[user_password]
username2gold.close()
username2password.close()
mainmenu()
print("welcome to Dawsgeon! please select what you would like to do: ")
print("1) Register a new account")
print("2) Login")
initial_option = int(input("please type your chosen option: "))
if initial_option == 1:
usereg()
elif initial_option ==2:
userlogin()
if main_option == 1:
play()
elif main_option == 2:
viewinventory()
elif main_option == 3:
viewloadout()
ошибки:
Traceback (most recent call last):
File "C:UsershpAppDataLocalProgramsPythonPython39libshelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'ghjsads'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:UsershpDesktop.pyDawsgeonmain.py", line 185, in <module>
usereg()
File "c:UsershpDesktop.pyDawsgeonmain.py", line 136, in usereg
gold_balance = username2gold[user_password]
File "C:UsershpAppDataLocalProgramsPythonPython39libshelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "C:UsershpAppDataLocalProgramsPythonPython39libdbmdumb.py", line 147,
in __getitem__
pos, siz = self._index[key] # may raise KeyError
KeyError: b'ghjsads'
Комментарии:
1.
#may raise KeyError
: ну, так оно и было….2.Я не знаю, что
shelve
это такое, поэтому я не могу помочь, но что произойдет, если вы просто передадите неправильный пароль? Похоже, что это, скорее всего, вызовет ошибку ключа3. когда вы вводите неверный пароль, он работает нормально; пользователь получает бесплатные шансы, а затем программа завершает работу