commands.py 5.15 KB

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

class CommandHandler(object):

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

  def look(self):
    self.mud.send_message(self.id, "")
    if len(self.tokens) > 0 and self.tokens[0] == 'at':
        del self.tokens[0]
    if len(self.tokens) == 0:
        self.mud.send_message(self.id, self.room.get_description())
    else:
        subject = self.tokens[0]
        items = self.room.get_look_items()
        for item in items:
            if subject in item:
                self.mud.send_message(self.id, items[item])
                return True
        self.mud.send_message(self.id, "That doesn't seem to be here.")

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

    # send player a message containing the list of players in the room
    self.mud.send_message(self.id, "Players here: {}".format(
                                            ", ".join(playershere)))

    # send player a message containing the list of exits from this room
    self.mud.send_message(self.id, "Exits are: {}".format(
                                  ", ".join(self.room.get_exits())))

    return True

  def who(self):
    self.mud.send_message(self.id, "")
    self.mud.send_message(self.id, "-------- {} Players Currently Online --------".format(len(self.players)))
    for pid, player in self.players.items():
        self.mud.send_message(self.id, "   " + player["name"])
    self.mud.send_message(self.id, "---------------------------------------------".format(len(self.players)))
    self.mud.send_message(self.id, "")
    return True

  def go(self):
    # store the exit name
    ex = self.params.lower().strip()

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

        # update the player's current room to the one the exit leads to
        loaded = self.load_room(self.room.get_exits()[ex])
        if loaded == None:
            self.mud.send_message(id, "An invisible force prevents you from going in that direction.")
            return True
        else:
            self.players[self.id]["room"] = self.room.get_exits()[ex]
            self.room = loaded

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

        # send the player a message telling them where they are now
        self.mud.send_message(id, "You arrive at '{}'".format(self.room.get_title()))

    # the specified exit wasn't found in the current room
    else:
        # send back an 'unknown exit' message
        self.mud.send_message(id, "Unknown exit '{}'".format(ex))
    return True


  def alias(self, command):
    if command in global_aliases:
        return global_aliases[command]
    if 'aliases' not in self.players[self.id]:
        self.players[self.id]["aliases"] = {}
    if command in self.players[self.id]["aliases"]:
        return self.players[self.id]["aliases"][command]
    return command

  def parse(self, id, cmd, params, room, mud, players, load_room):
    self.id = id
    self.params = params
    self.tokenize_params()
    self.room = room
    self.mud = mud
    self.players = players
    self.load_room = load_room
    self.cmd = self.alias(cmd)

    try:
        if self.cmd in self.room.get_exits():
            self.params = self.cmd + " " + self.params
            self.cmd = "go"
        method = getattr(self, self.cmd)
        return method()
    except AttributeError:
        mud.send_message(id, "Unknown command '{}'".format(self.cmd))
        return False