How to construct a basic parse to treat a sentence and extract an action contained in it that will be executed?

-2

I'm trying to mount a simple parse to parse commands entered by a user into a game of type Text Adventure . However, I've never had experience with it and I do not know if the structure and types of words I'm using are correct.

The class Parse contains the basic structure of the sentence that will be analyzed, see:

class Parse(object):
    def __init__(self, sentenca=''):
        self.sentenca = sentenca
        self.acoes = ['pega', 'use', 'olhe', 'ir', 'examine']
        self.verbos = ['pegar', 'usar', 'olhar', 'examinar']
        self.direcoes = ['norte', 'sul', 'leste','oeste']
        self.acaoatual = None
        self.direcaodestino = None
        if not self.sentenca.strip():
            raise Exception('A setenca informada nao eh uma setenca valida.')            

    @staticmethod
    def _extrairpalavras(sentenca=''):        
        if not sentenca:
            return None
        return sentenca.lower().split(' ')

    def parseAcao(self):        
        palavras = Parse._extrairpalavras(sentenca=self.sentenca)
        if palavras:
            for p in palavras:
                if p in self.acoes or p in self.verbos:
                    self.acaoatual = p
                    break

    def parseDirecao(self):
        palavras = Parse._extrairpalavras(sentenca=self.sentenca)
        if palavras:
            for p in palavras:
                if p in self.direcoes:
                    self.direcaodestino = p
                    break 

A small example of usage:

parse = Parse('pegar item')
parse.parseAcao()
parse.parseDirecao()
print(parse.acaoatual)
print(parse.direcaodestino)

Output:

  

pick up   None

The idea here is to use this parse in the future with two other classes that are:

Class Ambiente :

class Ambiente(object):
    def __init__(self, id=None, titulo='', descricao='', itens=[]):
        self.id = id
        self.titulo = titulo
        self.descricao = descricao
        self.itens = itens

And Item :

class Item(object):
    def __init__(self, id=None, descricao='', texto='', pegavel=False, pegado=False, usado=False):
        self.id = id
        self.descricao = descricao
        self.texto = texto
        self.pegavel = pegavel
        self.pegado = pegado
        self.usado = usado

In which class Ambiente represents a room that the protagonist is, and it will be possible to navigate from one room to another.

And the Item class will be pickable items, usable or not that will be in certain environments, some are a complement to the story. Of course I will create other classes, even a class to represent the protagonist. And this parse that I created is very limited and went as far as I could get.

Given this, I have doubts regarding grammar rules and structure and how parse should parse the sentence that has been reported by the user. Given that the primary actions for the basic operation of the game I want and which can be performed are:

 - Olhar
 - Locomover
 - Pegar um Item
 - Usar um Item
 - Examinar um item

So I can already have a basic and functional game limiting just these actions above. Here are the questions below.

Questions

  • How could I build a basic parse to handle a sentence and get it treat the words and correlate them with the action that will it be executed?
  • Do I need to adopt some grammatical rules? If so, which ones?
  • It is necessary to use a data structure as a tree for the parse or a simple list is enough?
  • asked by anonymous 08.09.2018 / 23:46

    1 answer

    2

    A simple way to read commands and call the correct function is to use the cmd module that comes with python. For example:

    comando> ajuda
    
    Comandos disponíveis:
    =====================
    ajuda  andar  help  pegar  sair
    
    comando> ajuda andar
    Anda em uma das direções possíveis
    comando> andar diagonal
    Não há saída para este lado!
    comando> andar norte
    Você se desloca no sentido norte
    comando> pegar faca
    Voce pegou o item: faca
    comando> pegar flor
    flor não disponível no momento
    

    This example execution was done with this class:

    import cmd
    
    class GameCommand(cmd.Cmd):
        prompt = "comando> "
        direcoes = ['norte', 'sul', 'leste', 'oeste', 'cima', 'baixo']
        doc_header = 'Comandos disponíveis:'
    
        def do_ajuda(self, comando):
            """Mostra ajuda"""
            return self.do_help(comando)
    
        def do_pegar(self, item):
            """Pega um item que esteja no local atual"""
            items = ['faca', 'disco', 'celular']
            if item in items:
                print('Voce pegou o item:', item)
            else:
                print(item, 'não disponível no momento')
    
        def do_andar(self, direcao):
            """Anda em uma das direções possíveis"""
            if direcao in self.direcoes:
                print('Você se desloca no sentido', direcao)
            else:
                print('Não há saída para este lado!')
    
        def do_sair(self, _ign):
            """Sai do jogo, lembre-se de salvar antes"""
            print('Saindo do jogo!!')
            return True
    
    if __name__ == '__main__':
        c = GameCommand()
        c.cmdloop()
    

    Remember that this is a simple example, this class would serve only for you to interpret the commands. You would have to create classes for the elements of the game as you are already doing ...

    This form of interpretation uses simpler syntax " comando argumentos " so it does not use grammar rules. But it can serve as a guide to how you will dispatch each command typed for a specific function that is executed.

        
    10.09.2018 / 17:21