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.