def enter(self, p, cons, oDO, oIDO):
     (sV, sDO, sPrep, sIDO) = p.diagram_sentence(p.words)
     if sDO == 'waterfall':
         if cons.user.wizardry_element != 'water':
             cons.user.perceive(
                 'You try to enter the waterfall, but get swept back by the rushing current.'
             )
             cons.user.emit(
                 '&nD%s dives into the waterfall, but gets swept back by the rushing current.'
             )
             return True
         dest = gametools.load_room('domains.school.school.water_lounge')
         if dest == None:
             cons.user.perceive(
                 "You try to enter the waterfall, but an error occurs! Please report it."
             )
             dbg.debug('Error! dest() of waterfall returned None on load!')
             return True
         cons.user.perceive(
             'You dive into the waterfall, and find yourself somewhere quite different.'
         )
         cons.user.emit(
             '&nD%s dives into the waterfall and dissapears from view.')
         cons.user.move_to(dest)
         dest.report_arrival(cons.user)
         return True
     return "Did you mean to enter the waterfall?"
Esempio n. 2
0
 def register_heartbeat(self, obj):
     """Add the specified object (obj) to the heartbeat_users list"""
     if obj not in self.heartbeat_users:
         self.heartbeat_users.append(obj)
     else:
         dbg.debug(
             "object %s is already in the heartbeat_users list!" % obj, 2)
Esempio n. 3
0
 def attack(self, enemy):
     if (self == enemy):
         dbg.debug('Creature tried to attack self!', 0)
         return
     chance_of_hitting = self.combat_skill + self.weapon_wielding.accuracy - enemy.get_armor_class(
     )
     if random.randint(1, 100) <= chance_of_hitting:
         d = self.weapon_wielding.damage
         damage_done = random.randint(int(d / 2), d) + self.strength / 10.0
         enemy.take_damage(damage_done)
         self.emit('&nd%s attacks &n%s with its %s!' %
                   (self, enemy, self.weapon_wielding),
                   ignore=[self, enemy])
         self.perceive('You attack &nd%s with your %s!' %
                       (enemy, self.weapon_wielding))
         enemy.perceive('&nd%s attacks you with its %s' %
                        (self, self.weapon_wielding))
         #TODO: Proper names and introductions: The monster attacks you with its sword, Cedric attacks you with his sword, Madiline attacks you with her sword.
         if self not in enemy.enemies:
             enemy.enemies.append(self)
     else:
         self.emit('&nd%s attacks &nd%s with its %s, but misses.' %
                   (self, enemy, self.weapon_wielding),
                   ignore=[self, enemy])
         self.perceive('You attack &nd%s with your %s, but miss.' %
                       (enemy, self.weapon_wielding))
         enemy.perceive('&nd%s attacks you, but misses %s.' %
                        (self, self.weapon_wielding))
Esempio n. 4
0
    def attack_enemy(self, enemy=None):
        """Attack any enemies, if possible, or if a highly aggressive Creature, attack anyone in the room."""
        targets = [
            x for x in self.location.contents
            if (isinstance(x, Creature)) and (x != self) and (
                x.invisible == False)
        ]
        assert self not in targets
        if not targets:
            return
        attacking = enemy
        if not attacking:
            for i in self.enemies:
                if i in self.location.contents and i.invisible == False:
                    attacking = i
                    assert attacking != self
                    break
        if self.aggressive == 2 and not attacking:
            attacking = random.choice(targets)
            self.enemies.append(attacking)
        dbg.debug("%s: attacking %s" % (self.id, attacking))
        self.attacking = attacking
        # Figured out who to attack, wield any weapons/armor
        self.weapon_and_armor_grab()

        if self.attack_freq() <= self.attack_now:
            self.attack(attacking)
        else:
            self.attack_now += 1
Esempio n. 5
0
    def move_around(self):
        """The NPC leaves the room, taking a random exit"""
        try:
            exit_list = list(self.location.exits)
            exit = random.choice(exit_list)
        except (AttributeError, IndexError):
            dbg.debug('NPC %s sees no exits, returning from move_around()' %
                      self.id)
            return

        dbg.debug("Trying to move to the %s exit!" % (exit))
        current_room = self.location
        new_room_string = self.location.exits[exit]
        new_room = gametools.load_room(new_room_string)
        if new_room.monster_safe:
            dbg.debug('Can\'t go to %s; monster safe room!' % new_room_string)
            return

        if new_room_string in self.forbidden_rooms:
            dbg.debug('Can\'t go to %s: forbidden to %s!' %
                      (new_room_string, self))

        self.emit("&nD%s goes %s." % (self.id, exit))
        self.move_to(new_room)
        self.emit("&nI%s arrives." % self.id)
        dbg.debug(
            "Creature %s moved to new room %s" %
            (self.names[0], new_room_string), 1)
        return
