How to associate a set of words to a "do_" method of class Cmd?

2

I'm using the Cmd class of Python's cmd module to create an interpreter for a game in Text Adventure. However, I came up with a problem regarding the words I use as methods for the interpreter to execute.

See this example example:

import cmd

class Comando(cmd.Cmd):
  prompt = ">"

  def do_olhar(self, valor):
    print('Olhar em volta')

  def do_ver(self, valor):
    print('Olhar em volta')

  def do_pegar(self, valor):
    print('Pegar algo')

  def do_pega(self, valor):
    print('Pegar algo')

  def do_obter(self, valor):
    print('Pegar algo')

c = Comando()
c.cmdloop()

Notice that some words are similar and have the same purposes, such as obter , pegar , pega , olha , olhar and ver .

So, I would like to know if it is possible to create a method that is associated with a set of words and not just one as is the case above i.e. do_palavra() ?

    
asked by anonymous 17.10.2018 / 04:34

1 answer

2

You can also use the cmd.precmd method, which according to documentation:

  

Cmd.precmd (line)

     

Hook method executed just before the command line line is interpreted,   but after the input prompt is generated and issued. This method is a   stub in Cmd; it exists to be overridden by subclasses. The return   value is used as the command which will be executed by the onecmd ()   method; the precmd () implementation may re-write the command or simply   return line unchanged.

The method always runs before the final command is executed and the value returned is the new command. In this case, you can analyze the value of line , check if the command entered is a synonym of another and return it.

SINONIMOS = {
  'ver': 'olhar',
  'pega': 'pegar',
  'obter': 'pegar'
}

def precmd(self, line):
  command, arguments, line = self.parseline(line)
  command = self.SINONIMOS.get(command, command)
  return ' '.join([command, arguments])

It would look something like this:

import cmd

class Comando(cmd.Cmd):
  prompt = ">"

  SINONIMOS = {
    'ver': 'olhar',
    'pega': 'pegar',
    'obter': 'pegar'
  }

  def precmd(self, line):
    command, arguments, line = self.parseline(line)
    command = self.SINONIMOS.get(command, command)
    return ' '.join([command, arguments])

  def do_olhar(self, valor):
    print('Olhar em volta')

  def do_pegar(self, valor):
    print('Pegar algo')

  def default(self, line):
    print('Não sei o que fazer ¯\_(ツ)_/¯')

c = Comando()
c.cmdloop()

See working at Repl.it

Result:

> ver
Olhar em volta
> pega
Pegar algo
> obter
Pegar algo
> pegar
Pegar algo
    
17.10.2018 / 13:27