commandhandler.py 1.44 KB
import utils

global_aliases = {
    'n': 'north',
    's': 'south',
    'e': 'east',
    'w': 'west',
    'u': 'up',
    'd': 'down',
    'l': 'look',
    '\'': 'say',
    'i': 'inventory',
    'inv': 'inventory',
}

class CommandHandler(object):

  def parse(self, id, cmd, params, mud, players):
    if cmd in global_aliases:
        cmd = global_aliases[cmd]
    else:
        if 'aliases' not in players[id]:
            players[id]["aliases"] = {}
        if cmd in players[id]["aliases"]:
            cmd = players[id]["aliases"][cmd]

    tokens = []
    for token in params.lower().strip().split(' '):
        token = token.strip()
        if len(token) > 0:
            tokens.append(token)
    locals()['tokens'] = tokens

    locals()['next_command'] = None
    try:
        if cmd in utils.load_object_from_file('rooms/' + players[id]["room"] + '.txt').get('exits'):
            params = cmd + " " + params.lower().strip()
            cmd = "go"
        ldict = locals()
        with open('commands/{}.txt'.format(cmd), 'r', encoding='utf-8') as f:
            exec(f.read(), globals(), ldict)
        if ldict['next_command'] != None:
            with open('commands/{}.txt'.format(ldict['next_command']), 'r', encoding='utf-8') as f:
                exec(f.read())
        return True
    except Exception as e:
        print('Something happened...')
        print(e)
        mud.send_message(id, "Unknown command '{}'".format(cmd))
        return False