Esempio n. 6
0
 def go_to(self, p, cons, oDO, oIDO):
     words = p.words
     user = cons.user
     sExit = words[1]
     if sExit in list(self.exits):
         try:
             destPath = self.exits[
                 sExit]  # filename of the destination room module
             dest = gametools.load_room(destPath)
         except KeyError:
             dbg.debug(
                 "KeyError: exit '%s' maps to '%s' which is not an object in the game!"
                 % (sExit, self.exits[sExit]), 0)
             cons.write("There was an internal error with the exit. ")
             return True
         if cons.user.move_to(dest):
             loc = user.location
             verb = words[0]
             conjugated = "goes" if verb == "go" else verb + 's'
             cons.write("You %s to the %s." % (verb, sExit))
             self.emit("&nD%s %s to the %s." % (user.id, conjugated, sExit))
             loc.report_arrival(user)
             return True
         else:
             return "For some reason you are unable to go to the %s." % sExit
     else:  # user did not specify a valid exit
         return "I don't see how to go %s!" % sExit
Esempio n. 7
0
 def saveToConsole(self, data, ts):
   '''
   print on Console
   '''
   dbg.debug("in")
   dbg.debug("exit")
  
   return 
Esempio n. 8
0
 def deregister_heartbeat(self, obj):
     """Remove the specified object (obj) from the heartbeat_users list"""
     if obj in self.heartbeat_users:
         del self.heartbeat_users[self.heartbeat_users.index(obj)]
     else:
         dbg.debug(
             "object %s, not in heartbeat_users, tried to deregister heartbeat!"
             % obj, 2)
Esempio n. 9
0
 def cbLoopDone(result):
     """
     Called when loop was stopped with success.
     """
     dbg.debug("Loop done.")
     dbg.shut_down()
     NetworkConnection.keep_going = False
     reactor.stop()
Esempio n. 10
0
    def saveToConsole(self, data, ts):
        '''
      print on Console
      '''
        dbg.debug("in")
        dbg.debug("exit")

        return
Esempio n. 11
0
    def saveToFiles(self, data, ts):
      dbg.debug("in")

      file=FileFactory('/tmp/%s' % ts)
      file.write(data)
      file.close

      dbg.debug("exit")
      return 
Esempio n. 12
0
    def saveToFiles(self, data, ts):
        dbg.debug("in")

        file = FileFactory('/tmp/%s' % ts)
        file.write(data)
        file.close

        dbg.debug("exit")
        return
Esempio n. 13
0
    def diagram_sentence(self, words):
        """Categorize sentence type and set verb, direct/indirect object strings.
        
        Returns a tuple (sV, sDO, sPrep, sIDO)
        sV is a string containing the verb 
        sDO is a string containing the direct object, or None
        sPrep is a string containing the preposition, or None
        sIDO is a string containing the indirect object, or None
        Currently supports three sentence types, which can be detected thus: 
        1.  if sDO == None:     <intransitive verb>
        2.  elif sIDO == None:  <transitive verb> <direct object>
        3.  else:               <transitive verb> <direct object> <preposition> <indirect object>
        """

        sV = words[0]
        if len(self.words) == 1:
            # sentence type 1, <intransitive verb>
            return (sV, None, None, None)

        # list of legal prepositions
        prepositions = [
            'in', 'on', 'over', 'under', 'with', 'at', 'from', 'off', 'out',
            'into', 'away', 'around', 'onto'
        ]
        textwords = words[1:]  # all words after the verb
        text = ' '.join(textwords)

        sDO = sPrep = sIDO = None
        for p in prepositions:
            if p in textwords:
                if sV == 'go' and p == 'in':  # what is this doing?
                    continue
                idxPrep = textwords.index(p)
                sPrep = textwords[idxPrep]
                sDO = ' '.join(textwords[:idxPrep])
                sIDO = ' '.join(textwords[idxPrep + 1:])
                # break after finding 1st preposition (simple sentences only)
                break
        if sPrep == None:
            # no preposition found: Sentence type 2, direct object is all text
            assert (sDO == sIDO == None)  # sDO and sIDO should still be None
            sDO = text
            return (sV, sDO, sPrep, sIDO)
        # has a preposition: Sentence type 3 or 4
        if sDO == "": sDO = None
        if sIDO == "": sIDO = None
        if not sIDO:
            dbg.debug(
                "Possibly malformed input: found preposition %s but missing indirect object."
                % sPrep)
            dbg.debug(
                "Ending a sentence in a preposition is something up with which I will not put."
            )
        return (sV, sDO, sPrep, sIDO)
