def func(self): # pass stats to the player self.caller.msg("DATA,name,%s" % self.caller.name) self.caller.msg("DATA,level,%d" % self.caller.db.level) self.caller.msg("DATA,health,%d" % self.caller.db.HP) self.caller.msg("DATA,xp,%d" % self.caller.db.XP) self.caller.msg("DATA,strength,%d" % self.caller.db.STR) self.caller.msg("DATA,combat,%d" % self.caller.db.combat) self.caller.msg("DATA,LOC,%s" % self.caller.location.name) # pass room items to the player for item in self.caller.location.contents: if item.dbref != self.caller.dbref: if utils.inherits_from(item, Character): self.caller.msg("DATA,char_add," + item.name + item.dbref) item.msg("DATA,char_add," + item.name + item.dbref) elif utils.inherits_from(item, Mob): self.caller.msg("DATA,char_add," + item.name + item.dbref) else: self.caller.msg("DATA,obj_add," + item.name + item.dbref) else: pass # pass inventory items to the player for item in self.caller.contents: self.caller.msg("DATA,inv_add," + item.name + item.dbref)
def at_post_puppet(self): """ Called when user logs in and starts puppeting a character """ # pass stats to the player self.msg("DATA,level,%d" % self.db.level) self.msg("DATA,health,%d" % self.db.HP) self.msg("DATA,xp,%d" % self.db.XP) self.msg("DATA,strength,%d" % self.db.STR) self.msg("DATA,combat,%d" % self.db.combat) self.msg("DATA,LOC,%s" % self.location.name) self.msg("Welcome back to the Matrix, %s" % self.name) self.db.just_entered=True # pass room items to the player for item in self.location.contents: if item.dbref != self.dbref: if utils.inherits_from(item, Character): self.msg("DATA,char_add," + item.name + item.dbref) item.msg("DATA,char_add," + item.name + item.dbref) elif utils.inherits_from(item, Mob): self.msg("DATA,char_add," + item.name + item.dbref) else: self.msg("DATA,obj_add," + item.name + item.dbref) else: pass # pass inventory items to the player for item in self.contents: self.msg("DATA,inv_add," + item.name + item.dbref) self.msg("In Game News today, the Federal Bureau of Intution closed its investigation into the recent spurt of attacks on the AI community at Dartmouth. It claims the case is unresolvable by its psychic experts.")
def at_object_receive(self, obj, source_location): if not utils.inherits_from( obj, 'typeclasses.characters.NPC') and utils.inherits_from( obj, 'typeclasses.characters.Character'): obj.execute_cmd('look') for item in self.contents: if utils.inherits_from(item, 'typeclasses.characters.NPC'): item.at_char_entered(obj)
def at_object_receive(self, obj, source_location): if utils.inherits_from(obj, Npc): # An NPC has entered pass else: if utils.inherits_from(obj, Character): # A PC has entered, NPC is caught above. # Cause the character to look around obj.execute_cmd('look') for item in self.contents: if utils.inherits_from(item, Npc): # An NPC is in the room item.at_char_entered(obj)
def parse(self): """ We run the parent parser as usual, then fix the result """ super(MuxAccountCommand, self).parse() if inherits_from(self.caller, "evennia.objects.objects.DefaultObject"): self.character = self.caller # caller is an Object/Character self.caller = self.caller.account elif inherits_from(self.caller, "evennia.accounts.accounts.DefaultAccount"): self.character = self.caller.get_puppet(self.session) # caller was already an Account else: self.character = None
def at_object_receive(self, obj, source_location): if utils.inherits_from( obj, 'typeclasses.patientēs.Patiēns'): # An NPC has entered pass else: if utils.inherits_from(obj, 'typeclasses.persōnae.Persōna'): # A PC has entered, NPC is caught above. # Cause the character to look around obj.execute_cmd('specta') for item in self.contents: if utils.inherits_from(item, 'typeclasses.patientēs.Patiēns'): # An NPC is in the room item.at_char_entered(obj)
def at_object_leave(self, obj, target_location): if utils.inherits_from(obj, Character): for item in self.contents: # if item in room not self if item.dbref != obj.dbref: # if item is of class Character if utils.inherits_from(item, Character): obj.msg("DATA,char_remove," + item.name + item.dbref) item.msg("DATA,char_remove," + obj.name + obj.dbref) # else if item is of class Mob elif utils.inherits_from(item, Mob): obj.msg("DATA,char_remove," + item.name + item.dbref) # else if item is of class Npc elif utils.inherits_from(item, Npc): obj.msg("DATA,char_remove," + item.name + item.dbref) # else (an object) else: obj.msg("DATA,obj_remove," + item.name + item.dbref) if utils.inherits_from(obj, Npc): # An NPC has left pass elif utils.inherits_from(obj, Mob): # A Mob has left pass else: # Else if a PC has left the room if utils.inherits_from(obj, Character): # Any NPCs in the room ? for item in self.contents: if utils.inherits_from(item, Npc): # Notify NPCs that a PC left the room tickerhandler.remove(item,1)
def func(self): "Implement command" caller = self.caller if not self.args: caller.msg("Drop what?") return # search for object referred in argument [custom added to deal with dbref] if '#' in self.args: # if '#' in argument search by dbref objname = "#"+self.args.split('#')[1] # object on player with same dbref objs = [item for item in caller.contents_get() if objname==item.dbref] # if object asked for on player if objs: obj = objs[0] else: caller.msg("You aren't carrying %s." % self.args) return else: # else search in room for object with same name # Because the DROP command by definition looks for items # in inventory, call the search function using location = caller obj = caller.search(self.args, location=caller, nofound_string="You aren't carrying %s." % self.args, multimatch_string="You carry more than one %s:" % self.args) if not obj: return obj.move_to(caller.location, quiet=True) caller.msg("You drop %s." % (obj.name,)) caller.msg("DATA,inv_remove," + obj.name + obj.dbref) for item in caller.location.contents: if utils.inherits_from(item, Character): item.msg("DATA,obj_add," + obj.name + obj.dbref) caller.location.msg_contents("%s drops %s." % (caller.name, obj.name), exclude=caller) # if object of type Weapon if (utils.inherits_from(obj, Weapon)): # if user wasn't equipped with any weapon if caller.db.equip==obj.dbref: caller.db.equip = "" # equip with got object caller.msg("You unequip %s" % obj.name) # Call the object script's at_drop() method. obj.at_drop(caller)
def at_object_receive(self, obj, source_location): if utils.inherits_from( obj, "typeclasses.characters.Character") and self.tags.get( "item", category='chargen'): spawn({ "prototype": "DAGGER", "location": self }, { "prototype": "SIMPLE_ROBE", "location": self }) if utils.inherits_from( obj, "typeclasses.characters.Character") and self.tags.get( "coins", category='chargen'): transfer_funds(obj, 1000)
def parse(self): """ We run the parent parser as usual, then fix the result """ super(MuxAccountCommand, self).parse() if inherits_from(self.caller, "evennia.objects.objects.DefaultObject"): self.character = self.caller # caller is an Object/Character self.caller = self.caller.account elif inherits_from(self.caller, "evennia.accounts.accounts.DefaultAccount"): self.character = self.caller.get_puppet( self.session) # caller was already an Account else: self.character = None
def func(self): "Implementing combat" # pass iff argument. assumes one argument passed if not self.args: caller = self.caller caller.msg("You need to pick a single target to attack.") return character = self.caller item = self.args # gets rid of the 1st space # search for object referred in argument if '#' in item: # if '#' in argument search by dbref enemyname = "#"+item.split('#')[1] # object in room with same dbref enemy = [obj for obj in character.location.contents_get() if enemyname==obj.dbref] # if enemy asked for in room if enemy: enemy = enemy[0] else: character.msg("%s doesn't exist in this room" % item) return else: # else search by name # object in room with same name enemy = character.search(item, location=character.location) # if object not of type character or mob or npc if not (utils.inherits_from(enemy, Character) or utils.inherits_from(enemy, Mob) or utils.inherits_from(enemy, Npc)): character.msg("%s can't be attacked" % item) return # if enemy = self if enemy.dbref==character.dbref: character.msg("Stop being suicidal! I've set an appointment for you with the shrink") return # if user has equipped weapon weapons = [pobj for pobj in character.contents_get() if utils.inherits_from(pobj, Weapon) and pobj.dbref==character.db.equip] if weapons: character.msg("You slash at %s" % enemy) character.execute_cmd("slash %s" % enemy) else: character.msg("You punch %s" % enemy) rules.roll_challenge(character, enemy, "kickbox")
def func(self): """Kick the object""" location = self.caller.location caller = self.caller if self.args: obj = self.caller.search(self.args.strip()) else: caller.msg("What do you want to kick?") return if utils.inherits_from(obj, Character): caller.msg("Don't kick other people!") return elif obj != self.obj: caller.msg("You can't kick that.") return location.msg_contents(text="{char} kicks the ball.", from_obj=caller, exclude=caller, mapping={"char": self.caller}) self.caller.msg("You kick the ball.") self.caller.location.msg_contents(text="The ball rolls around.", from_obj=self.caller)
def _destroy_room(self, room): """ Moves a room back to storage. If room is not a WildernessRoom or there is a player inside the room, then this does nothing. Args: room (WildernessRoom): the room to put in storage """ if not room or not inherits_from(room, WildernessRoom): return for item in room.contents: if item.has_account: # There is still a character in that room. We can't get rid of # it just yet break else: # No characters left in the room. # Clear the location of every obj in that room first for item in room.contents: if item.destination and item.destination == room: # Ignore the exits, they stay in the room continue item.location = None # Then delete its reference del self.db.rooms[room.ndb.active_coordinates] # And finally put this room away in storage self.db.unused_rooms.append(room)
def at_start(self): if not self.db.API_key: self.db.API_Key = 'e07c570e1f5f85a42dacce70bc6c63ce' if not self.db.fogmessage: self.db.fogmessage = ['A mist hangs over everything','The fog turns everything into murky shadows','You worry about your footing in the dense fog'] self.db.clearmessage = ['The bright sky feels light and carefree','The energy of the earth refreshes you','A clear day','Sunlight warms your face','The trees are bright and green','You hear the laughter of undergrads','You wish you had a frisbee'] self.db.cloudmessage = ['Clouds sweep across the sky.','A faint breeze is felt','A cloud in the distance reminds you of something','Tree branches creak and sway in the wind','A chill comes over you','You see a mountain in the distance'] self.db.rainmessage = ['The rain falls heavily on the ground','The dark clouds are pregnant with rain','The ground is slick, be careful','Rain, rain, go away, come again some other day'] self.db.snowmessage = ['White snow blankets the world','The cold bites at your face'] self.db.raremessage = ['You feel a pang of nostalgia','A faint smell reminds you of your mother','The air tastes like metal','You feel hopeless and lost','The meaninglessness of existence overcomes you','There\'s some trash on the ground','There doesn\'t seem to be anyone around','You notice the hum of electricity. Has it always been there?','The wounds of your childhood ache'] # search for veggies in room veggies_in_room = [obj for obj in self.obj.contents_get() if utils.inherits_from(obj, objects.Vegetable)] # if not veggies in room if not veggies_in_room: prototype = random.choice(self.db.available_veggies) # use the spawner to create a new Vegetable from the spawner dictionary veggie = spawn(objects.VEGETABLE_PROTOTYPES[prototype], prototype_parents=objects.VEGETABLE_PROTOTYPES)[0] veggie.location = self.obj veggiestring = ("A %s ripens" % veggie) self.obj.msg_contents(veggiestring) self.obj.msg_contents("DATA,obj_add," + veggie + veggie.dbref) # if weather not set for room if not self.db.cweather and self.db.location: loc = self.obj.db.location.split(',') # if location contains lat, lng if len(loc)==2: # Get Weather from Forecast.io forecast = forecastio.load_forecast(self.db.API_Key, loc[0], loc[1]) # Extract and store current weather summary self.obj.cweather = forecast.currently().summary
def func(self): # Check if it is player's combat_turn if self.caller.db.combat_turn: # Check to see if caller is in combat loop: if self.caller in self.combat_loop: self.caller.location.msg_contents(f"|025{self.caller.key} breaks away from combat.|n") # Instantiate combat loop class loop = CombatLoop(self.caller, target=None) # Run cleanup to move to next target self.combat_loop.remove(self.caller) # Reset stats self.caller.db.in_combat = 0 self.caller.db.combat_turn = 1 # Check for only npcs remaining. loop_contents = [char for char in self.combat_loop if utils.inherits_from(char, Npc)] if len(loop_contents) == len(self.caller.location.db.combat_loop): # Reset combat stats for char in self.combat_loop: char.db.combat_turn = 1 char.db.in_combat = 0 self.combat_loop.clear() self.caller.location.msg_contents("|025Combat is now over.|n") return else: loop.cleanup() else: self.msg(f"|400You are not part of the combat loop for {self.caller.location}.|n") else: self.caller.msg("|430You need to wait until it is your turn before you are able to act.|n")
def func(self): """ Implement the command. This works both as a look and a search command; there is a random chance of eventually finding a light source. """ caller = self.caller # count how many searches we've done nr_searches = caller.ndb.dark_searches if nr_searches is None: nr_searches = 0 caller.ndb.dark_searches = nr_searches if nr_searches < 4 and random.random() < 0.90: # we don't find anything caller.msg(random.choice(DARK_MESSAGES)) caller.ndb.dark_searches += 1 else: # we could have found something! if any(obj for obj in caller.contents if utils.inherits_from(obj, LightSource)): # we already carry a LightSource object. caller.msg(ALREADY_LIGHTSOURCE) else: # don't have a light source, create a new one. create_object(LightSource, key="splinter", location=caller) caller.msg(FOUND_LIGHTSOURCE)
def func(self): arglist = self.arglist args = self.args rhs = self.rhs lhs = self.lhs switches = self.switches if not args: self.caller.msg(evtable.EvTable("Downtime",table=self.caller.db.timelog)) return elif self.IsInt(lhs): if rhs != "": if int(lhs) <= self.caller.db.downtime: self.caller.db.timelog.append(self.TimeLog(int(lhs),self.caller.location.name,rhs)) self.caller.msg("Spending "+lhs+" hours of downtime for "+rhs) self.caller.db.downtime -= int(lhs) return else: self.caller.msg("You don't have that much downtime left!") return else: self.caller.msg("You must provide a reason for your downtime expenditure in order to spend it!") elif len(switches) > 0: if switches[0].lower() == "peek" and self.caller.IsAdmin(): timelog = [] if inherits_from(search.objects(arglist[0])[0],DefaultCharacter): try: for item in search.objects(arglist[0])[0].db.timelog: timelog.append(item) timebox = StatBlock(str(search.objects(arglist[0])[0])+"'s time log",False,timelog) timebox.SetColumns(1) self.caller.msg(timebox.Show()+timebox.Footer()) except AttributeError: self.caller.msg("Character not found!")
def at_object_receive(self, obj, source_location): if utils.inherits_from( obj, typeclasses.characters.Npc): # An NPC has entered pass else: if utils.inherits_from(obj, typeclasses.characters.Character): # An account character has entered. # Cause the character to look around # Note this used to be in "at_after_move" obj.execute_cmd('look') for item in self.contents: if utils.inherits_from(item, typeclasses.characters.Npc): # An NPC is in the room item.at_char_entered(obj)
def move_obj(self, obj, new_coordinates): """ Moves obj to new coordinates in this wilderness. Args: obj (object): the object to move new_coordinates (tuple): tuple of (x, y) where to move obj to. """ # Update the position of this obj in the wilderness self.itemcoordinates[obj] = new_coordinates old_room = obj.location # Remove the obj's location. This is needed so that the object does not # appear in its old room should that room be deleted. obj.location = None try: # See if we already have a room for that location room = self.db.rooms[new_coordinates] # There is. Try to destroy the old_room if it is not needed anymore self._destroy_room(old_room) except KeyError: # There is no room yet at new_location if (old_room and not inherits_from(old_room, WildernessRoom)) or ( not old_room ): # Obj doesn't originally come from a wilderness room. # We'll create a new one then. room = self._create_room(new_coordinates, obj) else: # Obj does come from another wilderness room create_new_room = False if old_room.wilderness != self: # ... but that other wilderness room belongs to another # wilderness map create_new_room = True old_room.wilderness.at_after_object_leave(obj) else: for item in old_room.contents: if item.has_account: # There is still a player in the old room. # Let's create a new room and not touch that old # room. create_new_room = True break if create_new_room: # Create a new room to hold obj, not touching any obj's in # the old room room = self._create_room(new_coordinates, obj) else: # The old_room is empty: we are just going to reuse that # room instead of creating a new one room = old_room room.set_active_coordinates(new_coordinates, obj) obj.location = room obj.ndb.wilderness = self
def move_obj(self, obj, new_coordinates): """ Moves obj to new coordinates in this wilderness. Args: obj (object): the object to move new_coordinates (tuple): tuple of (x, y) where to move obj to. """ # Update the position of this obj in the wilderness self.itemcoordinates[obj] = new_coordinates old_room = obj.location # Remove the obj's location. This is needed so that the object does not # appear in its old room should that room be deleted. obj.location = None try: # See if we already have a room for that location room = self.db.rooms[new_coordinates] # There is. Try to destroy the old_room if it is not needed anymore self._destroy_room(old_room) except KeyError: # There is no room yet at new_location if (old_room and not inherits_from(old_room, WildernessRoom)) or \ (not old_room): # Obj doesn't originally come from a wilderness room. # We'll create a new one then. room = self._create_room(new_coordinates, obj) else: # Obj does come from another wilderness room create_new_room = False if old_room.wilderness != self: # ... but that other wilderness room belongs to another # wilderness map create_new_room = True old_room.wilderness.at_after_object_leave(obj) else: for item in old_room.contents: if item.has_account: # There is still a player in the old room. # Let's create a new room and not touch that old # room. create_new_room = True break if create_new_room: # Create a new room to hold obj, not touching any obj's in # the old room room = self._create_room(new_coordinates, obj) else: # The old_room is empty: we are just going to reuse that # room instead of creating a new one room = old_room room.set_active_coordinates(new_coordinates, obj) obj.location = room obj.ndb.wilderness = self
def parse(self): """ Add convenience check to know if caller is an Account or not since this cmd will be able to add to either Object- or Account level. """ super().parse() self.caller_is_account = bool( inherits_from(self.caller, "evennia.accounts.accounts.DefaultAccount"))
def at_object_receive(self, moved_obj, source_location): """ Called when an object arrives in the room. This can be used to sum up the situation, set tags etc. """ if utils.inherits_from(moved_obj, "evennia.objects.objects.DefaultCharacter"): self.log(f"JOIN: {moved_obj} joined room") self.state.character_enters(moved_obj)
def at_look(self, target): desc = super(Character, self).at_look(target) self.msg(type(target)) if (utils.inherits_from(target, typeclasses.rooms.Room)): # Print out the map mapper = Mapper() mapper.generate_map(target) desc = desc + "\n" + str(mapper) return desc
def at_object_leave(self, moved_obj, target_location, **kwargs): """ Called when an object leaves the room; if this is a Character we need to clean them up and move them to the menu state. """ if utils.inherits_from(moved_obj, "evennia.objects.objects.DefaultCharacter"): self.character_cleanup(moved_obj) if len(self.get_all_characters()) <= 1: # after this move there'll be no more characters in the room - delete the room! self.delete()
def at_object_receive(self, obj, source_location): if utils.inherits_from(obj, Npc): # An NPC has entered pass else: # Else if a PC has entered if utils.inherits_from(obj, Character): # Cause the character to look around #obj.execute_cmd('look') for item in self.contents: # Any NPCs in the room ? if utils.inherits_from(item, Npc): # Notify NPCs that a PC entered the room item.at_char_entered(obj) tickerhandler.add(item,1) # if item in room not self if item.dbref != obj.dbref: # if item is of class Character if utils.inherits_from(item, Character): obj.msg("DATA,char_add," + item.name + item.dbref) item.msg("DATA,char_add," + obj.name + obj.dbref) # else if item is of class Mob elif utils.inherits_from(item, Mob): obj.msg("DATA,char_add," + item.name + item.dbref) # else if item is of class Npc elif utils.inherits_from(item, Npc): obj.msg("DATA,char_add," + item.name + item.dbref) # else (an object) else: obj.msg("DATA,obj_add," + item.name + item.dbref)
def exp_gain(caller, target): # self.db.exp_level = 10 # this is the relative level of the creature # self.db.exp_multiplier = 4 # If you're under the level, subtract player level from NPC level and multiply by the multiplier. # self.db.exp_max_level = 20 # At this level you won't gain any experience from killing this NPC. # # self.db.home_location = "#2" # This should be set! # # # So normally any kill is worth 1% exp. # # But if your level is under the npc's level, you get a bonus # # The bonus is level difference * multiplier. # # # This multiplier equation could similarly be used when attacking people below your current level, so you might # # level up multiple times from killing a high-level person. exp_gain_amount = target.db.level - caller.db.level if exp_gain_amount < 0 and utils.inherits_from( target, "typeclasses.npcs.Combat_Mob"): exp_gain_amount = 0 elif exp_gain_amount < 1: exp_gain_amount = 1 exp_gain_amount = exp_gain_amount * target.db.exp_multiplier caller.db.exp = caller.db.exp + exp_gain_amount while caller.db.exp > 99 and caller.db.level < 101: caller.db.exp = caller.db.exp - 100 caller.db.level = caller.db.level + 1 level_string = str(caller.db.level) level_suffix = "th" if level_string[-1:] == "1": level_suffix = "st" elif level_string[-1:] == "2": level_suffix = "nd" elif level_string[-1:] == "3": level_suffix = "rd" caller.msg( "Your aura overflows with power, producing a ringing sound as you reach the %s%s level!" % (caller.db.level, level_suffix)) string = "A ringing sound can be heard as %s reaches the %s%s level!" % ( caller.name, caller.db.level, level_suffix) caller.location.msg_contents(string, exclude=caller) new_max_health = caller.db.base_constitution * caller.db.level new_max_health = new_max_health + 100 caller.db.max_health = new_max_health
def func(self): # Check to see if caller is in combat loop: if self.caller in self.combat_loop: enemies = [char for char in self.combat_loop if utils.inherits_from(char, Npc)] table = self.styled_table(border="header") for enemy in enemies: table.add_row("|C%s|n" % enemy.name, enemy.db.desc or "", self.isBleeding(enemy), self.isDying(enemy)) string = "|430Current Targets:|n\n%s" % table self.caller.msg(string) else: self.msg(f"|400You are not part of any combat for {self.caller.location}.|n")
def at_repeat(self): newspaper_in_room = [obj for obj in self.obj.contents_get() if utils.inherits_from(obj, objects.Newspaper)] if not newspaper_in_room: "newspaper spawned if less than threshold in library" prototype = random.choice(self.db.available_newspaper) # randomly choose a newspaper edition(for now) # use the spawner to create a new Newspaper from the spawner dictionary based on type chosen in prototype newspaper = spawn(objects.NEWSPAPER_PROTOTYPES[prototype], prototype_parents=objects.NEWSPAPER_PROTOTYPES)[0] newspaper.location = self.obj newspaperstring = ("The newspaper man drop the latest %s" % newspaper) self.obj.msg_contents(newspaperstring) self.obj.msg_contents("DATA,obj_add," + newspaper + newspaper.dbref)
def can_hit(caller, target): if not target: caller.msg("Hit whom?") return False if not utils.inherits_from(target, 'typeclasses.characters.Character'): caller.msg("This is not a valid target.") return False if target == caller: caller.msg("You affectionately pat yourself on the back.") caller.location.msg_contents("{} affectionately pats themselves on the back.".format(caller.name), exclude=[caller]) return False else: return True
def room_type_check(self, target): caller = self.caller # rooms if utils.inherits_from(caller.location, "typeclasses.rooms.DeathRoom"): caller.msg("You can't do that now.") return True if caller.location.tags.get( 'city', category='corinth' ) and target.db.citizenship == "Corinth": # or any of the other final rooms caller.msg( "It's not wise to attack another citizen in Corinth without approval from the Magistrates." ) return True
def create_evscaperoom_object(typeclass=None, key="testobj", location=None, delete_duplicates=True, **kwargs): """ This is a convenience-wrapper for quickly building EvscapeRoom objects. This is called from the helper-method create_object on states, but is also useful for the object-create admin command. Note that for the purpose of the Evscaperoom, we only allow one instance of each *name*, deleting the old version if it already exists. Kwargs: typeclass (str): This can take just the class-name in the evscaperoom's objects.py module. Otherwise, a full path is needed. key (str): Name of object. location (Object): The location to create new object. delete_duplicates (bool): Delete old object with same key. kwargs (any): Will be passed into create_object. Returns: new_obj (Object): The newly created object, if any. """ if not (callable(typeclass) or typeclass.startswith("evennia") or typeclass.startswith("typeclasses") or typeclass.startswith("evscaperoom")): # unless we specify a full typeclass path or the class itself, # auto-complete it typeclass = _BASE_TYPECLASS_PATH + typeclass if delete_duplicates: old_objs = [ obj for obj in search_object(key) if not inherits_from(obj, "evennia.objects.objects.DefaultCharacter") ] if location: # delete only matching objects in the given location [obj.delete() for obj in old_objs if obj.location == location] else: [obj.delete() for obj in old_objs] new_obj = create_object(typeclass=typeclass, key=key, location=location, **kwargs) return new_obj
def _search(self, query, required): """ This implements the various search modes Args: query (str): The search query required (bool or None): This defines if query *must* be found to match a single local Object or not. If None, a non-match means returning the query unchanged. When False, immediately return the query. If required is False, don't search at all. Return: match (Object or str): The match or the search string depending on the `required` mode. Raises: InterruptCommand: Aborts the command quietly. Notes: The _AT_SEARCH_RESULT function will handle all error messaging for us. """ if required is False: return None, query matches = self.caller.search(query, quiet=True) if len(matches) > 1: # prioritize in-room objects over characters matches = [ match for match in matches if not inherits_from( match, "evennia.objects.objects.DefaultObject") ] if not matches or len(matches) > 1: if required: if not query: self.caller.msg("You must give an argument.") else: _AT_SEARCH_RESULT(matches, self.caller, query=query) raise InterruptCommand else: if query: self.caller.msg( f"Found no '{query}' to examine. Maybe be more specific?" ) return None, query else: return matches[0], None
def get_display_name(self, viewer, **kwargs): """ Displays the name of the object in a viewer-aware manner. Args: self (Object, Character, Exit or Room): viewer (TypedObject): The Tangible object, account, or session that needs the name of this Tangible object. Kwargs: pose Return pose appended to name if True color Return includes color style markup prefix if True mxp Return includes mxp command markup prefix if provided db_id Return includes database id to privileged viewers if True plain Return does not include database id or color Returns: name (str): A string of the sdesc containing the name of the object, if this is defined. including the DBREF if viewer is privileged to control this. """ name = self.key if not viewer: viewer = viewer.get_puppet_or_account if inherits_from(viewer, "evennia.accounts.accounts.DefaultAccount"): viewer = viewer.get_puppet( viewer.sessions.all() [0]) # viewer is an Account, convert to tangible if not (viewer and viewer.has_account): return '{}{}|n'.format(self.STYLE, name) color, pose = [kwargs.get('color', True), kwargs.get('pose', False)] # Read kwargs, set defaults. mxp, db_id = [kwargs.get('mxp', False), kwargs.get('db_id', True)] if kwargs.get('plain', False): # "plain" means "without color, without db_id" color, db_id = [False, False] display_name = ("%s%s|n" % (self.STYLE, name)) if color else name if mxp: display_name = "|lc%s|lt%s|le" % (mxp, display_name) if not viewer.account.attributes.has('_quell') and self.access( viewer, access_type='control') and db_id: display_name += '|w(#%s)|n' % self.id if pose and self.db.messages and ( self.db.messages.get('pose') or self.db.messages.get('pose_default')): display_pose = self.db.messages.get('pose') if self.db.messages.get('pose', None)\ else self.db.messages.get('pose_default') display_name += ('|n' if color else '') + display_pose return display_name
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, "evennia.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 DeathRoom_Ticker(self, *args, **kwargs): "ticked at regular intervals" for i in self.contents: if utils.inherits_from(i, "typeclasses.characters.Character"): i.db.death_ticker = i.db.death_ticker + 1 if i.db.death_ticker == 2: i.msg("\nYou see nothing, hear nothing, feel nothing. Then you realize that your consciousness has returned.") elif i.db.death_ticker == 3: i.msg("\nYou realize that there is something floating in the darkness ahead of you... a fearsome black lion! At first you are afraid, but then you realize that this can only be the One True King of Encarnia: Ashlan, the Black Lion!") elif i.db.death_ticker == 4: i.msg("\n|cAshlan the King Roars, \"%s... %s! Go towards the light! The light!\"|n" % (i.name, i.name)) elif i.db.death_ticker == 5: i.msg("\nYou try to move towards the light but an invisible wall holds you back!") elif i.db.death_ticker == 6: i.msg("\n|cAshlan says, \"Oh wow. Wow. Well, bye.\"|n") elif i.db.death_ticker == 7: i.msg("\nA moment later you realize that Ashlan is gone.") elif i.db.death_ticker == 8: i.msg("\nAfter an interminable amount of time, you notice something else in the darkness. A massive, slow-moving snake!") elif i.db.death_ticker == 9: i.msg("\n|cThe great Python hisses, \"%s! Go towards the light, or I shall devour your soul!\"|n" % i.name) elif i.db.death_ticker == 10: i.msg("\nYou run towards the light, this time in a panic but it rejects you again.") elif i.db.death_ticker == 11: i.msg("\n|cThe great Python hisses, \"Sucks to be you...\"|n and melts into the shadows.") elif i.db.death_ticker == 13: i.msg("\nAfter another period of time; it might have been minutes or years, you don't know... you see another being in the shadows.") elif i.db.death_ticker == 14: i.msg("\nUnlike the other two, this one is deathly pale. Cold iron chains sprout from his clawed hands, feet and neck.") elif i.db.death_ticker == 15: i.msg("\n|m\"%s... you know me,\" the pale horror croaks.|n Uncomfortably, you look around for the light but it is nowhere to be seen!" % i.name) elif i.db.death_ticker == 16: i.msg("\n|m\"You have fed off my might. Hidden in my shadow. Pretended that my power was your power. But it was not. And now, you are mine!\"|n") elif i.db.death_ticker == 17: i.msg("\n|mThe pale horror continues, \"That fool Ashlan thinks me humiliated. He thinks his children have gotten the better of me. But this is only the beginning of our game. You are mine and you will not die until I permit it!\"|n") elif i.db.death_ticker == 18: i.msg("\nThe horror twitches a hand towards you and cold iron shackles suddenly appear! They fasten onto your arms, your legs, your neck. They drag you off into the darkness...") elif i.db.death_ticker >= 19: i.db.dead = False destination = i.search("#737", global_search=True) # caller.msg(destination) i.msg( "You wake up beneath a willow tree, next to a recently dug shallow grave.") i.move_to(destination, quiet=True) return
def resolve_attack(self, defense_score, attack_score, attack_weapon, target): dealt_damage = attack_score - defense_score # If the target's stance is evasive or defensive they have a chance to avoid damage stance = target.db.stance if stance in ("evasive", "defensive"): if stance == "evasive": dex = target.db.dex stat = dex elif stance == "defensive": defense = target.db.defense stat = defense # Stat values determine how many dice are rolled num_dice = get_num_dice(stat) or 1 # If a '1' is rolled target successfully blocks or dodges dice = DiceRoll(num_dice, pass_cond=[20]) passed = dice.roll()[1] if passed == True and stance == "evasive": dealt_damage = None message = str(target) + " dodges and takes no damage!" elif passed == True and stance == "defensive": dealt_damage = None message = str(target) + " blocks and takes no damage!" # Target didn't block or dodge and took damage if dealt_damage != None and dealt_damage > 0: xp = XP(self.caller, 30) message = str(self.caller) + " attacked " + str( target) + " for " + str(dealt_damage) if not utils.inherits_from(self.caller, 'typeclasses.characters.NPC'): message += " with " + str(attack_weapon) # Target didn't block or dodge but didn't take damage elif dealt_damage != None and dealt_damage <= 0: message = str(target) + " shrugs off an attack from " + str( self.caller) return dealt_damage, message
def parse(self): caller = self.caller if not self.args: caller.msg("Light what?") raise InterruptCommand else: args = self.args.strip() obj = caller.search(args, quiet=True) obj = obj[0] if obj: if not inherits_from(obj, 'items.objects.Lighting'): caller.msg( f"{obj.get_display_name(caller)} cannot be lit!") raise InterruptCommand else: self.obj = obj else: caller.msg(f"{args} not found!") raise InterruptCommand
def at_repeat(self): "called every self.interval seconds." # Atmosphere if (random.randint(1,20) == 1): target = random.choice(self.obj.contents) target.msg(random.choice(self.db.raremessage)) # Weather weathermessage = 'A clear day' # if outdoor and room has cweather set if self.obj.db.roomtype_key != 'building' and self.obj.db.cweather: "weather updates if outdoors" # trigger random message of type found from last weather summary of room if 'Haze' in self.obj.db.cweather or 'Fog' in self.obj.db.cweather: weathermessage = random.choice(self.db.fogmessage) elif 'Clear' in self.obj.db.cweather: weathermessage = random.choice(self.db.clearmessage) elif 'Cloud' in self.obj.db.cweather or 'Overcast' in self.obj.db.cweather: weathermessage = random.choice(self.db.cloudmessage) elif 'Rain' in self.obj.db.cweather or 'Thunder' in self.obj.db.cweather or 'thunder' in self.obj.db.cweather or 'Drizzle' in self.obj.db.cweather: weathermessage = random.choice(self.db.rainmessage) elif 'Snow' in self.obj.db.cweather or 'snow' in self.obj.db.cweather or 'flurry' in self.obj.db.cweather: weathermessage = random.choice(self.db.snowmessage) # send this message to everyone inside the object this script is attached to (likely a room) self.obj.msg_contents(weathermessage) # Vegetable Spawning veggies_in_room = [obj for obj in self.obj.contents_get() if utils.inherits_from(obj, objects.Vegetable)] if self.obj.db.roomtype_key != 'building' and not veggies_in_room: "vegetables spawned if less than threshold in farms" prototype = random.choice(self.db.available_veggies) # use the spawner to create a new Vegetable from the spawner dictionary veggie = spawn(objects.VEGETABLE_PROTOTYPES[prototype], prototype_parents=objects.VEGETABLE_PROTOTYPES)[0] veggie.location = self.obj veggiestring = ("A %s ripens" % veggie) self.obj.msg_contents(veggiestring) self.obj.msg_contents("DATA,obj_add," + veggie + veggie.dbref)
def _get_callback(self, callback): """ Analyze callback and determine its consituents Args: callback (function or method): This is either a stand-alone function or class method on a typeclassed entitye (that is, an entity that can be saved to the database). Returns: ret (tuple): This is a tuple of the form `(obj, path, callfunc)`, where `obj` is the database object the callback is defined on if it's a method (otherwise `None`) and vice-versa, `path` is the python-path to the stand-alone function (`None` if a method). The `callfunc` is either the name of the method to call or the callable function object itself. Raises: TypeError: If the callback is of an unsupported type. """ outobj, outpath, outcallfunc = None, None, None if callable(callback): if inspect.ismethod(callback): outobj = callback.__self__ outcallfunc = callback.__func__.__name__ elif inspect.isfunction(callback): outpath = "%s.%s" % (callback.__module__, callback.__name__) outcallfunc = callback else: raise TypeError(f"{callback} is not a method or function.") else: raise TypeError( f"{callback} is not a callable function or method.") if outobj and not inherits_from( outobj, "evennia.typeclasses.models.TypedObject"): raise TypeError( f"{callback} is a method on a normal object - it must " "be either a method on a typeclass, or a stand-alone function." ) return outobj, outpath, outcallfunc
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, "evennia.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 func(self): "Implements eating" # pass iff argument. assumes one argument passed if not self.args: caller = self.caller caller.msg("You need to pick a single target to attack.") return character = self.caller item = self.args # gets rid of the 1st space # search for object referred in argument if '#' in item: # if '#' in argument search by dbref vegetablename = "#"+item.split('#')[1] # object in room with same dbref vegetable = [obj for obj in character.contents_get() if vegetablename==obj.dbref] # if vegetable asked for in room if vegetable: vegetable = vegetable[0] else: character.msg("%s doesn't exist in this room" % item) return else: # else search in room for object with same name vegetable = character.search(item, location=character.location) # if object not of class vegetable if not (utils.inherits_from(vegetable, Vegetable)): character.msg("%s can't be eaten" % item) return # if vegetable to be eaten is in the room string = ("You eat your %s" % vegetable) character.msg("DATA,inv_remove,%s" % item[1:]) character.msg(string) character.db.HP += vegetable.db.heal character.db.STR += vegetable.db.strength vegetable.delete()
def func(self): "implements the actual functionality" caller = self.caller target = caller.search(self.target) if not target: return if not utils.inherits_from(target, 'typeclasses.characters.Character'): caller.msg("This is not a valid target.") return if target.db.hp['Current'] > target.db.hp['Min']: target.msg("{} wounds you!".format(caller.name)) caller.msg("You wound {}!".format(target.name)) target.db.hp['Current'] = target.db.hp['Current'] - 10 caller.msg( "{}'s HP has been reduced by 10 and is now {}. Their max is {}" .format(target.name, target.db.hp['Current'], target.db.hp['Max'])) caller.location.msg_contents("{} wounds {}!".format( caller.name, target.name), exclude=[caller, target]) else: caller.msg("That would kill him!")
def func(self): caller = self.caller total = 0 merchant_name = "none" item_sold = "none" for i in caller.location.contents: if utils.inherits_from(i, "typeclasses.npcs.Combat_Merchant_Mob"): merchant_name = i.name for i in caller.contents: if i.name == "a small and crude fur pelt": total = total + 1 item_sold = "pelt" i.delete() elif i.name == "a small fur pelt": total = total + 2 item_sold = "pelt" i.delete() elif i.name == "a small but fine fur pelt": total = total + 3 item_sold = "pelt" i.delete() if item_sold == "none": caller.msg("You have nothing to sell!") if item_sold == "pelt": string = merchant_name + " gives you " + str( total) + " silver sovereigns in return for your pelts." caller.msg(string) caller.db.silver_carried = caller.db.silver_carried + total string_r = merchant_name + " gives " + caller.name + " " + str( total ) + " silver sovereigns in return for " + caller.db.genderp + " pelts." caller.location.msg_contents(string_r, exclude=caller)
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 compatibility fallback if utils.inherits_from(obj, ExtendedRoom): # this is an extended room, 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 arrive_at(self, position): """ # The following code moves an object to a new position and room that # matches that position. """ vessel = self # Check the arguments to make sure vessel is a vessel and # position is a position # Look up room in teh entier DB if position: room = search.search_object_attribute(key="coordinates", value=position) else: string = "position: %s" % str(position) self.msg_contents(string) return # move to room if room: # If the destination room exists, we go there. vessel.msg_contents("%s already exists." % room) room = room[0] # TODO: fix this^ throw on multimatch rooms there should only # ever be one room per coordinates # unless it is dry land if inherits_from(room, "typeclasses.rooms.DryLandRoom"): vessel.msg_contents("It's dry land so cancelling move.") return # but if not dry land # ... lets get on with it and move else: vessel.msg_contents("Moving to %s" % room) vessel.move_to(room) return elif vessel.location.is_typeclass("rooms.DynamicRoom") and len(vessel.location.contents) == 1: # This means we are in a dynamic room alone vessel.msg_contents("updating room coordinates to %s" % str(position)) vessel.location.db.coordinates = position # have to update vessel position to match rooms new position vessel.db.position = position return else: # Assume the current room is occupied or not dynamic # create the room vessel.msg_contents("Creating new room at %s" % str(position)) room = create_object(typeclass="rooms.DynamicRoom", key="The Open Ocean", location=None) room.db.coordinates = position vessel.msg_contents("Moving to %s" % room) vessel.move_to(room) return def make_way(self, course): old_position = self.db.position position = move_vector(old_position, course) self.msg_contents("New position = %s" % str(position)) self.arrive_at(self, position) def at_tick(self): """ All floating objects move every tick unless anchored/moored. So at tick, we calculate course and make_way """ pass
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, "evennia.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 isCharacter(obj): return utils.inherits_from(obj, 'typeclasses.character.Character')
def func(self): "implements the command." caller = self.caller if not self.args and self.args.split()>1: caller.msg("Get what?") return # search for object referred in argument [custom added to deal with dbref] if '#' in self.args: # if '#' in argument search by dbref objname = "#"+self.args.split('#')[1] # object in room with same dbref objs = [item for item in caller.location.contents_get() if objname==item.dbref] # if object asked for in room if objs: obj = objs[0] else: caller.msg("You can't get that.") return else: # else search in room for object with same name obj = caller.search(self.args, location=caller.location) if not obj: return if caller == obj: caller.msg("You can't get yourself.") return if not obj.access(caller, 'get'): if obj.db.get_err_msg: caller.msg(obj.db.get_err_msg) else: caller.msg("You can't get that.") return obj.move_to(caller, quiet=True) caller.msg("You pick up %s." % obj.name) # pass inventory addition to caller in machine readable format caller.msg("DATA,inv_add," + obj.name + obj.dbref) # pass object removal from room to characters in room in machine readable format for item in caller.location.contents: if utils.inherits_from(item, Character): item.msg("DATA,obj_remove," + obj.name + obj.dbref) # pass object removal from room to characters in room in human readable format caller.location.msg_contents("%s picks up %s." % (caller.name, obj.name), exclude=caller) # if object of type Weapon if (utils.inherits_from(obj, Weapon)): # if user wasn't equipped with any weapon if caller.db.equip=="": caller.db.equip = obj.dbref # equip with got object caller.msg("You equip yourself with %s" % obj.name) # calling hook method obj.at_get(caller) if obj.name == "The Quantum Spanner": caller.location.msg_contents("The earth opens up beneath you. You fall down a deep hole. You land in a pile of robot parts. One of the robot's faces looks very familiar. How can this be?! The face of the robot is.... Michael's face! Michael must be a robot!")
def func(self): caller = self.caller self.difficulty = "Easy" self.damage_type = "Cut" self.base_speed = 5 self.attack_damage_mod = 1 self.attack_success_bonus = 0 if not self.target: caller.msg("No target specified. (Usage: chop <target> <location>).") return target = caller.search(self.target, location=caller.location, nofound_string="Your intended target, %s, cannot be found here." % self.target) hitbox = self.hitbox if not target: return if not utils.inherits_from(target, Character): caller.msg("You cannot attack that!") return if caller.ndb.is_busy: # You are still busy. timeleft = self.caller.ndb.busy_timer.getTime() - time() caller.msg("You are still busy for " + str(int(math.ceil(timeleft))) + " seconds.") return self.target = target defender_weapon = self.target.db.right_hand['Wielding'] caller_attempt_string = "You chop down with %s viciously, striking at %s." % (self.obj, target) target_attempt_string = "%s chops down with %s viciously, striking at you." % (caller, self.obj) room_attempt_string = "%s chops down with %s viciously, striking at %s." % (caller, self.obj, target) raw_success, refined_success, thresholds = rules.getCombatSuccess(self) hit = rules.getHit() roll_string = "[Success: %s, Roll: %s] \n" % (refined_success, hit) if hit > refined_success: if hitbox == "Normal" or hitbox == "High": hit_locations = ["Face", "Head", "Neck", "Left shoulder", "Right shoulder"] self.hitlocation = choice(hit_locations) elif hitbox == "Mid": hit_locations = ["Chest", "Waist", "Left arm", "Right arm", "Left hand", "Right hand"] self.hitlocation = choice(hit_locations) else: hit_locations = ["Left thigh", "Right thigh", "Left calf", "Right calf", "Left foot", "Right foot"] self.hitlocation = choice(hit_locations) damage = rules.getDamage(self, raw_success, hit) rules.inflictDamage(self, damage) injury = rules.getDamageDesc(self.damage_type, damage) caller_damage_string = " Hit! %s suffers a %s to their %s." % (target, injury.lower(), self.hitlocation.lower()) target_damage_string = " Hit! You suffer a %s to your %s." % (injury.lower(), self.hitlocation.lower()) caller.msg(roll_string + caller_attempt_string + caller_damage_string) target.msg(roll_string + target_attempt_string + target_damage_string) caller.location.msg_contents(room_attempt_string + caller_damage_string, exclude=(caller, target)) else: for defence in thresholds: if hit <= thresholds[defence]: #Call relevant message strings and their formats to fill %s. caller_block_string = rules.WEAPONBLOCKS[defence.rsplit()[0]][defence.rsplit()[1]]["CallerString"] target_block_string = rules.WEAPONBLOCKS[defence.rsplit()[0]][defence.rsplit()[1]]["TargetString"] room_block_string = rules.WEAPONBLOCKS[defence.rsplit()[0]][defence.rsplit()[1]]["RoomString"] caller_format = rules.WEAPONBLOCKS[defence.rsplit()[0]][defence.rsplit()[1]]["CallerFormat"] target_format = rules.WEAPONBLOCKS[defence.rsplit()[0]][defence.rsplit()[1]]["TargetFormat"] room_format = rules.WEAPONBLOCKS[defence.rsplit()[0]][defence.rsplit()[1]]["RoomFormat"] #initialise lists for formats caller_format_list = [] target_format_list = [] room_format_list = [] #Call what the format strings represent and append the resulting variables to the lists. for formats in caller_format: caller_format_list.append(eval(formats)) for formats in target_format: target_format_list.append(eval(formats)) for formats in room_format: room_format_list.append(eval(formats)) caller_string = (caller_block_string % tuple(caller_format_list)) target_string = (target_block_string % tuple(target_format_list)) room_string = (room_block_string % tuple(room_format_list)) caller.msg(roll_string + caller_attempt_string + " " + caller_string) target.msg(roll_string + target_attempt_string + " " + target_string) caller.location.msg_contents(room_attempt_string + " " + room_string, exclude=(caller, target)) break else: pass self.makeBusy()
def isBuildingLocation(obj): return obj.__class__.__name__ == 'Building' or \ obj.__class__.__name__ == 'BuildingFloor' or \ obj.__class__.__name__ == 'Box' or \ utils.inherits_from(obj, 'BuildingApartment')
def func(self): # pass iff argument. assumes one argument passed if not self.args and self.args.split()>1: self.caller.msg("You need to pick a single target to act on.") return character = self.caller itempassed = self.args.split()[0] # gets rid of the 1st space # search for item referred in argument # by dbref if '#' in itempassed: # if '#' in argument search by dbref itemname = "#"+itempassed.split('#')[1] # check if object with requested dbref on self item = [obj for obj in character.contents_get() if itemname==obj.dbref] # check if object with requested dbref in room if not item: item = [obj for obj in character.location.contents_get() if itemname==obj.dbref] # if item asked for was found on self or in room if item: item = item[0] else: character.msg("%s doesn't exist in this room" % itempassed) return # by name else: # search on self for object with same name item = character.search(itempassed, location=character) # if not found on self if not item: # search in room for object with same name item = character.search(itempassed, location=character.location) # if still not found if not item: character.msg("%s doesn't exist here" % itempassed) return # if object of class weapon if (utils.inherits_from(item, Weapon)): # if weapon was equipped if character.db.equip==item.dbref: # dequip character.db.equip = "" character.msg("You've unequipped yourself") # if weapon was dequipped else: # equip character.db.equip = item.dbref character.msg("You've equipped yourself with %s" % item.name) return # if item to be acted on is in the room/inventory and doesn't belong to above categories # if has hook at_defact, call it if hasattr(item, "at_defact"): return item.at_defact(self.caller) # else if has default action associated with it, call that elif item.db.defact: command=item.db.defact+" "+ item.name+item.dbref # else just execute a look on the object else: command="look " + item.name+item.dbref character.execute_cmd(command)