commandhandler.py 2.27 KB
import utils

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


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"] + '.json').get('exits'):
                params = cmd + " " + params.lower().strip()
                cmd = "go"
            if cmd in players[id]["sp"]:
                params = cmd + " " + params.lower().strip()
                cmd = "cast"
            if cmd in players[id]["at"]:
                params = cmd + " " + params.lower().strip()
                cmd = "perform"
            if cmd == '':
                return True
            command = cmd
            ldict = locals()
            with open('commands/{}.txt'.format(cmd), 'r', encoding='utf-8') as f:
                command_text = f.read()
                exec(command_text, globals(), ldict)
                del command_text
            if ldict['next_command'] is not None:
                locals()['tokens'] = []
                tokens = []
                with open('commands/{}.txt'.format(ldict['next_command']), 'r', encoding='utf-8') as f:
                    exec(f.read())
            del ldict
            return True
        except Exception as e:
            print('Something happened...')
            import sys
            if 'esp' not in sys.platform:
                import traceback
                traceback.print_exc()
            else:
                print(e)
            mud.send_message(id, "Unknown command '{}'".format(cmd))
            return False