Esempio n. 14
0
 def start_loop(self):
     print("Starting game...")
     reactor.listenTCP(9123, connections.NetConnFactory())
     print("Listening on port 9123...")
     self.loop = task.LoopingCall(self.beat)
     loopDeferred = self.loop.start(1.0)
     loopDeferred.addCallback(self.cbLoopDone)
     loopDeferred.addErrback(self.ebLoopFailed)
     dbg.debug("Entering main game loop!")
     reactor.run()
     dbg.debug("Exiting main game loop!")
Esempio n. 15
0
def validate_func(modpath, func):
    try:
        mod = importlib.import_module(modpath)
        if hasattr(mod, func):
            return True
        else:
            return False
    except ImportError:
        dbg.debug("Error checking load on module %s: no module with path" %
                  modpath)
        return False
Esempio n. 16
0
 def _replace_aliases(self):
     cmd = ""
     for t in self.words:
         if t in self.alias_map:
             cmd += self.alias_map[t] + " "
             dbg.debug("Replacing alias '%s' with expansion '%s'" % (t, self.alias_map[t]), 3)
         else:
             cmd += t + " "
     cmd = cmd[:-1]   # strip trailing space added above
     dbg.debug("User input with aliases resolved:\n    %s" % (cmd), 3)
     return cmd
Esempio n. 17
0
 def is_dark(self):
     total_light = self.default_light
     obj_list = self.contents[:]
     for obj in obj_list:
         if hasattr(obj, 'light'):
             total_light += obj.light
         # recursively check for lights inside containers or players
         if isinstance(obj, Container) and (obj.see_inside or hasattr(obj, 'cons')):
             if obj.contents: 
                 obj_list += obj.contents 
         dbg.debug('Room %s: light level is %s' % (self.id, total_light), 3)
     return (total_light <= 0)
Esempio n. 18
0
 def get_short_desc(self, perceiver=None, definite=False, indefinite=False):
     '''Overloads `Thing.get_short_desc()` to return short description of
     the creature, optionally prepended by a definite or indefinite article
     ('a', 'an', 'the', etc.), OR to return the creature's proper name if
     this creature has introduced itself to <perceiver> (usually the 
     player for whom the description is intended).'''
     if perceiver == None:
         dbg.debug("%s.get_short_desc() called with no perceiver specified" % self)
         return "<Error: no perceiver>" + self.short_desc
     if self.id in perceiver.introduced:
         return self.proper_name
     else:
         return super().get_short_desc(perceiver, definite, indefinite)
Esempio n. 19
0
    def __init__(self):
        dbg.debug("<%s> in", __func__())
        dbg.debug("<%s> exit", __func__())
        '''
      {
       'from':xx, 'to':xx, 'date':xx, 
       'texts':queue, 'pictures':queue,
       'voices':queue, 'video': queue
      }
      '''

        # xmldoc to return
        self.data = {}
        self.timestamp = ''
Esempio n. 20
0
    def __init__(self, req, args):
      dbg.debug("in")
      dbg.debug("exit")
      self.method = req.method.lower()
      self.params=req.environ['wsgiorg.routing_args'][1]
      self.params_1=req.params.copy()
      self.params_sig=req.params.get('signature', '0')
      self.params_ts =req.params.get('timestamp', '0')
      self.params_nonce =req.params.get('nonce', '0')
      #params_echostr =req.params.get('echostr')
      self.params_echostr =req.params.get('echostr', 'helloW!')

      #local:
      content_type = req.headers['Content-Type']
      content_length = req.headers['Content-Length']

      dbg.info("content_type: <%s> Len<%s>, args.id: %s",content_type, content_length ,args['id'])
      if content_type == 'text/plain':
        return params_echostr

      if args['id'] != 'upload':
        dbg.error("Not Support Command by Qi'e")
        return params_echostr
      else:
        dbg.debug("Upload Support")

      self.host = req.headers['Host'] 
        
      if content_type != 'text/xml':
        dbg.error("Only support xml format! <%s>", content_type)
        return 
      else:
        dbg.debug("Xml is appreicated!")
