def func(self): "Implement the command." caller = self.caller # we don't have light, grasp around blindly. messages = ("It's pitch black. You fumble around but cannot find anything.", "You don't see a thing. You feel around, managing to bump your fingers hard against something. Ouch!", "You don't see a thing! Blindly grasping the air around you, you find nothing.", "It's totally dark here. You almost stumble over some un-evenness in the ground.", "You are completely blind. For a moment you think you hear someone breathing nearby ... \n ... surely you must be mistaken.", "Blind, you think you find some sort of object on the ground, but it turns out to be just a stone.", "Blind, you bump into a wall. The wall seems to be covered with some sort of vegetation, but its too damp to burn.", "You can't see anything, but the air is damp. It feels like you are far underground.") irand = random.randint(0, 10) if irand < len(messages): caller.msg(messages[irand]) else: # check so we don't already carry a lightsource. carried_lights = [obj for obj in caller.contents if utils.inherits_from(obj, LightSource)] if carried_lights: string = "You don't want to stumble around in blindness anymore. You already found what you need. Let's get light already!" caller.msg(string) return #if we are lucky, we find the light source. lightsources = [obj for obj in self.obj.contents if utils.inherits_from(obj, LightSource)] if lightsources: lightsource = lightsources[0] else: # create the light source from scratch. lightsource = create_object(LightSource, key="splinter") lightsource.location = caller string = "Your fingers bump against a splinter of wood in a corner. It smells of resin and seems dry enough to burn!" string += "\nYou pick it up, holding it firmly. Now you just need to {wlight{n it using the flint and steel you carry with you." caller.msg(string)
def func(self): "Implement the command." caller = self.caller if caller.ndb.is_first_look: caller.ndb.is_first_look = False caller.display_available_cmds() return string = "\n{c=============================================================={n" string += "\n{c摸索{n" string += "\n{c=============================================================={n" # we don't have light, grasp around blindly. messages = ("周围一片漆黑。你四处摸索,但无法找到任何东西。", "你看不到任何东西。你摸索着周围,手指突然重重地撞上了某个物体。哎哟!", "你看不到任何东西!你盲目地向周围抓去,什么都没碰到。", "这里一丝光都没有,你差点被凹凸不平的地面绊倒。", "你完全失明了。有一会儿,你觉得好像听到附近有呼吸声……\n……想必你是弄错了。", "看不见。你以为在地上找到了什么,但发现这只是块石头。", "看不见。你撞到墙了,墙壁上似乎覆盖着一些植物,但它们太潮湿了,无法点燃。", "你什么都看不到。周围的空气很潮湿,你感觉像是在深深的地下。") irand = random.randint(0, 10) if irand < len(messages): string += "\n" + messages[irand] commands = caller.available_cmd_list(None) if commands: string += "\n\n动作:" + " ".join(commands) caller.msg(string, clear_links=True) else: # check so we don't already carry a lightsource. carried_lights = [obj for obj in caller.contents if utils.inherits_from(obj, LightSource)] if carried_lights: string += "\n你不想继续在黑暗中摸索了。你已经找到了所需的东西,点亮它吧!" commands = ["{lclight{lt点燃木片{le"] + caller.available_cmd_list(None) string += "\n\n动作:" + " ".join(commands) caller.msg(string, clear_links=True) return #if we are lucky, we find the light source. lightsources = [obj for obj in self.obj.contents if utils.inherits_from(obj, LightSource)] if lightsources: lightsource = lightsources[0] else: # create the light source from scratch. lightsource = create_object(LightSource, key="木片") lightsource.location = caller string += "\n在角落里,你的手指碰到了一些木片。它们还带着树脂的香味,而且比较干燥,应该可以点燃!" string += "\n你把它捡起来,紧紧地握手里。现在,你只需要用随身携带的火石{w点着{n它就行了。" commands = ["{lclight{lt点燃木片{le"] + caller.available_cmd_list(None) string += "\n\n动作:" + " ".join(commands) caller.msg(string, clear_links=True)
def bad(self): if not self.location or not utils.inherits_from(self.location, 'game.gamesrc.latitude.objects.region.Region'): return 'area has no region' area_spawn = self.db.area_spawn if area_spawn: for spawn_point in area_spawn: if not spawn_point in self.contents: return 'area has spawn point outside area' if not utils.inherits_from(spawn_point, 'src.objects.objects.Room'): return 'area spawn point is not a room' return super(Area, self).bad()
def func(self): switches = [switch.lower() for switch in self.switches] character = self.character if self.cmdstring.lower() == 'ws': if not switches and not self.args: if not character: self.msg("{RYou have no location. (See {rhelp @char{R for more information)") return if not character.location: self.msg("{RYou don't seem to have any specific location.") return self.display_users([ con for con in character.location.contents if utils.inherits_from(con, "src.objects.objects.Character") ]) return else: if (not switches or switches == ['characters']) and not self.args: characters = set() for session in SESSIONS.get_sessions(): character = session.get_character() if character: character = character.typeclass characters.add(character) self.display_users(characters) return if switches == ['players'] and not self.args: players = set() for session in SESSIONS.get_sessions(): player = session.get_player() if player: player = player.typeclass players.add(player) self.display_users(players) return if switches == ['far'] and self.args: target = match(self.args) if not target: self.msg('%cnNo match found for "' + self.args + "'") return self.display_users([target]) return if switches == ['room'] and not self.args: if not character: self.msg("{RYou have no location. (See {rhelp @char{R for more information)") return if not character.location: self.msg("{RYou don't seem to have any specific location.") return self.display_users([ con for con in character.location.contents if utils.inherits_from(con, "src.objects.objects.Character") ]) return self.msg("Invalid '%s' command. See 'help %s' for usage" % (self.cmdstring, self.key))
def pursue(self): """ In pursue mode, the enemy tries to find players in adjoining rooms, preferably those that previously attacked it. """ last_attacker = self.db.last_attacker players = [ obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser ] if players: # we found players in the room. Maybe we caught up with some, # or some walked in on us before we had time to pursue them. # Switch to battle mode. self.battle_mode = True self.roam_mode = False self.pursue_mode = False else: # find all possible destinations. destinations = [ ex.destination for ex in self.location.exits if ex.access(self, "traverse") ] # find all players in the possible destinations. OBS-we cannot # just use the player's current position to move the Enemy; this # might have changed when the move is performed, causing the enemy # to teleport out of bounds. players = {} for dest in destinations: for obj in [ o for o in dest.contents if utils.inherits_from(o, BASE_CHARACTER_TYPECLASS) ]: players[obj] = dest if players: # we found targets. Move to intercept. if last_attacker in players: # preferably the one that last attacked us self.move_to(players[last_attacker]) else: # otherwise randomly. key = players.keys()[random.randint(0, len(players) - 1)] self.move_to(players[key]) else: # we found no players nearby. Return to roam mode. self.battle_mode = False self.roam_mode = True self.pursue_mode = False
def _all_protected(self, obj): retval = [] if utils.inherits_from(obj, 'game.gamesrc.latitude.objects.protected.Protected'): retval.append(obj) for con in obj.contents: retval.extend(self._all_protected(con)) return retval
def autosweep(self): """ Sweep sleeping occupants if configured to do so """ if not self.db.autosweep_active: return now = time.time() for character in self.contents: # Ensure we're dealing with a player character if not utils.inherits_from(character, 'game.gamesrc.latitude.objects.character.Character'): continue # Ensure the character is awake if character.sessions: continue # Ensure the time delay hasn't run out yet if self.db.autosweep_delay: last_unpuppet = character.db.stats_last_unpuppet_time if last_unpuppet and now - last_unpuppet <= self.db.autosweep_delay: # Time's not up yet continue # Inform the room about the sweep if self.db.autosweep_msg: self.msg_contents(self.objsub(self.db.autosweep_msg, character)) else: self.msg_contents(self.objsub('&1N is sent home.', character)) # Perform the sweep destination = character.get_region() if not destination: destination = character.home.get_region() if not destination: destination = character.home character.move_to(destination, quiet=True) # Mark the user for bringback if appropriate if self.db.autosweep_bringback: character.db.autosweep_bringback_to = self
def func(self): if not self.switches and self.args: target = match(self.args) if not target: self.msg('{R[Could not find "%s"]' % self.args) return if utils.inherits_from(target, "src.objects.objects.Character"): if target.sessid: self.msg('{Y[%s is online right now]' % (target.key)) elif not target.has_attribute('stats_last_unpuppet_time'): self.msg('{R[The time %s last left the game is unknown]' % (target.key)) elif target.db.stats_last_unpuppet_time == None: self.msg('{Y[%s has never entered the game]' % (target.key)) else: self.msg('{Y[%s last left the game at %s]' % (target.key, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(target.db.stats_last_unpuppet_time)))) else: if target.sessions: self.msg('{Y[%s is online right now]' % (target.key)) elif not target.has_attribute('stats_last_logout_time'): self.msg('{R[The time %s last left the game is unknown]' % (target.key)) elif target.db.stats_last_logout_time == None: self.msg('{Y[%s has never entered the game]' % (target.key)) else: self.msg('{Y[%s last left the game at %s]' % (target.key, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(target.db.stats_last_logout_time)))) else: # Unrecognized command self.msg("{R[Invalid '{r%s{R' command. See '{rhelp %s{R' for usage]" % (self.cmdstring, self.key))
def load_prop(self, editor_result): target = getattr(self.obj.db, self.attrname) if (not utils.inherits_from(target, unicode)) and (not target == None): self.caller.msg( "{rWARNING! If you save this buffer, you will overwrite this property of type '%s' with a unicode string!{n" % type(target).__name__) return str(target)
def roam(self): "Called by Attack timer. Will move randomly as long as exits are open." # in this mode, the mob is healed. self.db.health = self.db.full_health players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # we found players in the room. Attack. self.db.roam_mode = False self.db.pursue_mode = False self.db.battle_mode = True elif random.random() < 0.2: # no players to attack, move about randomly. exits = [ex.destination for ex in self.location.exits if ex.access(self, "traverse")] if exits: # Try to make it so the mob doesn't backtrack. new_exits = [ex for ex in exits if ex.destination != self.db.last_location] if new_exits: exits = new_exits self.db.last_location = self.location # locks should be checked here self.move_to(exits[random.randint(0, len(exits) - 1)]) else: # no exits - a dead end room. Respawn back to start. self.move_to(self.home)
def get_region(self): """ Ascends the tree until it hits the first region, and returns it. """ for obj in self.trace(): if utils.inherits_from(obj, 'game.gamesrc.latitude.objects.region.Region'): return obj return None
def load_prop(self, editor_result): target = getattr(self.obj.db, self.attrname) if (not utils.inherits_from(target, unicode)) and (not target == None): self.caller.msg( "{rWARNING! If you save this buffer, you will overwrite this property of type '%s' with a unicode string!{n" % type(target).__name__ ) return str(target)
def select_weapon(self): # select a weapon. self.ndb.weapon = None items = self.contents for item in items: if utils.inherits_from(item, Weapon): self.ndb.weapon = item break
def get_area(self): """ Ascends the tree until it hits the first area, and returns it. """ for obj in self.trace(): if utils.inherits_from(obj, 'game.gamesrc.latitude.objects.area.Area'): return obj return None
def attack(self): """ This is the main mode of combat. It will try to hit players in the location. If players are defeated, it will whisp them off to the defeat location. """ last_attacker = self.db.last_attacker players = [ obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser ] if players: # find a target if last_attacker in players: # prefer to attack the player last attacking. target = last_attacker else: # otherwise attack a random player in location target = players[random.randint(0, len(players) - 1)] # try to use the weapon in hand attack_cmds = ("thrust", "pierce", "stab", "slash", "chop") cmd = attack_cmds[random.randint(0, len(attack_cmds) - 1)] self.execute_cmd("%s %s" % (cmd, target)) # analyze result. if target.db.health <= 0: # we reduced enemy to 0 health. Whisp them off to # the prison room. tloc = search_object(self.db.defeat_location) tstring = self.db.defeat_text if not tstring: tstring = "You feel your conciousness slip away ... you fall to the ground as " tstring += "the misty apparition envelopes you ...\n The world goes black ...\n" target.msg(tstring) ostring = self.db.defeat_text_room if tloc: if not ostring: ostring = "\n%s envelops the fallen ... and then their body is suddenly gone!" % self.key # silently move the player to defeat location # (we need to call hook manually) target.location = tloc[0] tloc[0].at_object_receive(target, self.location) elif not ostring: ostring = "%s falls to the ground!" % target.key self.location.msg_contents(ostring, exclude=[target]) # Pursue any stragglers after the battle self.battle_mode = False self.roam_mode = False self.pursue_mode = True else: # no players found, this could mean they have fled. # Switch to pursue mode. self.battle_mode = False self.roam_mode = False self.pursue_mode = True
def attack(self): """ This is the main mode of combat. It will try to hit players in the location. If players are defeated, it will whisp them off to the defeat location. """ last_attacker = self.db.last_attacker players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # find a target if last_attacker in players: # prefer to attack the player last attacking. target = last_attacker else: # otherwise attack a random player in location target = players[random.randint(0, len(players) - 1)] # try to use the weapon in hand cmd = "fight %s=" % target.dbref attack_cmds = ("stab", "slash") cmd += attack_cmds[random.randint(0, len(attack_cmds) - 1)] self.execute_cmd(cmd) # analyze result. if target.db.health <= 0: # we reduced enemy to 0 health. Whisp them off to # the prison room. tloc = search_object(self.db.defeat_location) tstring = self.db.defeat_text if not tstring: tstring = "你被幽灵缠绕着,意识渐渐变得模糊了……你重重地摔倒在地上。\n" tstring += "整个世界变得一片漆黑……\n" tstring += target.get_available_cmd_desc(target) target.msg(tstring) ostring = self.db.defeat_text_room if tloc: if not ostring: ostring = "\n%s缠绕着勇士的尸体……一下子尸体就消失不见了!" % self.key # silently move the player to defeat location # (we need to call hook manually) target.location = tloc[0] tloc[0].at_object_receive(target, self.location) elif not ostring: ostring = "%s倒在了地上!" % target.key self.location.msg_contents(ostring, exclude=[target]) # Pursue any stragglers after the battle self.battle_mode = False self.roam_mode = False self.pursue_mode = True else: # no players found, this could mean they have fled. # Switch to pursue mode. self.battle_mode = False self.roam_mode = False self.pursue_mode = True
def is_lit(self): """ Helper method to check if the room is lit up. It checks all characters in room to see if they carry an active object of type LightSource. """ return any([any([True for obj in char.contents if utils.inherits_from(obj, LightSource) and obj.db.is_active]) for char in self.contents if char.has_player])
def move_redirect(self, obj): """ Redirect for redirectable_move_to requests. By default, areas redirect users to one of its spawn points at random. """ if utils.inherits_from(obj, 'game.gamesrc.latitude.objects.character.Character'): spawn = self.db.area_spawn if spawn: return choice(list(spawn)) return None
def script_obj(accessing_obj, accessed_obj, *args, **kwargs): """ Returns true if accessed_obj is a script, and the script is attached to accessing_obj """ if not utils.inherits_from(accessed_obj.typeclass, "src.scripts.scripts.Script"): return False try: return accessing_obj.typeclass == accessed_obj.obj.typeclass except AttributeError: return False
def friend(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: friend() Returns True if the accessing_obj and accessed_obj are friends in the @friend system. If they objects are not players, it checks for a get_owner() method, and uses their owner player if available. """ accessing_obj = accessing_obj.typeclass accessed_obj = accessed_obj.typeclass if not utils.inherits_from(accessing_obj, 'src.players.player.Player'): if not hasattr(accessing_obj, 'get_owner'): return False accessing_obj = accessing_obj.get_owner() if not utils.inherits_from(accessed_obj, 'src.players.player.Player'): if not hasattr(accessed_obj, 'get_owner'): return False accessed_obj = accessed_obj.get_owner() return accessing_obj in accessed_obj.get_friend_players()
def attack(self): """ This is the main mode of combat. It will try to hit players in the location. If players are defeated, it will whisp them off to the defeat location. """ last_attacker = self.db.last_attacker players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # find a target if last_attacker in players: # prefer to attack the player last attacking. target = last_attacker else: # otherwise attack a random player in location target = players[random.randint(0, len(players) - 1)] # try to use the weapon in hand attack_cmds = ("thrust", "pierce", "stab", "slash", "chop") cmd = attack_cmds[random.randint(0, len(attack_cmds) - 1)] self.execute_cmd("%s %s" % (cmd, target)) # analyze result. if target.db.health <= 0: # we reduced enemy to 0 health. Whisp them off to # the prison room. tloc = search_object(self.db.defeat_location) tstring = self.db.defeat_text if not tstring: tstring = "You feel your conciousness slip away ... you fall to the ground as " tstring += "the misty apparition envelopes you ...\n The world goes black ...\n" target.msg(tstring) ostring = self.db.defeat_text_room if tloc: if not ostring: ostring = "\n%s envelops the fallen ... and then their body is suddenly gone!" % self.key # silently move the player to defeat location # (we need to call hook manually) target.location = tloc[0] tloc[0].at_object_receive(target, self.location) elif not ostring: ostring = "%s falls to the ground!" % target.key self.location.msg_contents(ostring, exclude=[target]) # Pursue any stragglers after the battle self.battle_mode = False self.roam_mode = False self.pursue_mode = True else: # no players found, this could mean they have fled. # Switch to pursue mode. self.battle_mode = False self.roam_mode = False self.pursue_mode = True
def pursue(self): """ In pursue mode, the enemy tries to find players in adjoining rooms, preferably those that previously attacked it. """ last_attacker = self.db.last_attacker players = [obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser] if players: # we found players in the room. Maybe we caught up with some, # or some walked in on us before we had time to pursue them. # Switch to battle mode. self.battle_mode = True self.roam_mode = False self.pursue_mode = False else: # find all possible destinations. destinations = [ex.destination for ex in self.location.exits if ex.access(self, "traverse")] # find all players in the possible destinations. OBS-we cannot # just use the player's current position to move the Enemy; this # might have changed when the move is performed, causing the enemy # to teleport out of bounds. players = {} for dest in destinations: for obj in [o for o in dest.contents if utils.inherits_from(o, BASE_CHARACTER_TYPECLASS)]: players[obj] = dest if players: # we found targets. Move to intercept. if last_attacker in players: # preferably the one that last attacked us self.move_to(players[last_attacker]) else: # otherwise randomly. key = players.keys()[random.randint(0, len(players) - 1)] self.move_to(players[key]) else: # we found no players nearby. Return to roam mode. self.battle_mode = False self.roam_mode = True self.pursue_mode = False
def at_object_receive(self, character, source_location): """ Do cleanup. """ if character.has_player: del character.db.health del character.db.has_climbed del character.db.puzzle_clue del character.db.combat_parry_mode del character.db.tutorial_bridge_position for tut_obj in [obj for obj in character.contents if utils.inherits_from(obj, TutorialObject)]: tut_obj.reset()
def func(self): "Process command" caller = self.caller def get_cmdset_callback(cmdset): """ We make use of the cmdhandeler.get_and_merge_cmdsets below. This is an asynchronous function, returning a Twisted deferred. So in order to properly use this we need use this callback; it is called with the result of get_and_merge_cmdsets, whenever that function finishes. Taking the resulting cmdset, we continue to format and output the result. """ string = self.format_output(obj, cmdset) self.msg(string.strip()) if not self.args: # If no arguments are provided, examine the invoker's location. if hasattr(caller, "location"): obj = caller.location # using callback for printing result whenever function returns. get_and_merge_cmdsets(obj).addCallback(get_cmdset_callback) else: self.msg("You need to supply a target to examine.") return # we have given a specific target object for objdef in self.lhs_objattr: obj_name = objdef['name'] obj_attrs = objdef['attrs'] self.player_mode = utils.inherits_from(caller, "src.players.player.Player") or \ "player" in self.switches or obj_name.startswith('*') if self.player_mode: try: obj = caller.search_player(obj_name.lstrip('*')) except AttributeError: # this means we are calling examine from a player object obj = caller.search(obj_name.lstrip('*')) else: obj = caller.search(obj_name) if not obj: continue if obj_attrs: for attrname in obj_attrs: # we are only interested in specific attributes caller.msg(self.format_attributes(obj, attrname, crop=False)) else: # using callback to print results whenever function returns. get_and_merge_cmdsets(obj).addCallback(get_cmdset_callback)
def get_mods(self, slot=None): """ Returns a set of Mod objects which apply to this Object. """ self.scripts.validate() # Produce a list of all objects, which if derived from Mod, qualify on this character candidates = set(self.get_equipment()) for script in self.scripts.all(): candidates.add(script) candidates.add(self.location) # TODO: Global mods # Return the set of mods return set(candidate for candidate in candidates if utils.inherits_from(candidate, 'game.gamesrc.latitude.struct.mod.Mod'))
def resident(accessing_obj, accessed_obj, *args, **kwargs): """ Used in a lockstring as resident() to determine if the accessed_obj is within a residence of the accessing_obj. It works by ascending the object tree until it hits a room, then checking the 'resident' attribute of the room. It returns True only if the attribute is set, and there is a match. """ room = accessed_obj while not utils.inherits_from(room.typeclass, "src.objects.objects.Room"): if not room.location: return False room = room.location return(accessing_obj == room.db.resident)
def get_desc_appearance(self, looker=None): desc = [] # Title if self.db.resident: desc.append(self.get_desc_styled_name(looker=looker) + ' {B[Non-canon (%s)]' % (self.db.resident.key)) else: desc.append(self.get_desc_styled_name(looker=looker)) # Description if self.db.desc_appearance: desc.append(self.objsub(self.db.desc_appearance)) # Contents/Exits characters = [] exits = [] items = [] for obj in self.contents: if obj == looker: continue if utils.inherits_from(obj, 'game.gamesrc.latitude.objects.character.Character'): characters.append(obj) elif utils.inherits_from(obj, 'game.gamesrc.latitude.objects.exit.Exit'): exits.append(obj) else: items.append(obj) characters.sort(key=lambda character: (not character.sessions, character.key)) exits.sort(key=lambda exit: exit.key) items.sort(key=lambda item: item.key) desc.append('{C[Exits: ' + ', '.join([exit.alias_highlight_name() for exit in exits]) + ']{n') if characters or items: desc.append('') desc.append('{nYou see:') for character_index in range(0, len(characters), 3): desc.append(' ' + ' '.join([evennia_color_left(character.get_desc_styled_name(), 23, dots=True) for character in characters[character_index:character_index+3]])) for item_index in range(0, len(items), 3): desc.append(' ' + ' '.join([evennia_color_left(item.get_desc_styled_name(), 23, dots=True) for item in items[item_index:item_index+3]])) # Return constructed string return '\n{n'.join(desc)
def at_object_receive(self, character, source_location): """ Do cleanup. """ if character.has_player: if self.db.wracklist: for wrackid in self.db.wracklist: character.del_attribute(wrackid) del character.db.health_max del character.db.health del character.db.last_climbed del character.db.puzzle_clue del character.db.combat_parry_mode for obj in [obj for obj in character.contents if utils.inherits_from(obj, Object)]: obj.reset()
def at_object_receive(self, character, source_location): """ Do cleanup. """ if character.has_player: if self.db.wracklist: for wrackid in self.db.wracklist: character.del_attribute(wrackid) del character.db.health_max del character.db.health del character.db.last_climbed del character.db.puzzle_clue del character.db.combat_parry_mode del character.db.tutorial_bridge_position for tut_obj in [obj for obj in character.contents if utils.inherits_from(obj, TutorialObject)]: tut_obj.reset()
def owner_lock(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: owner_lock(lockname) Passes this check on to the owner object. Returns False if not run on an object which has the get_owner() method. """ if not args or not len(args) == 1: return False if not hasattr(accessed_obj, 'get_owner'): return False owner = accessed_obj.get_owner() if not owner or not utils.inherits_from(owner, 'src.players.player.Player'): return False return owner.access(accessing_obj, args[0])
def func(self): """ Tries to create the Character object. We also put an attribute on ourselves to remember it. """ # making sure caller is really a player self.character = None if utils.inherits_from(self.caller, "src.objects.objects.Object"): # An object of some type is calling. Convert to player. #print self.caller, self.caller.__class__ self.character = self.caller if hasattr(self.caller, "player"): self.caller = self.caller.player if not self.args: self.caller.msg("Usage: create <character name>") return charname = self.args.strip() old_char = managers.objects.get_objs_with_key_and_typeclass( charname, CHARACTER_TYPECLASS) if old_char: self.caller.msg("Character {c%s{n already exists." % charname) return # create the character new_character = create_object(CHARACTER_TYPECLASS, key=charname) if not new_character: self.caller.msg( "{rThe Character couldn't be created. This is a bug. Please contact an admin." ) return # make sure to lock the character to only be puppeted by this player new_character.locks.add( "puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, self.caller.id)) # save dbref avail_chars = self.caller.db._character_dbrefs if avail_chars: avail_chars.append(new_character.id) else: avail_chars = [new_character.id] self.caller.db._character_dbrefs = avail_chars self.caller.msg("{gThe Character {c%s{g was successfully created!" % charname)
def partial_pmatch(me, name, local_only=False): """ Feed this a name, and it will return character matches. It will return only one match if the name is exact or unambiguous, and it will return multiple if there are multiple people online who match, but none of which are exact matches. All results are returned in a list. An empty list is returned if there is no match. Me is the object that will be returned if the query is 'me'. """ if local_only: target = [] targets = me.search(name, ignore_errors=True) if type(targets) == list: for thing in targets: if utils.inherits_from(thing, settings.BASE_CHARACTER_TYPECLASS): target.append(thing) elif not targets: pass else: target.append(targets) return target else: try: # In case user explicitely indicates a ref. if name[0] in ['*', '#']: global_name = name else: global_name = '*' + name except IndexError: pass target = me.search(global_name, global_search=True, ignore_errors=False, use_nicks=True) if target: if type(target) == list: return target else: return [target] matches = [] for session in SESSIONS.sessions.values(): character = session.get_character() if character and character.name.lower().startswith(name.lower()): matches.append(character) return matches
def stack_contents(self): """ Combines all stacks of the same type, for the contents of this object. """ # Produce a mapping from stackable classes to objects class_map = {} for con in self.contents: if not utils.inherits_from(con, 'game.gamesrc.latitude.objects.stackable.Stackable'): continue stackable_class = type(con) if not stackable_class in class_map: class_map[stackable_class] = [] class_map[stackable_class].append(con) # Combine classes for stackable_class, objects in class_map.iteritems(): for combine_me in objects[1:]: objects[0].combine(combine_me)
def partial_pmatch(me, name, local_only=False): """ Feed this a name, and it will return character matches. It will return only one match if the name is exact or unambiguous, and it will return multiple if there are multiple people online who match, but none of which are exact matches. All results are returned in a list. An empty list is returned if there is no match. Me is the object that will be returned if the query is 'me'. """ if local_only: target = [] targets = me.search(name, ignore_errors=True) if type(targets) == list: for thing in targets: if utils.inherits_from(thing, settings.BASE_CHARACTER_TYPECLASS): target.append(thing) elif not targets: pass else: target.append(targets) return target else: try: # In case user explicitely indicates a ref. if name[0] in [ '*', '#' ]: global_name = name else: global_name = '*' + name except IndexError: pass target = me.search(global_name, global_search=True, quiet=True, use_nicks=True) if target: if type(target) == list: return target else: return [ target ] matches = [] for session in SESSIONS.sessions.values(): character = session.get_character() if character and character.name.lower().startswith(name.lower()): matches.append(character) return matches
def func(self): """ Tries to create the Character object. We also put an attribute on ourselves to remember it. """ # making sure caller is really a player self.character = None if utils.inherits_from(self.caller, "src.objects.objects.Object"): # An object of some type is calling. Convert to player. #print self.caller, self.caller.__class__ self.character = self.caller if hasattr(self.caller, "player"): self.caller = self.caller.player if not self.args: self.caller.msg("Usage: create <character name>") return charname = self.args.strip() old_char = managers.objects.get_objs_with_key_and_typeclass(charname, CHARACTER_TYPECLASS) if old_char: self.caller.msg("Character {c%s{n already exists." % charname) return # create the character new_character = create_object(CHARACTER_TYPECLASS, key=charname) if not new_character: self.caller.msg("{rThe Character couldn't be created. This is a bug. Please contact an admin.") return # make sure to lock the character to only be puppeted by this player new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, self.caller.id)) # save dbref avail_chars = self.caller.db._character_dbrefs if avail_chars: avail_chars.append(new_character.id) else: avail_chars = [new_character.id] self.caller.db._character_dbrefs = avail_chars self.caller.msg("{gThe Character {c%s{g was successfully created!" % charname)
def give(self, typeclass, quantity=1, key=None, attributes=None): """ Create one or more new objects with the specified typeclass. Returns a list of created or modified objects. Stackable objects are handled correctly. """ quantity = int(quantity) if not callable(typeclass): typeclass = _get_object_class(typeclass) is_stackable = utils.inherits_from(typeclass, 'game.gamesrc.latitude.objects.stackable.Stackable') # Verify parameters if quantity < 1: raise ValueError('quantity must be greater than 0') if is_stackable and key: raise ValueError('name specified for stackable item') if is_stackable and attributes: raise ValueError('attributes specified for stackable item') # If there's an existing stackable object of this type, just add to it if is_stackable: for con in self.contents: if type(con) is typeclass: con.db.quantity += quantity return [con] # Create a new object if is_stackable: obj = create_object(typeclass, location=self) obj.db.quantity = quantity return [obj] else: retval = [] for i in range(quantity): new_obj = create_object(typeclass, location=self, key=key) if attributes: for name, val in attributes.iteritems(): new_obj.set_attribute(name, val) retval.append(new_obj) return(retval)
def roam(self): "Called by Attack timer. Will move randomly as long as exits are open." # in this mode, the mob is healed. self.db.health = self.db.full_health players = [ obj for obj in self.location.contents if utils.inherits_from(obj, BASE_CHARACTER_TYPECLASS) and not obj.is_superuser ] if players: # we found players in the room. Attack. self.db.roam_mode = False self.db.pursue_mode = False self.db.battle_mode = True elif random.random() < 0.2: # no players to attack, move about randomly. exits = [ ex.destination for ex in self.location.exits if ex.access(self, "traverse") ] if exits: # Try to make it so the mob doesn't backtrack. new_exits = [ ex for ex in exits if ex.destination != self.db.last_location ] if new_exits: exits = new_exits self.db.last_location = self.location # locks should be checked here self.move_to(exits[random.randint(0, len(exits) - 1)]) else: # no exits - a dead end room. Respawn back to start. self.move_to(self.home)
def func(self): """ Implements the ooc look command We use an attribute _character_dbrefs on the player in order to figure out which characters are "theirs". A drawback of this is that only the CmdCharacterCreate command adds this attribute, and thus e.g. player #1 will not be listed (although it will work). Existence in this list does not depend on puppeting rights though, that is checked by the @ic command directly. """ # making sure caller is really a player self.character = None if utils.inherits_from(self.caller, "src.objects.objects.Object"): # An object of some type is calling. Convert to player. #print self.caller, self.caller.__class__ self.character = self.caller if hasattr(self.caller, "player"): self.caller = self.caller.player if not self.character: # ooc mode, we are players avail_chars = self.caller.db._character_dbrefs if self.args: # Maybe the caller wants to look at a character if not avail_chars: self.caller.msg( "You have no characters to look at. Why not create one?" ) return objs = managers.objects.get_objs_with_key_and_typeclass( self.args.strip(), CHARACTER_TYPECLASS) objs = [obj for obj in objs if obj.id in avail_chars] if not objs: self.caller.msg("You cannot see this Character.") return self.caller.msg(objs[0].return_appearance(self.caller)) return # not inspecting a character. Show the OOC info. charobjs = [] charnames = [] if self.caller.db._character_dbrefs: dbrefs = self.caller.db._character_dbrefs charobjs = [managers.objects.get_id(dbref) for dbref in dbrefs] charnames = [charobj.key for charobj in charobjs if charobj] if charnames: charlist = "The following Character(s) are available:\n\n" charlist += "\n\r".join( ["{w %s{n" % charname for charname in charnames]) charlist += "\n\n Use {w@ic <character name>{n to switch to that Character." else: charlist = "You have no Characters." string = \ """ You, %s, are an {wOOC ghost{n without form. The world is hidden from you and besides chatting on channels your options are limited. You need to have a Character in order to interact with the world. %s Use {wcreate <name>{n to create a new character and {whelp{n for a list of available commands.""" % (self.caller.key, charlist) self.caller.msg(string) else: # not ooc mode - leave back to normal look # we have to put this back for normal look to work. self.caller = self.character super(CmdOOCLook, self).func()
def func(self): "Define extended command" caller = self.caller location = caller.location if self.cmdstring == '@detail': # switch to detailing mode. This operates only on current location if not location: caller.msg("No location to detail!") return if not self.rhs: # no '=' used - list content of given detail if self.args in location.db.details: string = "{wDetail '%s' on %s:\n{n" % (self.args, location) string += location.db.details[self.args] caller.msg(string) return if not self.args: # No args given. Return all details on location string = "{wDetails on %s{n:\n" % location string += "\n".join(" {w%s{n: %s" % (key, utils.crop(text)) for key, text in location.db.details.items()) caller.msg(string) return if self.switches and self.switches[0] in 'del': # removing a detail. if self.lhs in location.db.details: del location.db.detail caller.msg("Detail %s deleted, if it existed." % self.lhs) self.reset_times(location) return # setting a detail location.db.details[self.lhs] = self.rhs caller.msg("Set Detail %s to '%s'." % (self.lhs, self.rhs)) self.reset_times(location) return else: # we are doing a @desc call if not self.args: if location: string = "{wDescriptions on %s{n:\n" % location.key string += " {wspring:{n %s\n" % location.db.spring_desc string += " {wsummer:{n %s\n" % location.db.summer_desc string += " {wautumn:{n %s\n" % location.db.autumn_desc string += " {wwinter:{n %s\n" % location.db.winter_desc string += " {wgeneral:{n %s" % location.db.general_desc caller.msg(string) return if self.switches and self.switches[0] in ("spring", "summer", "autumn", "winter"): # a seasonal switch was given if self.rhs: caller.msg("Seasonal descs only works with rooms, not objects.") return switch = self.switches[0] if not location: caller.msg("No location was found!") return if switch == 'spring': location.db.spring_desc = self.args elif switch == 'summer': location.db.summer_desc = self.args elif switch == 'autumn': location.db.autumn_desc = self.args elif switch == 'winter': location.db.winter_desc = self.args # clear flag to force an update self.reset_times(location) caller.msg("Seasonal description was set on %s." % location.key) else: # Not seasonal desc set, maybe this is not an extended room if self.rhs: text = self.rhs obj = caller.search(self.lhs) if not obj: return else: text = self.args obj = location obj.db.desc = self.rhs # a compatability fallback if utils.inherits_from(obj, ExtendedRoom): # this is an extendedroom, we need to reset # times and set general_desc obj.db.general_desc = text self.reset_times(obj) caller.msg("General description was set on %s." % obj.key) else: caller.msg("The description was set on %s." % obj.key)
def func(self): """ Tries to create the Character object. We also put an attribute on ourselves to remember it. """ # making sure caller is really a player self.character = None if utils.inherits_from(self.caller, "src.objects.objects.Object"): # An object of some type is calling. Convert to player. #print self.caller, self.caller.__class__ self.character = self.caller if hasattr(self.caller, "player"): self.caller = self.caller.player if not self.args: self.caller.msg("Usage: create <character name>") return charname = self.args.strip() old_char = managers.objects.get_objs_with_key_and_typeclass( charname, CHARACTER_TYPECLASS) if old_char: self.caller.msg("Character {c%s{n already exists." % charname) return # create the character new_character = create_object(CHARACTER_TYPECLASS, key=charname) if not new_character: self.caller.msg( "{rThe Character couldn't be created. This is a bug. Please contact an admin." ) return # make sure to lock the character to only be puppeted by this player new_character.locks.add( "puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" % (new_character.id, self.caller.id)) # save dbref avail_chars = self.caller.db._character_dbrefs if avail_chars: avail_chars.append(new_character.id) else: avail_chars = [new_character.id] self.caller.db._character_dbrefs = avail_chars self.caller.msg("{gThe Character {c%s{g was successfully created!" % charname) self.caller.obj = new_character attributes = new_character.db.attributes nodes = [] copy_dir = '/Users/geoffrey/gitrepos/avaloria/game/gamesrc/copy/' for option in ['race', 'deity', 'alignment', 'gender']: if 'race' in option: for race in [ 'bardok', 'erelania', 'the unknowns', 'earthen', 'gerdling' ]: confirm_node = MenuNode( "confirm-%s" % race, links=['deity'], linktexts=['Choose your deity.'], code="self.caller.obj.set_race('%s')" % race) nodes.append(confirm_node) if 'bardok' in race: text = copyreader.read_file( "%s/races/bardok_desc.txt" % copy_dir) race_node = MenuNode("%s" % race, text=text, links=['confirm-bardok', 'race'], linktexts=[ 'Confirm Race Selection', 'Back to Races' ]) elif 'erelania' in race: text = copyreader.read_file( "%s/races/erelania_desc.txt" % copy_dir) race_node = MenuNode( "%s" % race, text=text, links=['confirm-erelania', 'race'], linktexts=[ 'Confirm Race Selection', 'Back to Races' ]) elif 'gerdling' in race: text = copyreader.read_file( "%s/races/gerdling_desc.txt" % copy_dir) race_node = MenuNode( "%s" % race, text=text, links=['confirm-gerdling', 'race'], linktexts=[ 'Confirm Race Selection', 'Back to Races' ]) elif 'earthen' in race: text = copyreader.read_file( "%s/races/earthen_desc.txt" % copy_dir) race_node = MenuNode("%s" % race, text=text, links=['confirm-earthen', 'race'], linktexts=[ 'Confirm Race Selection', 'Back to Races' ]) nodes.append(race_node) text = copyreader.read_file("%s/races/races_desc.txt" % copy_dir) root_race_node = MenuNode( "%s" % option, text=text, links=['bardok', 'erelania', 'gerdling', 'earthen'], linktexts=[ 'The Bardok', 'The Erelania', 'The Gerdling', 'The Earthen' ]) nodes.append(root_race_node) elif 'deity' in option: deities = ['ankarith', 'slyth', 'green warden', 'kaylynne'] for deity in deities: confirm_node = MenuNode( 'confirm-%s' % deity, links=['gender'], linktexts=['Choose your gender.'], code="self.caller.obj.set_deity('%s')" % deity) nodes.append(confirm_node) if 'karith' in deity: text = copyreader.read_file( "%s/deities/ankarith_desc.txt" % copy_dir) deity_node = MenuNode( "%s" % deity, text=text, links=['confirm-ankarith', 'deity'], linktexts=[ 'Confirm Deity Selection', 'Back to Deities' ]) #self.obj.msg("links: %s, linktexts: %s" % (deity_node.links, deity_node.linktexts)) elif 'slyth' in deity: text = copyreader.read_file( "%s/deities/slyth_desc.txt" % copy_dir) deity_node = MenuNode("%s" % deity, text=text, links=['confirm-slyth', 'deity'], linktexts=[ 'Confirm Deity Selection', 'Back to Deities' ]) elif 'green warden' in deity: text = copyreader.read_file( "%s/deities/greenwarden_desc.txt" % copy_dir) deity_node = MenuNode( "%s" % deity, text=text, links=['confirm-green warden', 'deity'], linktexts=[ 'Confirm Deity Selection', 'Back to Deities' ]) elif 'kaylynne' in deity: text = copyreader.read_file( "%s/deities/kaylynne_desc.txt" % copy_dir) deity_node = MenuNode( "%s" % deity, text=text, links=['confirm-kaylynne', 'deity'], linktexts=[ 'Confirm Deity Selection', 'Back to Deities' ]) nodes.append(deity_node) deity_node_text = copyreader.read_file( "%s/deities/deities_desc.txt" % copy_dir) root_deity_node = MenuNode( "deity", text=deity_node_text, links=['ankarith', 'slyth', 'green warden', 'kaylynne'], linktexts=[ 'An\'Karith', 'Slyth of the Glade', 'The Green Warden', 'Kaylynne' ]) nodes.append(root_deity_node) elif 'gender' in option: confirm_male = MenuNode( "confirm-gender-male", links=['END'], linktexts=["Go forth"], code="self.caller.obj.set_gender('male')") confirm_female = MenuNode( "confirm-gender-female", links=['END'], linktexts=["Go forth"], code="self.caller.obj.set_gender('female')") nodes.append(confirm_male) nodes.append(confirm_female) text = """ --{rGender Selection{n-- Please select which gender you would like to be: """ gender_node = MenuNode( "gender", text=text, links=['confirm-gender-male', 'confirm-gender-female'], linktexts=['Male', 'Female']) nodes.append(gender_node) start_node = MenuNode( "START", text= "{bWelcome to Avaloria. Please proceed through the menu to customize your character.{n", links=['race'], linktexts=['Choose your race.']) nodes.append(start_node) node_string = ' '.join([node.key for node in nodes]) self.caller.msg("{mDEBUG: nodes: %s{n" % node_string) menutree = MenuTree(caller=self.caller, nodes=nodes) menutree.start()