0

I'm currently trying to make a text-based game, and I'd like to add a feature where, based on the user's input in the command line (or Python shell), it detects a corresponding method, and returns it.

For example, when the user types in 'legal moves!' in the command line:

>>> legal moves!
'You have 10 legal moves, which are...'

Or something like that.

I know that if I make a class, and a method called legal_moves(self), the user would be able to type in CLASSNAME.legal_moves() to call the same thing, but I'm trying to make it as simple as possible for the player, assuming they know nothing about python.

Currently I have something like this, but I'm not quite sure exactly how to make it work:

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...")
1
  • 1
    This is quite broad - what exactly are you stuck on? Your current code doesn't even seem to call input, and it's not clear why you do that in __init__. How wide a range of inputs is acceptable from the user? Could you create a method to tell them the valid inputs? Commented Jan 27, 2015 at 14:22

2 Answers 2

1

You are very close!

First, you have to use class and not def to declare a class:

class MyClass():

And then, use input() in order to get user input.

Sign up to request clarification or add additional context in comments.

Comments

1

There are several options; you could use the getattr() function to turn strings into attributes on your instance; this includes access to methods:

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...")

This translates 'Help me' into help_me and finds the corresponding method to call.

To list all the possible methods, you could use the inspect.getmembers() function, together with the inspect.ismethod() predicate function to list all methods your class offers; you'll have to filter these as you don't want to present the __init__ method to your visitor. Perhaps you could overload the __doc__ attribute for functions for this purpose; it contains the function documentation string:

from inspect import getmembers, ismethod

def is_documented_method(ob):
    return ismethod(ob) and ob.__doc__

class MyClass():
    def __init__(self):
        available_methods = getmembers(self, is_documented_method)
        help_info = [
            (name.replace('_', ' ').title(), func.__doc__)
            for name, func in available_methods]
        for name, documentation in help_info:
            print(name, documentation, sep=': ')
        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):
        """Provide help on all commands"""
        print("To receive help...")

    def frob_the_foobar(self):
        """Frobbing the Foobar will ..."""
        print("Frobbing the Foobar, sir!")

Demo of the latter:

>>> 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.