Esempio n. 21
0
    def __init__(self):
      dbg.debug("<%s> in", __func__())
      dbg.debug("<%s> exit", __func__())
      '''
      {
       'from':xx, 'to':xx, 'date':xx, 
       'texts':queue, 'pictures':queue,
       'voices':queue, 'video': queue
      }
      '''

      # xmldoc to return
      self.data = {}
      self.timestamp = ''
Esempio n. 22
0
    def __init__(self, req, args):
        dbg.debug("in")
        dbg.debug("exit")
        self.method = req.method.lower()
        self.params = req.environ["wsgiorg.routing_args"][1]
        self.params_1 = req.params.copy()
        self.params_sig = req.params.get("signature", "0")
        self.params_ts = req.params.get("timestamp", "0")
        self.params_nonce = req.params.get("nonce", "0")
        # params_echostr =req.params.get('echostr')
        self.params_echostr = req.params.get("echostr", "helloW!")

        # local:
        content_type = req.headers["Content-Type"]
        content_length = req.headers["Content-Length"]

        dbg.info("content_type: <%s> Len<%s>, args.id: %s", content_type, content_length, args["id"])
        if content_type == "text/plain":
            return params_echostr

        if args["id"] != "upload":
            dbg.error("Not Support Command by Qi'e")
            return params_echostr
        else:
            dbg.debug("Upload Support")

        self.host = req.headers["Host"]

        if content_type != "text/xml":
            dbg.error("Only support xml format! <%s>", content_type)
            return
        else:
            dbg.debug("Xml is appreicated!")
Esempio n. 23
0
    def extract(self, obj):
        """Remove obj from this Container, returning True if the operation failed"""
        if obj not in self.contents:
            dbg.debug(
                "Error! " + str(self) + " doesn't contain item " + str(obj.id),
                0)
            return True

        found = -1
        for i in range(0, len(self.contents)):
            if obj == self.contents[i]:
                found = i
                break
        assert found != -1
        del self.contents[i]
Esempio n. 24
0
 def weapon_and_armor_grab(self):
     if not self.weapon_wielding:
         for w in self.contents:
             if isinstance(w, Weapon):
                 self.weapon_wielding = w
                 dbg.debug("weapon chosen: %s" % self.weapon_wielding)
                 self.visible_inventory.append(self.weapon_wielding)
                 break
     if not self.armor_worn:
         for a in self.contents:
             if isinstance(a, Armor):
                 self.armor_worn = a
                 dbg.debug("armor chosen: %s" % self.armor_worn)
                 self.visible_inventory.append(self.armor_worn)
                 break
Esempio n. 25
0
    def load_game(self, filename):
        if not filename.endswith('.OAD'):
            filename += '.OAD'
        try:
            f = open(filename, 'r+b')
        except FileNotFoundError:
            self.cons.write("Error, couldn't find file named %s" % filename)
            return
        try:
            backup_ID_dict = Thing.ID_dict.copy()
            Thing.ID_dict.clear()  # unpickling will re-create Thing.ID_dict
            backup_heartbeat_users = self.heartbeat_users.copy()
            self.heartbeat_users.clear()
            saved = pickle.load(f)
            new_ID_dict, newgame = saved
        except pickle.PickleError:
            self.cons.write(
                "Encountered error while loading from file %s, game not loaded."
                % filename)
            Thing.ID_dict = backup_ID_dict
            self.heartbeat_users = backup_heartbeat_users
            f.close()
            return
        del backup_ID_dict
        # TODO: move below code for deleting player to Player.__del__()
        # Unlink player object from room, contents:
        if self.user.location.extract(self.user):
            dbg.debug("Error deleting player from room during load_game()")
        for o in self.user.contents:
            if self.user.extract(o):
                dbg.debug(
                    "Error deleting contents of player (%s) during load_game()"
                    % o)
        self.cons.user = None

        self.user, self.heartbeat_users = newgame.user, newgame.heartbeat_users
        self.user.cons = self.cons  # custom pickling code for Player doesn't save console
        self.cons.user = self.user  # update backref from cons

        for o in Thing.ID_dict:
            Thing.ID_dict[o]._restore_objs_from_IDs()

        self.cons.change_players = True

        self.cons.write("Restored game state from file %s" % filename)

        f.close()
