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

Asked

Viewed 50 times

2

I’m using the class Cmd of module cmd Python to create an interpreter for a game in Text Adventure. However, I have come up with a problem regarding the words I use as methods for the interpreter to perform.

See this illustration 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()

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

Therefore, 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()?

1 answer

2


You can also use the method cmd.precmd, that 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 is always executed before the final command is executed and the value returned will be the new command. In this case, you can analyze the value of line, check if the informed command is synonymous with 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])

Would 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 on Repl.it

Upshot:

> ver
Olhar em volta
> pega
Pegar algo
> obter
Pegar algo
> pegar
Pegar algo
  • This method is better, I will erase my answer

  • @nosklo I think you could leave your answer, it’s good to have alternatives :)

Browser other questions tagged

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