Как получить универсальный вызов функции, который может вызывать различные функции в Python? - PullRequest
2 голосов
/ 13 ноября 2011

Я пытаюсь создать текстовую игру на Python, однако код может очень быстро выйти из-под контроля, если я не смогу сделать что-то в одной строке.

Во-первых, исходный код:

from sys import exit

prompt = "> "
inventory = []

def menu():
    while True:
        print "Enter \"start game\" to start playing."
        print "Enter \"password\" to skip to the level you want."
        print "Enter \"exit\" to exit the game."
        choice = raw_input(prompt)
        if choice == "start game":
            shell()
        elif choice == "password":
            password()
        elif choice == "exit":
            exit(0)
        else:
            print "Input invalid. Try again."

def password():
    print "Enter a password."
    password = raw_input(prompt)
    if password == "go back":
        print "Going to menu..."
    else:
        print "Wrong password. You are trying to cheat by (pointlessly) guess passwords."
        dead("cheating")

def shell(location="default", item ="nothing"):
    if location == "default" and item == "nothing":
        print "Starting game..."
        # starter_room (disabled until room is actually made)
    elif location != "default" and item != "nothing":
        print "You picked up %s." % item
        inventory.append(item)
        location()
    elif location != "default" and item == "nothing":
        print "You enter the room."
        location()
    else:
        print "Error: Closing game."

def location():
    print "Nothing to see here."
    # Placeholder location so the script won't spout errors.

def dead(reason):
    print "You died of %s." % reason
    exit(0)

print "Welcome."
menu()

Во-первых, объяснение того, как моя игра в основном работает. В игре есть «оболочка» (где ввод сделан), которая получает информацию и отправляет информацию в разные «комнаты» в игре, а также сохраняет инвентарь. Он может получить два аргумента: местоположение и возможный предмет, который будет добавлен в инвентарь. Тем не менее, строки 40-42 (первый блок elif в «оболочке») и строка 43-45 (последний блок elif в «оболочке») должны вернуться в любое место, где было местоположение (строки 42 и 45, чтобы быть точный). Я пробовал "% s ()% location", но это не работает, кажется, работает только при печати чего-либо или чего-то такого.

Есть ли способ сделать это? Если нет, то даже написание движка для этой игры было бы кошмаром. Или мне пришлось бы создать совершенно другой движок, который, я думаю, был бы намного лучше в таком случае.

Извините, если я допустил какие-либо ошибки, первый вопрос / сообщение.

Ответы [ 3 ]

1 голос
/ 13 ноября 2011
elif location != "default" and item != "nothing":
    print "You picked up %s." % item
    inventory.append(item)
    location()
elif location != "default" and item == "nothing":
    print "You enter the room."
    location()

Полагаю, вы хотите вызвать функцию с именем.Для этого вам нужна ссылка на модуль или класс, внутри которого он был определен:

module = some_module # where the function is defined
function = getattr(module, location) # get the reference to the function
function() # call the function

Если функция определена в текущем модуле:

function = globals()[location]
function() # call the function
0 голосов
/ 13 ноября 2011

Я думаю, вы можете использовать метод getattr ().

Пример: вы хотите вызвать метод "helloword ()" из модуля "test", затем выполните:

methodYouWantToCall = getattr(test, "helloworld")
caller = methodYouWantToCall()

Надеюсь, это даст вам подсказку.

0 голосов
/ 13 ноября 2011

Если я правильно понимаю, что вы хотите, это что-то вроде этого: игрок введет название местоположения, и вы хотите вызвать связанный метод. "%s"()%location не будет работать, строка (то есть то, что "% s" не вызывается).

Давайте попробуем путь ООП:

class Maze:
   def __init__(self):
      # do what you need to initialize your maze

   def bathroom(self):
      #go to the bathroom

   def kitchen(self):
      # go to the kitchen

   def shell(self, location="", item=""):
      if location == "" and item == "":
         print "Starting game..."
         # starter_room (disabled until room is actually made)
      elif location and item:
         print "You picked up %s." % item
         inventory.append(item)
         getattr(self, location)()
      elif location and item == "":
         print "You enter the room."
         getattr(self, location)()
      else:
         print "Error: Closing game."

maze = Maze()
while True:   # or whatever you want as stop condition
   location = raw_input("enter your location :")
   item = raw_input("enter your location :")
   maze.shell(location=location, item=item)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...