Esempio n. 26
0
 def weapon_and_armor_grab(self):
     if not self.weapon_wielding or self.weapon_wielding == self.default_weapon:
         for w in self.contents:
             if isinstance(w, Weapon) and w.damage > self.default_weapon.damage:
                 self.weapon_wielding = w
                 dbg.debug("weapon chosen: %s" % self.weapon_wielding)
                 self.visible_inventory.append(self.weapon_wielding)
                 self.perceive('You wield the %s, rather than using your %s.' % (self.weapon_wielding.short_desc, self.default_weapon.short_desc))
                 break
     if not self.armor_worn or self.armor_worn == self.default_armor:
         for a in self.contents:
             if isinstance(a, Armor) and a.bonus > self.default_armor.bonus:
                 self.armor_worn = a
                 dbg.debug("armor chosen: %s" % self.armor_worn)
                 self.visible_inventory.append(self.armor_worn)
                 self.perceive('You wear the %s, rather than your %s.' % (self.armor_worn.short_desc, self.default_armor.short_desc))
                 break
Esempio n. 27
0
 def take_input(self):
     if (self.raw_input == ''):
         return None
     (self.command, sep, self.raw_input) = self.raw_input.partition('\n')
     self.words = self.command.split()
     # if user types a console command, handle it and start over unless the player that called this is deactive
     internal = self._handle_console_commands()
     if internal:
         return "__noparse__"
     if self.input_redirect != None:
         try:
             self.input_redirect.console_recv(self.command)
             return "__noparse__"
         except AttributeError:
             dbg.debug('Error! Input redirect is not valid!')
             self.input_redirect = None
     # replace any aliases with their completed version
     self.final_command = self._replace_aliases()
     return self.final_command
Esempio n. 28
0
    def heartbeat(self):
        self.act_soon += 1
        if self.act_soon >= self.act_frequency or (set(self.enemies) & set(
                self.location.contents)) or self.attacking:
            acting = False
            self.act_soon = 0
            if self.current_script:  # if currently reciting, continue
                self.talk()
                acting = True
            try:
                for i in self.location.contents:  # if an enemy is in room, attack
                    if i in self.enemies:
                        if self.aggressive:
                            self.attack_enemy(i)
                        else:  #can't attack (e.g. bluebird)? Run away.
                            self.move_around()
                        acting = True
            except AttributeError:
                dbg.debug('AttributeError, not in any room.', 0)
                return
            if self.attacking:
                if (self.attacking not in self.location.contents):
                    for l in self.location.exits:
                        if l == self.attacking.location:
                            self.move_to(l)
                            moved = True
                            break

#                if not moved:
#                    self.attacking = None
            if not acting:  # otherwise pick a random action
                choice = random.choice(self.choices)
                try:
                    try:
                        choice()
                    except TypeError:
                        choice(self)
                except NameError:
                    dbg.debug(
                        "Object " + str(self.id) +
                        " heartbeat tried to run non-existant action choice " +
                        str(choice) + "!", 0)
Esempio n. 29
0
 def go_to(self, p, cons, oDO, oIDO):
     if p.words[1] == 'east':
         return Room.go_to(self, p, cons, oDO, oIDO)
     elif cons == self.last_cons:
         if cons != None:
             self.last_cons = cons
         cons.write('You convince yourself to enter the scary cave.')
         cons.user.emit('&nD%s slowly enters the cave, visibly shaking.' %
                        cons.user.id)
         Room.go_to(self, p, cons, oDO, oIDO)
         return True
     else:
         cons.write(
             'Entering the cave is very scary, and you have a hard time convincing yourself to go in.'
         )
         if cons != None:
             self.last_cons = cons
             dbg.debug(
                 'self.last_cons was just set to %s, %s' %
                 (self.last_cons, cons), 2)
         return True
