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

Asked

Viewed 169 times

-3

I’m trying to put together a simple parse to parse commands entered by a user for a type game Text Adventure. However, I’ve never had experience with it and I don’t 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 use:

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

Exit:

catch
None

The idea here is to use this in the future parse 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 in, and it will be possible to navigate from one room to another.

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

That said, I have doubts related to grammar rules and the structure and way that parse should analyze the sentence that was informed by the user. Since the primary actions for the basic functioning of the game that I want and that 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 only these actions above. Below follows the questions.

Questions

  1. How I could build a parse basic to treat a sentence and make it treat the words and correlate them with the action that will be executed?
  2. Do I need to adopt some grammatical rules? If yes which?
  3. It is necessary to use a data structure as a tree to the parse or a simple list that’s enough?
  • Your questions are very broad for the site, but: R1) Whatever! There are endless ways to do this R2) You know! It is you who will define to what extent the program will be smart and how precise the Parsing needs to be. Most games of this type are quite simple and require the player to use the "complement verb" structure but only you set the limit of what your code will be capable of. R3) Again, it depends on what you want to do; I think you have to define use cases, phrases that you would like to be accepted and as far as you want to invest in this development.

1 answer

2


A simple way to read commands and call the correct function, is to use the module cmd which 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 of 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 game elements as you are already doing...

This form of interpretation uses a simpler syntax "comando argumentos" so you don’t use grammatical rules. But it can serve as a guide to how you will dispatch each entered command to a specific function that is executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.