Python 基于用户输入调用方法(基于文本的游戏)
我目前正在尝试制作一个基于文本的游戏,我想添加一个功能,根据用户在命令行(或pythonshell)中的输入,它检测一个相应的方法,并返回它 例如,当用户键入Python 基于用户输入调用方法(基于文本的游戏),python,python-3.x,Python,Python 3.x,我目前正在尝试制作一个基于文本的游戏,我想添加一个功能,根据用户在命令行(或pythonshell)中的输入,它检测一个相应的方法,并返回它 例如,当用户键入“合法移动!”在命令行中: >>> legal moves! 'You have 10 legal moves, which are...' 或者类似的 我知道,如果我创建一个类和一个名为legal\u moves(self)的方法,用户将能够键入CLASSNAME.legal\u moves()来调用相同的东西,但我正
“合法移动!”代码>在命令行中:
>>> legal moves!
'You have 10 legal moves, which are...'
或者类似的
我知道,如果我创建一个类和一个名为legal\u moves(self)
的方法,用户将能够键入CLASSNAME.legal\u moves()
来调用相同的东西,但我正试图让玩家尽可能简单,假设他们对python一无所知
目前我有类似的东西,但我不太确定如何使其工作:
def MyClass():
def __init__(self):
player_words = input
if player_words == "help me":
return self.help_menu()
def help_menu(self):
print("To receive help...")
你很接近
首先,必须使用class
而不是def
来声明类:
class MyClass():
然后,使用input()
获取用户输入。有几个选项;可以使用将字符串转换为实例上的属性;这包括访问以下方法:
class MyClass():
def __init__(self):
player_words = input()
player_words = player_words.lower().replace(' ', '_')
try:
getattr(self, player_words)()
except AttributeError:
print("Sorry, there is no such command")
def help_me(self):
print("To receive help...")
这将'Help me'
转换为Help\u me
,并找到要调用的相应方法
要列出所有可能的方法,可以使用,以及列出类提供的所有方法;您必须过滤这些内容,因为您不想向访问者展示\uuuu init\uuuu
方法。也许您可以为用于此目的的函数重载\uuuu doc\uuu
属性;它包括:
后者的演示:
>>> MyClass()
Frob The Foobar: Frobbing the Foobar will ...
Help Me: Provide help on all commands
help me
To receive help...
<__main__.MyClass object at 0x1114829e8>
>>> MyClass()
Frob The Foobar: Frobbing the Foobar will ...
Help Me: Provide help on all commands
Frob The Foobar
Frobbing the Foobar, sir!
<__main__.MyClass object at 0x111482b38>
>>MyClass()
翻跟头:翻跟头会。。。
帮助我:提供所有命令的帮助
帮助我
接受帮助。。。
>>>MyClass()
翻跟头:翻跟头会。。。
帮助我:提供所有命令的帮助
弗罗布美食家酒店
先生,在酒吧里嬉戏!
这是一个相当宽泛的问题-你到底在坚持什么?您当前的代码甚至似乎没有调用输入
,也不清楚您为什么在\uuuuu init\uuuuu
中这样做。用户可接受的输入范围有多大?你能创建一个方法告诉他们有效的输入吗?
>>> MyClass()
Frob The Foobar: Frobbing the Foobar will ...
Help Me: Provide help on all commands
help me
To receive help...
<__main__.MyClass object at 0x1114829e8>
>>> MyClass()
Frob The Foobar: Frobbing the Foobar will ...
Help Me: Provide help on all commands
Frob The Foobar
Frobbing the Foobar, sir!
<__main__.MyClass object at 0x111482b38>