Esempio n. 30
0
    def running(self, msg):
      '''
      parse :
       1. Text
       2. Picture
       3. Voice
       4. Video
       ...
      save to :
       1. console
       2. files
       3. db...
      '''
      dbg.debug("<%s> in", __func__())

      xmldoc = etree.fromstring(msg)
      msg_type = xmldoc.find('MsgType')
      if msg_type.text == 'text':
        self.text_get(xmldoc)
      else:
        dbg.debug("Not support format sent by Qi'e")

      dbg.debug("<%s> exit", __func__())

      return
Esempio n. 31
0
 def emit(self, message, ignore=[]):
     """Write a message to be seen by creatures holding this Thing or in the same  
     room, skipping creatures in the list <ignore>."""
     if hasattr(self, 'invisible') and self.invisible == True:
         return
     # pass message to containing object, if it can receive messages
     holder = self.location
     if not holder:
         #  this Thing is a room, pass message to all creatures in the room
         holder = self
     try:
         if holder not in ignore and hasattr(holder, 'perceive'):
             # immediate container can see messages, probably a creature/player
             dbg.debug("creature holding this object is: " + holder.id, 3)
             holder.perceive(message)
     except TypeError:
         dbg.debug("Warning, emit() called with non-list ignore parameter!",
                   level=0)
     # now get list of recipients (usually creatures) contained by holder (usually a Room)
     recipients = [
         x for x in holder.contents
         if hasattr(x, 'perceive') and (x is not self) and (x not in ignore)
     ]
     dbg.debug("other creatures in this room include: " + str(recipients),
               3)
     for recipient in recipients:
         recipient.perceive(message)
Esempio n. 32
0
    def running(self, req, args):
        """
      parse :
      save to :
      ack :
      """
        dbg.debug("in")

        xmldoc = etree.fromstring(req.body)

        parser = MsgParser()
        parser.running(req.body)

        store = MsgSaverAdapter()
        store.running(parser)

        # print "req is %s\n" % req
        dbg.debug("req.body is %s", req.body)
        """
      dbg.debug("headers is %s" , req.headers)
      dbg.debug("host is %s" , self.host)
      dbg.debug("params is %s" , self.params)
      dbg.debug("req.params is %s" , req.params)
      dbg.debug("params_1 is %s" , self.params_1)
      dbg.debug("params_sig is %s" , self.params_sig)
      dbg.debug("params_ts is %s" , self.params_ts)
      dbg.debug("params_nonce is %s" , self.params_nonce)
      dbg.debug("params_echostr is %s" , self.params_echostr)
      dbg.debug("method is %s" , self.method )
      """

        dbg.debug("Exit")
        return self.params_echostr
Esempio n. 33
0
    def running(self, msg):
        '''
      parse :
       1. Text
       2. Picture
       3. Voice
       4. Video
       ...
      save to :
       1. console
       2. files
       3. db...
      '''
        dbg.debug("<%s> in", __func__())

        xmldoc = etree.fromstring(msg)
        msg_type = xmldoc.find('MsgType')
        if msg_type.text == 'text':
            self.text_get(xmldoc)
        else:
            dbg.debug("Not support format sent by Qi'e")

        dbg.debug("<%s> exit", __func__())

        return
Esempio n. 34
0
    def emit(self, message, ignore=[]):
        """Write a message to be seen by creatures holding this Thing or in the same  
        room, skipping creatures in the list <ignore>.  See Player.perceive() for a 
        list of "perceive semantics" that can be used in emitted messages, for example
        to specify the species, gender, or proper name of a creature.  

        To avoid printing a message to certain players (for example if that player
        should receive a custom message), include them in the ignore[] list. Note that
        `Player.perceive()` will skip printing the message to any Player explicitly  
        named in the message using the &n tag. """
        if hasattr(self, 'invisible') and self.invisible == True:
            return
        # pass message to containing object, if it can receive messages
        holder = self.location
        if not holder:
            #  this Thing is a room, pass message to all creatures in the room
            holder = self
        try:
            if holder not in ignore and hasattr(holder, 'perceive'):
                # immediate container can see messages, probably a creature/player
                dbg.debug("creature holding this object is: " + holder.id, 3)
                holder.perceive(message)
        except TypeError:
            dbg.debug("Warning, emit() called with non-list ignore parameter!",
                      level=0)
        # now get list of recipients (usually creatures) contained by holder (usually a Room)
        recipients = [
            x for x in holder.contents
            if hasattr(x, 'perceive') and (x is not self) and (x not in ignore)
        ]
        dbg.debug("other creatures in this room include: " + str(recipients),
                  3)
        for recipient in recipients:
            recipient.perceive(message)
