commandhandler.py 38.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
import utils
import sys

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',
    'equipment': 'equip',
    'wear': 'equip',
    'eq': 'equip',
    'goto': 'go',
    'sc': 'score'
}


class Commands(object):


    def actions(self, id, params, players, mud, tokens, command):
        mud.send_message(id, '\r\n-Action----------=Actions=-----------Cost-\r\n')
        for name, action in players[id]['at'].items():
            mud.send_message(id, '{} {}'.format("%-37s" % name, action['cost']))
        mud.send_message(id, '\r\n------------------------------------------\r\n')
        mud.send_message(id, 'For more detail on a specific action use "help [action]"')


    # for now spells can only be cast on the thing you are fighting since I don't have a good lexer to pull
    # out targets. This also means that spells are offensive only since you cant cast on 'me'
    # TODO: Add proper parsing so you can do: cast fireball on turkey or even better, cast fireball on the first turkey
    def cast(self, id, params, players, mud, tokens, command):
        if params == '':
            params = command.strip()
        else:
            params = params.strip()
        if len(params) == 0:
            mud.send_message(id, 'What spell do you want to cast?')
            return True
        spell = players[id]['sp'].get(params)
        if not spell:
            mud.send_message(id, 'You do not appear to know how to cast %s.' % (params,))
            return True
        mp = players[id]['mp']
        if mp > 0 and mp > spell['cost']:
            room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
            if not room_monsters:
                mud.send_message(id, 'There is nothing here to cast that spell on.')
            for mon_name, monster in room_monsters.items():
                monster_template = utils.load_object_from_file('mobs/{}.json'.format(mon_name))
                if not monster_template:
                    continue
                fighting = False
                for active_monster_idx, active_monster in enumerate(monster['active']):
                    if active_monster['action'] == "attack" and active_monster['target'] == players[id]['name']:
                        fighting = True
                        att, mp = utils.calc_att(mud, id, [], mp, spell)

                        players[id]['mp'] = mp
                        active_monster['hp'] -= att
                        # don't let them off without saving cheating sons of bees
                        utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                        room_monsters[mon_name]['active'][active_monster_idx] = active_monster
                if not fighting:
                    mud.send_message(id, 'You are not currently in combat')
                    return True
                
            utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
        else:
            mud.send_message(id, 'You do not have enough mana to cast that spell.')

    def drop(self, id, params, players, mud, tokens, command):
        room_name = players[id]["room"]
        if len(tokens) == 0:
            mud.send_message(id, 'What do you want to drop?')
            return True
        room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
        if tokens[0] in players[id]['inventory']:
            if tokens[0] in room_data['inventory']:
                room_data['inventory'][tokens[0]].append(players[id]['inventory'][tokens[0]].pop())
            else:
                room_data['inventory'][tokens[0]] = [players[id]['inventory'][tokens[0]].pop()]
            if len(players[id]['inventory'][tokens[0]]) <= 0:
                del players[id]['inventory'][tokens[0]]

            utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
            for pid, pl in players.items():
                # if they're in the same room as the player
                if players[pid]["room"] == players[id]["room"]:
                    # send them a message telling them what the player said
                    mud.send_message(pid, "{} dropped a {}.".format(
                                                players[id]["name"], tokens[0]))
            utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
        else:
            mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))


    def emote(self, id, params, players, mud, tokens, command):
        # go through every player in the game
        for pid, pl in players.items():
            # if they're in the same room as the player
            if players[pid]["room"] == players[id]["room"]:
                # send them a message telling them what the player said
                mud.send_message(pid, "{} {}".format(players[id]["name"], params))


    def equip(self, id, params, players, mud, tokens, command):
        if len(tokens) == 0:
            mud.send_message(id, "  %green+-Item---------------------=Equipment=------------------Loc----+", nowrap=True)
            if players[id].get('equipment'):
                for item, item_list in players[id]['equipment'].items():
                    if isinstance(item_list, list):
                        vals = [val for val in item_list if val]
                        if len(vals) > 0:
                            mud.send_message(id, '  %green|%reset {} {} %green|'.format("%-51s" % ', '.join(vals), '{0: <8}'.format(item)))
                        else:
                            mud.send_message(id, '  %green|%reset {} {} %green|'.format("%-51s" % 'None', '{0: <8}'.format(item)))
                    else:
                        mud.send_message(id, '  %green|%reset {} {} %green|'.format("%-51s" % item_list or "None", '{0: <8}'.format(item)))
                mud.send_message(id, '  %green|%reset {} {} %green|'.format("%-51s" % players[id]['weapon'] or "None", '{0: <8}'.format('weapon')))
            mud.send_message(id, "  %green+--------------------------------------------------------------+", nowrap=True)
        else:
            if tokens[0] not in players[id]["inventory"]:
                mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
            else:
                gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
                if gear["type"] == "weapon":
                    mud.send_message(id, 'That is a weapon and must be "wield".')
                elif gear["type"] != "armor":
                    mud.send_message(id, 'That cannot be worn.')
                else:
                    players[id]["equipment"][gear['loc']] = tokens[0]
                    mud.send_message(id, 'You wear the {} on your {}.'.format(tokens[0], gear['loc']))
                    players[id]["inventory"][tokens[0]].pop()
                    if len(players[id]["inventory"][tokens[0]]) == 0:
                        del players[id]["inventory"][tokens[0]]
                        
                    utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))

    def get(self, id, params, players, mud, tokens, command):
        room_name = players[id]["room"]
        if len(tokens) == 0:
            mud.send_message(id, 'What do you want to get?')
            return True

        room_data = utils.load_object_from_file('rooms/' + room_name + '.json')

        container = None
        if any(x in params for x in ['from', 'out of']):
            if 'out of' in params:
                container = params.split('out of')[1].strip()
            else:
                container = params.split('from')[1].strip()
            if room_data["inventory"].get(container) is None and players[id]["inventory"].get(container) is None:
                mud.send_message(id, 'You do not see the container {} here.'.format(container))
                return True

        if container:
            found = False
            if container in players[id]["inventory"]:
                if tokens[0] in players[id]['inventory'][container][0]['inventory']:
                    found = True
                    if tokens[0] in players[id]['inventory']:
                        print(players[id]['inventory'][container][0]['inventory'][tokens[0]])
                        players[id]['inventory'][tokens[0]].append(players[id]['inventory'][container][0]['inventory'][tokens[0]].pop())
                    else:
                        players[id]['inventory'][tokens[0]] = [players[id]['inventory'][container][0]['inventory'][tokens[0]].pop()]
                    if len(players[id]['inventory'][container][0]['inventory'][tokens[0]]) <= 0:
                        del players[id]['inventory'][container][0]['inventory'][tokens[0]]
            elif container in room_data["inventory"]:
                if tokens[0] in room_data['inventory'][container][0]['inventory']:
                    found = True
                    if tokens[0] in players[id]['inventory']:
                        players[id]['inventory'][tokens[0]].append(room_data['inventory'][container][0]['inventory'][tokens[0]].pop())
                    else:
                        players[id]['inventory'][tokens[0]] = [room_data['inventory'][container][0]['inventory'][tokens[0]].pop()]
                    if len(room_data['inventory'][container][0]['inventory'][tokens[0]]) <= 0:
                        del room_data['inventory'][container][0]['inventory'][tokens[0]]
            if not found:
                mud.send_message(id, 'You do not see a {} in the {}.'.format(tokens[0], container))
            else:
                for pid, pl in players.items():
                    # if they're in the same room as the player
                    if players[pid]["room"] == players[id]["room"]:
                        # send them a message telling them what the player said
                        mud.send_message(pid, "{} picked up a {} from a {}.".format(players[id]["name"], tokens[0], container))
                utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
            return True
        else:
            if tokens[0] in room_data.get('inventory'):
                if tokens[0] in players[id]['inventory']:
                    players[id]['inventory'][tokens[0]].append(room_data['inventory'][tokens[0]].pop())
                else:
                    players[id]['inventory'][tokens[0]] = [room_data['inventory'][tokens[0]].pop()]

                if len(room_data['inventory'][tokens[0]]) <= 0:
                    del room_data['inventory'][tokens[0]]
                for pid, pl in players.items():
                    # if they're in the same room as the player
                    if players[pid]["room"] == players[id]["room"]:
                        # send them a message telling them what the player said
                        mud.send_message(pid, "{} picked up a {}.".format(
                                                    players[id]["name"], tokens[0]))
                utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
            else:
                mud.send_message(id, 'There is no {} here to get.'.format(tokens[0]))


    def go(self, id, params, players, mud, tokens, command):
        # store the exit name
        if params == '':
            params = command.strip().lower()
        else:
            params = params.strip().lower()

        room_data = utils.load_object_from_file('rooms/' + players[id]["room"] + '.json')

        # if the specified exit is found in the room's exits list
        exits = room_data['exits']

        if params in exits:
            # go through all the players in the game
            for pid, pl in players.items():
                # if player is in the same room and isn't the player
                # sending the command
                if players[pid]["room"] == players[id]["room"] \
                        and pid != id:
                    # send them a message telling them that the player
                    # left the room
                    mud.send_message(pid, "{} left via exit '{}'".format(
                                                  players[id]["name"], params))

            # update the player's current room to the one the exit leads to
            
            if exits[params] == None:
                mud.send_message(id, "An invisible force prevents you from going in that direction.")
                return None
            else:
                new_room = utils.load_object_from_file('rooms/' + exits[params][0] + '.json')
                if not new_room:
                    mud.send_message(id, "An invisible force prevents you from going in that direction.")
                    return None
                else:
                    players[id]["room"] = exits[params][0]
                    utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                    mud.send_message(id, "You arrive at '{}'".format(new_room['title']))

            # go through all the players in the game
            for pid, pl in players.items():
                # if player is in the same (new) room and isn't the player
                # sending the command
                if players[pid]["room"] == players[id]["room"] \
                        and pid != id:
                    # send them a message telling them that the player
                    # entered the room
                    mud.send_message(pid,
                                     "{} arrived via exit '{}'".format(
                                                  players[id]["name"], params))

            # send the player a message telling them where they are now
            tokens = []
            return self.look(id, params, players, mud, tokens, command)
        # the specified exit wasn't found in the current room
        else:
            # send back an 'unknown exit' message
            mud.send_message(id, "Unknown exit '{}'".format(params))


    def help(self, id, params, players, mud, tokens, command):
        if len(tokens) > 0:
            filename = 'help/' + tokens[0] + '.txt'
        else:
            filename = 'help/help.txt'
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                for line in f:
                    mud.send_message(id, line, '\r')
                mud.send_message(id, '')
        except:
            mud.send_message(id, 'No help topics available for \"{}\". A list\r\n of all commands is available at: help index'.format(tokens[0]))


    def inventory(self, id, params, players, mud, tokens, command):
        mud.send_message(id, "  %green+-Item---------------------=Inventory=--------------------Qty--+", nowrap=True)
        for item, item_list in players[id]['inventory'].items():
            mud.send_message(id, '  %green|%reset {} {:^4} %green|'.format("%-55s" % item, str(len(item_list))))
        mud.send_message(id, "  %green+--------------------------------------------------------------+", nowrap=True)

    def kill(self, id, params, players, mud, tokens, command):
        if len(params) == 0:
            mud.send_message(id, 'What did you want to attack?')
            return True
        room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
        for mon_name, monster in room_monsters.items():
            if mon_name in params.lower():
                if len(monster['active']) > 0:
                    if monster['active'][0]['target'] == players[id]['name']:
                        mud.send_message(id, 'You are already engaged in combat with that target.')
                        return True
                    else:
                        room_monsters[mon_name]['active'][0]['target'] = players[id]['name']
                        mud.send_message(id, 'You attack the {}.'.format(mon_name), color=['red', 'bold'])
                        utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
                        return True
        if params[0] in 'aeiou':
            mud.send_message(id, 'You do not see an {} here.'.format(params))
        else:
            mud.send_message(id, 'You do not see a {} here.'.format(params))


    def look(self, id, params, players, mud, tokens, command):
        room_name = players[id]["room"]
        room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
        room_monsters = utils.load_object_from_file('rooms/' + room_name + '_monsters.json')
        mud.send_message(id, "")
        if len(tokens) > 0 and tokens[0] == 'at':
            del tokens[0]
        container = False
        if len(tokens) > 0 and tokens[0] == 'in':
            del tokens[0]
            container = True
        if len(tokens) == 0:
            exits = {}
            for exit_name, exit in room_data.get('exits').items():
                exits[exit_name] = exit[1]
            print(room_data)
            # clid, name, zone, terrain, description, exits, coords
            mud.send_room(id, room_data.get('num'), room_data.get('title'), room_data.get('zone'),
                          'City', '', exits, room_data.get('coords'))
            mud.send_message(id, room_data.get('title'), color=['bold', 'green'])
            mud.send_message(id, room_data.get('description'), line_ending='\r\n\r\n', color='green')
        else:
            subject = tokens[0]
            items = room_data.get('look_items')
            for item in items:
                if subject in item:
                    mud.send_message(id, items[item])
                    return True
            if subject in room_data['inventory']:
                if container and room_data["inventory"][subject][0].get("inventory") is not None:
                    items = room_data["inventory"][subject][0]["inventory"]
                    if len(items) > 0:
                        mud.send_message(id, 'You look in the {} and see:\r\n'.format(subject))
                        inv_list = []
                        for name, i in items.items():
                            if len(i) > 1:
                                inv_list.append(str(len(i)) + " " + name + "s")
                            else:
                                inv_list.append(name)
                        mud.send_list(id, inv_list, "look")

                    else:
                        mud.send_message(id, 'You look in the {} and see nothing.'.format(subject))
                else:
                    item = utils.load_object_from_file('inventory/' + subject + '.json')
                    mud.send_message(id, 'You see {}'.format(item.get('description')))                
                return True
            if subject in players[id]['inventory']:
                if container and players[id]["inventory"][subject][0].get("inventory") is not None:
                    items = players[id]["inventory"][subject][0]["inventory"]
                    if len(items) > 0:
                        mud.send_message(id, 'You look in your {} and see:\r\n'.format(subject))
                        inv_list = []
                        print(items)
                        for name, i in items.items():
                            if len(i) > 1:
                                inv_list.append(str(len(i)) + " " + name + "s")
                            else:
                                inv_list.append(name)
                        mud.send_list(id, inv_list, "look")
                    else:
                        mud.send_message(id, 'You look in your {} and see nothing.'.format(subject))
                else:
                    item = utils.load_object_from_file('inventory/' + subject + '.json')
                    mud.send_message(id, 'You check your inventory and see {}'.format(item.get('description')))
                return True
            if subject in room_monsters:
                if len(room_monsters[subject]['active']) > 0:
                    monster_template = utils.load_object_from_file('mobs/{}.json'.format(subject))
                    if monster_template:
                        mud.send_message(id, 'You see {}'.format(monster_template.get('desc').lower()))
                        return True
            mud.send_message(id, "That doesn't seem to be here.")
            return

        playershere = []
        # go through every player in the game
        for pid, pl in players.items():
            # if they're in the same room as the player
            if players[pid]["room"] == players[id]["room"]:
                # ... and they have a name to be shown
                if players[pid]["name"] is not None and players[id]["name"] != players[pid]["name"]:
                    # add their name to the list
                    playershere.append(players[pid]["name"])

        # send player a message containing the list of players in the room
        if len(playershere) > 0:
            mud.send_message(id, "%boldPlayers here:%reset {}".format(", ".join(playershere)))

        mud.send_message(id, "%boldObvious Exits:%reset ", line_ending='')
        mud.send_list(id, room_data.get('exits'), "go")

        # send player a message containing the list of exits from this room
        if len(room_data.get('inventory')) > 0:
            mud.send_message(id, "%boldItems here:%reset ", line_ending='')
            inv_list = []
            for name, i in room_data.get('inventory').items():
                if len(i) > 1:
                    inv_list.append(str(len(i)) + " " + name + "s")
                else:
                    inv_list.append(name)
            mud.send_list(id, inv_list, "look")

        # send player a message containing the list of players in the room
        for mon_name, monster in room_monsters.items():
            count = len(monster['active'])
            if count > 1:
                mud.send_message(id, "{} {} are here.".format(count, mon_name))
            elif count > 0:
                mud.send_message(id, "a {} is here.".format(mon_name))



    # for now actions can only be cast on the thing you are fighting since I don't have a good lexer to pull
    # out targets. This also means that actions are offensive only since you cant cast on 'me'
    # TODO: Add proper parsing so you can do: cast fireball on turkey or even better, cast fireball on the first turkey
    def perform(self, id, params, players, mud, tokens, command):
        if params == '':
            params = command.strip()
        else:
            params = params.strip()
        if len(params) == 0:
            mud.send_message(id, 'What action do you want to perform?')
            return True
        action = players[id]['at'].get(params)
        if not action:
            mud.send_message(id, 'You do not appear to know the action %s.' % (params,))
            return True
        sta = players[id]['sta']
        if sta > 0 and sta > action['cost']:
            room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
            if not room_monsters:
                mud.send_message(id, 'There is nothing here to perform that action on.')
            for mon_name, monster in room_monsters.items():
                monster_template = utils.load_object_from_file('mobs/{}.json'.format(mon_name))
                if not monster_template:
                    continue
                fighting = False
                for active_monster_idx, active_monster in enumerate(monster['active']):
                    if active_monster['action'] == "attack" and active_monster['target'] == players[id]['name']:
                        fighting = True
                        att, sta = utils.calc_att(mud, id, [], sta, action)

                        players[id]['sta'] = sta
                        active_monster['hp'] -= att
                        # don't let them off without saving cheating sons of bees
                        utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                        room_monsters[mon_name]['active'][active_monster_idx] = active_monster
                if not fighting:
                    mud.send_message(id, 'You are not currently in combat')
                    return True
            
            utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
        else:
            mud.send_message(id, 'You do not have enough stamina to perform that action.')


    def prompt(self, id, params, players, mud, tokens, command):
        if len(tokens) == 0:
            mud.send_message(id, 'No prompt provided, no changes will be made.\r\nEx: prompt %hp>')

        players[id]['prompt'] = params + ' '
        utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))

    def put(self, id, params, players, mud, tokens, command):
        if len(tokens) == 0:
            mud.send_message(id, 'What do you want to put and where do you want to put it?')
            return True
        subject = tokens[0]
        if 'in' == tokens[1]:
            del tokens[1]
        dest = tokens[1]

        room_name = players[id]["room"]
        room_data = utils.load_object_from_file('rooms/' + room_name + '.json')

        if subject in players[id]['inventory']:
            if dest in players[id]['inventory'] or dest in room_data['inventory']:

                if dest in room_data['inventory']:
                    if len(room_data['inventory'][dest][0]["inventory"]) == 0 and not room_data['inventory'][dest][0]["inventory"].get(subject):
                        room_data['inventory'][dest][0]["inventory"][subject] = [players[id]['inventory'][subject].pop()]
                    else:
                        room_data['inventory'][dest][0]["inventory"][subject].append(players[id]['inventory'][subject].pop())
                elif dest in players[id]['inventory']:
                    #print(players[id]['inventory'][dest][0]["inventory"])
                    print(players[id]['inventory'][dest][0]["inventory"].get(subject))
                    if len(players[id]['inventory'][dest][0]["inventory"]) == 0 and not players[id]['inventory'][dest][0]["inventory"].get(subject):
                        players[id]['inventory'][dest][0]["inventory"][subject] = [players[id]['inventory'][subject].pop()]
                    else:
                        players[id]['inventory'][dest][0]["inventory"][subject].append(players[id]['inventory'][subject].pop())
                if len(players[id]['inventory'][tokens[0]]) <= 0:
                    del players[id]['inventory'][tokens[0]]

                utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
                for pid, pl in players.items():
                    # if they're in the same room as the player
                    if players[pid]["room"] == players[id]["room"]:
                        # send them a message telling them what the player said
                        mud.send_message(pid, "{} put a {} in a {}.".format(players[id]["name"], subject, dest))
                utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
            else:
                mud.send_message(id, 'You cannot put {} in {} since it is not here.'.format(subject, dest))
        else:
            mud.send_message(id, 'You do not have {} in your inventory.'.format(subject))


    def quit(self, id, params, players, mud, tokens, command):
        # send the player back the list of possible commands
        mud.send_message(id, "Saving...")
        utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
        mud.disconnect_player(id)


    def remove(self, id, params, players, mud, tokens, command):
        if len(tokens) == 0:
            mud.send_message(id, 'What do you want to stop wearing?')
        else:
            for item, item_list in players[id]['equipment'].items():
                if isinstance(item_list, list):
                    for idx, li in enumerate(item_list):
                        print(li)
                        if li == tokens[0]:
                            item_list[idx] = None
                            if tokens[0] in players[id]['inventory']:
                                players[id]['inventory'][tokens[0]].append({"expries": 0})
                            else:
                                players[id]['inventory'][tokens[0]] = [{"expries": 0}]
                            mud.send_message(id, 'You remove the {}.'.format(tokens[0]))
                            utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                            return
                elif item_list == tokens[0]:
                    players[id]['equipment'][item] = None
                    if tokens[0] in players[id]['inventory']:
                        players[id]['inventory'][tokens[0]].append({"expries": 0})
                    else:
                        players[id]['inventory'][tokens[0]] = [{"expries": 0}]
                    mud.send_message(id, 'You remove the {}.'.format(tokens[0]))
                    utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                    return

            if tokens[0] == players[id]['weapon']:
                if tokens[0] in players[id]['inventory']:
                    players[id]['inventory'][tokens[0]].append({"expries": 0})
                else:
                    players[id]['inventory'][tokens[0]] = [{"expries": 0}]
                mud.send_message(id, 'You unwield the {}.'.format(tokens[0]))
                utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
                return

            mud.send_message(id, 'You are not wearing a {}.'.format(tokens[0]))
            # else:
            #     gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
            #     if gear["type"] == "weapon":
            #         mud.send_message(id, 'That is a weapon and must be "wield".'.format(tokens[0]))
            #     elif gear["type"] != "armor":
            #         mud.send_message(id, 'That cannot be worn.'.format(tokens[0]))
            #     else:
            #         players[id]["equipment"][gear['loc']] = tokens[0]
            #         mud.send_message(id, 'You wear the {} on your {}.'.format(tokens[0], gear['loc']))
            #         if len(players[id]["inventory"][tokens[0]]) == 0:
            #             del players[id]["inventory"][tokens[0]]
            #         else:
            #             players[id]["inventory"][tokens[0]].pop()
            #         utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))


    def save(self, id, params, players, mud, tokens, command):
        # send the player back the list of possible commands
        mud.send_message(id, "Saving...")
        utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
        mud.send_message(id, "Save complete")
        return True


    def say(self, id, params, players, mud, tokens, command):
        # go through every player in the game
        for pid, pl in players.items():
            # if they're in the same room as the player
            if players[pid]["room"] == players[id]["room"]:
                # send them a message telling them what the player said
                mud.send_message(pid, "{} says: {}".format(
                                            players[id]["name"], params))


    def score(self, id, params, players, mud, tokens, command):
        from math import floor
        
        mud.send_message(id, "  %green+----------------------------=Score=---------------------------+", nowrap=True)
        hp = "{:^12}".format(str(floor(players[id]['hp'])) + str(floor(players[id]['maxhp'])))
        mp = "{:^12}".format(str(floor(players[id]['mp'])) + str(floor(players[id]['maxmp'])))
        sta = "{:^12}".format(str(floor(players[id]['sta'])) + str(floor(players[id]['maxsta'])))
        # hp = str("%d/%s" % (floor(players[id]['hp']), '{:^12}'.format(floor(players[id]['maxhp']))))
        # mp = str("%d/%s" % (floor(players[id]['mp']), '{:^12}'.format(floor(players[id]['maxmp']))))
        # sta = str("%d/%s" % (floor(players[id]['sta']), '{:^12}'.format(floor(players[id]['maxsta']))))

        mud.send_message(id, "  %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{:^62}'.format(players[id]["name"]),), nowrap=True)
        mud.send_message(id, "  %green+--------------------------------------------------------------+", nowrap=True)
        mud.send_message(id, "  %%green|%%reset %%cyanHP:%%reset %%white[%s]%%reset %%green|%%reset %%cyanMP:%%reset %%white[%s]%%reset %%green|%%reset %%cyanST:%%reset %%white[%s]%%reset %%green|%%reset" % (hp, mp, sta), nowrap=True)
        

      #   output = """
      # --------------------------------------------
      # HP:  {hp}    Max HP:  {maxhp}
      # MP:  {mp}    Max MP:  {maxmp}
      # Sta: {sta}   Max Sta: {maxsta}
      # Experience: {exp}
      # Skills:""".format(hp=floor(players[id]['hp']),
      #          mp=floor(players[id]['mp']),
      #          maxhp=floor(players[id]['maxhp']),
      #          maxmp=floor(players[id]['maxmp']),
      #          sta=floor(players[id]['sta']),
      #          maxsta=floor(players[id]['maxsta']),
      #          exp=0)
        # mud.send_message(id, output)

        mud.send_message(id, "  %green+---------------------------=Skills=---------------------------+", nowrap=True)
        skills = ["skillasdfasdfasdfasdf", "skill 2 sdfg sdfg", "Skill 3 asdf ewrewwr"]
        for skill in skills:
            mud.send_message(id, "  %green|%reset {0: <61}%green|%reset".format(skill), nowrap=True)

        mud.send_message(id, "  %green+--------------------------------------------------------------+", nowrap=True)


    def spells(self, id, params, players, mud, tokens, command):
        mud.send_message(id, '\r\n-Spell-----------=Spells=-----------Cost-\r\n')
        for name, spell in players[id]['sp'].items():
            mud.send_message(id, '{} {}'.format("%-37s" % name, spell['cost']))
        mud.send_message(id, '\r\n-----------------------------------------\r\n')
        mud.send_message(id, 'For more detail on a specific spell use "help <spell>"')


    def whisper(self, id, params, players, mud, tokens, command):
        # go through every player in the game
        for pid, pl in players.items():
            # if they're in the same room as the player
            if players[pid]["name"] == tokens[0]:
                # send them a message telling them what the player said
                mud.send_message(pid, "{} whispers: {}".format(
                                            players[id]["name"], ' '.join(tokens[1:])))


    def who(self, id, params, players, mud, tokens, command):
        mud.send_message(id, "")
        mud.send_message(id, "-------- {} Players Currently Online --------".format(len(players)))
        for pid, player in players.items():
            if player["name"] is None:
                continue
            mud.send_message(id, "   " + player["name"])
        mud.send_message(id, "---------------------------------------------".format(len(players)))
        mud.send_message(id, "")


    def wield(self, id, params, players, mud, tokens, command):
        if len(tokens) == 0:
            mud.send_message(id, " %greenYou are currently wielding: %reset%bold%white{}".format(players[id]['weapon']))
        else:
            if tokens[0] not in players[id]["inventory"]:
                mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
            else:
                gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
                if gear["type"] == "armor":
                    mud.send_message(id, 'That is armor and must be "equip".')
                elif gear["type"] != "weapon":
                    mud.send_message(id, 'That cannot be wielded.')
                else:
                    players[id]["weapon"] = tokens[0]
                    mud.send_message(id, 'You wield the {}!'.format(tokens[0]))
                    players[id]["inventory"][tokens[0]].pop()
                    if len(players[id]["inventory"][tokens[0]]) == 0:
                        del players[id]["inventory"][tokens[0]]

                    utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))


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)

        try:
            if cmd in (exit.lower() for exit 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
            commands = Commands()
            command_method = getattr(commands, cmd, None)
            if callable(command_method):
                params = params.lower().strip()
                return command_method(id, params, players, mud, tokens, cmd)
            # else:
            #     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
            #raise Exception("Missing command: {}".format(cmd))
        except Exception as e:
            print('Command handler exception:')
            if 'esp' not in sys.platform:
                import traceback
                traceback.print_exc()
            else:
                print(repr(e))
                #raise
            mud.send_message(id, "Unknown command '{}'".format(cmd))
            return False