我正在尝试创建一个RPG游戏,我正在使代码更简洁。我遇到了一个我无法解决的问题,我也做了一些研究,但我似乎无法解决它。
我将主要代码DragonFightingRPG.py
与我在同一目录(prints.py
和options.py
)中导入的其他文件一起使用。
我正在尝试从另一个文件导入一个列表,因此它可以检查用户是否输入了其中一个答案,并且可以相应地回答。
DragonFightingRPG.py
import prints
import options
class Player(object):
def __init__(self):
self.name = None
self.gold = None
self.maxhealth = 100
self.health = 100
def get_name(self):
self.name = input("Hey there! What's your name?\n~~> ")
print("Nice name, {0}!".format(self.name))
def give_gold(self):
print("Since you are new around here, 100 gold doubloons have been given to you!")
self.gold = 100
def gold_counter(self):
print("You currently have {0} gold!".format(player.gold))
player = Player()
def start():
player.get_name()
player.give_gold()
gold_counter()
prints.intro()
def gold_counter():
while True:
option = input("Do you want to see your balance?\n~~> ").upper()
if option in {options.yes_opt}:
print("You currently have {0} gold.".format(player.gold))
elif option in {options.no_opt}:
print("You can check your balance later in the game.")
else:
print("Please try again.")
continue
break
start()
prints.py
class Player(object):
def __init__(self):
self.name = None
self.gold = None
self.maxhealth = 100
self.health = 100
def get_name(self):
self.name = input("Hey there! What's your name?\n~~> ")
print("Nice name, {0}!".format(self.name))
def give_gold(self):
print("Since you are new around here, 100 gold doubloons have been given to you!")
self.gold = 100
def gold_counter(self):
print("You currently have {0} gold!".format(player.gold))
def intro():
print("Narrator: Uhhhm...")
print("N: Let me check my list...")
print("N: Ah! Yes! {0}, that's right. I heard you were supposed to be arriving today.".format(player.name))
print("N: Welcome to... THE DRAGON FIGHTER GAME!")
print("N: I know, it isn't the most imaginative name.")
print("N: Don't look at me like that, I tried my hardest!")
print("N: Anywho, let's carry on.")
print("N: For some stupid reason, the creator of this game didn't give me an actual name, so\nmy name is just \"Narrator\" or \"N\".")
print("N:")
player = Player()
options.py
def yes_opt():
{"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
def no_opt():
{"N", "NO", "NOPE"}
我正在努力的部分是elif option in {options.no_opt}:
和if option in {options.yes_opt}:
。如果我只在主代码中输入列表,它可以工作,但我想尝试从其他文件导入它。有什么想法吗?
答案 0 :(得分:1)
只需进行一些小改动,就可以实现这一目标。
options.py
您应该从方法中返回这些集。
def yes_opt():
return {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
def no_opt():
return {"N", "NO", "NOPE"}
DragonFightingRPG.py
中,您将from options import yes_opt, no_opt
指定为导入语句。当你调用这些函数时,它们将返回相应的集合。
if option in yes_opt():
等等。
答案 1 :(得分:1)
def yes_opt(): {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}
这定义了一个名为yes_opt
的函数(实际上什么都不做),而不是一个带有该名称的 set 。
因此,option in yes_opt
不起作用。
你可能只想写这个:
yes_opt = {"Y", "YE", "YES", "YEAH", "PLEASE", "YES PLEASE"}