Esempio n. 35
0
    def running(self, req, args):
      '''
      parse :
      save to :
      ack :
      '''
      dbg.debug("in")

      xmldoc = etree.fromstring(req.body)

      parser = MsgParser()
      parser.running(req.body)

      store=MsgSaverAdapter()
      store.running(parser)
      
      #print "req is %s\n" % req
      dbg.debug("req.body is %s",req.body)
      '''
      dbg.debug("headers is %s" , req.headers)
      dbg.debug("host is %s" , self.host)
      dbg.debug("params is %s" , self.params)
      dbg.debug("req.params is %s" , req.params)
      dbg.debug("params_1 is %s" , self.params_1)
      dbg.debug("params_sig is %s" , self.params_sig)
      dbg.debug("params_ts is %s" , self.params_ts)
      dbg.debug("params_nonce is %s" , self.params_nonce)
      dbg.debug("params_echostr is %s" , self.params_echostr)
      dbg.debug("method is %s" , self.method )
      '''

      dbg.debug("Exit")
      return self.params_echostr
Esempio n. 36
0
    def __setstate__(self, state):
        """Custom unpickling code for Thing.

        Re-create the Thing.ID_dict{} dictionary during unpickling:
        if an object's ID is in the dictionary (because some other object
        referred to it, e.g. via the location[] or contents[] fields)
        just leave it there; otherwise create its entry.

        After unpickling, another pass will be required to replace ID strings
        (in location and contents fields) with the actual object references.
        All objects end up in Thing.ID_dict, so we can just iterate over it.
        """
        # Restore instance attributes
        try:
            obj = Thing.ID_dict[state['id']]  # is this obj already in dict?
            dbg.debug("Note: %s already in Thing.ID_dict, maps to %s" %
                      (state['id'], obj))
        except KeyError:  # Not already in dict
            Thing.ID_dict[state['id']] = self
        if 'has_beat' in state:
            Thing.game.register_heartbeat(self)
        self.__dict__.update(state)
Esempio n. 37
0
 def print_node(node):
   '''Print Dom'''
   dbg.info("==============================================")
   if node.attrib:
     dbg.debug("node.attrib:%s" % node.attrib)
   if node.attrib.has_key("MsgId") > 0 :
     dbg.debug("node.attrib['MsgId']:%s" % node.attrib['MsgId'])
   dbg.debug("<%s>:<%s>" % (node.tag, node.text))
Esempio n. 38
0
 def close(self):
   dbg.debug("Close file: %s", self.file)
   return
Esempio n. 39
0
 def write(self, data):
   dbg.debug("Write file: %s", self.file)
   return
Esempio n. 40
0
        #print "req is %s\n" % req
        dbg.debug("req.body is %s",req.body)
        dbg.debug("headers is %s" , req.headers)
        dbg.debug("headers.type is %s", content_type)
        dbg.debug("headers.length is %s" ,content_length)
        dbg.debug("host is %s" , host)
        dbg.debug("params is %s" , params)
        dbg.debug("req.params is %s" , req.params)
        dbg.debug("params_1 is %s" , params_1)
        dbg.debug("params_sig is %s" , params_sig)
        dbg.debug("params_ts is %s" , params_ts)
        dbg.debug("params_nonce is %s" , params_nonce)
        dbg.debug("params_echostr is %s" , params_echostr)
        dbg.debug("method is %s" , method )
        dbg.debug("args.id is %s" , args['id'])
        dbg.debug("args is %s" , args)
        #return 'uploaded!')

        return params_echostr
'''


if __name__ == '__main__':
  dbg.debug("Weclome!")
  sock = eventlet.listen(('119.84.78.194', 80))
  #sock = eventlet.listen(('', 12345))
  map = routes.Mapper()
  map.connect('/v1.0/{action}/{id}', controller=API())
  eventlet.wsgi.server(sock, routes.middleware.RoutesMiddleware(ParsedRoutes(webob.exc.HTTPNotFound()), map))
Esempio n. 41
0
 def __init__(self):
   dbg.debug("in")
   dbg.debug("exit")
   self.config = {'file':'1'}
Esempio n. 42
0
    def text_get(self, xmldoc):
      '''
      <xml>
      <ToUserName><![CDATA[toUser]]></ToUserName>
      <FromUserName><![CDATA[fromUser]]></FromUserName> 
      <CreateTime>1348831860</CreateTime>
      <MsgType><![CDATA[text]]></MsgType>
      <Content><![CDATA[this is a test]]></Content>
      <MsgId>1234567890123456</MsgId>
      </xml>
      '''
      dbg.debug("<%s> in", __func__())
      dbg.debug("xmldoc: <%s>", xmldoc)

      to_username = xmldoc.find('ToUserName')
      from_username = xmldoc.find('FromUserName')
      create_time = xmldoc.find('CreateTime')
      text_content = xmldoc.find('Content')
      msg_id = xmldoc.find('MsgId')

      dbg.debug("to username: %s ", to_username.text)
      dbg.debug("from username: %s ", from_username.text)
      dbg.debug("create time: %s ", create_time.text)
      dbg.debug("text_content: %s ", text_content.text)
      dbg.debug("msg_id: %s ", msg_id.text)
      dbg.debug("time is %s", time.localtime(float(create_time.text)))
      tmp = time.strftime("%Y-%m-%d",time.localtime(float(create_time.text)))
      #tmp = time.strftime("%Y-%m-%d %X",time.localtime(float(create_time.text)))
      dbg.debug("time str: %s", tmp)

      #Save
      self.data['text'] = xmldoc
      self.timestamp='%s.%s.%s' %(from_username.text,to_username.text,tmp)
      dbg.debug("timestamp : %s", self.timestamp)
      dbg.debug("<%s> exit", __func__())

      return 'text_get return'
Esempio n. 43
0
 def __init__(self, log='/tmp/log.xml'):
   dbg.debug("in")
   self.file=log
   dbg.debug("exit")
Esempio n. 44
0
      dbg.debug("text_content: %s ", text_content.text)
      dbg.debug("msg_id: %s ", msg_id.text)
      dbg.debug("time is %s", time.localtime(float(create_time.text)))
      tmp = time.strftime("%Y-%m-%d",time.localtime(float(create_time.text)))
      #tmp = time.strftime("%Y-%m-%d %X",time.localtime(float(create_time.text)))
      dbg.debug("time str: %s", tmp)

      #Save
      self.data['text'] = xmldoc
      self.timestamp='%s.%s.%s' %(from_username.text,to_username.text,tmp)
      dbg.debug("timestamp : %s", self.timestamp)
      dbg.debug("<%s> exit", __func__())

      return 'text_get return'

    def print_node(node):
      '''Print Dom'''
      dbg.info("==============================================")
      if node.attrib:
        dbg.debug("node.attrib:%s" % node.attrib)
      if node.attrib.has_key("MsgId") > 0 :
        dbg.debug("node.attrib['MsgId']:%s" % node.attrib['MsgId'])
      dbg.debug("<%s>:<%s>" % (node.tag, node.text))

if __name__ == '__main__':
  dbg.debug("Ongmani.: <%s> . verion: <%s>", __name__, __ver__)
  sys.exit(main(sys.argv))
else:
  dbg.debug("Ongmani.: <%s> . verion: <%s>", __name__, __ver__)

Esempio n. 45
0
 def open(self):
   dbg.debug("Open file: %s", self.file)
   return
Esempio n. 46
0
 def saveToDB(self, data):
   dbg.debug("in")
   dbg.debug("exit")
   return 
Esempio n. 47
0
    def running(self, parser):
      '''
      save to :
       1. console
       2. files
       3. db...
      '''
      dbg.debug("in")

      data = parser.data
      ts = parser.timestamp

      if data.has_key('text'):
        dbg.debug("Got a text to saving")
      elif data.has_key('picture'):
        dbg.debug("Got a picture to saving")
      else:
        dbg.debug("Not support format!!")
        return

      if self.config.has_key('file'):
        self.saveToFiles(data, ts)
        dbg.debug("Sucess")

      if self.config.has_key('console'):
        self.printToConsole(data, ts)
        dbg.debug("Sucess")

      if self.config.has_key('db'):
        dbg.debug("Not Support")

      dbg.debug("exit")

      return