code
stringlengths
321
95.4k
apis
list
extract_api
stringlengths
105
90.3k
""" TutorialMirror A simple mirror object to experiment with. """ from evennia import DefaultObject from evennia.utils import make_iter, is_iter from evennia import logger class TutorialMirror(DefaultObject): """ A simple mirror object that - echoes back the description of the object looking at it - echoes back whatever is being sent to its .msg - to the sender, if given, otherwise to the location of the mirror. """ def return_appearance(self, looker, **kwargs): """ This formats the description of this object. Called by the 'look' command. Args: looker (Object): Object doing the looking. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ if isinstance(looker, self.__class__): # avoid infinite recursion by having two mirrors look at each other return "The image of yourself stretches into infinity." return f"{self.key} shows your reflection:\n{looker.db.desc}" def msg(self, text=None, from_obj=None, **kwargs): """ Simply override .msg to echo back to the messenger or to the current location. Args: text (str or tuple, optional): The message to send. This is treated internally like any send-command, so its value can be a tuple if sending multiple arguments to the `text` oob command. from_obj (obj or iterable) given, at_msg_send will be called. This value will be passed on to the protocol. If iterable, will execute hook on all entities in it. """ if not text: text = "<silence>" text = text[0] if is_iter(text) else text if from_obj: for obj in make_iter(from_obj): obj.msg(f'{self.key} echoes back to you:\n"{text}".') elif self.location: self.location.msg_contents(f'{self.key} echoes back:\n"{text}".', exclude=[self]) else: # no from_obj and no location, just log logger.log_msg(f"{self.key}.msg was called without from_obj and .location is None.")
[ "evennia.logger.log_msg", "evennia.utils.make_iter", "evennia.utils.is_iter" ]
[((1810, 1823), 'evennia.utils.is_iter', 'is_iter', (['text'], {}), '(text)\n', (1817, 1823), False, 'from evennia.utils import make_iter, is_iter\n'), ((1878, 1897), 'evennia.utils.make_iter', 'make_iter', (['from_obj'], {}), '(from_obj)\n', (1887, 1897), False, 'from evennia.utils import make_iter, is_iter\n'), ((2169, 2258), 'evennia.logger.log_msg', 'logger.log_msg', (['f"""{self.key}.msg was called without from_obj and .location is None."""'], {}), "(\n f'{self.key}.msg was called without from_obj and .location is None.')\n", (2183, 2258), False, 'from evennia import logger\n')]
""" Combat Manager. This is where the magic happens. And by magic, we mean characters dying, most likely due to vile sorcery. The Combat Manager is invoked by a character starting combat with the +fight command. Anyone set up as a defender of either of those two characters is pulled into combat automatically. Otherwise, players can enter into combat that is in progress with the appropriate defend command, or by a +fight command to attack one of the belligerent parties. Turn based combat has the obvious drawback that someone who is AFK or deliberately not taking their turn completely halts the action. There isn't an easy solution to this. GMs will have tools to skip someone's turn or remove them from combat, and a majority vote by all parties can cause a turn to proceed even when someone has not taken their turn. Phase 1 is the setup phase. This phase is designed to have a pause before deciding actions so that other people can join combat. Characters who join in later phases will not receive a combat turn, and will be added to the fight in the following turn. Phase 1 is also when players can vote to end the combat. Every player MUST enter a command to continue for combat to proceed. There will never be a case where a character can be AFK and in combat. It is possible to vote a character out of combat due to AFK in order for things to proceed. Immediately after every current combatant selects to continue, the participants are locked in and we go to phase 2. Phase 2 is the action phase. Initiative is rolled, and then each player must take an action when it is their turn. 'pass' is a valid action. Each combat action is resolved during the character's turn. Characters who are incapacitated lose their action. Characters who join combat during Phase 2 must wait for the following turn to be allowed a legal action. """ import time from operator import attrgetter from evennia.utils.utils import fill, dedent from server.utils.prettytable import PrettyTable from server.utils.arx_utils import list_to_string from typeclasses.scripts.combat import combat_settings from typeclasses.scripts.combat.state_handler import CombatantStateHandler from typeclasses.scripts.scripts import Script as BaseScript COMBAT_INTRO = combat_settings.COMBAT_INTRO PHASE1_INTRO = combat_settings.PHASE1_INTRO PHASE2_INTRO = combat_settings.PHASE2_INTRO MAX_AFK = combat_settings.MAX_AFK ROUND_DELAY = combat_settings.ROUND_DELAY class CombatManager(BaseScript): """ Players are added via add_combatant or add_observer. These are invoked by commands in normal commandsets. Characters added receive the combat commandset, which give commands that invoke the other methods. Turns proceed based on every combatant submitting an action, which is a dictionary of combatant IDs to their actions. Dead characters are moved to observer status, incapacitated characters are moved to a special list to denote that they're still in combat but can take no action. Attribute references to the combat manager script are stored in the room location under room.ndb.combat_manager, and inside each character in the combat under character.ndb.combat_manager. Note that all the data for the combat manager is stored inside non-database attributes, since it is designed to be non-persistent. If there's a server reset, combat will end. Non-database attributes: self.ndb.combatants - list of everyone active in the fight. If it's empty, combat ends self.ndb.observers - People passively watching the fight self.ndb.incapacitated - People who are too injured to act, but still can be attacked self.ndb.fighter_data - CharacterCombatData for each combatant. dict with character.id as keys self.ndb.combat_location - room where script happens self.ndb.initiative_list - CharacterCombatData for each fighter. incapacitated chars aren't in it self.ndb.active_character - Current turn of player in phase 2. Not used in phase 1 self.ndb.phase - Phase 1 or 2. 1 is setup, 2 is resolution self.ndb.afk_check - anyone we're checking to see if they're afk self.ndb.votes_to_end - anyone voting to end combat self.ndb.flee_success - Those who can run this turn self.ndb.fleeing - Those intending to try to run Admin Methods: self.msg() - Message to all combatants/observers. self.end_combat() - shut down the fight self.next_character_turn() - move to next character in initiative list in phase 2 self.add_observer(character) self.add_combatant(character) self.remove_combatant(character) self.move_to_observer(character) """ # noinspection PyAttributeOutsideInit def at_script_creation(self): """ Setup the script """ self.key = "CombatManager" self.desc = "Manages the combat state for a group of combatants" # Not persistent because if someone goes LD, we don't want them reconnecting # in combat a week later with no way to leave it. Intentionally quitting out # to avoid combat will just need to be corrected with rules enforcement. self.persistent = False self.interval = ROUND_DELAY self.start_delay = True self.ndb.combatants = [] # those actively involved in fight self.ndb.observers = [] # sent combat data, but cannot act self.ndb.combat_location = self.obj # room of the fight self.ndb.initiative_list = [] # CharacterCombatData of characters in order of initiative self.ndb.active_character = None # who is currently acting during phase 2 self.ndb.phase = 1 self.ndb.afk_check = [] # characters who are flagged afk until they take an action self.ndb.votes_to_end = [] # if all characters vote yes, combat ends self.ndb.flee_success = [] # if we're here, the character is allowed to flee on their turn self.ndb.fleeing = [] # if we're here, they're attempting to flee but haven't rolled yet self.ndb.ready = [] # those ready for phase 2 self.ndb.not_ready = [] # not ready for phase 2 self.ndb.surrender_list = [] # peoeple trying to surrender self.ndb.affect_real_dmg = not self.obj.tags.get("nonlethal_combat") self.ndb.random_deaths = not self.obj.tags.get("no_random_deaths") self.ndb.max_rounds = 250 self.ndb.rounds = 0 # to ensure proper shutdown, prevent some timing errors self.ndb.shutting_down = False self.ndb.status_table = None self.ndb.initializing = True if self.obj.event: self.ndb.risk = self.obj.event.risk else: self.ndb.risk = 4 self.ndb.special_actions = [] self.ndb.gm_afk_counter = 0 @property def status_table(self): """text table of the combat""" if not self.ndb.status_table: self.build_status_table() return self.ndb.status_table def at_repeat(self): """Called at the script timer interval""" if self.check_if_combat_should_end(): return # reset the script timers if self.ndb.shutting_down: return # proceed to combat if self.ndb.phase == 1: self.ready_check() self.msg("Use {w+cs{n to see the current combat status.") self.remove_surrendering_characters() def is_valid(self): """ Check if still has combatants. Incapacitated characters are still combatants, just with very limited options - they can either pass turn or vote to end the fight. The fight ends when all combatants either pass they turn or choose to end. Players can be forced out of active combat if they are AFK, moved to observer status. """ if self.ndb.shutting_down: return False if self.ndb.combatants: return True if self.ndb.initializing: return True return False # ----Methods for passing messages to characters------------- @staticmethod def send_intro_message(character, combatant=True): """ Displays intro message of combat to character """ if not combatant: msg = fill("{mYou are now in observer mode for a fight. {n" + "Most combat commands will not function. To " + "join the fight, use the {w+fight{n command.") else: msg = "{rEntering combat mode.{n\n" msg += "\n\n" + fill(COMBAT_INTRO) character.msg(msg) return def display_phase_status(self, character, disp_intro=True): """ Gives message based on the current combat phase to character.cmdset In phase 1, just list combatants and observers, anyone marked AFK, dead, whatever, and any votes to end. In phase 2, list initiative order and who has the current action. """ if self.ndb.shutting_down: return msg = "" if self.ndb.phase == 1: if disp_intro: msg += PHASE1_INTRO + "\n" msg += str(self.status_table) + "\n" vote_str = self.vote_string if vote_str: msg += vote_str + "\n" elif self.ndb.phase == 2: if disp_intro: msg += PHASE2_INTRO + "\n" msg += str(self.status_table) + "\n" msg += self.get_initiative_list() + "\n" msg += "{wCurrent Round:{n %d" % self.ndb.rounds character.msg(msg) def build_status_table(self): """Builds a table of the status of combatants""" combatants = sorted(self.ndb.combatants) table = PrettyTable(["{wCombatant{n", "{wDamage{n", "{wFatigue{n", "{wAction{n", "{wReady?{n"]) for state in combatants: name = state.combat_handler.name dmg = state.character.get_wound_descriptor(state.character.dmg) fatigue = str(state.fatigue_penalty) action = "None" if not state.queued_action else state.queued_action.table_str rdy = "yes" if state.ready else "{rno{n" table.add_row([name, dmg, fatigue, action, rdy]) self.ndb.status_table = table def display_phase_status_to_all(self, intro=False): """Sends status to all characters in or watching the fight""" msglist = set([ob.character for ob in self.ndb.combatants] + self.ndb.observers) self.build_status_table() self.ready_check() for ob in msglist: self.display_phase_status(ob, disp_intro=intro) def msg(self, message, exclude=None, options=None): """ Sends a message to all objects in combat/observers except for individuals in the exclude list. """ # those in incapacitated list should still be in combatants also msglist = [ob.character for ob in self.ndb.combatants] + self.ndb.observers if not exclude: exclude = [] msglist = [ob for ob in msglist if ob not in exclude] for ob in msglist: mymsg = message ob.msg(mymsg, options) # --------------------------------------------------------------------- # -----Admin Methods for OOC character status: adding, removing, etc---- def check_character_is_combatant(self, character): """Returns True if the character is one of our combatants.""" try: state = character.combat.state return state and state in self.ndb.combatants except AttributeError: return False def add_combatant(self, character, adder=None, reset=False): """ Adds a character to combat. The adder is the character that started the process, and the return message is sent to them. We return None if they're already fighting, since then it's likely a state change in defending or so on, and messages will be sent from elsewhere. """ # if we're already fighting, nothing happens cdata = character.combat if adder: adder_state = adder.combat.state else: adder_state = None if self.check_character_is_combatant(character): if character == adder: return "You are already in the fight." if cdata.state and adder: cdata.state.add_foe(adder) if adder_state: adder_state.add_foe(character) return "%s is already fighting." % character.key # check if attackable if not character.attackable: return "%s is not attackable." % character.key if character.location != self.obj: return "%s is not in the same room as the fight." % character.key # if we were in observer list, we stop since we're participant now self.remove_observer(character) self.send_intro_message(character) # add combat state to list of combatants if character not in self.characters_in_combat: CombatantStateHandler(character, self, reset=reset) if character == adder: return "{rYou have entered combat.{n" # if we have an adder, they're fighting one another. set targets elif self.check_character_is_combatant(adder): # make sure adder is a combatant, not a GM cdata.state.add_foe(adder) cdata.state.prev_targ = adder adder_state.add_foe(character) adder_state.prev_targ = character adder_state.setup_attacks() cdata.state.setup_attacks() return "You have added %s to a fight." % character.name @property def characters_in_combat(self): """Returns characters from our combat states""" return [ob.character for ob in self.ndb.combatants] def register_state(self, state): """ Stores reference to a CombatantStateHandler in self.ndb.combatants. Called by CombatantStateHandler's init, done this way to avoid possible infinite recursion """ if state not in self.ndb.combatants: self.ndb.combatants.append(state) def finish_initialization(self): """ Finish the initial setup of combatants we add """ self.ndb.initializing = False self.reset_combatants() self.display_phase_status_to_all(intro=True) def reset_combatants(self): """Resets all our combatants for the next round, displaying prep message to them""" for state in self.ndb.combatants: state.reset() for state in self.ndb.combatants: state.setup_phase_prep() def check_if_combat_should_end(self): """Checks if combat should be over""" if not self or not self.pk or self.ndb.shutting_down: self.end_combat() return True if not self.ndb.combatants and not self.ndb.initializing and self.managed_mode_permits_ending(): self.msg("No combatants found. Exiting.") self.end_combat() return True active_combatants = [ob for ob in self.ndb.combatants if ob.conscious] active_fighters = [ob for ob in active_combatants if not (ob.automated and ob.queued_action and ob.queued_action.qtype == "Pass")] if not active_fighters and not self.ndb.initializing: if self.managed_mode_permits_ending(): self.msg("All combatants are incapacitated or automated npcs who are passing their turn. Exiting.") self.end_combat() return True def managed_mode_permits_ending(self): """If we're in managed mode, increment a counter of how many checks before we decide it's idle and end""" if not self.managed_mode: return True if self.ndb.gm_afk_counter > 3: return True self.ndb.gm_afk_counter += 1 return False def ready_check(self, checker=None): """ Check all combatants. If all ready, move to phase 2. If checker is set, it's a character who is already ready but is using the command to see a list of who might not be, so the message is only sent to them. """ self.ndb.ready = [] self.ndb.not_ready = [] if self.ndb.phase == 2: # already in phase 2, do nothing return for state in self.ndb.combatants: if state.ready: self.ndb.ready.append(state.character) elif not state.conscious: self.ndb.ready.append(state.character) else: self.ndb.not_ready.append(state.character) if self.ndb.not_ready: # not ready for phase 2, tell them why if checker: self.display_phase_status(checker, disp_intro=False) else: try: self.start_phase_2() except ValueError: import traceback traceback.print_exc() self.end_combat() def afk_check(self, checking_char, char_to_check): """ Prods a character to make a response. If the character is not in the afk_check list, we add them and send them a warning message, then update their combat data with the AFK timer. Subsequent checks are votes to kick the player if they have been AFK longer than a given idle timer. Any action removes them from AFK timer and resets the AFK timer in their combat data as well as removes all votes there. """ # No, they can't vote themselves AFK as a way to escape combat if checking_char == char_to_check: checking_char.msg("You cannot vote yourself AFK to leave combat.") return if self.ndb.phase == 1 and char_to_check.combat.state.ready: checking_char.msg("That character is ready to proceed " + "with combat. They are not holding up the fight.") return if self.ndb.phase == 2 and not self.ndb.active_character == char_to_check: checking_char.msg("It is not their turn to act. You may only " + "vote them AFK if they are holding up the fight.") return if char_to_check not in self.ndb.afk_check: msg = "{w%s is checking if you are AFK. Please take" % checking_char.name msg += " an action within a few minutes.{n" char_to_check.msg(msg) checking_char.msg("You have nudged %s to take an action." % char_to_check.name) self.ndb.afk_check.append(char_to_check) char_to_check.combat.state.afk_timer = time.time() # current time return # character is in the AFK list. Check if they've been gone long enough to vote against elapsed_time = time.time() - char_to_check.combat.state.afk_timer if elapsed_time < MAX_AFK: msg = "It has been %s since %s was first checked for " % (elapsed_time, char_to_check.name) msg += "AFK. They have %s seconds to respond before " % (MAX_AFK - elapsed_time) msg += "votes can be lodged against them to remove them from combat." checking_char.msg(msg) return # record votes. if we have enough votes, boot 'em. votes = char_to_check.combat.state.votes_to_kick if checking_char in votes: checking_char.msg("You have already voted for their removal. Every other player " + "except for %s must vote for their removal." % char_to_check.name) return votes.append(checking_char) if votes >= len(self.ndb.combatants) - 1: self.msg("Removing %s from combat due to inactivity." % char_to_check.name) self.move_to_observer(char_to_check) return char_to_check.msg("A vote has been lodged for your removal from combat due to inactivity.") def remove_afk(self, character): """ Removes a character from the afk_check list after taking a combat action. Resets relevant fields in combat data """ if character in self.ndb.afk_check: self.ndb.afk_check.remove(character) character.combat.state.afk_timer = None character.combat.state.votes_to_kick = [] character.msg("You are no longer being checked for AFK.") return def move_to_observer(self, character): """ If a character is marked AFK or dies, they are moved from the combatant list to the observer list. """ self.remove_combatant(character) self.add_observer(character) def remove_combatant(self, character, in_shutdown=False): """ Remove a character from combat altogether. Do a ready check if we're in phase one. """ state = character.combat.state self.clear_lists_of_character(character) if state in self.ndb.combatants: self.ndb.combatants.remove(state) if state: state.leave_combat() # if we're already shutting down, avoid redundant messages if len(self.ndb.combatants) < 2 and not in_shutdown: # We weren't shutting down and don't have enough fighters to continue. end the fight. self.end_combat() return if self.ndb.phase == 1 and not in_shutdown: self.ready_check() return if self.ndb.phase == 2 and not in_shutdown: if state in self.ndb.initiative_list: self.ndb.initiative_list.remove(state) return if self.ndb.active_character == character: self.next_character_turn() def clear_lists_of_character(self, character): """Removes a character from any of the lists they might be in""" if character in self.ndb.fleeing: self.ndb.fleeing.remove(character) if character in self.ndb.afk_check: self.ndb.afk_check.remove(character) if character in self.ndb.surrender_list: self.ndb.surrender_list.remove(character) def add_observer(self, character): """ Character becomes a non-participating observer. This is usually for GMs who are watching combat, but other players may be moved to this - dead characters are no longer combatants, nor are characters who have been marked as AFK. """ # first make sure that any other combat they're watching removes them as a spectator currently_spectating = character.combat.spectated_combat if currently_spectating and currently_spectating != self: currently_spectating.remove_observer(character) # now we start them spectating character.combat.spectated_combat = self self.send_intro_message(character, combatant=False) self.display_phase_status(character, disp_intro=False) if character not in self.ndb.observers: self.ndb.observers.append(character) return def remove_observer(self, character, quiet=True): """ Leave observer list, either due to stop observing or due to joining the fight """ character.combat.spectated_combat = None if character in self.ndb.observers: character.msg("You stop spectating the fight.") self.ndb.observers.remove(character) return if not quiet: character.msg("You were not an observer, but stop anyway.") def build_initiative_list(self): """ Rolls initiative for each combatant, resolves ties, adds them to list in order from first to last. Sets current character to first character in list. """ fighter_states = self.ndb.combatants for fighter in fighter_states: fighter.roll_initiative() self.ndb.initiative_list = sorted([data for data in fighter_states if data.can_act], key=attrgetter('initiative', 'tiebreaker'), reverse=True) def get_initiative_list(self): """Displays who the acting character is and the remaining order""" acting_char = self.ndb.active_character msg = "" if acting_char: msg += "{wIt is {c%s's {wturn.{n " % acting_char.name if self.ndb.initiative_list: msg += "{wTurn order for remaining characters:{n %s" % list_to_string(self.ndb.initiative_list) return msg def next_character_turn(self): """ It is now a character's turn in the iniative list. They will be prompted to take an action. If there is no more characters, end the turn when this is called and start over at Phase 1. """ if self.ndb.shutting_down: return if self.ndb.phase != 2: return self.ndb.initiative_list = [ob for ob in self.ndb.initiative_list if ob.can_act and ob.remaining_attacks > 0] if not self.ndb.initiative_list: self.start_phase_1() self.display_phase_status_to_all() return character_state = self.ndb.initiative_list.pop(0) acting_char = character_state.character self.ndb.active_character = acting_char # check if they went LD, teleported, or something if acting_char.location != self.ndb.combat_location: self.msg("%s is no longer here. Removing them from combat." % acting_char.name) self.remove_combatant(acting_char) return self.next_character_turn() # For when we put in subdue/hostage code elif not character_state.can_act: acting_char.msg("It would be your turn, but you cannot act. Passing your turn.") self.msg("%s cannot act." % acting_char.name, exclude=[acting_char]) return self.next_character_turn() # turns lost from botches or other effects elif character_state.lost_turn_counter > 0: character_state.remaining_attacks -= 1 character_state.lost_turn_counter -= 1 if character_state.remaining_attacks == 0: acting_char.msg("It would be your turn, but you are recovering from a botch. Passing.") self.msg("%s is recovering from a botch and loses their turn." % acting_char.name, exclude=[acting_char]) return self.next_character_turn() self.msg("{wIt is now{n {c%s's{n {wturn.{n" % acting_char.name, exclude=[acting_char]) if self.managed_mode: return self.send_managed_mode_prompt() result = character_state.do_turn_actions() if not result and self.ndb.phase == 2: mssg = dedent(""" It is now {wyour turn{n to act in combat. Please give a little time to make sure other players have finished their poses or emits before you select an action. For your character's action, you may either pass your turn with the {wpass{n command, or execute a command like {wattack{n. Once you have executed your command, control will pass to the next character, but please describe the results of your action with appropriate poses. """) acting_char.msg(mssg) def start_phase_1(self): """ Setup for phase 1, the 'setup' phase. We'll mark all current combatants as being non-ready. Characters will need to hit the 'continue' command to be marked as ready. Once all combatants have done so, we move to phase 2. Alternately, everyone can vote to end the fight, and then we're done. """ if self.ndb.shutting_down: return self.remove_surrendering_characters() self.ndb.phase = 1 self.ndb.active_character = None self.ndb.votes_to_end = [] allchars = self.ndb.combatants + self.ndb.observers if not allchars: return self.reset_combatants() self.ndb.rounds += 1 if self.ndb.rounds >= self.ndb.max_rounds: self.end_combat() self.msg("{ySetup Phase{n") def start_phase_2(self): """ Setup for phase 2, the 'resolution' phase. We build the list for initiative, which will be a list of CombatCharacterData objects from self.ndb.fighter_data.values(). Whenever it comes to a character's turn, they're popped from the front of the list, and it remains their turn until they take an action. Any action they take will call the next_character_turn() to proceed, and when there are no more characters, we go back to phase 1. """ if self.ndb.shutting_down: return self.ndb.phase = 2 # determine who can flee this turn self.ndb.flee_success = [] # if they were attempting to flee last turn, roll for them for char in self.ndb.fleeing: c_fite = char.combat if c_fite.state.roll_flee_success(): # they can now flee self.ndb.flee_success.append(char) self.remove_fled_characters() if self.ndb.shutting_down: return self.msg("{yResolution Phase{n") self.build_initiative_list() self.next_character_turn() def remove_fled_characters(self): """Checks characters who fled and removes them""" for char in self.all_combatant_characters: if char.location != self.ndb.combat_location: self.remove_combatant(char) continue def vote_to_end(self, character): """ Allows characters to vote to bring the fight to a conclusion. """ mess = "" try: self.register_vote_to_end(character) mess = "%s has voted to end the fight.\n" % character.name except combat_settings.CombatError as err: character.msg(err) if self.check_sufficient_votes_to_end(): return mess += self.vote_string if mess: self.msg(mess) def register_vote_to_end(self, character): """ If eligible to vote for an end to combat, appends our state to a tally. """ state = character.combat.state if state not in self.ndb.combatants: raise combat_settings.CombatError("Only participants in the fight may vote to end it.") elif state in self.ndb.votes_to_end: raise combat_settings.CombatError("You have already voted to end the fight.") else: self.ndb.votes_to_end.append(state) def check_sufficient_votes_to_end(self): """ Messages and ends combat if everyone has voted to do so. """ if not self.not_voted: self.msg("All participants have voted to end combat.") self.end_combat() return True @property def not_voted(self): """List of combat states who voted to end""" not_voted = [ob for ob in self.ndb.combatants if ob and ob not in self.ndb.votes_to_end] # only let conscious people vote not_voted = [ob for ob in not_voted if ob.can_fight and not ob.wants_to_end] return not_voted @property def vote_string(self): """Get string of any who have voted to end, and who still has to vote for combat to end""" mess = "" if self.ndb.votes_to_end: mess += "{wCurrently voting to end combat:{n %s\n" % list_to_string(self.ndb.votes_to_end) mess += "{wFor the fight to end, the following characters must also use +end_combat:{n " mess += "%s" % list_to_string(self.not_voted) return mess # noinspection PyBroadException def end_combat(self): """ Shut down combat. """ self.msg("Ending combat.") self.ndb.shutting_down = True for char in self.all_combatant_characters: self.remove_combatant(char, in_shutdown=True) for char in self.ndb.observers[:]: self.remove_observer(char) self.obj.ndb.combat_manager = None try: self.stop() # delete script except Exception: import traceback traceback.print_exc() @property def all_combatant_characters(self): """All characters from the states saved in combatants""" return [ob.character for ob in self.ndb.combatants] def register_surrendering_character(self, character): """ Adds a character to the surrender list. Args: character: Character who wants to surrender Returns: True if successfully added, False otherwise """ if self.check_surrender_prevent(character): return self.ndb.surrender_list.append(character) return True def check_surrender_prevent(self, character): """ Checks if character is prevented from surrendering Args: character: Character who is trying to surrender Returns: True if character is prevented, False otherwise """ for state in self.ndb.combatants: if character in state.prevent_surrender_list: return True return False def remove_surrendering_characters(self): """ Check our surrendering characters, remove them from combat if not prevented """ for character in self.ndb.surrender_list[:]: if self.check_surrender_prevent(character): self.ndb.surrender_list.remove(character) return self.remove_combatant(character) @property def special_actions(self): """GM defined actions that players can take""" return self.ndb.special_actions def add_special_action(self, name, stat="", skill="", difficulty=15): """Adds a new special action recognized by the combat that players can choose to do""" from .special_actions import ActionByGM self.special_actions.append(ActionByGM(combat=self, name=name, stat=stat, skill=skill, difficulty=difficulty)) def list_special_actions(self): """Gets string display of GM-defined special actions""" msg = "Current Actions:\n" table = PrettyTable(["#", "Name", "Stat", "Skill", "Difficulty"]) for num, action in enumerate(self.special_actions, 1): table.add_row([num, action.name, action.stat, action.skill, action.difficulty]) return msg + str(table) def list_rolls_for_special_actions(self): """Gets string display of all rolls players have made for GM-defined special actions""" actions = self.get_current_and_queued_actions() actions = [ob for ob in actions if ob.special_action in self.special_actions] table = PrettyTable(["Name", "Action", "Roll"]) for action in actions: table.add_row([str(action.character), str(action.special_action), action.display_roll()]) return str(table) def get_current_and_queued_actions(self): """Returns list of current actions for each combatant""" actions = [] for state in self.ndb.combatants: actions.extend(state.get_current_and_queued_actions()) return actions def make_all_checks_for_special_action(self, special_action): """Given a special action, make checks for all corresponding queued actions""" pc_actions = [ob for ob in self.get_current_and_queued_actions() if ob.special_action == special_action] special_action.make_checks(pc_actions) @property def managed_mode(self): """Whether or not a GM controls combat pacing""" return self.ndb.managed_mode @managed_mode.setter def managed_mode(self, value): self.ndb.managed_mode = value def send_managed_mode_prompt(self): """Notifies GMs that we're waiting on them to evaluate the character's turn.""" character = self.ndb.active_character msg = "%s's current action: %s\n" % (character, character.combat.state.get_action_description()) msg += "Use @admin_combat/roll to make a check, /execute to perform their action, and /next to mark resolved." self.msg_gms(msg) def msg_gms(self, message): """Sends a message to current GMs for this combat.""" for gm in self.gms: gm.msg(message) def add_gm(self, character): """Adds a character to our list of gms.""" if character not in self.gms: self.gms.append(character) @property def gms(self): """Characters who have admin powers for this combat.""" if self.ndb.gms is None: self.ndb.gms = [] return self.ndb.gms
[ "evennia.utils.utils.fill", "evennia.utils.utils.dedent" ]
[((9754, 9845), 'server.utils.prettytable.PrettyTable', 'PrettyTable', (["['{wCombatant{n', '{wDamage{n', '{wFatigue{n', '{wAction{n', '{wReady?{n']"], {}), "(['{wCombatant{n', '{wDamage{n', '{wFatigue{n', '{wAction{n',\n '{wReady?{n'])\n", (9765, 9845), False, 'from server.utils.prettytable import PrettyTable\n'), ((34817, 34874), 'server.utils.prettytable.PrettyTable', 'PrettyTable', (["['#', 'Name', 'Stat', 'Skill', 'Difficulty']"], {}), "(['#', 'Name', 'Stat', 'Skill', 'Difficulty'])\n", (34828, 34874), False, 'from server.utils.prettytable import PrettyTable\n'), ((35363, 35402), 'server.utils.prettytable.PrettyTable', 'PrettyTable', (["['Name', 'Action', 'Roll']"], {}), "(['Name', 'Action', 'Roll'])\n", (35374, 35402), False, 'from server.utils.prettytable import PrettyTable\n'), ((8273, 8431), 'evennia.utils.utils.fill', 'fill', (["('{mYou are now in observer mode for a fight. {n' +\n 'Most combat commands will not function. To ' +\n 'join the fight, use the {w+fight{n command.')"], {}), "('{mYou are now in observer mode for a fight. {n' +\n 'Most combat commands will not function. To ' +\n 'join the fight, use the {w+fight{n command.')\n", (8277, 8431), False, 'from evennia.utils.utils import fill, dedent\n'), ((13127, 13178), 'typeclasses.scripts.combat.state_handler.CombatantStateHandler', 'CombatantStateHandler', (['character', 'self'], {'reset': 'reset'}), '(character, self, reset=reset)\n', (13148, 13178), False, 'from typeclasses.scripts.combat.state_handler import CombatantStateHandler\n'), ((18876, 18887), 'time.time', 'time.time', ([], {}), '()\n', (18885, 18887), False, 'import time\n'), ((19041, 19052), 'time.time', 'time.time', ([], {}), '()\n', (19050, 19052), False, 'import time\n'), ((27124, 27665), 'evennia.utils.utils.dedent', 'dedent', (['"""\n It is now {wyour turn{n to act in combat. Please give a little time to make\n sure other players have finished their poses or emits before you select\n an action. For your character\'s action, you may either pass your turn\n with the {wpass{n command, or execute a command like {wattack{n. Once you\n have executed your command, control will pass to the next character, but\n please describe the results of your action with appropriate poses.\n """'], {}), '(\n """\n It is now {wyour turn{n to act in combat. Please give a little time to make\n sure other players have finished their poses or emits before you select\n an action. For your character\'s action, you may either pass your turn\n with the {wpass{n command, or execute a command like {wattack{n. Once you\n have executed your command, control will pass to the next character, but\n please describe the results of your action with appropriate poses.\n """\n )\n', (27130, 27665), False, 'from evennia.utils.utils import fill, dedent\n'), ((30774, 30860), 'typeclasses.scripts.combat.combat_settings.CombatError', 'combat_settings.CombatError', (['"""Only participants in the fight may vote to end it."""'], {}), "(\n 'Only participants in the fight may vote to end it.')\n", (30801, 30860), False, 'from typeclasses.scripts.combat import combat_settings\n'), ((8560, 8578), 'evennia.utils.utils.fill', 'fill', (['COMBAT_INTRO'], {}), '(COMBAT_INTRO)\n', (8564, 8578), False, 'from evennia.utils.utils import fill, dedent\n'), ((24344, 24382), 'operator.attrgetter', 'attrgetter', (['"""initiative"""', '"""tiebreaker"""'], {}), "('initiative', 'tiebreaker')\n", (24354, 24382), False, 'from operator import attrgetter\n'), ((24810, 24850), 'server.utils.arx_utils.list_to_string', 'list_to_string', (['self.ndb.initiative_list'], {}), '(self.ndb.initiative_list)\n', (24824, 24850), False, 'from server.utils.arx_utils import list_to_string\n'), ((30919, 30990), 'typeclasses.scripts.combat.combat_settings.CombatError', 'combat_settings.CombatError', (['"""You have already voted to end the fight."""'], {}), "('You have already voted to end the fight.')\n", (30946, 30990), False, 'from typeclasses.scripts.combat import combat_settings\n'), ((31939, 31976), 'server.utils.arx_utils.list_to_string', 'list_to_string', (['self.ndb.votes_to_end'], {}), '(self.ndb.votes_to_end)\n', (31953, 31976), False, 'from server.utils.arx_utils import list_to_string\n'), ((32105, 32135), 'server.utils.arx_utils.list_to_string', 'list_to_string', (['self.not_voted'], {}), '(self.not_voted)\n', (32119, 32135), False, 'from server.utils.arx_utils import list_to_string\n'), ((32697, 32718), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (32716, 32718), False, 'import traceback\n'), ((17154, 17175), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (17173, 17175), False, 'import traceback\n')]
""" The filehelp-system allows for defining help files outside of the game. These will be treated as non-command help entries and displayed in the same way as help entries created using the `sethelp` default command. After changing an entry on-disk you need to reload the server to have the change show in-game. An filehelp file is a regular python module with dicts representing each help entry. If a list `HELP_ENTRY_DICTS` is found in the module, this should be a list of dicts. Otherwise *all* top-level dicts in the module will be assumed to be a help-entry dict. Each help-entry dict is on the form :: {'key': <str>, 'text': <str>, 'category': <str>, # optional, otherwise settings.DEFAULT_HELP_CATEGORY 'aliases': <list>, # optional 'locks': <str>} # optional, use access-type 'view'. Default is view:all() The `text`` should be formatted on the same form as other help entry-texts and can contain ``# subtopics`` as normal. New help-entry modules are added to the system by providing the python-path to the module to `settings.FILE_HELP_ENTRY_MODULES`. Note that if same-key entries are added, entries in latter modules will override that of earlier ones. Use `settings.DEFAULT_HELP_CATEGORY`` to customize what category is used if not set explicitly. An example of the contents of a module: :: help_entry1 = { "key": "The Gods", # case-insensitive, also partial-matching ('gods') works "aliases": ['pantheon', 'religion'], "category": "Lore", "locks": "view:all()", # this is optional unless restricting access "text": ''' The gods formed the world ... # Subtopics ## Pantheon ... ### God of love ... ### God of war ... ''' } HELP_ENTRY_DICTS = [ help_entry1, ... ] ---- """ from dataclasses import dataclass from django.conf import settings from django.urls import reverse from django.utils.text import slugify from evennia.utils.utils import ( variable_from_module, make_iter, all_from_module) from evennia.utils import logger from evennia.utils.utils import lazy_property from evennia.locks.lockhandler import LockHandler _DEFAULT_HELP_CATEGORY = settings.DEFAULT_HELP_CATEGORY @dataclass class FileHelpEntry: """ Represents a help entry read from file. This mimics the api of the database-bound HelpEntry so that they can be used interchangeably in the help command. """ key: str aliases: list help_category: str entrytext: str lock_storage: str @property def search_index_entry(self): """ Property for easily retaining a search index entry for this object. """ return { "key": self.key, "aliases": " ".join(self.aliases), "category": self.help_category, "tags": "", "locks": "", "text": self.entrytext, } def __str__(self): return self.key def __repr__(self): return f"<FileHelpEntry {self.key}>" @lazy_property def locks(self): return LockHandler(self) def web_get_detail_url(self): """ Returns the URI path for a View that allows users to view details for this object. ex. Oscar (Character) = '/characters/oscar/1/' For this to work, the developer must have defined a named view somewhere in urls.py that follows the format 'modelname-action', so in this case a named view of 'character-detail' would be referenced by this method. ex. :: url(r'characters/(?P<slug>[\w\d\-]+)/(?P<pk>[0-9]+)/$', CharDetailView.as_view(), name='character-detail') If no View has been created and defined in urls.py, returns an HTML anchor. This method is naive and simply returns a path. Securing access to the actual view and limiting who can view this object is the developer's responsibility. Returns: path (str): URI path to object detail page, if defined. """ try: return reverse( 'help-entry-detail', kwargs={"category": slugify(self.help_category), "topic": slugify(self.key)}, ) except Exception: return "#" def web_get_admin_url(self): """ Returns the URI path for the Django Admin page for this object. ex. Account#1 = '/admin/accounts/accountdb/1/change/' Returns: path (str): URI path to Django Admin page for object. """ return False def access(self, accessing_obj, access_type="view", default=True): """ Determines if another object has permission to access this help entry. Args: accessing_obj (Object or Account): Entity trying to access this one. access_type (str): type of access sought. default (bool): What to return if no lock of `access_type` was found. """ return self.locks.check(accessing_obj, access_type=access_type, default=default) class FileHelpStorageHandler: """ This reads and stores help entries for quick access. By default it reads modules from `settings.FILE_HELP_ENTRY_MODULES`. Note that this is not meant to any searching/lookup - that is all handled by the help command. """ def __init__(self, help_file_modules=settings.FILE_HELP_ENTRY_MODULES): """ Initialize the storage. """ self.help_file_modules = [str(part).strip() for part in make_iter(help_file_modules)] self.help_entries = [] self.help_entries_dict = {} self.load() def load(self): """ Load/reload file-based help-entries from file. """ loaded_help_dicts = [] for module_or_path in self.help_file_modules: help_dict_list = variable_from_module( module_or_path, variable="HELP_ENTRY_DICTS" ) if not help_dict_list: help_dict_list = [ dct for dct in all_from_module(module_or_path).values() if isinstance(dct, dict)] if help_dict_list: loaded_help_dicts.extend(help_dict_list) else: logger.log_err(f"Could not find file-help module {module_or_path} (skipping).") # validate and parse dicts into FileEntryHelp objects and make sure they are unique-by-key # by letting latter added ones override earlier ones. unique_help_entries = {} for dct in loaded_help_dicts: key = dct.get('key').lower().strip() category = dct.get('category', _DEFAULT_HELP_CATEGORY).strip() aliases = list(dct.get('aliases', [])) entrytext = dct.get('text', '') locks = dct.get('locks', '') if not key and entrytext: logger.error(f"Cannot load file-help-entry (missing key or text): {dct}") continue unique_help_entries[key] = FileHelpEntry( key=key, help_category=category, aliases=aliases, lock_storage=locks, entrytext=entrytext) self.help_entries_dict = unique_help_entries self.help_entries = list(unique_help_entries.values()) def all(self, return_dict=False): """ Get all help entries. Args: return_dict (bool): Return a dict ``{key: FileHelpEntry,...}``. Otherwise, return a list of ``FileHelpEntry`. Returns: dict or list: Depending on the setting of ``return_dict``. """ return self.help_entries_dict if return_dict else self.help_entries # singleton to hold the loaded help entries FILE_HELP_ENTRIES = FileHelpStorageHandler()
[ "evennia.locks.lockhandler.LockHandler", "evennia.utils.logger.error", "evennia.utils.logger.log_err", "evennia.utils.utils.all_from_module", "evennia.utils.utils.make_iter", "evennia.utils.utils.variable_from_module" ]
[((3197, 3214), 'evennia.locks.lockhandler.LockHandler', 'LockHandler', (['self'], {}), '(self)\n', (3208, 3214), False, 'from evennia.locks.lockhandler import LockHandler\n'), ((6067, 6132), 'evennia.utils.utils.variable_from_module', 'variable_from_module', (['module_or_path'], {'variable': '"""HELP_ENTRY_DICTS"""'}), "(module_or_path, variable='HELP_ENTRY_DICTS')\n", (6087, 6132), False, 'from evennia.utils.utils import variable_from_module, make_iter, all_from_module\n'), ((5734, 5762), 'evennia.utils.utils.make_iter', 'make_iter', (['help_file_modules'], {}), '(help_file_modules)\n', (5743, 5762), False, 'from evennia.utils.utils import variable_from_module, make_iter, all_from_module\n'), ((6477, 6556), 'evennia.utils.logger.log_err', 'logger.log_err', (['f"""Could not find file-help module {module_or_path} (skipping)."""'], {}), "(f'Could not find file-help module {module_or_path} (skipping).')\n", (6491, 6556), False, 'from evennia.utils import logger\n'), ((7106, 7179), 'evennia.utils.logger.error', 'logger.error', (['f"""Cannot load file-help-entry (missing key or text): {dct}"""'], {}), "(f'Cannot load file-help-entry (missing key or text): {dct}')\n", (7118, 7179), False, 'from evennia.utils import logger\n'), ((4303, 4330), 'django.utils.text.slugify', 'slugify', (['self.help_category'], {}), '(self.help_category)\n', (4310, 4330), False, 'from django.utils.text import slugify\n'), ((4341, 4358), 'django.utils.text.slugify', 'slugify', (['self.key'], {}), '(self.key)\n', (4348, 4358), False, 'from django.utils.text import slugify\n'), ((6268, 6299), 'evennia.utils.utils.all_from_module', 'all_from_module', (['module_or_path'], {}), '(module_or_path)\n', (6283, 6299), False, 'from evennia.utils.utils import variable_from_module, make_iter, all_from_module\n')]
""" MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import random import evennia from evennia.utils import create from evennia.contrib import gendersub from world.definitions.language import Language from world.definitions.chardefs import OccupationTable from world.definitions.chardefs import get_random_occupation from world.definitions.chardefs import BirthAugur from world.definitions.chardefs import BirthAugurAuraTable from world.definitions.chardefs import Race from world.definitions.chardefs import Alignment from world.definitions.bodytype import BodyType import typeclasses.auras as auras from world.definitions.auradefs import AuraEffectType # PLACED IN THIS FILE UNTIL A BETTER SPOT FOUND def roll_dice(num_dice, die_type): """ 3d6, for example, would be num_dice = 3, die_type = 6 """ result = 0 for i in range(num_dice): result += random.randint(1, die_type) return result def calculate_ability_modifier(ability_score): modifier = 0 if ability_score <= 3: modifier = -3 elif ability_score <= 5: modifier = -2 elif ability_score <= 8: modifier = -1 elif ability_score <= 12: modifier = 0 elif ability_score <= 15: modifier = 1 elif ability_score <= 17: modifier = 2 elif ability_score > 17: modifier = 3 return modifier # PLACED IN THIS FILE UNTIL A BETTER SPOT FOUND class Character(gendersub.GenderCharacter): """ The Character defaults to reimplementing some of base Object's hook methods with the following functionality: at_basetype_setup - always assigns the DefaultCmdSet to this object type (important!)sets locks so character cannot be picked up and its commands only be called by itself, not anyone else. (to change things, use at_object_creation() instead). at_after_move(source_location) - Launches the "look" command after every move. at_post_unpuppet(account) - when Account disconnects from the Character, we store the current location in the pre_logout_location Attribute and move it to a None-location so the "unpuppeted" character object does not need to stay on grid. Echoes "Account has disconnected" to the room. at_pre_puppet - Just before Account re-connects, retrieves the character's pre_logout_location Attribute and move it back on the grid. at_post_puppet - Echoes "AccountName has entered the game" to the room. """ def at_object_creation(self): super().at_object_creation() self.db.level = 0 self.db.xp = 0 self.db.ac = 10 self.db.alignment = Alignment.Neutral self.db.strength = 7 self.db.agility = 7 self.db.stamina = 7 self.db.personality = 7 self.db.intelligence = 7 self.db.luck = 7 self.db.hp = 1 self.db.speed = 30 self.db.auras = [] self.db.known_languages = [] self.db.known_languages.append(Language.Common) self.db.weapon_proficiencies = [] self.db.gold = 0 self.db.silver = 0 self.db.copper = 0 self.db.occupation = get_random_occupation() self.db.race = Race.Human self.db.age = 0 self.db.current_hp = self.get_modified_hp() def get_modified_hp(self): stam = self.get_modified_stamina() modifier = calculate_ability_modifier(stam) for aura in self.db.auras: if AuraEffectType.HP in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.HP] return (self.db.hp + modifier) def get_modified_strength(self): modifier = 0 for aura in self.db.auras: if AuraEffectType.Strength in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.Strength] return (self.db.strength + modifier) def get_modified_agility(self): modifier = 0 for aura in self.db.auras: if AuraEffectType.Agility in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.Agility] return (self.db.agility + modifier) def get_modified_stamina(self): modifier = 0 for aura in self.db.auras: if AuraEffectType.Stamina in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.Stamina] return (self.db.stamina + modifier) def get_modified_personality(self): modifier = 0 for a in self.db.auras: if AuraEffectType.Personality in a.db.effect_modifiers.keys(): modifier += a.db.effect_modifiers[AuraEffectType.Personality] return (self.db.personality + modifier) def get_modified_intelligence(self): modifier = 0 for a in self.db.auras: if AuraEffectType.Intelligence in a.db.effect_modifiers.keys(): modifier += \ a.db.effect_modifiers[AuraEffectType.Intelligence] return (self.db.intelligence + modifier) def get_modified_luck(self): modifier = 0 for aura in self.db.auras: if AuraEffectType.Luck in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.Luck] return (self.db.luck + modifier) def get_modified_speed(self): modifier = 0 for aura in self.db.auras: if AuraEffectType.Speed in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.Speed] return (self.db.speed + modifier) def get_modified_ac(self): agi = self.get_modified_agility() modifier = calculate_ability_modifier(agi) for aura in self.db.auras: if AuraEffectType.AC in aura.db.effect_modifiers.keys(): modifier += aura.db.effect_modifiers[AuraEffectType.AC] return (self.db.ac + modifier) def set_birth_augur_effect(self): if self.db.birth_augur not in BirthAugurAuraTable: return luck_modifier = calculate_ability_modifier(self.db.luck) augur_data = BirthAugurAuraTable[self.db.birth_augur] if "effects" in augur_data and luck_modifier != 0: aura_effects = {} for m in augur_data["effects"]: if "modifier_multiplier" in augur_data: aura_effects[m] = \ luck_modifier * augur_data["modifier_multiplier"] else: aura_effects[m] = luck_modifier aura = create.create_object( auras.PersistentEffectAura, key=self.db.birth_augur.display_name[0], location=self, attributes=[ ("desc", self.db.birth_augur.display_name[1]), ("effect_modifiers", aura_effects) ] ) aura.build_modifier_description() self.db.auras.append(aura) class RandomlyGeneratedCharacter(Character): """ A character randomly generated follows most of the guidelines from the rulebook. Some initial values set can be modified later. """ def at_object_creation(self): super().at_object_creation() self.db.strength = roll_dice(3, 6) self.db.agility = roll_dice(3, 6) self.db.stamina = roll_dice(3, 6) self.db.personality = roll_dice(3, 6) self.db.intelligence = roll_dice(3, 6) self.db.luck = roll_dice(3, 6) self.db.hp = roll_dice(1, 4) self.db.speed = 30 self.db.birth_augur = random.choice(list(BirthAugur)) self.set_birth_augur_effect() self.db.gold = 0 self.db.silver = 0 self.db.copper = roll_dice(5, 12) self.db.occupation = get_random_occupation() occupation = self.db.occupation if "weapon_proficiencies" in OccupationTable[occupation]: self.db.weapon_proficiencies.append( OccupationTable[occupation]["weapon_proficiencies"] ) for item in OccupationTable[occupation]["items"]: item_clone = dict(item) item_clone["location"] = self evennia.prototypes.spawner.spawn(item_clone) if "race" in OccupationTable[occupation]: self.db.race = OccupationTable[occupation]["race"] else: self.db.race = Race.Human if self.db.race == Race.Dwarf or self.db.race == Race.Halfling: self.db.speed = 20 if self.db.race == Race.Human: self.db.body_type = BodyType.Normal self.db.age = random.randint(18, 45) elif self.db.race == Race.Dwarf: self.db.body_type = BodyType.Short self.db.age = random.randint(37, 75) elif self.db.race == Race.Elf: self.db.age = random.randint(35, 100) self.db.body_type = BodyType.Tall elif self.db.race == Race.Halfling: self.db.body_type = BodyType.Short self.db.age = random.randint(20, 55) items = self.contents if items: for item in items: if item.attributes.has("possible_wear_locations"): item.db.target_body_type = self.db.body_type if "money" in OccupationTable[occupation]: money_data = OccupationTable[occupation]["money"] if "gold" in money_data: self.db.gold += money_data["gold"] if "silver" in money_data: self.db.silver += money_data["silver"] if "copper" in money_data: self.db.copper += money_data["copper"] if self.db.intelligence >= 8: if self.db.race == Race.Dwarf: self.db.known_languages.append(Language.Dwarf) elif self.db.race == Race.Elf: self.db.known_languages.append(Language.Elf) elif self.db.race == Race.Halfling: self.db.known_languages.append(Language.Halfling) self.db.current_hp = self.get_modified_hp()
[ "evennia.utils.create.create_object", "evennia.prototypes.spawner.spawn" ]
[((1899, 1926), 'random.randint', 'random.randint', (['(1)', 'die_type'], {}), '(1, die_type)\n', (1913, 1926), False, 'import random\n'), ((4326, 4349), 'world.definitions.chardefs.get_random_occupation', 'get_random_occupation', ([], {}), '()\n', (4347, 4349), False, 'from world.definitions.chardefs import get_random_occupation\n'), ((9085, 9108), 'world.definitions.chardefs.get_random_occupation', 'get_random_occupation', ([], {}), '()\n', (9106, 9108), False, 'from world.definitions.chardefs import get_random_occupation\n'), ((7842, 8052), 'evennia.utils.create.create_object', 'create.create_object', (['auras.PersistentEffectAura'], {'key': 'self.db.birth_augur.display_name[0]', 'location': 'self', 'attributes': "[('desc', self.db.birth_augur.display_name[1]), ('effect_modifiers',\n aura_effects)]"}), "(auras.PersistentEffectAura, key=self.db.birth_augur.\n display_name[0], location=self, attributes=[('desc', self.db.\n birth_augur.display_name[1]), ('effect_modifiers', aura_effects)])\n", (7862, 8052), False, 'from evennia.utils import create\n'), ((9495, 9539), 'evennia.prototypes.spawner.spawn', 'evennia.prototypes.spawner.spawn', (['item_clone'], {}), '(item_clone)\n', (9527, 9539), False, 'import evennia\n'), ((9924, 9946), 'random.randint', 'random.randint', (['(18)', '(45)'], {}), '(18, 45)\n', (9938, 9946), False, 'import random\n'), ((10061, 10083), 'random.randint', 'random.randint', (['(37)', '(75)'], {}), '(37, 75)\n', (10075, 10083), False, 'import random\n'), ((10149, 10172), 'random.randint', 'random.randint', (['(35)', '(100)'], {}), '(35, 100)\n', (10163, 10172), False, 'import random\n'), ((10336, 10358), 'random.randint', 'random.randint', (['(20)', '(55)'], {}), '(20, 55)\n', (10350, 10358), False, 'import random\n')]
""" Functions for processing input commands. All global functions in this module whose name does not start with "_" is considered an inputfunc. Each function must have the following callsign (where inputfunc name is always lower-case, no matter what the OOB input name looked like): inputfunc(session, *args, **kwargs) Where "options" is always one of the kwargs, containing eventual protocol-options. There is one special function, the "default" function, which is called on a no-match. It has this callsign: default(session, cmdname, *args, **kwargs) Evennia knows which modules to use for inputfuncs by settings.INPUT_FUNC_MODULES. """ import importlib from codecs import lookup as codecs_lookup from django.conf import settings from evennia.commands.cmdhandler import cmdhandler from evennia.accounts.models import AccountDB from evennia.utils.logger import log_err from evennia.utils.utils import to_str BrowserSessionStore = importlib.import_module(settings.SESSION_ENGINE).SessionStore # always let "idle" work since we use this in the webclient _IDLE_COMMAND = settings.IDLE_COMMAND _IDLE_COMMAND = (_IDLE_COMMAND,) if _IDLE_COMMAND == "idle" else (_IDLE_COMMAND, "idle") _GA = object.__getattribute__ _SA = object.__setattr__ def _NA(o): return "N/A" _ERROR_INPUT = "Inputfunc {name}({session}): Wrong/unrecognized input: {inp}" # All global functions are inputfuncs available to process inputs def text(session, *args, **kwargs): """ Main text input from the client. This will execute a command string on the server. Args: session (Session): The active Session to receive the input. text (str): First arg is used as text-command input. Other arguments are ignored. """ # from evennia.server.profiling.timetrace import timetrace # text = timetrace(text, "ServerSession.data_in") txt = args[0] if args else None # explicitly check for None since text can be an empty string, which is # also valid if txt is None: return # this is treated as a command input # handle the 'idle' command if txt.strip() in _IDLE_COMMAND: session.update_session_counters(idle=True) return """ if session.account: # nick replacement puppet = session.puppet if puppet: txt = puppet.nicks.nickreplace( txt, categories=("inputline", "channel"), include_account=True ) else: txt = session.account.nicks.nickreplace( txt, categories=("inputline", "channel"), include_account=False ) """ kwargs.pop("options", None) cmdhandler(session, txt, callertype="session", session=session, **kwargs) session.update_session_counters() def bot_data_in(session, *args, **kwargs): """ Text input from the IRC and RSS bots. This will trigger the execute_cmd method on the bots in-game counterpart. Args: session (Session): The active Session to receive the input. text (str): First arg is text input. Other arguments are ignored. """ txt = args[0] if args else None # Explicitly check for None since text can be an empty string, which is # also valid if txt is None: return # this is treated as a command input # handle the 'idle' command if txt.strip() in _IDLE_COMMAND: session.update_session_counters(idle=True) return kwargs.pop("options", None) # Trigger the execute_cmd method of the corresponding bot. session.account.execute_cmd(session=session, txt=txt, **kwargs) session.update_session_counters() def echo(session, *args, **kwargs): """ Echo test function """ session.data_out(text="Echo returns: %s" % args) def default(session, cmdname, *args, **kwargs): """ Default catch-function. This is like all other input functions except it will get `cmdname` as the first argument. """ err = ( "Session {sessid}: Input command not recognized:\n" " name: '{cmdname}'\n" " args, kwargs: {args}, {kwargs}".format( sessid=session.sessid, cmdname=cmdname, args=args, kwargs=kwargs ) ) if session.protocol_flags.get("INPUTDEBUG", False): session.msg(err) log_err(err) _CLIENT_OPTIONS = ( "ANSI", "XTERM256", "MXP", "UTF-8", "SCREENREADER", "ENCODING", "MCCP", "SCREENHEIGHT", "SCREENWIDTH", "INPUTDEBUG", "RAW", "NOCOLOR", "NOGOAHEAD", ) def client_options(session, *args, **kwargs): """ This allows the client an OOB way to inform us about its name and capabilities. This will be integrated into the session settings Kwargs: get (bool): If this is true, return the settings as a dict (ignore all other kwargs). client (str): A client identifier, like "mushclient". version (str): A client version ansi (bool): Supports ansi colors xterm256 (bool): Supports xterm256 colors or not mxp (bool): Supports MXP or not utf-8 (bool): Supports UTF-8 or not screenreader (bool): Screen-reader mode on/off mccp (bool): MCCP compression on/off screenheight (int): Screen height in lines screenwidth (int): Screen width in characters inputdebug (bool): Debug input functions nocolor (bool): Strip color raw (bool): Turn off parsing """ old_flags = session.protocol_flags if not kwargs or kwargs.get("get", False): # return current settings options = dict((key, old_flags[key]) for key in old_flags if key.upper() in _CLIENT_OPTIONS) session.msg(client_options=options) return def validate_encoding(val): # helper: change encoding try: codecs_lookup(val) except LookupError: raise RuntimeError("The encoding '|w%s|n' is invalid. " % val) return val def validate_size(val): return {0: int(val)} def validate_bool(val): if isinstance(val, str): return True if val.lower() in ("true", "on", "1") else False return bool(val) flags = {} for key, value in kwargs.items(): key = key.lower() if key == "client": flags["CLIENTNAME"] = to_str(value) elif key == "version": if "CLIENTNAME" in flags: flags["CLIENTNAME"] = "%s %s" % (flags["CLIENTNAME"], to_str(value)) elif key == "ENCODING": flags["ENCODING"] = validate_encoding(value) elif key == "ansi": flags["ANSI"] = validate_bool(value) elif key == "xterm256": flags["XTERM256"] = validate_bool(value) elif key == "mxp": flags["MXP"] = validate_bool(value) elif key == "utf-8": flags["UTF-8"] = validate_bool(value) elif key == "screenreader": flags["SCREENREADER"] = validate_bool(value) elif key == "mccp": flags["MCCP"] = validate_bool(value) elif key == "screenheight": flags["SCREENHEIGHT"] = validate_size(value) elif key == "screenwidth": flags["SCREENWIDTH"] = validate_size(value) elif key == "inputdebug": flags["INPUTDEBUG"] = validate_bool(value) elif key == "nocolor": flags["NOCOLOR"] = validate_bool(value) elif key == "raw": flags["RAW"] = validate_bool(value) elif key == "nogoahead": flags["NOGOAHEAD"] = validate_bool(value) elif key in ( "Char 1", "Char.Skills 1", "Char.Items 1", "Room 1", "IRE.Rift 1", "IRE.Composer 1", ): # ignore mudlet's default send (aimed at IRE games) pass elif key not in ("options", "cmdid"): err = _ERROR_INPUT.format(name="client_settings", session=session, inp=key) session.msg(text=err) session.protocol_flags.update(flags) # we must update the protocol flags on the portal session copy as well session.sessionhandler.session_portal_partial_sync({session.sessid: {"protocol_flags": flags}}) def get_client_options(session, *args, **kwargs): """ Alias wrapper for getting options. """ client_options(session, get=True) def get_inputfuncs(session, *args, **kwargs): """ Get the keys of all available inputfuncs. Note that we don't get it from this module alone since multiple modules could be added. So we get it from the sessionhandler. """ inputfuncsdict = dict( (key, func.__doc__) for key, func in session.sessionhandler.get_inputfuncs().items() ) session.msg(get_inputfuncs=inputfuncsdict) def login(session, *args, **kwargs): """ Peform a login. This only works if session is currently not logged in. This will also automatically throttle too quick attempts. Kwargs: name (str): Account name password (<PASSWORD>): <PASSWORD> """ if not session.logged_in and "name" in kwargs and "password" in kwargs: from evennia.commands.default.unloggedin import create_normal_account account = create_normal_account(session, kwargs["name"], kwargs["password"]) if account: session.sessionhandler.login(session, account) _gettable = { "name": lambda obj: obj.key, "key": lambda obj: obj.key, "location": lambda obj: obj.location.key if obj.location else "None", "servername": lambda obj: settings.SERVERNAME, } def get_value(session, *args, **kwargs): """ Return the value of a given attribute or db_property on the session's current account or character. Kwargs: name (str): Name of info value to return. Only names in the _gettable dictionary earlier in this module are accepted. """ name = kwargs.get("name", "") obj = session.puppet or session.account if name in _gettable: session.msg(get_value={"name": name, "value": _gettable[name](obj)}) def _testrepeat(**kwargs): """ This is a test function for using with the repeat inputfunc. Kwargs: session (Session): Session to return to. """ import time kwargs["session"].msg(repeat="Repeat called: %s" % time.time()) _repeatable = {"test1": _testrepeat, "test2": _testrepeat} # example only # " def repeat(session, *args, **kwargs): """ Call a named function repeatedly. Note that this is meant as an example of limiting the number of possible call functions. Kwargs: callback (str): The function to call. Only functions from the _repeatable dictionary earlier in this module are available. interval (int): How often to call function (s). Defaults to once every 60 seconds with a minimum of 5 seconds. stop (bool): Stop a previously assigned ticker with the above settings. """ from evennia.scripts.tickerhandler import TICKER_HANDLER name = kwargs.get("callback", "") interval = max(5, int(kwargs.get("interval", 60))) if name in _repeatable: if kwargs.get("stop", False): TICKER_HANDLER.remove( interval, _repeatable[name], idstring=session.sessid, persistent=False ) else: TICKER_HANDLER.add( interval, _repeatable[name], idstring=session.sessid, persistent=False, session=session, ) else: session.msg("Allowed repeating functions are: %s" % (", ".join(_repeatable))) def unrepeat(session, *args, **kwargs): "Wrapper for OOB use" kwargs["stop"] = True repeat(session, *args, **kwargs) _monitorable = {"name": "db_key", "location": "db_location", "desc": "desc"} def _on_monitor_change(**kwargs): fieldname = kwargs["fieldname"] obj = kwargs["obj"] name = kwargs["name"] session = kwargs["session"] outputfunc_name = kwargs["outputfunc_name"] # the session may be None if the char quits and someone # else then edits the object if session: callsign = {outputfunc_name: {"name": name, "value": _GA(obj, fieldname)}} session.msg(**callsign) def monitor(session, *args, **kwargs): """ Adds monitoring to a given property or Attribute. Kwargs: name (str): The name of the property or Attribute to report. No db_* prefix is needed. Only names in the _monitorable dict earlier in this module are accepted. stop (bool): Stop monitoring the above name. outputfunc_name (str, optional): Change the name of the outputfunc name. This is used e.g. by MSDP which has its own specific output format. """ from evennia.scripts.monitorhandler import MONITOR_HANDLER name = kwargs.get("name", None) outputfunc_name = kwargs("outputfunc_name", "monitor") if name and name in _monitorable and session.puppet: field_name = _monitorable[name] obj = session.puppet if kwargs.get("stop", False): MONITOR_HANDLER.remove(obj, field_name, idstring=session.sessid) else: # the handler will add fieldname and obj to the kwargs automatically MONITOR_HANDLER.add( obj, field_name, _on_monitor_change, idstring=session.sessid, persistent=False, name=name, session=session, outputfunc_name=outputfunc_name, ) def unmonitor(session, *args, **kwargs): """ Wrapper for turning off monitoring """ kwargs["stop"] = True monitor(session, *args, **kwargs) def monitored(session, *args, **kwargs): """ Report on what is being monitored """ from evennia.scripts.monitorhandler import MONITOR_HANDLER obj = session.puppet monitors = MONITOR_HANDLER.all(obj=obj) session.msg(monitored=(monitors, {})) def _on_webclient_options_change(**kwargs): """ Called when the webclient options stored on the account changes. Inform the interested clients of this change. """ session = kwargs["session"] obj = kwargs["obj"] fieldname = kwargs["fieldname"] clientoptions = _GA(obj, fieldname) # the session may be None if the char quits and someone # else then edits the object if session: session.msg(webclient_options=clientoptions) def webclient_options(session, *args, **kwargs): """ Handles retrieving and changing of options related to the webclient. If kwargs is empty (or contains just a "cmdid"), the saved options will be sent back to the session. A monitor handler will be created to inform the client of any future options that changes. If kwargs is not empty, the key/values stored in there will be persisted to the account object. Kwargs: <option name>: an option to save """ account = session.account clientoptions = account.db._saved_webclient_options if not clientoptions: # No saved options for this account, copy and save the default. account.db._saved_webclient_options = settings.WEBCLIENT_OPTIONS.copy() # Get the _SaverDict created by the database. clientoptions = account.db._saved_webclient_options # The webclient adds a cmdid to every kwargs, but we don't need it. try: del kwargs["cmdid"] except KeyError: pass if not kwargs: # No kwargs: we are getting the stored options # Convert clientoptions to regular dict for sending. session.msg(webclient_options=dict(clientoptions)) # Create a monitor. If a monitor already exists then it will replace # the previous one since it would use the same idstring from evennia.scripts.monitorhandler import MONITOR_HANDLER MONITOR_HANDLER.add( account, "_saved_webclient_options", _on_webclient_options_change, idstring=session.sessid, persistent=False, session=session, ) else: # kwargs provided: persist them to the account object for key, value in kwargs.items(): clientoptions[key] = value # OOB protocol-specific aliases and wrappers # GMCP aliases hello = client_options supports_set = client_options # MSDP aliases (some of the the generic MSDP commands defined in the MSDP spec are prefixed # by msdp_ at the protocol level) # See https://tintin.sourceforge.io/protocols/msdp/ def msdp_list(session, *args, **kwargs): """ MSDP LIST command """ from evennia.scripts.monitorhandler import MONITOR_HANDLER args_lower = [arg.lower() for arg in args] if "commands" in args_lower: inputfuncs = [ key[5:] if key.startswith("msdp_") else key for key in session.sessionhandler.get_inputfuncs().keys() ] session.msg(commands=(inputfuncs, {})) if "lists" in args_lower: session.msg( lists=( [ "commands", "lists", "configurable_variables", "reportable_variables", "reported_variables", "sendable_variables", ], {}, ) ) if "configurable_variables" in args_lower: session.msg(configurable_variables=(_CLIENT_OPTIONS, {})) if "reportable_variables" in args_lower: session.msg(reportable_variables=(_monitorable, {})) if "reported_variables" in args_lower: obj = session.puppet monitor_infos = MONITOR_HANDLER.all(obj=obj) fieldnames = [tup[1] for tup in monitor_infos] session.msg(reported_variables=(fieldnames, {})) if "sendable_variables" in args_lower: session.msg(sendable_variables=(_monitorable, {})) def msdp_report(session, *args, **kwargs): """ MSDP REPORT command """ kwargs["outputfunc_name":"report"] monitor(session, *args, **kwargs) def msdp_unreport(session, *args, **kwargs): """ MSDP UNREPORT command """ unmonitor(session, *args, **kwargs) def msdp_send(session, *args, **kwargs): """ MSDP SEND command """ out = {} for varname in args: if varname.lower() in _monitorable: out[varname] = _monitorable[varname.lower()] session.msg(send=((), out)) # client specific def external_discord_hello(session, *args, **kwargs): """ Sent by Mudlet as a greeting; added here to avoid logging a missing inputfunc for it. """ pass
[ "evennia.scripts.monitorhandler.MONITOR_HANDLER.add", "evennia.scripts.monitorhandler.MONITOR_HANDLER.remove", "evennia.utils.logger.log_err", "evennia.utils.utils.to_str", "evennia.scripts.tickerhandler.TICKER_HANDLER.remove", "evennia.scripts.tickerhandler.TICKER_HANDLER.add", "evennia.scripts.monitor...
[((947, 995), 'importlib.import_module', 'importlib.import_module', (['settings.SESSION_ENGINE'], {}), '(settings.SESSION_ENGINE)\n', (970, 995), False, 'import importlib\n'), ((2671, 2744), 'evennia.commands.cmdhandler.cmdhandler', 'cmdhandler', (['session', 'txt'], {'callertype': '"""session"""', 'session': 'session'}), "(session, txt, callertype='session', session=session, **kwargs)\n", (2681, 2744), False, 'from evennia.commands.cmdhandler import cmdhandler\n'), ((4312, 4324), 'evennia.utils.logger.log_err', 'log_err', (['err'], {}), '(err)\n', (4319, 4324), False, 'from evennia.utils.logger import log_err\n'), ((14112, 14140), 'evennia.scripts.monitorhandler.MONITOR_HANDLER.all', 'MONITOR_HANDLER.all', ([], {'obj': 'obj'}), '(obj=obj)\n', (14131, 14140), False, 'from evennia.scripts.monitorhandler import MONITOR_HANDLER\n'), ((9289, 9355), 'evennia.commands.default.unloggedin.create_normal_account', 'create_normal_account', (['session', "kwargs['name']", "kwargs['password']"], {}), "(session, kwargs['name'], kwargs['password'])\n", (9310, 9355), False, 'from evennia.commands.default.unloggedin import create_normal_account\n'), ((15398, 15431), 'django.conf.settings.WEBCLIENT_OPTIONS.copy', 'settings.WEBCLIENT_OPTIONS.copy', ([], {}), '()\n', (15429, 15431), False, 'from django.conf import settings\n'), ((16103, 16257), 'evennia.scripts.monitorhandler.MONITOR_HANDLER.add', 'MONITOR_HANDLER.add', (['account', '"""_saved_webclient_options"""', '_on_webclient_options_change'], {'idstring': 'session.sessid', 'persistent': '(False)', 'session': 'session'}), "(account, '_saved_webclient_options',\n _on_webclient_options_change, idstring=session.sessid, persistent=False,\n session=session)\n", (16122, 16257), False, 'from evennia.scripts.monitorhandler import MONITOR_HANDLER\n'), ((17916, 17944), 'evennia.scripts.monitorhandler.MONITOR_HANDLER.all', 'MONITOR_HANDLER.all', ([], {'obj': 'obj'}), '(obj=obj)\n', (17935, 17944), False, 'from evennia.scripts.monitorhandler import MONITOR_HANDLER\n'), ((5855, 5873), 'codecs.lookup', 'codecs_lookup', (['val'], {}), '(val)\n', (5868, 5873), True, 'from codecs import lookup as codecs_lookup\n'), ((6356, 6369), 'evennia.utils.utils.to_str', 'to_str', (['value'], {}), '(value)\n', (6362, 6369), False, 'from evennia.utils.utils import to_str\n'), ((11321, 11418), 'evennia.scripts.tickerhandler.TICKER_HANDLER.remove', 'TICKER_HANDLER.remove', (['interval', '_repeatable[name]'], {'idstring': 'session.sessid', 'persistent': '(False)'}), '(interval, _repeatable[name], idstring=session.sessid,\n persistent=False)\n', (11342, 11418), False, 'from evennia.scripts.tickerhandler import TICKER_HANDLER\n'), ((11471, 11582), 'evennia.scripts.tickerhandler.TICKER_HANDLER.add', 'TICKER_HANDLER.add', (['interval', '_repeatable[name]'], {'idstring': 'session.sessid', 'persistent': '(False)', 'session': 'session'}), '(interval, _repeatable[name], idstring=session.sessid,\n persistent=False, session=session)\n', (11489, 11582), False, 'from evennia.scripts.tickerhandler import TICKER_HANDLER\n'), ((13272, 13336), 'evennia.scripts.monitorhandler.MONITOR_HANDLER.remove', 'MONITOR_HANDLER.remove', (['obj', 'field_name'], {'idstring': 'session.sessid'}), '(obj, field_name, idstring=session.sessid)\n', (13294, 13336), False, 'from evennia.scripts.monitorhandler import MONITOR_HANDLER\n'), ((13444, 13614), 'evennia.scripts.monitorhandler.MONITOR_HANDLER.add', 'MONITOR_HANDLER.add', (['obj', 'field_name', '_on_monitor_change'], {'idstring': 'session.sessid', 'persistent': '(False)', 'name': 'name', 'session': 'session', 'outputfunc_name': 'outputfunc_name'}), '(obj, field_name, _on_monitor_change, idstring=session.\n sessid, persistent=False, name=name, session=session, outputfunc_name=\n outputfunc_name)\n', (13463, 13614), False, 'from evennia.scripts.monitorhandler import MONITOR_HANDLER\n'), ((10393, 10404), 'time.time', 'time.time', ([], {}), '()\n', (10402, 10404), False, 'import time\n'), ((6509, 6522), 'evennia.utils.utils.to_str', 'to_str', (['value'], {}), '(value)\n', (6515, 6522), False, 'from evennia.utils.utils import to_str\n')]
""" Commands Commands describe the input the account can do to the game. """ from evennia.commands.command import Command as BaseCommand from evennia.utils import ansi # from evennia import default_cmds class Command(BaseCommand): """ Inherit from this if you want to create your own command styles from scratch. Note that Evennia's default commands inherits from MuxCommand instead. Note that the class's `__doc__` string (this text) is used by Evennia to create the automatic help entry for the command, so make sure to document consistently here. Each Command implements the following methods, called in this order (only func() is actually required): - at_pre_cmd(): If this returns anything truthy, execution is aborted. - parse(): Should perform any extra parsing needed on self.args and store the result on self. - func(): Performs the actual work. - at_post_cmd(): Extra actions, often things done after every command, like prompts. """ pass # ------------------------------------------------------------- # # The default commands inherit from # # evennia.commands.default.muxcommand.MuxCommand. # # If you want to make sweeping changes to default commands you can # uncomment this copy of the MuxCommand parent and add # # COMMAND_DEFAULT_CLASS = "commands.command.MuxCommand" # # to your settings file. Be warned that the default commands expect # the functionality implemented in the parse() method, so be # careful with what you change. # # ------------------------------------------------------------- from evennia.utils import utils class MuxCommand(Command): """ This sets up the basis for a MUX command. The idea is that most other Mux-related commands should just inherit from this and don't have to implement much parsing of their own unless they do something particularly advanced. Note that the class's __doc__ string (this text) is used by Evennia to create the automatic help entry for the command, so make sure to document consistently here. """ def has_perm(self, srcobj): """ This is called by the cmdhandler to determine if srcobj is allowed to execute this command. We just show it here for completeness - we are satisfied using the default check in Command. """ return super().has_perm(srcobj) def at_pre_cmd(self): """ This hook is called before self.parse() on all commands """ from typeclasses.characters import Character if type(self.caller) != Character: return command = self.cmdstring + self.args echo = "\n{icon} |220" + ansi.strip_ansi(command) + "\n\n" return self.caller.msg(echo, icon="graf62") def at_post_cmd(self): """ This hook is called after the command has finished executing (after self.func()). """ pass def parse(self): """ This method is called by the cmdhandler once the command name has been identified. It creates a new set of member variables that can be later accessed from self.func() (see below) The following variables are available for our use when entering this method (from the command definition, and assigned on the fly by the cmdhandler): self.key - the name of this command ('look') self.aliases - the aliases of this cmd ('l') self.permissions - permission string for this command self.help_category - overall category of command self.caller - the object calling this command self.cmdstring - the actual command name used to call this (this allows you to know which alias was used, for example) self.args - the raw input; everything following self.cmdstring. self.cmdset - the cmdset from which this command was picked. Not often used (useful for commands like 'help' or to list all available commands etc) self.obj - the object on which this command was defined. It is often the same as self.caller. A MUX command has the following possible syntax: name[ with several words][/switch[/switch..]] arg1[,arg2,...] [[=|,] arg[,..]] The 'name[ with several words]' part is already dealt with by the cmdhandler at this point, and stored in self.cmdname (we don't use it here). The rest of the command is stored in self.args, which can start with the switch indicator /. Optional variables to aid in parsing, if set: self.switch_options - (tuple of valid /switches expected by this command (without the /)) self.rhs_split - Alternate string delimiter or tuple of strings to separate left/right hand sides. tuple form gives priority split to first string delimiter. This parser breaks self.args into its constituents and stores them in the following variables: self.switches = [list of /switches (without the /)] self.raw = This is the raw argument input, including switches self.args = This is re-defined to be everything *except* the switches self.lhs = Everything to the left of = (lhs:'left-hand side'). If no = is found, this is identical to self.args. self.rhs: Everything to the right of = (rhs:'right-hand side'). If no '=' is found, this is None. self.lhslist - [self.lhs split into a list by comma] self.rhslist - [list of self.rhs split into a list by comma] self.arglist = [list of space-separated args (stripped, including '=' if it exists)] All args and list members are stripped of excess whitespace around the strings, but case is preserved. """ raw = self.args args = raw.strip() # Without explicitly setting these attributes, they assume default values: if not hasattr(self, "switch_options"): self.switch_options = None if not hasattr(self, "rhs_split"): self.rhs_split = "=" if not hasattr(self, "account_caller"): self.account_caller = False # split out switches switches, delimiters = [], self.rhs_split if self.switch_options: self.switch_options = [opt.lower() for opt in self.switch_options] if args and len(args) > 1 and raw[0] == "/": # we have a switch, or a set of switches. These end with a space. switches = args[1:].split(None, 1) if len(switches) > 1: switches, args = switches switches = switches.split("/") else: args = "" switches = switches[0].split("/") # If user-provides switches, parse them with parser switch options. if switches and self.switch_options: valid_switches, unused_switches, extra_switches = [], [], [] for element in switches: option_check = [ opt for opt in self.switch_options if opt == element ] if not option_check: option_check = [ opt for opt in self.switch_options if opt.startswith(element) ] match_count = len(option_check) if match_count > 1: extra_switches.extend( option_check ) # Either the option provided is ambiguous, elif match_count == 1: valid_switches.extend( option_check ) # or it is a valid option abbreviation, elif match_count == 0: unused_switches.append( element ) # or an extraneous option to be ignored. if extra_switches: # User provided switches self.msg( "|g%s|n: |wAmbiguous switch supplied: Did you mean /|C%s|w?" % (self.cmdstring, " |nor /|C".join(extra_switches)) ) if unused_switches: plural = "" if len(unused_switches) == 1 else "es" self.msg( '|g%s|n: |wExtra switch%s "/|C%s|w" ignored.' % (self.cmdstring, plural, "|n, /|C".join(unused_switches)) ) switches = valid_switches # Only include valid_switches in command function call arglist = [arg.strip() for arg in args.split()] # check for arg1, arg2, ... = argA, argB, ... constructs lhs, rhs = args.strip(), None if lhs: if ( delimiters and type(delimiters) != str and hasattr(delimiters, "__iter__") ): # If delimiter is iterable, best_split = delimiters[0] # (default to first delimiter) for this_split in delimiters: # try each delimiter if this_split in lhs: # to find first successful split best_split = this_split # to be the best split. break else: best_split = delimiters # Parse to separate left into left/right sides using best_split delimiter string if best_split in lhs: lhs, rhs = lhs.split(best_split, 1) # Trim user-injected whitespace rhs = rhs.strip() if rhs is not None else None lhs = lhs.strip() # Further split left/right sides by comma delimiter lhslist = [arg.strip() for arg in lhs.split(",")] if lhs is not None else "" rhslist = [arg.strip() for arg in rhs.split(",")] if rhs is not None else "" # save to object properties: self.raw = raw self.switches = switches self.args = args.strip() self.arglist = arglist self.lhs = lhs self.lhslist = lhslist self.rhs = rhs self.rhslist = rhslist # if the class has the account_caller property set on itself, we make # sure that self.caller is always the account if possible. We also create # a special property "character" for the puppeted object, if any. This # is convenient for commands defined on the Account only. if self.account_caller: if utils.inherits_from( self.caller, "evennia.objects.objects.DefaultObject" ): # caller is an Object/Character self.character = self.caller self.caller = self.caller.account elif utils.inherits_from( self.caller, "evennia.accounts.accounts.DefaultAccount" ): # caller was already an Account self.character = self.caller.get_puppet(self.session) else: self.character = None
[ "evennia.utils.ansi.strip_ansi", "evennia.utils.utils.inherits_from" ]
[((10948, 11021), 'evennia.utils.utils.inherits_from', 'utils.inherits_from', (['self.caller', '"""evennia.objects.objects.DefaultObject"""'], {}), "(self.caller, 'evennia.objects.objects.DefaultObject')\n", (10967, 11021), False, 'from evennia.utils import utils\n'), ((2754, 2778), 'evennia.utils.ansi.strip_ansi', 'ansi.strip_ansi', (['command'], {}), '(command)\n', (2769, 2778), False, 'from evennia.utils import ansi\n'), ((11213, 11289), 'evennia.utils.utils.inherits_from', 'utils.inherits_from', (['self.caller', '"""evennia.accounts.accounts.DefaultAccount"""'], {}), "(self.caller, 'evennia.accounts.accounts.DefaultAccount')\n", (11232, 11289), False, 'from evennia.utils import utils\n')]
import re from django.conf import settings from evennia.utils.ansi import strip_ansi from evennia.utils.utils import make_iter, to_str, wrap def capitalize(text): #allow ellipses to force lower case. if not "..." in text[0:4]: list_text = text if text.startswith("|"): list_text = text[2:] for character in list_text: #find the first alpha value and capitalize it, then break loop if character.isalpha(): i = text.index(character) if i == 0: text = text[i].upper() + text[i+1:] else: text = text[0:i] + text[i].upper() + text[i+1:] break return text def get_sw(caller): try: session = caller.sessions.all()[0] sw = session.protocol_flags.get("SCREENWIDTH")[0] except Exception: sw = settings.CLIENT_DEFAULT_WIDTH return sw def grammarize(text, ending='.'): text = text.strip() if not text.endswith((".", "!", "?", ".'", "!'", "?'", '."', '!"', '?"')): text += ending if text[-2] == " ": text = text[:-2] + text[-1] return text def list_to_string(initer, endsep=", and", addquote=False): """ This pretty-formats an iterable list as string output, adding an optional alternative separator to the second to last entry. If `addquote` is `True`, the outgoing strings will be surrounded by quotes. Args: initer (any): Usually an iterable to print. Each element must be possible to present with a string. Note that if this is a generator, it will be consumed by this operation. endsep (str, optional): If set, the last item separator will be replaced with this value. addquote (bool, optional): This will surround all outgoing values with double quotes. Returns: liststr (str): The list represented as a string. Examples: ```python # no endsep: [1,2,3] -> '1, 2, 3' # with endsep=='and': [1,2,3] -> '1, 2 and 3' # with addquote and endsep [1,2,3] -> '"1", "2" and "3"' ``` """ if not endsep: endsep = "," if not initer: return "" initer = tuple(str(val) for val in make_iter(initer)) if addquote: if len(initer) == 1: return '"%s"' % initer[0] return ", ".join('"%s"' % v for v in initer[:-1]) + "%s %s" % (endsep, '"%s"' % initer[-1]) else: if len(initer) == 1: return str(initer[0]) elif len(initer) == 2: return " and ".join(str(v) for v in initer) else: return ", ".join(str(v) for v in initer[:-1]) + "%s %s" % (endsep, initer[-1]) def wrap(text, text_width=None, screen_width=None, pre_text="", omit_pre_text=False, indent=0, align="l"): # Format Text text_width = text_width if text_width else settings.CLIENT_DEFAULT_WIDTH screen_width = screen_width if screen_width else settings.CLIENT_DEFAULT_WIDTH text_width = text_width-indent screen_width = screen_width-indent if screen_width is not None: text_lines = re.split(r"\n|\|/", text) if not omit_pre_text: final_text = pre_text else: final_text = "" first_line = True for x in text_lines: word_list = re.findall(r"((?:\S+\s*)|(?:^\s+))", x) line_list = [] line_len = len(x) - len(strip_ansi(x)) line_available_char = text_width - len(strip_ansi(pre_text))# + line_len line = "" for y in word_list: line_available_char = line_available_char + (len(y)-len(strip_ansi(y))) if (len(y) <= line_available_char): line += y line_available_char = line_available_char - len(y) else: if (len(y) > text_width - len(strip_ansi(pre_text))): line = "" line_available_char = text_width - len(strip_ansi(pre_text)) character_list = re.findall(r"((?:\|[bBcCgGmMrRwWxXyY])|\|\d{3}|(?:.))", y) for character in character_list: if (len(character) <= line_available_char): line += character if not character in character_list: line_available_char = line_available_char - len(character) else: line_list.append(line) line = character if character in character_list: line_available_char = text_width - len(strip_ansi(pre_text)) else: line_available_char = text_width - len(strip_ansi(pre_text)) - len(character) else: line_list.append(line) line = y line_available_char = text_width - len(strip_ansi(pre_text)) - len(y) + (len(y)-len(strip_ansi(y))) line_list.append(line) for y in line_list: if ((len(y) - len(strip_ansi(y))) > 0): spaces = len(y) - len(strip_ansi(y)) else: spaces = 0 line_text = "" if first_line: final_text = justify(final_text, width=screen_width+spaces, align=align, indent=indent) line_text = justify(y, width=screen_width+spaces, align=align) else: line_text = justify(y, width=screen_width+spaces, align=align, indent=len(strip_ansi(pre_text))+indent) final_text += line_text+"|/" first_line = False final_text = final_text[:-2] return final_text + "|n" def justify(text, width=settings.CLIENT_DEFAULT_WIDTH, align="l", indent=0): if align == "l": #|n return " "*indent + text elif align == "c": return " "*int(((width/2)-(len(text)/2))) + text return text
[ "evennia.utils.ansi.strip_ansi", "evennia.utils.utils.make_iter" ]
[((3253, 3279), 're.split', 're.split', (['"""\\\\n|\\\\|/"""', 'text'], {}), "('\\\\n|\\\\|/', text)\n", (3261, 3279), False, 'import re\n'), ((3464, 3505), 're.findall', 're.findall', (['"""((?:\\\\S+\\\\s*)|(?:^\\\\s+))"""', 'x'], {}), "('((?:\\\\S+\\\\s*)|(?:^\\\\s+))', x)\n", (3474, 3505), False, 'import re\n'), ((2353, 2370), 'evennia.utils.utils.make_iter', 'make_iter', (['initer'], {}), '(initer)\n', (2362, 2370), False, 'from evennia.utils.utils import make_iter, to_str, wrap\n'), ((3567, 3580), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['x'], {}), '(x)\n', (3577, 3580), False, 'from evennia.utils.ansi import strip_ansi\n'), ((3633, 3653), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (3643, 3653), False, 'from evennia.utils.ansi import strip_ansi\n'), ((4218, 4278), 're.findall', 're.findall', (['"""((?:\\\\|[bBcCgGmMrRwWxXyY])|\\\\|\\\\d{3}|(?:.))"""', 'y'], {}), "('((?:\\\\|[bBcCgGmMrRwWxXyY])|\\\\|\\\\d{3}|(?:.))', y)\n", (4228, 4278), False, 'import re\n'), ((3793, 3806), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['y'], {}), '(y)\n', (3803, 3806), False, 'from evennia.utils.ansi import strip_ansi\n'), ((5438, 5451), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['y'], {}), '(y)\n', (5448, 5451), False, 'from evennia.utils.ansi import strip_ansi\n'), ((5502, 5515), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['y'], {}), '(y)\n', (5512, 5515), False, 'from evennia.utils.ansi import strip_ansi\n'), ((4034, 4054), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (4044, 4054), False, 'from evennia.utils.ansi import strip_ansi\n'), ((4155, 4175), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (4165, 4175), False, 'from evennia.utils.ansi import strip_ansi\n'), ((5321, 5334), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['y'], {}), '(y)\n', (5331, 5334), False, 'from evennia.utils.ansi import strip_ansi\n'), ((5973, 5993), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (5983, 5993), False, 'from evennia.utils.ansi import strip_ansi\n'), ((5276, 5296), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (5286, 5296), False, 'from evennia.utils.ansi import strip_ansi\n'), ((4933, 4953), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (4943, 4953), False, 'from evennia.utils.ansi import strip_ansi\n'), ((5068, 5088), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['pre_text'], {}), '(pre_text)\n', (5078, 5088), False, 'from evennia.utils.ansi import strip_ansi\n')]
from evennia.prototypes.spawner import spawn def return_all_coin_types(coin_dict): """ Takes a coin dictionary and returns the value of all 4 types of coins, as individual variables. If a coin dictionary is not provided, the method attempts to pull one from the owner object. If that fails, a coin dictionary is created with all 0 values. Keyword Arguments: coin_dict (dict): A dictionary of coins and their values. Returns: plat (int): The value of platinum coin. gold (int): The value of gold coin. silver (int): The value of silver coin. copper (int): The value of copper coin. """ return coin_dict['plat'], coin_dict['gold'], coin_dict['silver'], coin_dict['copper'] def all_coin_types_to_string(coin_dict): """ Converts all coin elements into a string, no matter their value. Keyword Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: (string): The resulting string. """ return f"{coin_dict['plat']}p {coin_dict['gold']}g {coin_dict['silver']}s {coin_dict['copper']}c" def positive_coin_types_to_string(coin_dict): """ Converts only the coin elements that are greater than 0 into a string. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: (string): The resulting string. """ plat = "" gold = "" silver = "" copper = "" if coin_dict['plat'] > 0: plat = f"{coin_dict['plat']}p " if coin_dict['gold'] > 0: gold = f"{coin_dict['gold']}g " if coin_dict['silver'] > 0: silver = f"{coin_dict['silver']}s " if coin_dict['copper'] > 0: copper = f"{coin_dict['copper']}c" return f"{plat}{gold}{silver}{copper}".strip() def balance_coin_dict(coin_dict): """ Takes a coin dictionary and balances all coins in excess of 999. Pushes the quotient of 1,000 up to the next coin type and leaves the remainder. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: coin_dict (dict): A dictionary consisting of all 4 coin types. """ def quotient(value): return value // 1_000 def remainder(value): return value % 1_000 plat, gold, silver, copper = return_all_coin_types(coin_dict=coin_dict) if copper > 999: silver += quotient(copper) copper = remainder(copper) if silver > 999: gold += quotient(silver) silver = remainder(silver) if gold > 999: plat += quotient(gold) gold = remainder(gold) return create_coin_dict(plat=plat, gold=gold, silver=silver, copper=copper) def convert_coin_type(plat=0, gold=0, silver=0, copper=0, result_type='copper'): """ Converts any number of coin types into a single type of coin. For example, it can convert 585433 copper + 35 plat into silver. (Don't worry about how much silver that is. It's what this method is for!) Converting upward will likely result in a float, whereas only converting downward will always result in an integer. This is critical information to keep in mind when using this method. Keyword Arguments: plat (int): Amount of platinum to convert. gold (int): Amount of gold to convert. silver (int): Amount of silver to convert. coppper (int): Amount of copper to convert. result_type (string): The type of coin the result should be. Defaults to copper. Returns: plat (int) or (float) gold (int) or (float) silver (int) or (float) coppper (int) or (float) """ def convert_upward(current_tier_amount): return current_tier_amount / 1_000 def convert_downward(current_tier_amount): return current_tier_amount * 1_000 if result_type == 'plat': silver += convert_upward(copper) gold += convert_upward(silver) plat += convert_upward(gold) return plat elif result_type == 'gold': silver += convert_upward(copper) gold += convert_upward(silver) gold += convert_downward(plat) return gold elif result_type == 'silver': silver += convert_upward(copper) gold += convert_downward(plat) silver += convert_downward(gold) return silver else: # result_type == copper gold += convert_downward(plat) silver += convert_downward(gold) copper += convert_downward(silver) return copper def create_coin_dict(plat=0, gold=0, silver=0, copper=0): """ Creates a new dictionary with all 4 coin types. Any coin type that doesn't have a value passed to this method defaults to 0. Keyword Arguments: plat (int): The value of platinum coin. gold (int): The value of gold coin. silver (int): The value of silver coin. copper (int): The value of copper coin. Returns: coin_dict (dict): A dictionary consisting of all 4 coin types. """ return {'plat': plat, 'gold': gold, 'silver': silver, 'copper': copper} def coin_dict_to_copper(coin_dict): """ Converts a coin dictionary down to a total amount of copper. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: copper (int): The total copper value of the coin dictionary. """ return convert_coin_type(**coin_dict) def copper_to_coin_dict(copper): """ Takes any amount of coppper and converts it into a dictionary with that same amount of copper. It then balances the dictionary, pushing values above 999 up to the next coin type. Arguments: copper (int): The amount of copper to convert into a coin dictionary. Returns: coin_dict (dict): A dictionary consisting of all 4 coin types. """ return balance_coin_dict(create_coin_dict(copper=copper)) def is_homogenized(coin_dict): """ Checks a coin dictionary to find out if there's only 1 type of coin with a value above 0. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: is_homogenized (boolean): True or False """ num = 0 for coin_value in coin_dict.values(): if coin_value > 0: num += 1 if num > 1: return False else: return True def generate_coin_object(coin_dict=None, copper=None): """ Determines what type of coin object and key to generate based on the coin dictionary. Keyword Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. copper (integer): A value representing the total amount of coin. Returns: coin_obj (object): The final spawned object, with its key properly set. """ if copper is not None: coin_dict = copper_to_coin_dict(copper) elif coin_dict is None and copper is None: coin_dict = create_coin_dict() # A coin must have some sort of value, therefore generate a single copper coin. coin_dict['copper'] = 1 homogenized = is_homogenized(coin_dict) coin_prototype = None pluralized = False if homogenized: for coin_type, coin_value in coin_dict.items(): if coin_value > 0: coin_prototype = f"{coin_type}_coin" if coin_value > 1: pluralized = True else: coin_prototype = 'coin_pile' coin_obj = spawn(coin_prototype)[0] coin_obj.db.coin = coin_dict if pluralized: coin_obj.key = f"a pile of {coin_obj.db.plural_key}" return coin_obj
[ "evennia.prototypes.spawner.spawn" ]
[((7499, 7520), 'evennia.prototypes.spawner.spawn', 'spawn', (['coin_prototype'], {}), '(coin_prototype)\n', (7504, 7520), False, 'from evennia.prototypes.spawner import spawn\n')]
""" The default command parser. Use your own by assigning `settings.COMMAND_PARSER` to a Python path to a module containing the replacing cmdparser function. The replacement parser must accept the same inputs as the default one. """ import re from django.conf import settings from evennia.utils.logger import log_trace _MULTIMATCH_REGEX = re.compile(settings.SEARCH_MULTIMATCH_REGEX, re.I + re.U) _CMD_IGNORE_PREFIXES = settings.CMD_IGNORE_PREFIXES def create_match(cmdname, string, cmdobj, raw_cmdname): """ Builds a command match by splitting the incoming string and evaluating the quality of the match. Args: cmdname (str): Name of command to check for. string (str): The string to match against. cmdobj (str): The full Command instance. raw_cmdname (str, optional): If CMD_IGNORE_PREFIX is set and the cmdname starts with one of the prefixes to ignore, this contains the raw, unstripped cmdname, otherwise it is None. Returns: match (tuple): This is on the form (cmdname, args, cmdobj, cmdlen, mratio, raw_cmdname), where `cmdname` is the command's name and `args` is the rest of the incoming string, without said command name. `cmdobj` is the Command instance, the cmdlen is the same as len(cmdname) and mratio is a measure of how big a part of the full input string the cmdname takes up - an exact match would be 1.0. Finally, the `raw_cmdname` is the cmdname unmodified by eventual prefix-stripping. """ cmdlen, strlen = len(str(cmdname)), len(str(string)) mratio = 1 - (strlen - cmdlen) / (1.0 * strlen) args = string[cmdlen:] return (cmdname, args, cmdobj, cmdlen, mratio, raw_cmdname) def build_matches(raw_string, cmdset, include_prefixes=False): """ Build match tuples by matching raw_string against available commands. Args: raw_string (str): Input string that can look in any way; the only assumption is that the sought command's name/alias must be *first* in the string. cmdset (CmdSet): The current cmdset to pick Commands from. include_prefixes (bool): If set, include prefixes like @, ! etc (specified in settings) in the match, otherwise strip them before matching. Returns: matches (list) A list of match tuples created by `cmdparser.create_match`. """ matches = [] try: if include_prefixes: # use the cmdname as-is l_raw_string = raw_string.lower() for cmd in cmdset: matches.extend( [ create_match(cmdname, raw_string, cmd, cmdname) for cmdname in [cmd.key] + cmd.aliases if cmdname and l_raw_string.startswith(cmdname.lower()) and (not cmd.arg_regex or cmd.arg_regex.match(l_raw_string[len(cmdname) :])) ] ) else: # strip prefixes set in settings raw_string = ( raw_string.lstrip(_CMD_IGNORE_PREFIXES) if len(raw_string) > 1 else raw_string ) l_raw_string = raw_string.lower() for cmd in cmdset: for raw_cmdname in [cmd.key] + cmd.aliases: cmdname = ( raw_cmdname.lstrip(_CMD_IGNORE_PREFIXES) if len(raw_cmdname) > 1 else raw_cmdname ) if ( cmdname and l_raw_string.startswith(cmdname.lower()) and (not cmd.arg_regex or cmd.arg_regex.match(l_raw_string[len(cmdname) :])) ): matches.append(create_match(cmdname, raw_string, cmd, raw_cmdname)) except Exception: log_trace("cmdhandler error. raw_input:%s" % raw_string) return matches def try_num_prefixes(raw_string): """ Test if user tried to separate multi-matches with a number separator (default 1-name, 2-name etc). This is usually called last, if no other match was found. Args: raw_string (str): The user input to parse. Returns: mindex, new_raw_string (tuple): If a multimatch-separator was detected, this is stripped out as an integer to separate between the matches. The new_raw_string is the result of stripping out that identifier. If no such form was found, returns (None, None). Example: In the default configuration, entering 2-ball (e.g. in a room will more than one 'ball' object), will lead to a multimatch and this function will parse `"2-ball"` and return `(2, "ball")`. """ # no matches found num_ref_match = _MULTIMATCH_REGEX.match(raw_string) if num_ref_match: # the user might be trying to identify the command # with a #num-command style syntax. We expect the regex to # contain the groups "number" and "name". mindex, new_raw_string = num_ref_match.group("number"), num_ref_match.group("name") return mindex, new_raw_string else: return None, None def cmdparser(raw_string, cmdset, caller, match_index=None): """ This function is called by the cmdhandler once it has gathered and merged all valid cmdsets valid for this particular parsing. Args: raw_string (str): The unparsed text entered by the caller. cmdset (CmdSet): The merged, currently valid cmdset caller (Session, Account or Object): The caller triggering this parsing. match_index (int, optional): Index to pick a given match in a list of same-named command matches. If this is given, it suggests this is not the first time this function was called: normally the first run resulted in a multimatch, and the index is given to select between the results for the second run. Returns: matches (list): This is a list of match-tuples as returned by `create_match`. If no matches were found, this is an empty list. Notes: The cmdparser understand the following command combinations (where [] marks optional parts. ``` [cmdname[ cmdname2 cmdname3 ...] [the rest] ``` A command may consist of any number of space-separated words of any length, and contain any character. It may also be empty. The parser makes use of the cmdset to find command candidates. The parser return a list of matches. Each match is a tuple with its first three elements being the parsed cmdname (lower case), the remaining arguments, and the matched cmdobject from the cmdset. """ if not raw_string: return [] # find mathces, first using the full name matches = build_matches(raw_string, cmdset, include_prefixes=True) if not matches: # try to match a number 1-cmdname, 2-cmdname etc mindex, new_raw_string = try_num_prefixes(raw_string) if mindex is not None: return cmdparser(new_raw_string, cmdset, caller, match_index=int(mindex)) if _CMD_IGNORE_PREFIXES: # still no match. Try to strip prefixes raw_string = ( raw_string.lstrip(_CMD_IGNORE_PREFIXES) if len(raw_string) > 1 else raw_string ) matches = build_matches(raw_string, cmdset, include_prefixes=False) # only select command matches we are actually allowed to call. matches = [match for match in matches if match[2].access(caller, "cmd")] # try to bring the number of matches down to 1 if len(matches) > 1: # See if it helps to analyze the match with preserved case but only if # it leaves at least one match. trimmed = [match for match in matches if raw_string.startswith(match[0])] if trimmed: matches = trimmed if len(matches) > 1: # we still have multiple matches. Sort them by count quality. matches = sorted(matches, key=lambda m: m[3]) # only pick the matches with highest count quality quality = [mat[3] for mat in matches] matches = matches[-quality.count(quality[-1]) :] if len(matches) > 1: # still multiple matches. Fall back to ratio-based quality. matches = sorted(matches, key=lambda m: m[4]) # only pick the highest rated ratio match quality = [mat[4] for mat in matches] matches = matches[-quality.count(quality[-1]) :] if len(matches) > 1 and match_index is not None and 0 < match_index <= len(matches): # We couldn't separate match by quality, but we have an # index argument to tell us which match to use. matches = [matches[match_index - 1]] # no matter what we have at this point, we have to return it. return matches
[ "evennia.utils.logger.log_trace" ]
[((343, 400), 're.compile', 're.compile', (['settings.SEARCH_MULTIMATCH_REGEX', '(re.I + re.U)'], {}), '(settings.SEARCH_MULTIMATCH_REGEX, re.I + re.U)\n', (353, 400), False, 'import re\n'), ((3953, 4009), 'evennia.utils.logger.log_trace', 'log_trace', (["('cmdhandler error. raw_input:%s' % raw_string)"], {}), "('cmdhandler error. raw_input:%s' % raw_string)\n", (3962, 4009), False, 'from evennia.utils.logger import log_trace\n')]
from evennia.contrib import custom_gametime from commands.command import Command class CmdTime(Command): """ Display the time. Syntax: time """ key = "time" locks = "cmd:all()" def func(self): """Execute the time command.""" # Get the absolute game time # unknown, year, month, day, hour, min, sec = custom_gametime.custom_gametime(absolute=True) # string = "unknown: %s, year: %s, month: %s, day: %s, hour: %s, min: %s, sec: %s" % (unknown, year, month, day, hour, min, sec) # self.caller.msg(string) # Get the absolute game time year, month, day, hour, min, sec = custom_gametime.custom_gametime(absolute=True) #string = "We are in year {year}, day {day}, month {month}." #string += "\nIt's {hour:02}:{min:02}:{sec:02}." #self.msg(string.format(year=year, month=month, day=day, #hour=hour, min=min, sec=sec)) #self.caller.msg("You estimate that it's about %s hours in Encarnia." % hour) #self.caller.msg("Year: %s, Month: %s, Day: %s, Hour: %s, min: %s, sec: %s." % (year, month, day, hour, min, sec)) hour = int(hour) this_month = "Omeo" season = "winter" if month == 1: this_month = "Velis" season = "winter" elif month == 2: this_month = "Delfas" season = "winter" elif month == 3: this_month = "Flyrnio" season = "spring" elif month == 4: this_month = "Ultera" season = "spring" elif month == 5: this_month = "Magna" season = "spring" elif month == 6: this_month = "Altas" season = "summer" elif month == 7: this_month = "Helios" season = "summer" elif month == 8: this_month = "Icarus" season = "summer" elif month == 9: this_month = "Yarnos" season = "fall" elif month == 10: this_month = "Demio" season = "fall" elif month == 11: this_month = "Servia" season = "fall" elif month == 12: this_month = "Omeo" season = "winter" day_suffix = "th" if day == 1: day_suffix = "st" elif day == 2: day_suffix = "nd" elif day == 3: day_suffix = "rd" elif day == 21: day_suffix = "st" elif day == 22: day_suffix = "nd" elif day == 23: day_suffix = "rd" self.caller.msg("It is the %s%s day of %s, in the %s of the year %s AC." % (day, day_suffix, this_month, season, year)) if hour == 0: self.caller.msg("It's midnight in Encarnia.") elif 0 < hour <= 5: self.caller.msg("It's past midnight in Encarnia.") elif 5 < hour <= 7: self.caller.msg("It's early morning in Encarnia.") elif 7 < hour <= 11: self.caller.msg("It's morning in Encarnia.") elif 11 < hour < 12: self.caller.msg("It's almost high noon in Encarnia.") elif hour == 12: self.caller.msg("It's high noon in Encarnia.") elif 12 < hour <= 13: self.caller.msg("It's just after noon in Encarnia.") elif 13 < hour <= 15: self.caller.msg("It's afternoon in Encarnia.") elif 15 < hour <= 17: self.caller.msg("It's getting on towards the evening in Encarnia.") elif 17 < hour <= 19: self.caller.msg("It's evening in Encarnia.") elif 19 < hour <= 22: self.caller.msg("It's night in Encarnia.") elif 22 < hour <= 23: self.caller.msg("It's late night in Encarnia.") else: self.caller.msg("It's almost midnight in Encarnia.")
[ "evennia.contrib.custom_gametime.custom_gametime" ]
[((691, 737), 'evennia.contrib.custom_gametime.custom_gametime', 'custom_gametime.custom_gametime', ([], {'absolute': '(True)'}), '(absolute=True)\n', (722, 737), False, 'from evennia.contrib import custom_gametime\n')]
""" Containers Containers are storage classes usually initialized from a setting. They represent Singletons and acts as a convenient place to find resources ( available as properties on the singleton) evennia.GLOBAL_SCRIPTS evennia.OPTION_CLASSES """ from django.conf import settings from evennia.utils.utils import class_from_module, callables_from_module from evennia.utils import logger class Container(object): """ Base container class. A container is simply a storage object whose properties can be acquired as a property on it. This is generally considered a read-only affair. The container is initialized by a list of modules containing callables. """ storage_modules = [] def __init__(self): """ Read data from module. """ self.loaded_data = None def load_data(self): """ Delayed import to avoid eventual circular imports from inside the storage modules. """ if self.loaded_data is None: self.loaded_data = {} for module in self.storage_modules: self.loaded_data.update(callables_from_module(module)) def __getattr__(self, key): return self.get(key) def get(self, key, default=None): """ Retrive data by key (in case of not knowing it beforehand). Args: key (str): The name of the script. default (any, optional): Value to return if key is not found. Returns: any (any): The data loaded on this container. """ self.load_data() return self.loaded_data.get(key, default) def all(self): """ Get all stored data Returns: scripts (list): All global script objects stored on the container. """ self.load_data() return list(self.loaded_data.values()) class OptionContainer(Container): """ Loads and stores the final list of OPTION CLASSES. Can access these as properties or dictionary-contents. """ storage_modules = settings.OPTION_CLASS_MODULES class GlobalScriptContainer(Container): """ Simple Handler object loaded by the Evennia API to contain and manage a game's Global Scripts. Scripts to start are defined by `settings.GLOBAL_SCRIPTS`. Example: import evennia evennia.GLOBAL_SCRIPTS.scriptname Note: This does not use much of the BaseContainer since it's not loading callables from settings but a custom dict of tuples. """ def __init__(self): """ Initialize the container by preparing scripts. Lazy-load only when the script is requested. Note: We must delay loading of typeclasses since this module may get initialized before Scripts are actually initialized. """ self.loaded_data = {key: {} if data is None else data for key, data in settings.GLOBAL_SCRIPTS.items()} self.script_storage = {} self.typeclass_storage = None def load_data(self): """ This delayed import avoids trying to load Scripts before they are initialized. """ if self.typeclass_storage is None: self.typeclass_storage = {} for key, data in self.loaded_data.items(): try: typeclass = data.get('typeclass', settings.BASE_SCRIPT_TYPECLASS) self.typeclass_storage[key] = class_from_module(typeclass) except ImportError as err: logger.log_err( f"GlobalScriptContainer could not start global script {key}: {err}") def _load_script(self, key): self.load_data() typeclass = self.typeclass_storage[key] found = typeclass.objects.filter(db_key=key).first() interval = self.loaded_data[key].get('interval', None) start_delay = self.loaded_data[key].get('start_delay', None) repeats = self.loaded_data[key].get('repeats', 0) desc = self.loaded_data[key].get('desc', '') if not found: new_script, errors = typeclass.create(key=key, persistent=True, interval=interval, start_delay=start_delay, repeats=repeats, desc=desc) if errors: logger.log_err("\n".join(errors)) return None new_script.start() self.script_storage[key] = new_script return new_script if ((found.interval != interval) or (found.start_delay != start_delay) or (found.repeats != repeats)): found.restart(interval=interval, start_delay=start_delay, repeats=repeats) if found.desc != desc: found.desc = desc self.script_storage[key] = found return found def get(self, key, default=None): """ Retrive data by key (in case of not knowing it beforehand). Args: key (str): The name of the script. default (any, optional): Value to return if key is not found at all on this container (i.e it cannot be loaded at all). Returns: any (any): The data loaded on this container. """ if key not in self.loaded_data: return default return self.script_storage.get(key) or self._load_script(key) def all(self): """ Get all scripts. Returns: scripts (list): All global script objects stored on the container. """ return [self.__getattr__(key) for key in self.loaded_data] # Create all singletons GLOBAL_SCRIPTS = GlobalScriptContainer() OPTION_CLASSES = OptionContainer()
[ "evennia.utils.utils.class_from_module", "evennia.utils.utils.callables_from_module", "evennia.utils.logger.log_err" ]
[((2966, 2997), 'django.conf.settings.GLOBAL_SCRIPTS.items', 'settings.GLOBAL_SCRIPTS.items', ([], {}), '()\n', (2995, 2997), False, 'from django.conf import settings\n'), ((1139, 1168), 'evennia.utils.utils.callables_from_module', 'callables_from_module', (['module'], {}), '(module)\n', (1160, 1168), False, 'from evennia.utils.utils import class_from_module, callables_from_module\n'), ((3511, 3539), 'evennia.utils.utils.class_from_module', 'class_from_module', (['typeclass'], {}), '(typeclass)\n', (3528, 3539), False, 'from evennia.utils.utils import class_from_module, callables_from_module\n'), ((3603, 3691), 'evennia.utils.logger.log_err', 'logger.log_err', (['f"""GlobalScriptContainer could not start global script {key}: {err}"""'], {}), "(\n f'GlobalScriptContainer could not start global script {key}: {err}')\n", (3617, 3691), False, 'from evennia.utils import logger\n')]
from evennia.utils.create import create_object from evennia.utils.search import search_object """ At_initial_setup module template Custom at_initial_setup method. This allows you to hook special modifications to the initial server startup process. Note that this will only be run once - when the server starts up for the very first time! It is called last in the startup process and can thus be used to overload things that happened before it. The module must contain a global function at_initial_setup(). This will be called without arguments. Note that tracebacks in this module will be QUIETLY ignored, so make sure to check it well to make sure it does what you expect it to. """ def at_initial_setup(): # Search by dbref to find the #1 superuser char1 = search_object('#1', use_dbref=True)[0] room = search_object('#2', use_dbref=True)[0] room.key = 'default_home' room.db.desc = ("This is the room where objects travel to when their home location isn\'t " "explicity set in the source code or by a builder, " "and the object\'s current location is destroyed. " "Character typeclasses are not allowed to enter this room in a move_to check.") # Black Hole black_hole = create_object(typeclass='rooms.rooms.Room', key='black_hole') black_hole.db.desc = ("The room where all objects go to die. It is the default home for " "objects that are considered worthless. Any object entering this room is " "automatically deleted via the at_object_receive method.") black_hole.tags.add('black_hole', category='rooms') # Statis Chamber statis_chamber = create_object(typeclass='rooms.rooms.Room', key='statis_chamber') statis_chamber.db.desc = ("This room holds objects indefinitely. It is the default home for " "objects that are of significant value, unique, or otherwise should " "not be destroyed for any reason.") statis_chamber.tags.add('statis_chamber', category='rooms') # Trash Bin trash_bin = create_object(typeclass='rooms.rooms.Room', key='trash_bin') trash_bin.db.desc = ("This room holds objects for 90 days, before being sent to black_hole. " "It is the default home for objects of some value and the destination " "of said objects when discarded by players.") trash_bin.tags.add('trash_bin', category='rooms') # Superuser's equipment generation must take place after the item rooms are generated. # The inventory container requires trash_bin to exist. char1.equip.generate_starting_equipment() # Create the superuser's home room. rm3 = create_object(typeclass='rooms.rooms.Room', key='Main Office') char1.home = rm3 rm3.tags.add('main_office', category='ooc_room') char1.move_to(rm3, quiet=True, move_hooks=False) # Create the Common Room. This is where all portals will lead when entering public OOC areas. rm4 = create_object(typeclass='rooms.rooms.Room', key='Common Room') rm4.tags.add('common_room', category='ooc_room') rm4.tags.add(category='public_ooc') # Connect the main office and common room with exits. exit_rm3_rm4 = create_object(typeclass='travel.exits.Exit', key='a mahogany door', aliases = ['door', ], location=rm3, destination=rm4, tags=[('door', 'exits'), ]) exit_rm3_rm4.tags.add('n', category='card_dir') exit_rm3_rm4.tags.add(category='ooc_exit') exit_rm4_rm3 = create_object(typeclass='travel.exits.Exit', key='a mahogany door', aliases=['door', ], location=rm4, destination=rm3, tags=[('door', 'exits'), ]) exit_rm4_rm3.tags.add('s', category='card_dir') exit_rm4_rm3.tags.add(category='ooc_exit')
[ "evennia.utils.create.create_object", "evennia.utils.search.search_object" ]
[((1272, 1333), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""rooms.rooms.Room"""', 'key': '"""black_hole"""'}), "(typeclass='rooms.rooms.Room', key='black_hole')\n", (1285, 1333), False, 'from evennia.utils.create import create_object\n'), ((1709, 1774), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""rooms.rooms.Room"""', 'key': '"""statis_chamber"""'}), "(typeclass='rooms.rooms.Room', key='statis_chamber')\n", (1722, 1774), False, 'from evennia.utils.create import create_object\n'), ((2132, 2192), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""rooms.rooms.Room"""', 'key': '"""trash_bin"""'}), "(typeclass='rooms.rooms.Room', key='trash_bin')\n", (2145, 2192), False, 'from evennia.utils.create import create_object\n'), ((2767, 2829), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""rooms.rooms.Room"""', 'key': '"""Main Office"""'}), "(typeclass='rooms.rooms.Room', key='Main Office')\n", (2780, 2829), False, 'from evennia.utils.create import create_object\n'), ((3066, 3128), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""rooms.rooms.Room"""', 'key': '"""Common Room"""'}), "(typeclass='rooms.rooms.Room', key='Common Room')\n", (3079, 3128), False, 'from evennia.utils.create import create_object\n'), ((3300, 3447), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""travel.exits.Exit"""', 'key': '"""a mahogany door"""', 'aliases': "['door']", 'location': 'rm3', 'destination': 'rm4', 'tags': "[('door', 'exits')]"}), "(typeclass='travel.exits.Exit', key='a mahogany door', aliases\n =['door'], location=rm3, destination=rm4, tags=[('door', 'exits')])\n", (3313, 3447), False, 'from evennia.utils.create import create_object\n'), ((3605, 3752), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""travel.exits.Exit"""', 'key': '"""a mahogany door"""', 'aliases': "['door']", 'location': 'rm4', 'destination': 'rm3', 'tags': "[('door', 'exits')]"}), "(typeclass='travel.exits.Exit', key='a mahogany door', aliases\n =['door'], location=rm4, destination=rm3, tags=[('door', 'exits')])\n", (3618, 3752), False, 'from evennia.utils.create import create_object\n'), ((775, 810), 'evennia.utils.search.search_object', 'search_object', (['"""#1"""'], {'use_dbref': '(True)'}), "('#1', use_dbref=True)\n", (788, 810), False, 'from evennia.utils.search import search_object\n'), ((826, 861), 'evennia.utils.search.search_object', 'search_object', (['"""#2"""'], {'use_dbref': '(True)'}), "('#2', use_dbref=True)\n", (839, 861), False, 'from evennia.utils.search import search_object\n')]
# ------------------------------------------------------------- # # Teleport room - puzzles solution # # This is a sort of puzzle room that requires a certain # attribute on the entering character to be the same as # an attribute of the room. If not, the character will # be teleported away to a target location. This is used # by the Obelisk - grave chamber puzzle, where one must # have looked at the obelisk to get an attribute set on # oneself, and then pick the grave chamber with the # matching imagery for this attribute. # # ------------------------------------------------------------- from evennia import CmdSet, Command from evennia import utils, create_object, search_object from evennia import syscmdkeys, default_cmds from typeclasses.base import Room class TeleportRoom(Room): """ Teleporter - puzzle room. Important attributes (set at creation): puzzle_key - which attr to look for on character puzzle_value - what char.db.puzzle_key must be set to success_teleport_to - where to teleport in case if success success_teleport_msg - message to echo while teleporting to success failure_teleport_to - where to teleport to in case of failure failure_teleport_msg - message to echo while teleporting to failure """ def at_object_creation(self): """Called at first creation""" super().at_object_creation() # what character.db.puzzle_clue must be set to, to avoid teleportation. self.db.puzzle_value = 1 # target of successful teleportation. Can be a dbref or a # unique room name. self.db.success_teleport_msg = "You are successful!" self.db.success_teleport_to = "treasure room" # the target of the failure teleportation. self.db.failure_teleport_msg = "You fail!" self.db.failure_teleport_to = "dark cell" def at_object_receive(self, character, source_location): """ This hook is called by the engine whenever the player is moved into this room. """ if not character.has_account: # only act on player characters. return # determine if the puzzle is a success or not is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value) teleport_to = ( self.db.success_teleport_to if is_success else self.db.failure_teleport_to ) # note that this returns a list results = search_object(teleport_to) if not results or len(results) > 1: # we cannot move anywhere since no valid target was found. character.msg("no valid teleport target for %s was found." % teleport_to) return if character.is_superuser: # superusers don't get teleported character.msg( "Superuser block: You would have been teleported to %s." % results[0] ) return # perform the teleport if is_success: character.msg(self.db.success_teleport_msg) else: character.msg(self.db.failure_teleport_msg) # teleport quietly to the new place character.move_to(results[0], quiet=True, move_hooks=False) # we have to call this manually since we turn off move_hooks # - this is necessary to make the target dark room aware of an # already carried light. results[0].at_object_receive(character, self)
[ "evennia.search_object" ]
[((2471, 2497), 'evennia.search_object', 'search_object', (['teleport_to'], {}), '(teleport_to)\n', (2484, 2497), False, 'from evennia import utils, create_object, search_object\n')]
""" Channel commands are OOC commands and intended to be made available to the Account at all times. Send to Channel command exists in system.py """ from django.conf import settings from evennia import Command as BaseCommand from evennia.commands.default.comms import find_channel from evennia.comms.models import ChannelDB from evennia.utils.logger import tail_log_file from evennia.utils.utils import class_from_module from commands.command import Command CHANNEL_DEFAULT_TYPECLASS = class_from_module( settings.BASE_CHANNEL_TYPECLASS, fallback=settings.FALLBACK_CHANNEL_TYPECLASS ) class CmdLast(BaseCommand): """ Syntax: last <channel> Example: last chat Read the history of any channel you have access to. """ key = "last" locks = "cmd:not pperm(channel_banned)" account_caller = True def func(self): caller = self.caller channel = ChannelDB.objects.get_channel(self.args.strip()) self.channel = channel if not channel: caller.msg("Channel '%s' not found." % self.args.strip()) return if not channel.access(caller, "listen"): caller.msg("You are not allowed to listen to this channel.") return log_file = channel.attributes.get("log_file", default="channel_%s.log" % channel.key) tail_log_file(log_file, 0, 15, callback=self.send_msg) return def send_msg(self, lines): channel = self.channel msg = f"|145History of {channel.key}|n" sep = "|145" + ("-" * (len(msg)-6)) + "|n" msg += "\n" + sep + "\n" msg += "".join(line.split("[-]", 1)[1] if "[-]" in line else line for line in lines) msg += "\n" + sep self.msg(msg) return self.msg(prompt="> ") #return self.msg( # "".join(line.split("[-]", 1)[1] if "[-]" in line else line for line in lines) #) class CmdTune(Command): """ Syntax: tune tune <channel> Examples: tune - List channel toggle status. tune <channel> - Toggle the channel on or off. Set the channels you'd like to listen to. """ key = "tune" locks = "cmd:not pperm(channel_banned)" account_caller = True def func(self): caller = self.caller args = self.args.strip() # grab all available channels channels = [ chan for chan in CHANNEL_DEFAULT_TYPECLASS.objects.get_all_channels() if chan.access(caller, "listen") ] if not channels: caller.msg("No channels available.") return # Grab tuned channels. if not args: for channel in channels: if channel.has_connection(caller): caller.msg("Your %s channel is tuned in." % channel.key) else: caller.msg("Your %s channel is tuned out." % channel.key) else: channel = find_channel(caller, args, silent=True, noaliases=True) if channel: # We have given a channel name - flip tune. if not channel.has_connection(caller): if not channel.connect(caller): caller.msg("%s: You are not allowed to join this channel." % channel.key) else: caller.msg("Your %s channel will be tuned in." % channel.key) else: disconnect = channel.disconnect(caller) caller.msg("Your %s chanel will be tuned out." % channel.key)
[ "evennia.utils.logger.tail_log_file", "evennia.utils.utils.class_from_module", "evennia.commands.default.comms.find_channel" ]
[((490, 591), 'evennia.utils.utils.class_from_module', 'class_from_module', (['settings.BASE_CHANNEL_TYPECLASS'], {'fallback': 'settings.FALLBACK_CHANNEL_TYPECLASS'}), '(settings.BASE_CHANNEL_TYPECLASS, fallback=settings.\n FALLBACK_CHANNEL_TYPECLASS)\n', (507, 591), False, 'from evennia.utils.utils import class_from_module\n'), ((1344, 1398), 'evennia.utils.logger.tail_log_file', 'tail_log_file', (['log_file', '(0)', '(15)'], {'callback': 'self.send_msg'}), '(log_file, 0, 15, callback=self.send_msg)\n', (1357, 1398), False, 'from evennia.utils.logger import tail_log_file\n'), ((3005, 3060), 'evennia.commands.default.comms.find_channel', 'find_channel', (['caller', 'args'], {'silent': '(True)', 'noaliases': '(True)'}), '(caller, args, silent=True, noaliases=True)\n', (3017, 3060), False, 'from evennia.commands.default.comms import find_channel\n')]
from django.core.cache import caches from collections import deque from evennia.utils import logger import time from django.utils.translation import gettext as _ class Throttle: """ Keeps a running count of failed actions per IP address. Available methods indicate whether or not the number of failures exceeds a particular threshold. This version of the throttle is usable by both the terminal server as well as the web server, imposes limits on memory consumption by using deques with length limits instead of open-ended lists, and uses native Django caches for automatic key eviction and persistence configurability. """ error_msg = _("Too many failed attempts; you must wait a few minutes before trying again.") def __init__(self, **kwargs): """ Allows setting of throttle parameters. Keyword Args: name (str): Name of this throttle. limit (int): Max number of failures before imposing limiter. If `None`, the throttle is disabled. timeout (int): number of timeout seconds after max number of tries has been reached. cache_size (int): Max number of attempts to record per IP within a rolling window; this is NOT the same as the limit after which the throttle is imposed! """ try: self.storage = caches['throttle'] except Exception: logger.log_trace("Throttle: Errors encountered; using default cache.") self.storage = caches['default'] self.name = kwargs.get('name', 'undefined-throttle') self.limit = kwargs.get("limit", 5) self.cache_size = kwargs.get('cache_size', self.limit) self.timeout = kwargs.get("timeout", 5 * 60) def get_cache_key(self, *args, **kwargs): """ Creates a 'prefixed' key containing arbitrary terms to prevent key collisions in the same namespace. """ return '-'.join((self.name, *args)) def touch(self, key, *args, **kwargs): """ Refreshes the timeout on a given key and ensures it is recorded in the key register. Args: key(str): Key of entry to renew. """ cache_key = self.get_cache_key(key) if self.storage.touch(cache_key, self.timeout): self.record_key(key) def get(self, ip=None): """ Convenience function that returns the storage table, or part of. Args: ip (str, optional): IP address of requestor Returns: storage (dict): When no IP is provided, returns a dict of all current IPs being tracked and the timestamps of their recent failures. timestamps (deque): When an IP is provided, returns a deque of timestamps of recent failures only for that IP. """ if ip: cache_key = self.get_cache_key(str(ip)) return self.storage.get(cache_key, deque(maxlen=self.cache_size)) else: keys_key = self.get_cache_key('keys') keys = self.storage.get_or_set(keys_key, set(), self.timeout) data = self.storage.get_many((self.get_cache_key(x) for x in keys)) found_keys = set(data.keys()) if len(keys) != len(found_keys): self.storage.set(keys_key, found_keys, self.timeout) return data def update(self, ip, failmsg="Exceeded threshold."): """ Store the time of the latest failure. Args: ip (str): IP address of requestor failmsg (str, optional): Message to display in logs upon activation of throttle. Returns: None """ cache_key = self.get_cache_key(ip) # Get current status previously_throttled = self.check(ip) # Get previous failures, if any entries = self.storage.get(cache_key, []) entries.append(time.time()) # Store updated record self.storage.set(cache_key, deque(entries, maxlen=self.cache_size), self.timeout) # See if this update caused a change in status currently_throttled = self.check(ip) # If this makes it engage, log a single activation event if not previously_throttled and currently_throttled: logger.log_sec( f"Throttle Activated: {failmsg} (IP: {ip}, " f"{self.limit} hits in {self.timeout} seconds.)" ) self.record_ip(ip) def remove(self, ip, *args, **kwargs): """ Clears data stored for an IP from the throttle. Args: ip(str): IP to clear. """ exists = self.get(ip) if not exists: return False cache_key = self.get_cache_key(ip) self.storage.delete(cache_key) self.unrecord_ip(ip) # Return True if NOT exists return not bool(self.get(ip)) def record_ip(self, ip, *args, **kwargs): """ Tracks keys as they are added to the cache (since there is no way to get a list of keys after-the-fact). Args: ip(str): IP being added to cache. This should be the original IP, not the cache-prefixed key. """ keys_key = self.get_cache_key('keys') keys = self.storage.get(keys_key, set()) keys.add(ip) self.storage.set(keys_key, keys, self.timeout) return True def unrecord_ip(self, ip, *args, **kwargs): """ Forces removal of a key from the key registry. Args: ip(str): IP to remove from list of keys. """ keys_key = self.get_cache_key('keys') keys = self.storage.get(keys_key, set()) try: keys.remove(ip) self.storage.set(keys_key, keys, self.timeout) return True except KeyError: return False def check(self, ip): """ This will check the session's address against the storage dictionary to check they haven't spammed too many fails recently. Args: ip (str): IP address of requestor Returns: throttled (bool): True if throttling is active, False otherwise. """ if self.limit is None: # throttle is disabled return False now = time.time() ip = str(ip) cache_key = self.get_cache_key(ip) # checking mode latest_fails = self.storage.get(cache_key) if latest_fails and len(latest_fails) >= self.limit: # too many fails recently if now - latest_fails[-1] < self.timeout: # too soon - timeout in play self.touch(cache_key) return True else: # timeout has passed. clear faillist self.remove(ip) return False else: return False
[ "evennia.utils.logger.log_trace", "evennia.utils.logger.log_sec" ]
[((681, 760), 'django.utils.translation.gettext', '_', (['"""Too many failed attempts; you must wait a few minutes before trying again."""'], {}), "('Too many failed attempts; you must wait a few minutes before trying again.')\n", (682, 760), True, 'from django.utils.translation import gettext as _\n'), ((6511, 6522), 'time.time', 'time.time', ([], {}), '()\n', (6520, 6522), False, 'import time\n'), ((4049, 4060), 'time.time', 'time.time', ([], {}), '()\n', (4058, 4060), False, 'import time\n'), ((4130, 4168), 'collections.deque', 'deque', (['entries'], {'maxlen': 'self.cache_size'}), '(entries, maxlen=self.cache_size)\n', (4135, 4168), False, 'from collections import deque\n'), ((4424, 4539), 'evennia.utils.logger.log_sec', 'logger.log_sec', (['f"""Throttle Activated: {failmsg} (IP: {ip}, {self.limit} hits in {self.timeout} seconds.)"""'], {}), "(\n f'Throttle Activated: {failmsg} (IP: {ip}, {self.limit} hits in {self.timeout} seconds.)'\n )\n", (4438, 4539), False, 'from evennia.utils import logger\n'), ((1471, 1541), 'evennia.utils.logger.log_trace', 'logger.log_trace', (['"""Throttle: Errors encountered; using default cache."""'], {}), "('Throttle: Errors encountered; using default cache.')\n", (1487, 1541), False, 'from evennia.utils import logger\n'), ((3051, 3080), 'collections.deque', 'deque', ([], {'maxlen': 'self.cache_size'}), '(maxlen=self.cache_size)\n', (3056, 3080), False, 'from collections import deque\n')]
from .models import GeneratedLootFragment, Shardhaven from typeclasses.bauble import Bauble from typeclasses.wearable.wieldable import Wieldable from evennia.utils import create from server.utils.arx_utils import a_or_an from server.utils.picker import WeightedPicker import random class Trinket(Bauble): @property def type_description(self): return "trinket" @property def potential(self): return 20 + (self.db.quality_level * 10) def quality_level_from_primum(self, primum): return max(int((primum - 20) / 10), 0) class AncientWeapon(Wieldable): @property def type_description(self): if self.recipe: return "ancient %s" % self.recipe.name return "ancient weapon" def do_junkout(self, caller): """Junks us as if we were a crafted item.""" caller.msg("You destroy %s." % self) self.softdelete() return class LootGenerator(object): WPN_SMALL = 0 WPN_MEDIUM = 1 WPN_HUGE = 2 WPN_BOW = 3 @classmethod def set_alignment_and_affinity(cls, haven, obj): from world.magic.models import Alignment, Affinity align_picker = WeightedPicker() for alignment in haven.alignment_chances.all(): align_picker.add(alignment.alignment, alignment.weight) affinity_picker = WeightedPicker() for affinity in haven.affinity_chances.all(): affinity_picker.add(affinity.affinity, affinity.weight) alignment = align_picker.pick() affinity = affinity_picker.pick() if not alignment: alignment = Alignment.PRIMAL if not affinity: affinity = Affinity.objects.order_by('?').first() obj.db.alignment = alignment.id obj.db.affinity = affinity.id @classmethod def create_trinket(cls, haven): name = GeneratedLootFragment.generate_trinket_name() trinket = create.create_object(typeclass="world.exploration.loot.Trinket", key=name) trinket.db.desc = "\nAn ancient trinket, one that feels slightly warm to the touch.\n" quality_picker = WeightedPicker() quality_picker.add_option(4, 25) quality_picker.add_option(5, 45) quality_picker.add_option(6, 30) quality_picker.add_option(7, 10) quality_picker.add_option(8, 3) quality_picker.add_option(9, 1) trinket.db.quality_level = quality_picker.pick() trinket.db.found_shardhaven = haven.name cls.set_alignment_and_affinity(haven, trinket) return trinket @classmethod def get_weapon_recipe(cls, material, wpn_type=WPN_MEDIUM): recipes = { 'steel': { LootGenerator.WPN_SMALL: 105, LootGenerator.WPN_MEDIUM: 111, LootGenerator.WPN_HUGE: 117, LootGenerator.WPN_BOW: 134, }, 'rubicund': { LootGenerator.WPN_SMALL: 106, LootGenerator.WPN_MEDIUM: 112, LootGenerator.WPN_HUGE: 118, LootGenerator.WPN_BOW: 135, }, 'diamondplate': { LootGenerator.WPN_SMALL: 107, LootGenerator.WPN_MEDIUM: 113, LootGenerator.WPN_HUGE: 119, LootGenerator.WPN_BOW: 136, }, 'alaricite': { LootGenerator.WPN_SMALL: 108, LootGenerator.WPN_MEDIUM: 114, LootGenerator.WPN_HUGE: 120, LootGenerator.WPN_BOW: 137, } } return recipes[material][wpn_type] @classmethod def create_weapon(cls, haven, wpn_type=None): weapon_types = (LootGenerator.WPN_SMALL, LootGenerator.WPN_MEDIUM, LootGenerator.WPN_HUGE, LootGenerator.WPN_BOW) if not wpn_type: wpn_type = random.choice(weapon_types) picker = WeightedPicker() difficulty = haven.difficulty_rating if difficulty < 3: picker.add_option("steel", 30) picker.add_option("rubicund", 50) picker.add_option("diamondplate", 1) elif difficulty < 5: picker.add_option("steel", 10) picker.add_option("rubicund", 40) picker.add_option("diamondplate", 5) elif difficulty < 8: picker.add_option("rubicund", 30) picker.add_option("diamondplate", 20) picker.add_option("alaricite", 5) else: picker.add_option("rubicund", 10) picker.add_option("diamondplate", 30) picker.add_option("alaricite", 5) material = picker.pick() should_name = material in ['diamondplate', 'alaricite'] generator_wpn = GeneratedLootFragment.MEDIUM_WEAPON_TYPE if wpn_type == LootGenerator.WPN_SMALL: generator_wpn = GeneratedLootFragment.SMALL_WEAPON_TYPE elif wpn_type == LootGenerator.WPN_HUGE: generator_wpn = GeneratedLootFragment.HUGE_WEAPON_TYPE elif wpn_type == LootGenerator.WPN_BOW: generator_wpn = GeneratedLootFragment.BOW_WEAPON_TYPE name = GeneratedLootFragment.generate_weapon_name(material, include_name=should_name, wpn_type=generator_wpn) weapon = create.create_object(typeclass="world.exploration.loot.AncientWeapon", key=name) desc = "\n{particle} {adjective} ancient {material} weapon, with {decor} on the {element}.\n" if wpn_type == LootGenerator.WPN_BOW: desc = "\n{particle} {adjective} ancient {material} bow, decorated with {decor}.\n" adjective = GeneratedLootFragment.pick_random_fragment(GeneratedLootFragment.ADJECTIVE) decor = GeneratedLootFragment.pick_random_fragment(GeneratedLootFragment.WEAPON_DECORATION) element = GeneratedLootFragment.pick_random_fragment(GeneratedLootFragment.WEAPON_ELEMENT) particle = a_or_an(adjective).capitalize() desc = desc.replace("{particle}", particle) desc = desc.replace("{material}", material) desc = desc.replace("{adjective}", adjective) desc = desc.replace("{decor}", decor) desc = desc.replace("{element}", element) weapon.db.desc = desc quality_picker = WeightedPicker() quality_picker.add_option(4, 25) quality_picker.add_option(5, 45) quality_picker.add_option(6, 30) quality_picker.add_option(7, 10) quality_picker.add_option(8, 3) quality_picker.add_option(9, 1) weapon.db.quality_level = quality_picker.pick() weapon.db.found_shardhaven = haven.name weapon.db.recipe = LootGenerator.get_weapon_recipe(material, wpn_type=wpn_type) cls.set_alignment_and_affinity(haven, weapon) return weapon
[ "evennia.utils.create.create_object" ]
[((1183, 1199), 'server.utils.picker.WeightedPicker', 'WeightedPicker', ([], {}), '()\n', (1197, 1199), False, 'from server.utils.picker import WeightedPicker\n'), ((1351, 1367), 'server.utils.picker.WeightedPicker', 'WeightedPicker', ([], {}), '()\n', (1365, 1367), False, 'from server.utils.picker import WeightedPicker\n'), ((1941, 2015), 'evennia.utils.create.create_object', 'create.create_object', ([], {'typeclass': '"""world.exploration.loot.Trinket"""', 'key': 'name'}), "(typeclass='world.exploration.loot.Trinket', key=name)\n", (1961, 2015), False, 'from evennia.utils import create\n'), ((2137, 2153), 'server.utils.picker.WeightedPicker', 'WeightedPicker', ([], {}), '()\n', (2151, 2153), False, 'from server.utils.picker import WeightedPicker\n'), ((3944, 3960), 'server.utils.picker.WeightedPicker', 'WeightedPicker', ([], {}), '()\n', (3958, 3960), False, 'from server.utils.picker import WeightedPicker\n'), ((5313, 5398), 'evennia.utils.create.create_object', 'create.create_object', ([], {'typeclass': '"""world.exploration.loot.AncientWeapon"""', 'key': 'name'}), "(typeclass='world.exploration.loot.AncientWeapon', key=name\n )\n", (5333, 5398), False, 'from evennia.utils import create\n'), ((6298, 6314), 'server.utils.picker.WeightedPicker', 'WeightedPicker', ([], {}), '()\n', (6312, 6314), False, 'from server.utils.picker import WeightedPicker\n'), ((3898, 3925), 'random.choice', 'random.choice', (['weapon_types'], {}), '(weapon_types)\n', (3911, 3925), False, 'import random\n'), ((5954, 5972), 'server.utils.arx_utils.a_or_an', 'a_or_an', (['adjective'], {}), '(adjective)\n', (5961, 5972), False, 'from server.utils.arx_utils import a_or_an\n'), ((1690, 1720), 'world.magic.models.Affinity.objects.order_by', 'Affinity.objects.order_by', (['"""?"""'], {}), "('?')\n", (1715, 1720), False, 'from world.magic.models import Alignment, Affinity\n')]
from typeclasses.scripts.scripts import Script from . import utils from evennia.utils import create class WeatherScript(Script): def at_script_creation(self): self.key = "Weather Patterns" self.desc = "Keeps weather moving on the game." self.interval = 3600 self.persistent = True self.start_delay = False def at_repeat(self, **kwargs): utils.advance_weather() emit = utils.choose_current_weather() utils.announce_weather(emit) def init_weather(): """ This is called only once, when you want to enable the weather system. """ weather = create.create_script(WeatherScript) weather.start()
[ "evennia.utils.create.create_script" ]
[((630, 665), 'evennia.utils.create.create_script', 'create.create_script', (['WeatherScript'], {}), '(WeatherScript)\n', (650, 665), False, 'from evennia.utils import create\n')]
""" Room Rooms are simple containers that has no location of their own. """ from collections import defaultdict, OrderedDict from evennia import DefaultRoom from evennia.utils.utils import is_iter, make_iter from server.utils.utils import get_sw, list_to_string, wrap class Room(DefaultRoom): """ Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all Objects. """ exit_order = ['north', 'west', 'south', 'east', 'northwest', 'northeast', 'southwest', 'southeast', 'up', 'down'] def msg_contents(self, text=None, exclude=None, from_obj=None, mapping=None, **kwargs): """ Emits a message to all objects inside this object. Args: text (str or tuple): Message to send. If a tuple, this should be on the valid OOB outmessage form `(message, {kwargs})`, where kwargs are optional data passed to the `text` outputfunc. exclude (list, optional): A list of objects not to send to. from_obj (Object, optional): An object designated as the "sender" of the message. See `DefaultObject.msg()` for more info. mapping (dict, optional): A mapping of formatting keys `{"key":<object>, "key2":<object2>,...}. The keys must match `{key}` markers in the `text` if this is a string or in the internal `message` if `text` is a tuple. These formatting statements will be replaced by the return of `<object>.get_display_name(looker)` for every looker in contents that receives the message. This allows for every object to potentially get its own customized string. Keyword Args: Keyword arguments will be passed on to `obj.msg()` for all messaged objects. Notes: The `mapping` argument is required if `message` contains {}-style format syntax. The keys of `mapping` should match named format tokens, and its values will have their `get_display_name()` function called for each object in the room before substitution. If an item in the mapping does not have `get_display_name()`, its string value will be used. Example: Say Char is a Character object and Npc is an NPC object: char.location.msg_contents( "{attacker} kicks {defender}", mapping=dict(attacker=char, defender=npc), exclude=(char, npc)) This will result in everyone in the room seeing 'Char kicks NPC' where everyone may potentially see different results for Char and Npc depending on the results of `char.get_display_name(looker)` and `npc.get_display_name(looker)` for each particular onlooker """ try: if from_obj.db.admin['invis']: return except Exception: pass # we also accept an outcommand on the form (message, {kwargs}) is_outcmd = text and is_iter(text) inmessage = text[0] if is_outcmd else text outkwargs = text[1] if is_outcmd and len(text) > 1 else {} contents = self.contents if exclude: exclude = make_iter(exclude) contents = [obj for obj in contents if obj not in exclude] for obj in contents: if mapping: substitutions = { t: sub.get_display_name(obj) if hasattr(sub, "get_display_name") else str(sub) for t, sub in mapping.items() } outmessage = inmessage.format(**substitutions) else: outmessage = inmessage obj.msg(text=(outmessage, outkwargs), from_obj=from_obj, **kwargs) def return_appearance(self, looker, **kwargs): """ Format s adescription. It is the hook that 'look' calls. Args: looker (Object): Object doing the looking. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default.) """ if not looker: return "" #get and identify all objects visible = (con for con in self.contents if con != looker and con.access(looker, "view")) exits, users, things = defaultdict(list), [], [] #defaultdict(list) #gather visible items for con in visible: key = con.get_display_name(looker) if con.destination: #exits.append(key) exits[con.name] = key elif con.has_account: if not con.db.admin['invis'] or looker.permissions.get('admin'): users.append(con) else: #things can be pluralized #things[key].append(con) things.append(con) string = "|Y%s|n\n" % self.get_display_name(looker) #get description, build string desc = self.db.desc if desc: string += "\n%s\n" % wrap(desc, get_sw(looker), get_sw(looker), indent=2) #function for reordering exits. def _reorder_exits(exits): #create dictionary pair for cardinal exits and custom exits. default_exits = {} custom_exits = {} #determine placement of exits for exit in exits: if exit in self.exit_order: default_exits[exit] = exits[exit] else: custom_exits[exit] = exits[exit] #order cardinal exits by custom defintion default_exits = OrderedDict( sorted( default_exits.items(), key=lambda i: self.exit_order.index(i[0]) ) ) #merge dictionaries and convert to list merged_exits = default_exits | custom_exits ordered_exits = [v for v in merged_exits.values()] return ordered_exits #add exits to string #need to create method to wrap better. Idea: separate caller.msg if exits: exits = _reorder_exits(exits) exits = "|w" + list_to_string(exits) + ".|n" #cut 2 characters from exit_string due to color. exit_string = wrap(exits, get_sw(looker), get_sw(looker), pre_text="|wExits: ", indent=4) else: exit_string = wrap("There are no obvious exits.", get_sw(looker), get_sw(looker), pre_text="|wExits: ", indent=4) string += "\n"+exit_string #add users and contents to string if users: user_string = "" for user in users: rstatus = user.db.rstatus if not rstatus: user_string += "\n" + user.get_display_name(looker) + "." else: user_string += "\n" + user.get_display_name(looker) + f" ({rstatus})." string += "\n" + user_string if things: # handle pluralization of things (never pluralize users) #thing_strings = [] thing_string = "" for item in things: name = item.get_display_name(looker) + "." thing_string += "\n" + name string += "\n" + thing_string #for key, itemlist in sorted(things.items()): #nitem = len(itemlist) #if nitem == 1: # key, _ = itemlist[0].get_numbered_name(nitem, looker, key=key) #else: # key = [item.get_numbered_name(nitem, looker, key=key)[1] for item in itemlist][ # 0 # ] #thing_strings.append(key) #string += '\n' + list_to_string(thing_strings) #"\n|wYou see:|n " + list_to_string(users + thing_strings) return string pass
[ "evennia.utils.utils.is_iter", "evennia.utils.utils.make_iter" ]
[((3395, 3408), 'evennia.utils.utils.is_iter', 'is_iter', (['text'], {}), '(text)\n', (3402, 3408), False, 'from evennia.utils.utils import is_iter, make_iter\n'), ((3603, 3621), 'evennia.utils.utils.make_iter', 'make_iter', (['exclude'], {}), '(exclude)\n', (3612, 3621), False, 'from evennia.utils.utils import is_iter, make_iter\n'), ((4709, 4726), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (4720, 4726), False, 'from collections import defaultdict, OrderedDict\n'), ((6723, 6737), 'server.utils.utils.get_sw', 'get_sw', (['looker'], {}), '(looker)\n', (6729, 6737), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n'), ((6739, 6753), 'server.utils.utils.get_sw', 'get_sw', (['looker'], {}), '(looker)\n', (6745, 6753), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n'), ((6895, 6909), 'server.utils.utils.get_sw', 'get_sw', (['looker'], {}), '(looker)\n', (6901, 6909), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n'), ((6942, 6956), 'server.utils.utils.get_sw', 'get_sw', (['looker'], {}), '(looker)\n', (6948, 6956), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n'), ((5443, 5457), 'server.utils.utils.get_sw', 'get_sw', (['looker'], {}), '(looker)\n', (5449, 5457), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n'), ((5459, 5473), 'server.utils.utils.get_sw', 'get_sw', (['looker'], {}), '(looker)\n', (5465, 5473), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n'), ((6594, 6615), 'server.utils.utils.list_to_string', 'list_to_string', (['exits'], {}), '(exits)\n', (6608, 6615), False, 'from server.utils.utils import get_sw, list_to_string, wrap\n')]
""" Unit tests for the utilities of the evennia.utils.gametime module. """ from datetime import datetime import time import unittest from unittest.mock import Mock from django.conf import settings from django.test import TestCase from evennia.utils import gametime class TestGametime(TestCase): def setUp(self) -> None: self.time = time.time self._SERVER_EPOCH = gametime._SERVER_EPOCH time.time = Mock(return_value=datetime(2019, 4, 18, 13, 49, 38).timestamp()) gametime._SERVER_EPOCH = None gametime.SERVER_RUNTIME = 600.0 gametime.SERVER_START_TIME = time.time() - 300 gametime.SERVER_RUNTIME_LAST_UPDATED = time.time() - 30 gametime.TIMEFACTOR = 5.0 self.timescripts = [] def tearDown(self) -> None: time.time = self.time gametime._SERVER_EPOCH = self._SERVER_EPOCH gametime.SERVER_RUNTIME_LAST_UPDATED = 0.0 gametime.SERVER_RUNTIME = 0.0 gametime.SERVER_START_TIME = 0.0 gametime.TIMEFACTOR = settings.TIME_FACTOR for script in self.timescripts: script.stop() def test_runtime(self): self.assertAlmostEqual(gametime.runtime(), 630.0) def test_server_epoch(self): self.assertAlmostEqual(gametime.server_epoch(), time.time() - 630.0) def test_uptime(self): self.assertAlmostEqual(gametime.uptime(), 300.0) def test_game_epoch_no_setting(self): self.assertAlmostEqual(gametime.game_epoch(), gametime.server_epoch()) def test_game_epoch_setting(self): with self.settings(TIME_GAME_EPOCH=0): self.assertEqual(gametime.game_epoch(), 0) def test_gametime_simple(self): self.assertAlmostEqual(gametime.gametime(), 630.0 * 5) def test_gametime_absolute(self): self.assertAlmostEqual( gametime.gametime(absolute=True), datetime(2019, 4, 18, 14, 31, 38).timestamp() ) def test_gametime_downtimes(self): gametime.IGNORE_DOWNTIMES = True self.assertAlmostEqual(gametime.gametime(), 630 * 5.0) gametime.IGNORE_DOWNTIMES = False def test_real_seconds_until(self): # using the gametime value above, we are working from the following # datetime: datetime.datetime(2019, 4, 18, 14, 31, 38, 245449) self.assertAlmostEqual(gametime.real_seconds_until(sec=48), 2) self.assertAlmostEqual(gametime.real_seconds_until(min=32), 12) self.assertAlmostEqual(gametime.real_seconds_until(hour=15), 720) self.assertAlmostEqual(gametime.real_seconds_until(day=19), 17280) self.assertAlmostEqual(gametime.real_seconds_until(month=5), 518400) self.assertAlmostEqual(gametime.real_seconds_until(year=2020), 6324480) def test_real_seconds_until_behind(self): self.assertAlmostEqual(gametime.real_seconds_until(sec=28), 10) self.assertAlmostEqual(gametime.real_seconds_until(min=30), 708) self.assertAlmostEqual(gametime.real_seconds_until(hour=13), 16560) self.assertAlmostEqual(gametime.real_seconds_until(day=17), 501120) self.assertAlmostEqual(gametime.real_seconds_until(month=1), 4752000) def test_real_seconds_until_leap_year(self): self.assertAlmostEqual(gametime.real_seconds_until(month=3), 5788800) def test_schedule(self): callback = Mock() script = gametime.schedule(callback, day=19) self.timescripts.append(script) self.assertIsInstance(script, gametime.TimeScript) self.assertAlmostEqual(script.interval, 17280) self.assertEqual(script.repeats, 1) def test_repeat_schedule(self): callback = Mock() script = gametime.schedule(callback, repeat=True, min=32) self.timescripts.append(script) self.assertIsInstance(script, gametime.TimeScript) self.assertAlmostEqual(script.interval, 12) self.assertEqual(script.repeats, 0)
[ "evennia.utils.gametime.runtime", "evennia.utils.gametime.schedule", "evennia.utils.gametime.real_seconds_until", "evennia.utils.gametime.gametime", "evennia.utils.gametime.uptime", "evennia.utils.gametime.game_epoch", "evennia.utils.gametime.server_epoch" ]
[((3360, 3366), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (3364, 3366), False, 'from unittest.mock import Mock\n'), ((3384, 3419), 'evennia.utils.gametime.schedule', 'gametime.schedule', (['callback'], {'day': '(19)'}), '(callback, day=19)\n', (3401, 3419), False, 'from evennia.utils import gametime\n'), ((3674, 3680), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (3678, 3680), False, 'from unittest.mock import Mock\n'), ((3698, 3746), 'evennia.utils.gametime.schedule', 'gametime.schedule', (['callback'], {'repeat': '(True)', 'min': '(32)'}), '(callback, repeat=True, min=32)\n', (3715, 3746), False, 'from evennia.utils import gametime\n'), ((611, 622), 'time.time', 'time.time', ([], {}), '()\n', (620, 622), False, 'import time\n'), ((676, 687), 'time.time', 'time.time', ([], {}), '()\n', (685, 687), False, 'import time\n'), ((1179, 1197), 'evennia.utils.gametime.runtime', 'gametime.runtime', ([], {}), '()\n', (1195, 1197), False, 'from evennia.utils import gametime\n'), ((1271, 1294), 'evennia.utils.gametime.server_epoch', 'gametime.server_epoch', ([], {}), '()\n', (1292, 1294), False, 'from evennia.utils import gametime\n'), ((1376, 1393), 'evennia.utils.gametime.uptime', 'gametime.uptime', ([], {}), '()\n', (1391, 1393), False, 'from evennia.utils import gametime\n'), ((1476, 1497), 'evennia.utils.gametime.game_epoch', 'gametime.game_epoch', ([], {}), '()\n', (1495, 1497), False, 'from evennia.utils import gametime\n'), ((1499, 1522), 'evennia.utils.gametime.server_epoch', 'gametime.server_epoch', ([], {}), '()\n', (1520, 1522), False, 'from evennia.utils import gametime\n'), ((1734, 1753), 'evennia.utils.gametime.gametime', 'gametime.gametime', ([], {}), '()\n', (1751, 1753), False, 'from evennia.utils import gametime\n'), ((1849, 1881), 'evennia.utils.gametime.gametime', 'gametime.gametime', ([], {'absolute': '(True)'}), '(absolute=True)\n', (1866, 1881), False, 'from evennia.utils import gametime\n'), ((2051, 2070), 'evennia.utils.gametime.gametime', 'gametime.gametime', ([], {}), '()\n', (2068, 2070), False, 'from evennia.utils import gametime\n'), ((2343, 2378), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'sec': '(48)'}), '(sec=48)\n', (2370, 2378), False, 'from evennia.utils import gametime\n'), ((2414, 2449), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'min': '(32)'}), '(min=32)\n', (2441, 2449), False, 'from evennia.utils import gametime\n'), ((2486, 2522), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'hour': '(15)'}), '(hour=15)\n', (2513, 2522), False, 'from evennia.utils import gametime\n'), ((2560, 2595), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'day': '(19)'}), '(day=19)\n', (2587, 2595), False, 'from evennia.utils import gametime\n'), ((2635, 2671), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'month': '(5)'}), '(month=5)\n', (2662, 2671), False, 'from evennia.utils import gametime\n'), ((2712, 2750), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'year': '(2020)'}), '(year=2020)\n', (2739, 2750), False, 'from evennia.utils import gametime\n'), ((2839, 2874), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'sec': '(28)'}), '(sec=28)\n', (2866, 2874), False, 'from evennia.utils import gametime\n'), ((2911, 2946), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'min': '(30)'}), '(min=30)\n', (2938, 2946), False, 'from evennia.utils import gametime\n'), ((2984, 3020), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'hour': '(13)'}), '(hour=13)\n', (3011, 3020), False, 'from evennia.utils import gametime\n'), ((3060, 3095), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'day': '(17)'}), '(day=17)\n', (3087, 3095), False, 'from evennia.utils import gametime\n'), ((3136, 3172), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'month': '(1)'}), '(month=1)\n', (3163, 3172), False, 'from evennia.utils import gametime\n'), ((3264, 3300), 'evennia.utils.gametime.real_seconds_until', 'gametime.real_seconds_until', ([], {'month': '(3)'}), '(month=3)\n', (3291, 3300), False, 'from evennia.utils import gametime\n'), ((1296, 1307), 'time.time', 'time.time', ([], {}), '()\n', (1305, 1307), False, 'import time\n'), ((1640, 1661), 'evennia.utils.gametime.game_epoch', 'gametime.game_epoch', ([], {}), '()\n', (1659, 1661), False, 'from evennia.utils import gametime\n'), ((1883, 1916), 'datetime.datetime', 'datetime', (['(2019)', '(4)', '(18)', '(14)', '(31)', '(38)'], {}), '(2019, 4, 18, 14, 31, 38)\n', (1891, 1916), False, 'from datetime import datetime\n'), ((449, 482), 'datetime.datetime', 'datetime', (['(2019)', '(4)', '(18)', '(13)', '(49)', '(38)'], {}), '(2019, 4, 18, 13, 49, 38)\n', (457, 482), False, 'from datetime import datetime\n')]
""" This defines how Comm models are displayed in the web admin interface. """ from django import forms from django.contrib import admin from evennia.comms.models import ChannelDB, Msg from django.conf import settings from .attributes import AttributeInline from .tags import TagInline class MsgTagInline(TagInline): """ Inline display for Msg-tags. """ model = Msg.db_tags.through related_field = "msg" class MsgForm(forms.ModelForm): """ Custom Msg form. """ class Meta: models = Msg fields = "__all__" db_header = forms.CharField( label="Header", required=False, widget=forms.Textarea(attrs={"cols": "100", "rows": "2"}), help_text="Optional header for the message; it could be a title or " "metadata depending on msg-use." ) db_lock_storage = forms.CharField( label="Locks", required=False, widget=forms.Textarea(attrs={"cols": "100", "rows": "2"}), help_text="In-game lock definition string. If not given, defaults will be used. " "This string should be on the form " "<i>type:lockfunction(args);type2:lockfunction2(args);...", ) @admin.register(Msg) class MsgAdmin(admin.ModelAdmin): """ Defines display for Msg objects """ inlines = [MsgTagInline] form = MsgForm list_display = ( "id", "db_date_created", "sender", "receiver", "start_of_message", ) list_display_links = ("id", "db_date_created", "start_of_message") ordering = ["-db_date_created", "-id"] search_fields = ["=id", "^db_date_created", "^db_message", "^db_sender_accounts__db_key", "^db_sender_objects__db_key", "^db_sender_scripts__db_key", "^db_sender_external", "^db_receivers_accounts__db_key", "^db_receivers_objects__db_key", "^db_receivers_scripts__db_key", "^db_receiver_external"] readonly_fields = ["db_date_created", "serialized_string"] save_as = True save_on_top = True list_select_related = True view_on_site = False raw_id_fields = ( "db_sender_accounts", "db_sender_objects", "db_sender_scripts", "db_receivers_accounts", "db_receivers_objects", "db_receivers_scripts", "db_hide_from_accounts", "db_hide_from_objects") fieldsets = ( ( None, { "fields": ( ("db_sender_accounts", "db_sender_objects", "db_sender_scripts", "db_sender_external"), ("db_receivers_accounts", "db_receivers_objects", "db_receivers_scripts", "db_receiver_external"), ("db_hide_from_accounts", "db_hide_from_objects"), "db_header", "db_message", "serialized_string" ) }, ), ) def sender(self, obj): senders = [o for o in obj.senders if o] if senders: return senders[0] sender.help_text = "If multiple, only the first is shown." def receiver(self, obj): receivers = [o for o in obj.receivers if o] if receivers: return receivers[0] receiver.help_text = "If multiple, only the first is shown." def start_of_message(self, obj): crop_length = 50 if obj.db_message: msg = obj.db_message if len(msg) > (crop_length - 5): msg = msg[:50] + "[...]" return msg def serialized_string(self, obj): """ Get the serialized version of the object. """ from evennia.utils import dbserialize return str(dbserialize.pack_dbobj(obj)) serialized_string.help_text = ( "Copy & paste this string into an Attribute's `value` field to store it there." ) def get_form(self, request, obj=None, **kwargs): """ Overrides help texts. """ help_texts = kwargs.get("help_texts", {}) help_texts["serialized_string"] = self.serialized_string.help_text kwargs["help_texts"] = help_texts return super().get_form(request, obj, **kwargs) class ChannelAttributeInline(AttributeInline): """ Inline display of Channel Attribute - experimental """ model = ChannelDB.db_attributes.through related_field = "channeldb" class ChannelTagInline(TagInline): """ Inline display of Channel Tags - experimental """ model = ChannelDB.db_tags.through related_field = "channeldb" class ChannelForm(forms.ModelForm): """ Form for accessing channels. """ class Meta: model = ChannelDB fields = "__all__" db_lock_storage = forms.CharField( label="Locks", required=False, widget=forms.Textarea(attrs={"cols": "100", "rows": "2"}), help_text="In-game lock definition string. If not given, defaults will be used. " "This string should be on the form " "<i>type:lockfunction(args);type2:lockfunction2(args);...", ) @admin.register(ChannelDB) class ChannelAdmin(admin.ModelAdmin): """ Defines display for Channel objects """ inlines = [ChannelTagInline, ChannelAttributeInline] form = ChannelForm list_display = ("id", "db_key", "no_of_subscribers", "db_lock_storage", "db_typeclass_path", "db_date_created") list_display_links = ("id", "db_key") ordering = ["-db_date_created", "-id", "-db_key"] search_fields = ["id", "db_key", "db_tags__db_key"] readonly_fields = ["serialized_string"] save_as = True save_on_top = True list_select_related = True raw_id_fields = ("db_object_subscriptions", "db_account_subscriptions") fieldsets = ( ( None, { "fields": ( ("db_key",), "db_lock_storage", "db_account_subscriptions", "db_object_subscriptions", "serialized_string" ) }, ), ) def subscriptions(self, obj): """ Helper method to get subs from a channel. Args: obj (Channel): The channel to get subs from. """ return ", ".join([str(sub) for sub in obj.subscriptions.all()]) def no_of_subscribers(self, obj): """ Get number of subs for a a channel . Args: obj (Channel): The channel to get subs from. """ return sum(1 for sub in obj.subscriptions.all()) def serialized_string(self, obj): """ Get the serialized version of the object. """ from evennia.utils import dbserialize return str(dbserialize.pack_dbobj(obj)) serialized_string.help_text = ( "Copy & paste this string into an Attribute's `value` field to store it there." ) def get_form(self, request, obj=None, **kwargs): """ Overrides help texts. """ help_texts = kwargs.get("help_texts", {}) help_texts["serialized_string"] = self.serialized_string.help_text kwargs["help_texts"] = help_texts return super().get_form(request, obj, **kwargs) def save_model(self, request, obj, form, change): """ Model-save hook. Args: request (Request): Incoming request. obj (Object): Database object. form (Form): Form instance. change (bool): If this is a change or a new object. """ obj.save() if not change: # adding a new object # have to call init with typeclass passed to it obj.set_class_from_typeclass(typeclass_path=settings.BASE_CHANNEL_TYPECLASS) obj.at_init() def response_add(self, request, obj, post_url_continue=None): from django.http import HttpResponseRedirect from django.urls import reverse return HttpResponseRedirect(reverse("admin:comms_channeldb_change", args=[obj.id]))
[ "evennia.utils.dbserialize.pack_dbobj" ]
[((1216, 1235), 'django.contrib.admin.register', 'admin.register', (['Msg'], {}), '(Msg)\n', (1230, 1235), False, 'from django.contrib import admin\n'), ((5134, 5159), 'django.contrib.admin.register', 'admin.register', (['ChannelDB'], {}), '(ChannelDB)\n', (5148, 5159), False, 'from django.contrib import admin\n'), ((663, 713), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'cols': '100', 'rows': '2'}"}), "(attrs={'cols': '100', 'rows': '2'})\n", (677, 713), False, 'from django import forms\n'), ((951, 1001), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'cols': '100', 'rows': '2'}"}), "(attrs={'cols': '100', 'rows': '2'})\n", (965, 1001), False, 'from django import forms\n'), ((3745, 3772), 'evennia.utils.dbserialize.pack_dbobj', 'dbserialize.pack_dbobj', (['obj'], {}), '(obj)\n', (3767, 3772), False, 'from evennia.utils import dbserialize\n'), ((4870, 4920), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'cols': '100', 'rows': '2'}"}), "(attrs={'cols': '100', 'rows': '2'})\n", (4884, 4920), False, 'from django import forms\n'), ((6833, 6860), 'evennia.utils.dbserialize.pack_dbobj', 'dbserialize.pack_dbobj', (['obj'], {}), '(obj)\n', (6855, 6860), False, 'from evennia.utils import dbserialize\n'), ((8085, 8139), 'django.urls.reverse', 'reverse', (['"""admin:comms_channeldb_change"""'], {'args': '[obj.id]'}), "('admin:comms_channeldb_change', args=[obj.id])\n", (8092, 8139), False, 'from django.urls import reverse\n')]
""" Tests of create functions """ from evennia.utils.test_resources import EvenniaTest from evennia.scripts.scripts import DefaultScript from evennia.utils import create class TestCreateScript(EvenniaTest): def test_create_script(self): class TestScriptA(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.persistent = False script = create.create_script(TestScriptA, key="test_script") assert script is not None assert script.interval == 10 assert script.key == "test_script" script.stop() def test_create_script_w_repeats_equal_1(self): class TestScriptB(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 1 self.persistent = False # script is already stopped (interval=1, start_delay=False) script = create.create_script(TestScriptB, key="test_script") assert script is None def test_create_script_w_repeats_equal_1_persisted(self): class TestScriptB1(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 1 self.persistent = True # script is already stopped (interval=1, start_delay=False) script = create.create_script(TestScriptB1, key="test_script") assert script is None def test_create_script_w_repeats_equal_2(self): class TestScriptC(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 2 self.persistent = False script = create.create_script(TestScriptC, key="test_script") assert script is not None assert script.interval == 10 assert script.repeats == 2 assert script.key == "test_script" script.stop() def test_create_script_w_repeats_equal_1_and_delayed(self): class TestScriptD(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.start_delay = True self.repeats = 1 self.persistent = False script = create.create_script(TestScriptD, key="test_script") assert script is not None assert script.interval == 10 assert script.repeats == 1 assert script.key == "test_script" script.stop()
[ "evennia.utils.create.create_script" ]
[((463, 515), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptA'], {'key': '"""test_script"""'}), "(TestScriptA, key='test_script')\n", (483, 515), False, 'from evennia.utils import create\n'), ((1024, 1076), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptB'], {'key': '"""test_script"""'}), "(TestScriptB, key='test_script')\n", (1044, 1076), False, 'from evennia.utils import create\n'), ((1489, 1542), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptB1'], {'key': '"""test_script"""'}), "(TestScriptB1, key='test_script')\n", (1509, 1542), False, 'from evennia.utils import create\n'), ((1877, 1929), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptC'], {'key': '"""test_script"""'}), "(TestScriptC, key='test_script')\n", (1897, 1929), False, 'from evennia.utils import create\n'), ((2457, 2509), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptD'], {'key': '"""test_script"""'}), "(TestScriptD, key='test_script')\n", (2477, 2509), False, 'from evennia.utils import create\n')]
""" This module implements the telnet protocol. This depends on a generic session module that implements the actual login procedure of the game, tracks sessions etc. """ import re from twisted.internet import protocol from twisted.internet.task import LoopingCall from twisted.conch.telnet import Telnet, StatefulTelnetProtocol from twisted.conch.telnet import IAC, NOP, LINEMODE, GA, WILL, WONT, ECHO, NULL from django.conf import settings from evennia.server.session import Session from evennia.server.portal import ttype, mssp, telnet_oob, naws, suppress_ga from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP from evennia.server.portal.mxp import Mxp, mxp_parse from evennia.utils import ansi from evennia.utils.utils import to_str _RE_N = re.compile(r"\|n$") _RE_LEND = re.compile(r"\n$|\r$|\r\n$|\r\x00$|", re.MULTILINE) _RE_LINEBREAK = re.compile(r"\n\r|\r\n|\n|\r", re.DOTALL + re.MULTILINE) _RE_SCREENREADER_REGEX = re.compile(r"%s" % settings.SCREENREADER_REGEX_STRIP, re.DOTALL + re.MULTILINE) _IDLE_COMMAND = settings.IDLE_COMMAND + "\n" class TelnetServerFactory(protocol.ServerFactory): "This is only to name this better in logs" noisy = False def logPrefix(self): return "Telnet" class TelnetProtocol(Telnet, StatefulTelnetProtocol, Session): """ Each player connecting over telnet (ie using most traditional mud clients) gets a telnet protocol instance assigned to them. All communication between game and player goes through here. """ def __init__(self, *args, **kwargs): super(TelnetProtocol, self).__init__(*args, **kwargs) self.protocol_key = "telnet" def connectionMade(self): """ This is called when the connection is first established. """ # initialize the session self.line_buffer = "" client_address = self.transport.client client_address = client_address[0] if client_address else None # this number is counted down for every handshake that completes. # when it reaches 0 the portal/server syncs their data self.handshakes = 8 # suppress-go-ahead, naws, ttype, mccp, mssp, msdp, gmcp, mxp self.init_session(self.protocol_key, client_address, self.factory.sessionhandler) self.protocol_flags["ENCODING"] = settings.ENCODINGS[0] if settings.ENCODINGS else 'utf-8' # add this new connection to sessionhandler so # the Server becomes aware of it. self.sessionhandler.connect(self) # change encoding to ENCODINGS[0] which reflects Telnet default encoding # suppress go-ahead self.sga = suppress_ga.SuppressGA(self) # negotiate client size self.naws = naws.Naws(self) # negotiate ttype (client info) # Obs: mudlet ttype does not seem to work if we start mccp before ttype. /Griatch self.ttype = ttype.Ttype(self) # negotiate mccp (data compression) - turn this off for wireshark analysis self.mccp = Mccp(self) # negotiate mssp (crawler communication) self.mssp = mssp.Mssp(self) # oob communication (MSDP, GMCP) - two handshake calls! self.oob = telnet_oob.TelnetOOB(self) # mxp support self.mxp = Mxp(self) from evennia.utils.utils import delay # timeout the handshakes in case the client doesn't reply at all self._handshake_delay = delay(2, callback=self.handshake_done, timeout=True) # TCP/IP keepalive watches for dead links self.transport.setTcpKeepAlive(1) # The TCP/IP keepalive is not enough for some networks; # we have to complement it with a NOP keep-alive. self.protocol_flags["NOPKEEPALIVE"] = True self.nop_keep_alive = None self.toggle_nop_keepalive() def _send_nop_keepalive(self): """Send NOP keepalive unless flag is set""" if self.protocol_flags.get("NOPKEEPALIVE"): self._write(IAC + NOP) def toggle_nop_keepalive(self): """ Allow to toggle the NOP keepalive for those sad clients that can't even handle a NOP instruction. This is turned off by the protocol_flag NOPKEEPALIVE (settable e.g. by the default `@option` command). """ if self.nop_keep_alive and self.nop_keep_alive.running: self.nop_keep_alive.stop() else: self.nop_keep_alive = LoopingCall(self._send_nop_keepalive) self.nop_keep_alive.start(30, now=False) def handshake_done(self, timeout=False): """ This is called by all telnet extensions once they are finished. When all have reported, a sync with the server is performed. The system will force-call this sync after a small time to handle clients that don't reply to handshakes at all. """ if timeout: if self.handshakes > 0: self.handshakes = 0 self.sessionhandler.sync(self) else: self.handshakes -= 1 if self.handshakes <= 0: # do the sync self.sessionhandler.sync(self) def at_login(self): """ Called when this session gets authenticated by the server. """ pass def enableRemote(self, option): """ This sets up the remote-activated options we allow for this protocol. Args: option (char): The telnet option to enable. Returns: enable (bool): If this option should be enabled. """ return (option == LINEMODE or option == ttype.TTYPE or option == naws.NAWS or option == MCCP or option == mssp.MSSP or option == suppress_ga.SUPPRESS_GA) def enableLocal(self, option): """ Call to allow the activation of options for this protocol Args: option (char): The telnet option to enable locally. Returns: enable (bool): If this option should be enabled. """ return (option == MCCP or option == ECHO or option == suppress_ga.SUPPRESS_GA) def disableLocal(self, option): """ Disable a given option locally. Args: option (char): The telnet option to disable locally. """ if option == ECHO: return True if option == MCCP: self.mccp.no_mccp(option) return True else: return super(TelnetProtocol, self).disableLocal(option) def connectionLost(self, reason): """ this is executed when the connection is lost for whatever reason. it can also be called directly, from the disconnect method Args: reason (str): Motivation for losing connection. """ self.sessionhandler.disconnect(self) self.transport.loseConnection() def applicationDataReceived(self, data): """ Telnet method called when non-telnet-command data is coming in over the telnet connection. We pass it on to the game engine directly. Args: data (str): Incoming data. """ if not data: data = [data] elif data.strip() == NULL: # this is an ancient type of keepalive used by some # legacy clients. There should never be a reason to send a # lone NULL character so this seems to be a safe thing to # support for backwards compatibility. It also stops the # NULL from continuously popping up as an unknown command. data = [_IDLE_COMMAND] else: data = _RE_LINEBREAK.split(data) if self.line_buffer and len(data) > 1: # buffer exists, it is terminated by the first line feed data[0] = self.line_buffer + data[0] self.line_buffer = "" # if the last data split is empty, it means all splits have # line breaks, if not, it is unterminated and must be # buffered. self.line_buffer += data.pop() # send all data chunks for dat in data: self.data_in(text=dat + "\n") def _write(self, data): """hook overloading the one used in plain telnet""" data = data.replace('\n', '\r\n').replace('\r\r\n', '\r\n') super(TelnetProtocol, self)._write(mccp_compress(self, data)) def sendLine(self, line): """ Hook overloading the one used by linereceiver. Args: line (str): Line to send. """ # escape IAC in line mode, and correctly add \r\n (the TELNET end-of-line) line = line.replace(IAC, IAC + IAC) line = line.replace('\n', '\r\n') if not line.endswith("\r\n") and self.protocol_flags.get("FORCEDENDLINE", True): line += "\r\n" if not self.protocol_flags.get("NOGOAHEAD", True): line += IAC + GA return self.transport.write(mccp_compress(self, line)) # Session hooks def disconnect(self, reason=""): """ generic hook for the engine to call in order to disconnect this protocol. Args: reason (str, optional): Reason for disconnecting. """ self.data_out(text=((reason,), {})) self.connectionLost(reason) def data_in(self, **kwargs): """ Data User -> Evennia Kwargs: kwargs (any): Options from the protocol. """ # from evennia.server.profiling.timetrace import timetrace # DEBUG # text = timetrace(text, "telnet.data_in") # DEBUG self.sessionhandler.data_in(self, **kwargs) def data_out(self, **kwargs): """ Data Evennia -> User Kwargs: kwargs (any): Options to the protocol """ self.sessionhandler.data_out(self, **kwargs) # send_* methods def send_text(self, *args, **kwargs): """ Send text data. This is an in-band telnet operation. Args: text (str): The first argument is always the text string to send. No other arguments are considered. Kwargs: options (dict): Send-option flags - mxp: Enforce MXP link support. - ansi: Enforce no ANSI colors. - xterm256: Enforce xterm256 colors, regardless of TTYPE. - noxterm256: Enforce no xterm256 color support, regardless of TTYPE. - nocolor: Strip all Color, regardless of ansi/xterm256 setting. - raw: Pass string through without any ansi processing (i.e. include Evennia ansi markers but do not convert them into ansi tokens) - echo: Turn on/off line echo on the client. Turn off line echo for client, for example for password. Note that it must be actively turned back on again! """ text = args[0] if args else "" if text is None: return text = to_str(text, force_string=True) # handle arguments options = kwargs.get("options", {}) flags = self.protocol_flags xterm256 = options.get("xterm256", flags.get('XTERM256', False) if flags.get("TTYPE", False) else True) useansi = options.get("ansi", flags.get('ANSI', False) if flags.get("TTYPE", False) else True) raw = options.get("raw", flags.get("RAW", False)) nocolor = options.get("nocolor", flags.get("NOCOLOR") or not (xterm256 or useansi)) echo = options.get("echo", None) mxp = options.get("mxp", flags.get("MXP", False)) screenreader = options.get("screenreader", flags.get("SCREENREADER", False)) if screenreader: # screenreader mode cleans up output text = ansi.parse_ansi(text, strip_ansi=True, xterm256=False, mxp=False) text = _RE_SCREENREADER_REGEX.sub("", text) if options.get("send_prompt"): # send a prompt instead. prompt = text if not raw: # processing prompt = ansi.parse_ansi(_RE_N.sub("", prompt) + ("||n" if prompt.endswith("|") else "|n"), strip_ansi=nocolor, xterm256=xterm256) if mxp: prompt = mxp_parse(prompt) prompt = prompt.replace(IAC, IAC + IAC).replace('\n', '\r\n') prompt += IAC + GA self.transport.write(mccp_compress(self, prompt)) else: if echo is not None: # turn on/off echo. Note that this is a bit turned around since we use # echo as if we are "turning off the client's echo" when telnet really # handles it the other way around. if echo: # by telling the client that WE WON'T echo, the client knows # that IT should echo. This is the expected behavior from # our perspective. self.transport.write(mccp_compress(self, IAC + WONT + ECHO)) else: # by telling the client that WE WILL echo, the client can # safely turn OFF its OWN echo. self.transport.write(mccp_compress(self, IAC + WILL + ECHO)) if raw: # no processing self.sendLine(text) return else: # we need to make sure to kill the color at the end in order # to match the webclient output. linetosend = ansi.parse_ansi(_RE_N.sub("", text) + ("||n" if text.endswith("|") else "|n"), strip_ansi=nocolor, xterm256=xterm256, mxp=mxp) if mxp: linetosend = mxp_parse(linetosend) self.sendLine(linetosend) def send_prompt(self, *args, **kwargs): """ Send a prompt - a text without a line end. See send_text for argument options. """ kwargs["options"].update({"send_prompt": True}) self.send_text(*args, **kwargs) def send_default(self, cmdname, *args, **kwargs): """ Send other oob data """ if not cmdname == "options": self.oob.data_out(cmdname, *args, **kwargs)
[ "evennia.server.portal.suppress_ga.SuppressGA", "evennia.utils.ansi.parse_ansi", "evennia.server.portal.naws.Naws", "evennia.server.portal.telnet_oob.TelnetOOB", "evennia.server.portal.mccp.Mccp", "evennia.server.portal.ttype.Ttype", "evennia.utils.utils.to_str", "evennia.server.portal.mccp.mccp_compr...
[((761, 780), 're.compile', 're.compile', (['"""\\\\|n$"""'], {}), "('\\\\|n$')\n", (771, 780), False, 'import re\n'), ((792, 848), 're.compile', 're.compile', (['"""\\\\n$|\\\\r$|\\\\r\\\\n$|\\\\r\\\\x00$|"""', 're.MULTILINE'], {}), "('\\\\n$|\\\\r$|\\\\r\\\\n$|\\\\r\\\\x00$|', re.MULTILINE)\n", (802, 848), False, 'import re\n'), ((860, 921), 're.compile', 're.compile', (['"""\\\\n\\\\r|\\\\r\\\\n|\\\\n|\\\\r"""', '(re.DOTALL + re.MULTILINE)'], {}), "('\\\\n\\\\r|\\\\r\\\\n|\\\\n|\\\\r', re.DOTALL + re.MULTILINE)\n", (870, 921), False, 'import re\n'), ((942, 1020), 're.compile', 're.compile', (["('%s' % settings.SCREENREADER_REGEX_STRIP)", '(re.DOTALL + re.MULTILINE)'], {}), "('%s' % settings.SCREENREADER_REGEX_STRIP, re.DOTALL + re.MULTILINE)\n", (952, 1020), False, 'import re\n'), ((2644, 2672), 'evennia.server.portal.suppress_ga.SuppressGA', 'suppress_ga.SuppressGA', (['self'], {}), '(self)\n', (2666, 2672), False, 'from evennia.server.portal import ttype, mssp, telnet_oob, naws, suppress_ga\n'), ((2725, 2740), 'evennia.server.portal.naws.Naws', 'naws.Naws', (['self'], {}), '(self)\n', (2734, 2740), False, 'from evennia.server.portal import ttype, mssp, telnet_oob, naws, suppress_ga\n'), ((2892, 2909), 'evennia.server.portal.ttype.Ttype', 'ttype.Ttype', (['self'], {}), '(self)\n', (2903, 2909), False, 'from evennia.server.portal import ttype, mssp, telnet_oob, naws, suppress_ga\n'), ((3013, 3023), 'evennia.server.portal.mccp.Mccp', 'Mccp', (['self'], {}), '(self)\n', (3017, 3023), False, 'from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP\n'), ((3093, 3108), 'evennia.server.portal.mssp.Mssp', 'mssp.Mssp', (['self'], {}), '(self)\n', (3102, 3108), False, 'from evennia.server.portal import ttype, mssp, telnet_oob, naws, suppress_ga\n'), ((3192, 3218), 'evennia.server.portal.telnet_oob.TelnetOOB', 'telnet_oob.TelnetOOB', (['self'], {}), '(self)\n', (3212, 3218), False, 'from evennia.server.portal import ttype, mssp, telnet_oob, naws, suppress_ga\n'), ((3260, 3269), 'evennia.server.portal.mxp.Mxp', 'Mxp', (['self'], {}), '(self)\n', (3263, 3269), False, 'from evennia.server.portal.mxp import Mxp, mxp_parse\n'), ((3422, 3474), 'evennia.utils.utils.delay', 'delay', (['(2)'], {'callback': 'self.handshake_done', 'timeout': '(True)'}), '(2, callback=self.handshake_done, timeout=True)\n', (3427, 3474), False, 'from evennia.utils.utils import delay\n'), ((11268, 11299), 'evennia.utils.utils.to_str', 'to_str', (['text'], {'force_string': '(True)'}), '(text, force_string=True)\n', (11274, 11299), False, 'from evennia.utils.utils import to_str\n'), ((4432, 4469), 'twisted.internet.task.LoopingCall', 'LoopingCall', (['self._send_nop_keepalive'], {}), '(self._send_nop_keepalive)\n', (4443, 4469), False, 'from twisted.internet.task import LoopingCall\n'), ((8527, 8552), 'evennia.server.portal.mccp.mccp_compress', 'mccp_compress', (['self', 'data'], {}), '(self, data)\n', (8540, 8552), False, 'from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP\n'), ((9127, 9152), 'evennia.server.portal.mccp.mccp_compress', 'mccp_compress', (['self', 'line'], {}), '(self, line)\n', (9140, 9152), False, 'from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP\n'), ((12051, 12116), 'evennia.utils.ansi.parse_ansi', 'ansi.parse_ansi', (['text'], {'strip_ansi': '(True)', 'xterm256': '(False)', 'mxp': '(False)'}), '(text, strip_ansi=True, xterm256=False, mxp=False)\n', (12066, 12116), False, 'from evennia.utils import ansi\n'), ((12726, 12753), 'evennia.server.portal.mccp.mccp_compress', 'mccp_compress', (['self', 'prompt'], {}), '(self, prompt)\n', (12739, 12753), False, 'from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP\n'), ((12570, 12587), 'evennia.server.portal.mxp.mxp_parse', 'mxp_parse', (['prompt'], {}), '(prompt)\n', (12579, 12587), False, 'from evennia.server.portal.mxp import Mxp, mxp_parse\n'), ((14077, 14098), 'evennia.server.portal.mxp.mxp_parse', 'mxp_parse', (['linetosend'], {}), '(linetosend)\n', (14086, 14098), False, 'from evennia.server.portal.mxp import Mxp, mxp_parse\n'), ((13291, 13329), 'evennia.server.portal.mccp.mccp_compress', 'mccp_compress', (['self', '(IAC + WONT + ECHO)'], {}), '(self, IAC + WONT + ECHO)\n', (13304, 13329), False, 'from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP\n'), ((13524, 13562), 'evennia.server.portal.mccp.mccp_compress', 'mccp_compress', (['self', '(IAC + WILL + ECHO)'], {}), '(self, IAC + WILL + ECHO)\n', (13537, 13562), False, 'from evennia.server.portal.mccp import Mccp, mccp_compress, MCCP\n')]
""" Comsystem command module. Comm commands are OOC commands and intended to be made available to the Account at all times (they go into the AccountCmdSet). So we make sure to homogenize self.caller to always be the account object for easy handling. """ import hashlib import time from django.conf import settings from evennia.comms.models import ChannelDB, Msg from evennia.accounts.models import AccountDB from evennia.accounts import bots from evennia.comms.channelhandler import CHANNELHANDLER from evennia.locks.lockhandler import LockException from evennia.utils import create, logger, utils, evtable from evennia.utils.utils import make_iter, class_from_module COMMAND_DEFAULT_CLASS = class_from_module(settings.COMMAND_DEFAULT_CLASS) CHANNEL_DEFAULT_TYPECLASS = class_from_module(settings.BASE_CHANNEL_TYPECLASS) # limit symbol import for API __all__ = ( "CmdAddCom", "CmdDelCom", "CmdAllCom", "CmdChannels", "CmdCdestroy", "CmdCBoot", "CmdCemit", "CmdCWho", "CmdChannelCreate", "CmdClock", "CmdCdesc", "CmdPage", "CmdIRC2Chan", "CmdRSS2Chan", ) _DEFAULT_WIDTH = settings.CLIENT_DEFAULT_WIDTH def find_channel(caller, channelname, silent=False, noaliases=False): """ Helper function for searching for a single channel with some error handling. """ channels = CHANNEL_DEFAULT_TYPECLASS.objects.channel_search(channelname) if not channels: if not noaliases: channels = [ chan for chan in CHANNEL_DEFAULT_TYPECLASS.objects.get_all_channels() if channelname in chan.aliases.all() ] if channels: return channels[0] if not silent: caller.msg("Channel '%s' not found." % channelname) return None elif len(channels) > 1: matches = ", ".join(["%s(%s)" % (chan.key, chan.id) for chan in channels]) if not silent: caller.msg("Multiple channels match (be more specific): \n%s" % matches) return None return channels[0] class CmdAddCom(COMMAND_DEFAULT_CLASS): """ add a channel alias and/or subscribe to a channel Usage: addcom [alias=] <channel> Joins a given channel. If alias is given, this will allow you to refer to the channel by this alias rather than the full channel name. Subsequent calls of this command can be used to add multiple aliases to an already joined channel. """ key = "addcom" aliases = ["aliaschan", "chanalias"] help_category = "Comms" locks = "cmd:not pperm(channel_banned)" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implement the command""" caller = self.caller args = self.args account = caller if not args: self.msg("Usage: addcom [alias =] channelname.") return if self.rhs: # rhs holds the channelname channelname = self.rhs alias = self.lhs else: channelname = self.args alias = None channel = find_channel(caller, channelname) if not channel: # we use the custom search method to handle errors. return # check permissions if not channel.access(account, "listen"): self.msg("%s: You are not allowed to listen to this channel." % channel.key) return string = "" if not channel.has_connection(account): # we want to connect as well. if not channel.connect(account): # if this would have returned True, the account is connected self.msg("%s: You are not allowed to join this channel." % channel.key) return else: string += "You now listen to the channel %s. " % channel.key else: if channel.unmute(account): string += "You unmute channel %s." % channel.key else: string += "You are already connected to channel %s." % channel.key if alias: # create a nick and add it to the caller. caller.nicks.add(alias, channel.key, category="channel") string += " You can now refer to the channel %s with the alias '%s'." self.msg(string % (channel.key, alias)) else: string += " No alias added." self.msg(string) class CmdDelCom(COMMAND_DEFAULT_CLASS): """ remove a channel alias and/or unsubscribe from channel Usage: delcom <alias or channel> delcom/all <channel> If the full channel name is given, unsubscribe from the channel. If an alias is given, remove the alias but don't unsubscribe. If the 'all' switch is used, remove all aliases for that channel. """ key = "delcom" aliases = ["delaliaschan", "delchanalias"] help_category = "Comms" locks = "cmd:not perm(channel_banned)" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implementing the command. """ caller = self.caller account = caller if not self.args: self.msg("Usage: delcom <alias or channel>") return ostring = self.args.lower() channel = find_channel(caller, ostring, silent=True, noaliases=True) if channel: # we have given a channel name - unsubscribe if not channel.has_connection(account): self.msg("You are not listening to that channel.") return chkey = channel.key.lower() delnicks = "all" in self.switches # find all nicks linked to this channel and delete them if delnicks: for nick in [ nick for nick in make_iter(caller.nicks.get(category="channel", return_obj=True)) if nick and nick.pk and nick.value[3].lower() == chkey ]: nick.delete() disconnect = channel.disconnect(account) if disconnect: wipednicks = " Eventual aliases were removed." if delnicks else "" self.msg("You stop listening to channel '%s'.%s" % (channel.key, wipednicks)) return else: # we are removing a channel nick channame = caller.nicks.get(key=ostring, category="channel") channel = find_channel(caller, channame, silent=True) if not channel: self.msg("No channel with alias '%s' was found." % ostring) else: if caller.nicks.get(ostring, category="channel"): caller.nicks.remove(ostring, category="channel") self.msg("Your alias '%s' for channel %s was cleared." % (ostring, channel.key)) else: self.msg("You had no such alias defined for this channel.") class CmdAllCom(COMMAND_DEFAULT_CLASS): """ perform admin operations on all channels Usage: allcom [on | off | who | destroy] Allows the user to universally turn off or on all channels they are on, as well as perform a 'who' for all channels they are on. Destroy deletes all channels that you control. Without argument, works like comlist. """ key = "allcom" locks = "cmd: not pperm(channel_banned)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Runs the function""" caller = self.caller args = self.args if not args: self.execute_cmd("channels") self.msg("(Usage: allcom on | off | who | destroy)") return if args == "on": # get names of all channels available to listen to # and activate them all channels = [ chan for chan in CHANNEL_DEFAULT_TYPECLASS.objects.get_all_channels() if chan.access(caller, "listen") ] for channel in channels: self.execute_cmd("addcom %s" % channel.key) elif args == "off": # get names all subscribed channels and disconnect from them all channels = CHANNEL_DEFAULT_TYPECLASS.objects.get_subscriptions(caller) for channel in channels: self.execute_cmd("delcom %s" % channel.key) elif args == "destroy": # destroy all channels you control channels = [ chan for chan in CHANNEL_DEFAULT_TYPECLASS.objects.get_all_channels() if chan.access(caller, "control") ] for channel in channels: self.execute_cmd("cdestroy %s" % channel.key) elif args == "who": # run a who, listing the subscribers on visible channels. string = "\n|CChannel subscriptions|n" channels = [ chan for chan in CHANNEL_DEFAULT_TYPECLASS.objects.get_all_channels() if chan.access(caller, "listen") ] if not channels: string += "No channels." for channel in channels: string += "\n|w%s:|n\n %s" % (channel.key, channel.wholist) self.msg(string.strip()) else: # wrong input self.msg("Usage: allcom on | off | who | clear") class CmdChannels(COMMAND_DEFAULT_CLASS): """ list all channels available to you Usage: channels clist comlist Lists all channels available to you, whether you listen to them or not. Use 'comlist' to only view your current channel subscriptions. Use addcom/delcom to join and leave channels """ key = "channels" aliases = ["clist", "comlist", "chanlist", "channellist", "all channels"] help_category = "Comms" locks = "cmd: not pperm(channel_banned)" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implement function""" caller = self.caller # all channels we have available to listen to channels = [ chan for chan in CHANNEL_DEFAULT_TYPECLASS.objects.get_all_channels() if chan.access(caller, "listen") ] if not channels: self.msg("No channels available.") return # all channel we are already subscribed to subs = CHANNEL_DEFAULT_TYPECLASS.objects.get_subscriptions(caller) if self.cmdstring == "comlist": # just display the subscribed channels with no extra info comtable = self.styled_table( "|wchannel|n", "|wmy aliases|n", "|wdescription|n", align="l", maxwidth=_DEFAULT_WIDTH, ) for chan in subs: clower = chan.key.lower() nicks = caller.nicks.get(category="channel", return_obj=True) comtable.add_row( *[ "%s%s" % ( chan.key, chan.aliases.all() and "(%s)" % ",".join(chan.aliases.all()) or "", ), "%s" % ",".join( nick.db_key for nick in make_iter(nicks) if nick and nick.value[3].lower() == clower ), chan.db.desc, ] ) self.msg( "\n|wChannel subscriptions|n (use |wchannels|n to list all," " |waddcom|n/|wdelcom|n to sub/unsub):|n\n%s" % comtable ) else: # full listing (of channels caller is able to listen to) comtable = self.styled_table( "|wsub|n", "|wchannel|n", "|wmy aliases|n", "|wlocks|n", "|wdescription|n", maxwidth=_DEFAULT_WIDTH, ) for chan in channels: clower = chan.key.lower() nicks = caller.nicks.get(category="channel", return_obj=True) nicks = nicks or [] if chan not in subs: substatus = "|rNo|n" elif caller in chan.mutelist: substatus = "|rMuted|n" else: substatus = "|gYes|n" comtable.add_row( *[ substatus, "%s%s" % ( chan.key, chan.aliases.all() and "(%s)" % ",".join(chan.aliases.all()) or "", ), "%s" % ",".join( nick.db_key for nick in make_iter(nicks) if nick.value[3].lower() == clower ), str(chan.locks), chan.db.desc, ] ) comtable.reformat_column(0, width=9) comtable.reformat_column(3, width=14) self.msg( "\n|wAvailable channels|n (use |wcomlist|n,|waddcom|n and |wdelcom|n" " to manage subscriptions):\n%s" % comtable ) class CmdCdestroy(COMMAND_DEFAULT_CLASS): """ destroy a channel you created Usage: cdestroy <channel> Destroys a channel that you control. """ key = "cdestroy" help_category = "Comms" locks = "cmd: not pperm(channel_banned)" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Destroy objects cleanly.""" caller = self.caller if not self.args: self.msg("Usage: cdestroy <channelname>") return channel = find_channel(caller, self.args) if not channel: self.msg("Could not find channel %s." % self.args) return if not channel.access(caller, "control"): self.msg("You are not allowed to do that.") return channel_key = channel.key message = "%s is being destroyed. Make sure to change your aliases." % channel_key msgobj = create.create_message(caller, message, channel) channel.msg(msgobj) channel.delete() CHANNELHANDLER.update() self.msg("Channel '%s' was destroyed." % channel_key) logger.log_sec( "Channel Deleted: %s (Caller: %s, IP: %s)." % (channel_key, caller, self.session.address) ) class CmdCBoot(COMMAND_DEFAULT_CLASS): """ kick an account from a channel you control Usage: cboot[/quiet] <channel> = <account> [:reason] Switch: quiet - don't notify the channel Kicks an account or object from a channel you control. """ key = "cboot" switch_options = ("quiet",) locks = "cmd: not pperm(channel_banned)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """implement the function""" if not self.args or not self.rhs: string = "Usage: cboot[/quiet] <channel> = <account> [:reason]" self.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return reason = "" if ":" in self.rhs: accountname, reason = self.rhs.rsplit(":", 1) searchstring = accountname.lstrip("*") else: searchstring = self.rhs.lstrip("*") account = self.caller.search(searchstring, account=True) if not account: return if reason: reason = " (reason: %s)" % reason if not channel.access(self.caller, "control"): string = "You don't control this channel." self.msg(string) return if not channel.subscriptions.has(account): string = "Account %s is not connected to channel %s." % (account.key, channel.key) self.msg(string) return if "quiet" not in self.switches: string = "%s boots %s from channel.%s" % (self.caller, account.key, reason) channel.msg(string) # find all account's nicks linked to this channel and delete them for nick in [ nick for nick in account.character.nicks.get(category="channel") or [] if nick.value[3].lower() == channel.key ]: nick.delete() # disconnect account channel.disconnect(account) CHANNELHANDLER.update() logger.log_sec( "Channel Boot: %s (Channel: %s, Reason: %s, Caller: %s, IP: %s)." % (account, channel, reason, self.caller, self.session.address) ) class CmdCemit(COMMAND_DEFAULT_CLASS): """ send an admin message to a channel you control Usage: cemit[/switches] <channel> = <message> Switches: sendername - attach the sender's name before the message quiet - don't echo the message back to sender Allows the user to broadcast a message over a channel as long as they control it. It does not show the user's name unless they provide the /sendername switch. """ key = "cemit" aliases = ["cmsg"] switch_options = ("sendername", "quiet") locks = "cmd: not pperm(channel_banned) and pperm(Player)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implement function""" if not self.args or not self.rhs: string = "Usage: cemit[/switches] <channel> = <message>" self.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return if not channel.access(self.caller, "control"): string = "You don't control this channel." self.msg(string) return message = self.rhs if "sendername" in self.switches: message = "%s: %s" % (self.caller.key, message) channel.msg(message) if "quiet" not in self.switches: string = "Sent to channel %s: %s" % (channel.key, message) self.msg(string) class CmdCWho(COMMAND_DEFAULT_CLASS): """ show who is listening to a channel Usage: cwho <channel> List who is connected to a given channel you have access to. """ key = "cwho" locks = "cmd: not pperm(channel_banned)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """implement function""" if not self.args: string = "Usage: cwho <channel>" self.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return if not channel.access(self.caller, "listen"): string = "You can't access this channel." self.msg(string) return string = "\n|CChannel subscriptions|n" string += "\n|w%s:|n\n %s" % (channel.key, channel.wholist) self.msg(string.strip()) class CmdChannelCreate(COMMAND_DEFAULT_CLASS): """ create a new channel Usage: ccreate <new channel>[;alias;alias...] = description Creates a new channel owned by you. """ key = "ccreate" aliases = "channelcreate" locks = "cmd:not pperm(channel_banned) and pperm(Player)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implement the command""" caller = self.caller if not self.args: self.msg("Usage ccreate <channelname>[;alias;alias..] = description") return description = "" if self.rhs: description = self.rhs lhs = self.lhs channame = lhs aliases = None if ";" in lhs: channame, aliases = lhs.split(";", 1) aliases = [alias.strip().lower() for alias in aliases.split(";")] channel = CHANNEL_DEFAULT_TYPECLASS.objects.channel_search(channame) if channel: self.msg("A channel with that name already exists.") return # Create and set the channel up lockstring = "send:all();listen:all();control:id(%s)" % caller.id new_chan = create.create_channel(channame.strip(), aliases, description, locks=lockstring) new_chan.connect(caller) CHANNELHANDLER.update() self.msg("Created channel %s and connected to it." % new_chan.key) class CmdClock(COMMAND_DEFAULT_CLASS): """ change channel locks of a channel you control Usage: clock <channel> [= <lockstring>] Changes the lock access restrictions of a channel. If no lockstring was given, view the current lock definitions. """ key = "clock" locks = "cmd:not pperm(channel_banned)" aliases = ["clock"] help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """run the function""" if not self.args: string = "Usage: clock channel [= lockstring]" self.msg(string) return channel = find_channel(self.caller, self.lhs) if not channel: return if not self.rhs: # no =, so just view the current locks string = "Current locks on %s:" % channel.key string = "%s\n %s" % (string, channel.locks) self.msg(string) return # we want to add/change a lock. if not channel.access(self.caller, "control"): string = "You don't control this channel." self.msg(string) return # Try to add the lock try: channel.locks.add(self.rhs) except LockException as err: self.msg(err) return string = "Lock(s) applied. " string += "Current locks on %s:" % channel.key string = "%s\n %s" % (string, channel.locks) self.msg(string) class CmdCdesc(COMMAND_DEFAULT_CLASS): """ describe a channel you control Usage: cdesc <channel> = <description> Changes the description of the channel as shown in channel lists. """ key = "cdesc" locks = "cmd:not pperm(channel_banned)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implement command""" caller = self.caller if not self.rhs: self.msg("Usage: cdesc <channel> = <description>") return channel = find_channel(caller, self.lhs) if not channel: self.msg("Channel '%s' not found." % self.lhs) return # check permissions if not channel.access(caller, "control"): self.msg("You cannot admin this channel.") return # set the description channel.db.desc = self.rhs channel.save() self.msg("Description of channel '%s' set to '%s'." % (channel.key, self.rhs)) class CmdPage(COMMAND_DEFAULT_CLASS): """ send a private message to another account Usage: page[/switches] [<account>,<account>,... = <message>] tell '' page <number> Switch: last - shows who you last messaged list - show your last <number> of tells/pages (default) Send a message to target user (if online). If no argument is given, you will get a list of your latest messages. """ key = "page" aliases = ["tell"] switch_options = ("last", "list") locks = "cmd:not pperm(page_banned)" help_category = "Comms" # this is used by the COMMAND_DEFAULT_CLASS parent account_caller = True def func(self): """Implement function using the Msg methods""" # Since account_caller is set above, this will be an Account. caller = self.caller # get the messages we've sent (not to channels) pages_we_sent = Msg.objects.get_messages_by_sender(caller, exclude_channel_messages=True) # get last messages we've got pages_we_got = Msg.objects.get_messages_by_receiver(caller) if "last" in self.switches: if pages_we_sent: recv = ",".join(obj.key for obj in pages_we_sent[-1].receivers) self.msg("You last paged |c%s|n:%s" % (recv, pages_we_sent[-1].message)) return else: self.msg("You haven't paged anyone yet.") return if not self.args or not self.rhs: pages = pages_we_sent + pages_we_got pages = sorted(pages, key=lambda page: page.date_created) number = 5 if self.args: try: number = int(self.args) except ValueError: self.msg("Usage: tell [<account> = msg]") return if len(pages) > number: lastpages = pages[-number:] else: lastpages = pages template = "|w%s|n |c%s|n to |c%s|n: %s" lastpages = "\n ".join( template % ( utils.datetime_format(page.date_created), ",".join(obj.key for obj in page.senders), "|n,|c ".join([obj.name for obj in page.receivers]), page.message, ) for page in lastpages ) if lastpages: string = "Your latest pages:\n %s" % lastpages else: string = "You haven't paged anyone yet." self.msg(string) return # We are sending. Build a list of targets if not self.lhs: # If there are no targets, then set the targets # to the last person we paged. if pages_we_sent: receivers = pages_we_sent[-1].receivers else: self.msg("Who do you want to page?") return else: receivers = self.lhslist recobjs = [] for receiver in set(receivers): if isinstance(receiver, str): pobj = caller.search(receiver) elif hasattr(receiver, "character"): pobj = receiver else: self.msg("Who do you want to page?") return if pobj: recobjs.append(pobj) if not recobjs: self.msg("Noone found to page.") return header = "|wAccount|n |c%s|n |wpages:|n" % caller.key message = self.rhs # if message begins with a :, we assume it is a 'page-pose' if message.startswith(":"): message = "%s %s" % (caller.key, message.strip(":").strip()) # create the persistent message object create.create_message(caller, message, receivers=recobjs) # tell the accounts they got a message. received = [] rstrings = [] for pobj in recobjs: if not pobj.access(caller, "msg"): rstrings.append("You are not allowed to page %s." % pobj) continue pobj.msg("%s %s" % (header, message)) if hasattr(pobj, "sessions") and not pobj.sessions.count(): received.append("|C%s|n" % pobj.name) rstrings.append( "%s is offline. They will see your message if they list their pages later." % received[-1] ) else: received.append("|c%s|n" % pobj.name) if rstrings: self.msg("\n".join(rstrings)) self.msg("You paged %s with: '%s'." % (", ".join(received), message)) def _list_bots(cmd): """ Helper function to produce a list of all IRC bots. Args: cmd (Command): Instance of the Bot command. Returns: bots (str): A table of bots or an error message. """ ircbots = [ bot for bot in AccountDB.objects.filter(db_is_bot=True, username__startswith="ircbot-") ] if ircbots: table = cmd.styled_table( "|w#dbref|n", "|wbotname|n", "|wev-channel|n", "|wirc-channel|n", "|wSSL|n", maxwidth=_DEFAULT_WIDTH, ) for ircbot in ircbots: ircinfo = "%s (%s:%s)" % ( ircbot.db.irc_channel, ircbot.db.irc_network, ircbot.db.irc_port, ) table.add_row( "#%i" % ircbot.id, ircbot.db.irc_botname, ircbot.db.ev_channel, ircinfo, ircbot.db.irc_ssl, ) return table else: return "No irc bots found." class CmdIRC2Chan(COMMAND_DEFAULT_CLASS): """ Link an evennia channel to an external IRC channel Usage: irc2chan[/switches] <evennia_channel> = <ircnetwork> <port> <#irchannel> <botname>[:typeclass] irc2chan/delete botname|#dbid Switches: /delete - this will delete the bot and remove the irc connection to the channel. Requires the botname or #dbid as input. /remove - alias to /delete /disconnect - alias to /delete /list - show all irc<->evennia mappings /ssl - use an SSL-encrypted connection Example: irc2chan myircchan = irc.dalnet.net 6667 #mychannel evennia-bot irc2chan public = irc.freenode.net 6667 #evgaming #evbot:accounts.mybot.MyBot This creates an IRC bot that connects to a given IRC network and channel. If a custom typeclass path is given, this will be used instead of the default bot class. The bot will relay everything said in the evennia channel to the IRC channel and vice versa. The bot will automatically connect at server start, so this command need only be given once. The /disconnect switch will permanently delete the bot. To only temporarily deactivate it, use the |wservices|n command instead. Provide an optional bot class path to use a custom bot. """ key = "irc2chan" switch_options = ("delete", "remove", "disconnect", "list", "ssl") locks = "cmd:serversetting(IRC_ENABLED) and pperm(Developer)" help_category = "Comms" def func(self): """Setup the irc-channel mapping""" if not settings.IRC_ENABLED: string = """IRC is not enabled. You need to activate it in game/settings.py.""" self.msg(string) return if "list" in self.switches: # show all connections self.msg(_list_bots(self)) return if "disconnect" in self.switches or "remove" in self.switches or "delete" in self.switches: botname = "ircbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, username=botname) dbref = utils.dbref(self.lhs) if not matches and dbref: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=dbref) if matches: matches[0].delete() self.msg("IRC connection destroyed.") else: self.msg("IRC connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = ( "Usage: irc2chan[/switches] <evennia_channel> =" " <ircnetwork> <port> <#irchannel> <botname>[:typeclass]" ) self.msg(string) return channel = self.lhs self.rhs = self.rhs.replace("#", " ") # to avoid Python comment issues try: irc_network, irc_port, irc_channel, irc_botname = [ part.strip() for part in self.rhs.split(None, 4) ] irc_channel = "#%s" % irc_channel except Exception: string = "IRC bot definition '%s' is not valid." % self.rhs self.msg(string) return botclass = None if ":" in irc_botname: irc_botname, botclass = [part.strip() for part in irc_botname.split(":", 2)] botname = "ircbot-%s" % irc_botname # If path given, use custom bot otherwise use default. botclass = botclass if botclass else bots.IRCBot irc_ssl = "ssl" in self.switches # create a new bot bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use an existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: try: bot = create.create_account(botname, None, None, typeclass=botclass) except Exception as err: self.msg("|rError, could not create the bot:|n '%s'." % err) return bot.start( ev_channel=channel, irc_botname=irc_botname, irc_channel=irc_channel, irc_network=irc_network, irc_port=irc_port, irc_ssl=irc_ssl, ) self.msg("Connection created. Starting IRC bot.") class CmdIRCStatus(COMMAND_DEFAULT_CLASS): """ Check and reboot IRC bot. Usage: ircstatus [#dbref ping||nicklist||reconnect] If not given arguments, will return a list of all bots (like irc2chan/list). The 'ping' argument will ping the IRC network to see if the connection is still responsive. The 'nicklist' argument (aliases are 'who' and 'users') will return a list of users on the remote IRC channel. Finally, 'reconnect' will force the client to disconnect and reconnect again. This may be a last resort if the client has silently lost connection (this may happen if the remote network experience network issues). During the reconnection messages sent to either channel will be lost. """ key = "ircstatus" locks = "cmd:serversetting(IRC_ENABLED) and perm(ircstatus) or perm(Builder))" help_category = "Comms" def func(self): """Handles the functioning of the command.""" if not self.args: self.msg(_list_bots(self)) return # should always be on the form botname option args = self.args.split() if len(args) != 2: self.msg("Usage: ircstatus [#dbref ping||nicklist||reconnect]") return botname, option = args if option not in ("ping", "users", "reconnect", "nicklist", "who"): self.msg("Not a valid option.") return matches = None if utils.dbref(botname): matches = AccountDB.objects.filter(db_is_bot=True, id=utils.dbref(botname)) if not matches: self.msg( "No matching IRC-bot found. Use ircstatus without arguments to list active bots." ) return ircbot = matches[0] channel = ircbot.db.irc_channel network = ircbot.db.irc_network port = ircbot.db.irc_port chtext = "IRC bot '%s' on channel %s (%s:%s)" % ( ircbot.db.irc_botname, channel, network, port, ) if option == "ping": # check connection by sending outself a ping through the server. self.caller.msg("Pinging through %s." % chtext) ircbot.ping(self.caller) elif option in ("users", "nicklist", "who"): # retrieve user list. The bot must handles the echo since it's # an asynchronous call. self.caller.msg("Requesting nicklist from %s (%s:%s)." % (channel, network, port)) ircbot.get_nicklist(self.caller) elif self.caller.locks.check_lockstring( self.caller, "dummy:perm(ircstatus) or perm(Developer)" ): # reboot the client self.caller.msg("Forcing a disconnect + reconnect of %s." % chtext) ircbot.reconnect() else: self.caller.msg("You don't have permission to force-reload the IRC bot.") # RSS connection class CmdRSS2Chan(COMMAND_DEFAULT_CLASS): """ link an evennia channel to an external RSS feed Usage: rss2chan[/switches] <evennia_channel> = <rss_url> Switches: /disconnect - this will stop the feed and remove the connection to the channel. /remove - " /list - show all rss->evennia mappings Example: rss2chan rsschan = http://code.google.com/feeds/p/evennia/updates/basic This creates an RSS reader that connects to a given RSS feed url. Updates will be echoed as a title and news link to the given channel. The rate of updating is set with the RSS_UPDATE_INTERVAL variable in settings (default is every 10 minutes). When disconnecting you need to supply both the channel and url again so as to identify the connection uniquely. """ key = "rss2chan" switch_options = ("disconnect", "remove", "list") locks = "cmd:serversetting(RSS_ENABLED) and pperm(Developer)" help_category = "Comms" def func(self): """Setup the rss-channel mapping""" # checking we have all we need if not settings.RSS_ENABLED: string = """RSS is not enabled. You need to activate it in game/settings.py.""" self.msg(string) return try: import feedparser assert feedparser # to avoid checker error of not being used except ImportError: string = ( "RSS requires python-feedparser (https://pypi.python.org/pypi/feedparser)." " Install before continuing." ) self.msg(string) return if "list" in self.switches: # show all connections rssbots = [ bot for bot in AccountDB.objects.filter(db_is_bot=True, username__startswith="rssbot-") ] if rssbots: table = self.styled_table( "|wdbid|n", "|wupdate rate|n", "|wev-channel", "|wRSS feed URL|n", border="cells", maxwidth=_DEFAULT_WIDTH, ) for rssbot in rssbots: table.add_row( rssbot.id, rssbot.db.rss_rate, rssbot.db.ev_channel, rssbot.db.rss_url ) self.msg(table) else: self.msg("No rss bots found.") return if "disconnect" in self.switches or "remove" in self.switches or "delete" in self.switches: botname = "rssbot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, db_key=botname) if not matches: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=self.args.lstrip("#")) if matches: matches[0].delete() self.msg("RSS connection destroyed.") else: self.msg("RSS connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: rss2chan[/switches] <evennia_channel> = <rss url>" self.msg(string) return channel = self.lhs url = self.rhs botname = "rssbot-%s" % url bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: # create a new bot bot = create.create_account(botname, None, None, typeclass=bots.RSSBot) bot.start(ev_channel=channel, rss_url=url, rss_rate=10) self.msg("RSS reporter created. Fetching RSS.") class CmdGrapevine2Chan(COMMAND_DEFAULT_CLASS): """ Link an Evennia channel to an exteral Grapevine channel Usage: grapevine2chan[/switches] <evennia_channel> = <grapevine_channel> grapevine2chan/disconnect <connection #id> Switches: /list - (or no switch): show existing grapevine <-> Evennia mappings and available grapevine chans /remove - alias to disconnect /delete - alias to disconnect Example: grapevine2chan mygrapevine = gossip This creates a link between an in-game Evennia channel and an external Grapevine channel. The game must be registered with the Grapevine network (register at https://grapevine.haus) and the GRAPEVINE_* auth information must be added to game settings. """ key = "grapevine2chan" switch_options = ("disconnect", "remove", "delete", "list") locks = "cmd:serversetting(GRAPEVINE_ENABLED) and pperm(Developer)" help_category = "Comms" def func(self): """Setup the Grapevine channel mapping""" if not settings.GRAPEVINE_ENABLED: self.msg("Set GRAPEVINE_ENABLED=True in settings to enable.") return if "list" in self.switches: # show all connections gwbots = [ bot for bot in AccountDB.objects.filter( db_is_bot=True, username__startswith="grapevinebot-" ) ] if gwbots: table = self.styled_table( "|wdbid|n", "|wev-channel", "|wgw-channel|n", border="cells", maxwidth=_DEFAULT_WIDTH, ) for gwbot in gwbots: table.add_row(gwbot.id, gwbot.db.ev_channel, gwbot.db.grapevine_channel) self.msg(table) else: self.msg("No grapevine bots found.") return if "disconnect" in self.switches or "remove" in self.switches or "delete" in self.switches: botname = "grapevinebot-%s" % self.lhs matches = AccountDB.objects.filter(db_is_bot=True, db_key=botname) if not matches: # try dbref match matches = AccountDB.objects.filter(db_is_bot=True, id=self.args.lstrip("#")) if matches: matches[0].delete() self.msg("Grapevine connection destroyed.") else: self.msg("Grapevine connection/bot could not be removed, does it exist?") return if not self.args or not self.rhs: string = "Usage: grapevine2chan[/switches] <evennia_channel> = <grapevine_channel>" self.msg(string) return channel = self.lhs grapevine_channel = self.rhs botname = "grapewinebot-%s-%s" % (channel, grapevine_channel) bot = AccountDB.objects.filter(username__iexact=botname) if bot: # re-use existing bot bot = bot[0] if not bot.is_bot: self.msg("Account '%s' already exists and is not a bot." % botname) return else: self.msg("Reusing bot '%s' (%s)" % (botname, bot.dbref)) else: # create a new bot bot = create.create_account(botname, None, None, typeclass=bots.GrapevineBot) bot.start(ev_channel=channel, grapevine_channel=grapevine_channel) self.msg(f"Grapevine connection created {channel} <-> {grapevine_channel}.")
[ "evennia.comms.channelhandler.CHANNELHANDLER.update", "evennia.comms.models.Msg.objects.get_messages_by_receiver", "evennia.accounts.models.AccountDB.objects.filter", "evennia.utils.create.create_message", "evennia.comms.models.Msg.objects.get_messages_by_sender", "evennia.utils.utils.class_from_module", ...
[((695, 744), 'evennia.utils.utils.class_from_module', 'class_from_module', (['settings.COMMAND_DEFAULT_CLASS'], {}), '(settings.COMMAND_DEFAULT_CLASS)\n', (712, 744), False, 'from evennia.utils.utils import make_iter, class_from_module\n'), ((773, 823), 'evennia.utils.utils.class_from_module', 'class_from_module', (['settings.BASE_CHANNEL_TYPECLASS'], {}), '(settings.BASE_CHANNEL_TYPECLASS)\n', (790, 823), False, 'from evennia.utils.utils import make_iter, class_from_module\n'), ((14708, 14755), 'evennia.utils.create.create_message', 'create.create_message', (['caller', 'message', 'channel'], {}), '(caller, message, channel)\n', (14729, 14755), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((14817, 14840), 'evennia.comms.channelhandler.CHANNELHANDLER.update', 'CHANNELHANDLER.update', ([], {}), '()\n', (14838, 14840), False, 'from evennia.comms.channelhandler import CHANNELHANDLER\n'), ((14911, 15020), 'evennia.utils.logger.log_sec', 'logger.log_sec', (["('Channel Deleted: %s (Caller: %s, IP: %s).' % (channel_key, caller, self.\n session.address))"], {}), "('Channel Deleted: %s (Caller: %s, IP: %s).' % (channel_key,\n caller, self.session.address))\n", (14925, 15020), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((17121, 17144), 'evennia.comms.channelhandler.CHANNELHANDLER.update', 'CHANNELHANDLER.update', ([], {}), '()\n', (17142, 17144), False, 'from evennia.comms.channelhandler import CHANNELHANDLER\n'), ((17153, 17308), 'evennia.utils.logger.log_sec', 'logger.log_sec', (["('Channel Boot: %s (Channel: %s, Reason: %s, Caller: %s, IP: %s).' % (\n account, channel, reason, self.caller, self.session.address))"], {}), "(\n 'Channel Boot: %s (Channel: %s, Reason: %s, Caller: %s, IP: %s).' % (\n account, channel, reason, self.caller, self.session.address))\n", (17167, 17308), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((21150, 21173), 'evennia.comms.channelhandler.CHANNELHANDLER.update', 'CHANNELHANDLER.update', ([], {}), '()\n', (21171, 21173), False, 'from evennia.comms.channelhandler import CHANNELHANDLER\n'), ((24782, 24855), 'evennia.comms.models.Msg.objects.get_messages_by_sender', 'Msg.objects.get_messages_by_sender', (['caller'], {'exclude_channel_messages': '(True)'}), '(caller, exclude_channel_messages=True)\n', (24816, 24855), False, 'from evennia.comms.models import ChannelDB, Msg\n'), ((24917, 24961), 'evennia.comms.models.Msg.objects.get_messages_by_receiver', 'Msg.objects.get_messages_by_receiver', (['caller'], {}), '(caller)\n', (24953, 24961), False, 'from evennia.comms.models import ChannelDB, Msg\n'), ((27710, 27767), 'evennia.utils.create.create_message', 'create.create_message', (['caller', 'message'], {'receivers': 'recobjs'}), '(caller, message, receivers=recobjs)\n', (27731, 27767), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((33341, 33391), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'username__iexact': 'botname'}), '(username__iexact=botname)\n', (33365, 33391), False, 'from evennia.accounts.models import AccountDB\n'), ((35617, 35637), 'evennia.utils.utils.dbref', 'utils.dbref', (['botname'], {}), '(botname)\n', (35628, 35637), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((40544, 40594), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'username__iexact': 'botname'}), '(username__iexact=botname)\n', (40568, 40594), False, 'from evennia.accounts.models import AccountDB\n'), ((44035, 44085), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'username__iexact': 'botname'}), '(username__iexact=botname)\n', (44059, 44085), False, 'from evennia.accounts.models import AccountDB\n'), ((28874, 28946), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'username__startswith': '"""ircbot-"""'}), "(db_is_bot=True, username__startswith='ircbot-')\n", (28898, 28946), False, 'from evennia.accounts.models import AccountDB\n'), ((31741, 31799), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'username': 'botname'}), '(db_is_bot=True, username=botname)\n', (31765, 31799), False, 'from evennia.accounts.models import AccountDB\n'), ((31820, 31841), 'evennia.utils.utils.dbref', 'utils.dbref', (['self.lhs'], {}), '(self.lhs)\n', (31831, 31841), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((39825, 39881), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'db_key': 'botname'}), '(db_is_bot=True, db_key=botname)\n', (39849, 39881), False, 'from evennia.accounts.models import AccountDB\n'), ((40871, 40936), 'evennia.utils.create.create_account', 'create.create_account', (['botname', 'None', 'None'], {'typeclass': 'bots.RSSBot'}), '(botname, None, None, typeclass=bots.RSSBot)\n', (40892, 40936), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((43238, 43294), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'db_key': 'botname'}), '(db_is_bot=True, db_key=botname)\n', (43262, 43294), False, 'from evennia.accounts.models import AccountDB\n'), ((44453, 44524), 'evennia.utils.create.create_account', 'create.create_account', (['botname', 'None', 'None'], {'typeclass': 'bots.GrapevineBot'}), '(botname, None, None, typeclass=bots.GrapevineBot)\n', (44474, 44524), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((31940, 31990), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'id': 'dbref'}), '(db_is_bot=True, id=dbref)\n', (31964, 31990), False, 'from evennia.accounts.models import AccountDB\n'), ((33661, 33723), 'evennia.utils.create.create_account', 'create.create_account', (['botname', 'None', 'None'], {'typeclass': 'botclass'}), '(botname, None, None, typeclass=botclass)\n', (33682, 33723), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((35705, 35725), 'evennia.utils.utils.dbref', 'utils.dbref', (['botname'], {}), '(botname)\n', (35716, 35725), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((38950, 39022), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'username__startswith': '"""rssbot-"""'}), "(db_is_bot=True, username__startswith='rssbot-')\n", (38974, 39022), False, 'from evennia.accounts.models import AccountDB\n'), ((42410, 42488), 'evennia.accounts.models.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'db_is_bot': '(True)', 'username__startswith': '"""grapevinebot-"""'}), "(db_is_bot=True, username__startswith='grapevinebot-')\n", (42434, 42488), False, 'from evennia.accounts.models import AccountDB\n'), ((26008, 26048), 'evennia.utils.utils.datetime_format', 'utils.datetime_format', (['page.date_created'], {}), '(page.date_created)\n', (26029, 26048), False, 'from evennia.utils import create, logger, utils, evtable\n'), ((11644, 11660), 'evennia.utils.utils.make_iter', 'make_iter', (['nicks'], {}), '(nicks)\n', (11653, 11660), False, 'from evennia.utils.utils import make_iter, class_from_module\n'), ((13239, 13255), 'evennia.utils.utils.make_iter', 'make_iter', (['nicks'], {}), '(nicks)\n', (13248, 13255), False, 'from evennia.utils.utils import make_iter, class_from_module\n')]
""" Player The Player represents the game "account" and each login has only one Player object. A Player is what chats on default channels but has no other in-game-world existance. Rather the Player puppets Objects (such as Characters) in order to actually participate in the game world. Guest Guest players are simple low-level accounts that are created/deleted on the fly and allows users to test the game without the committment of a full registration. Guest accounts are deactivated by default; to activate them, add the following line to your settings file: GUEST_ENABLED = True You will also need to modify the connection screen to reflect the possibility to connect with a guest account. The setting file accepts several more options for customizing the Guest account system. """ from evennia import DefaultAccount from typeclasses.mixins import MsgMixins, InformMixin class Account(InformMixin, MsgMixins, DefaultAccount): """ This class describes the actual OOC player (i.e. the user connecting to the MUD). It does NOT have visual appearance in the game world (that is handled by the character which is connected to this). Comm channels are attended/joined using this object. It can be useful e.g. for storing configuration options for your game, but should generally not hold any character-related info (that's best handled on the character level). Can be set using BASE_PLAYER_TYPECLASS. * available properties key (string) - name of player name (string)- wrapper for user.username aliases (list of strings) - aliases to the object. Will be saved to database as AliasDB entries but returned as strings. dbref (int, read-only) - unique #id-number. Also "id" can be used. date_created (string) - time stamp of object creation permissions (list of strings) - list of permission strings user (User, read-only) - django User authorization object obj (Object) - game object controlled by player. 'character' can also be used. sessions (list of Sessions) - sessions connected to this player is_superuser (bool, read-only) - if the connected user is a superuser * Handlers locks - lock-handler: use locks.add() to add new lock strings db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data scripts - script-handler. Add new scripts to object with scripts.add() cmdset - cmdset-handler. Use cmdset.add() to add new cmdsets to object nicks - nick-handler. New nicks with nicks.add(). * Helper methods msg(text=None, **kwargs) swap_character(new_character, delete_old_character=False) execute_cmd(raw_string, session=None) search(ostring, global_search=False, attribute_name=None, use_nicks=False, location=None, ignore_errors=False, player=False) is_typeclass(typeclass, exact=False) swap_typeclass(new_typeclass, clean_attributes=False, no_default=True) access(accessing_obj, access_type='read', default=False) check_permstring(permstring) * Hook methods (when re-implementation, remember methods need to have self as first arg) basetype_setup() at_player_creation() - note that the following hooks are also found on Objects and are usually handled on the character level: at_init() at_cmdset_get(**kwargs) at_first_login() at_post_login(session=None) at_disconnect() at_message_receive() at_message_send() at_server_reload() at_server_shutdown() """ def __str__(self): return self.name def __unicode__(self): return self.name def at_account_creation(self): """ This is called once, the very first time the player is created (i.e. first time they register with the game). It's a good place to store attributes all players should have, like configuration values etc. """ # set an (empty) attribute holding the characters this player has lockstring = "attrread:perm(Wizards);attredit:perm(Wizards);attrcreate:perm(Wizards)" self.attributes.add("_playable_characters", [], lockstring=lockstring) self.db.mails = [] self.db.readmails = set() # noinspection PyBroadException def at_post_login(self, session=None): """ Called at the end of the login process, just before letting them loose. This is called before an eventual Character's at_post_login hook. :type self: AccountDB :type session: Session """ self.db._last_puppet = self.char_ob or self.db._last_puppet super(Account, self).at_post_login(session) if self.tags.get("new_mail"): self.msg("{y*** You have new mail. ***{n") self.announce_informs() pending = self.db.pending_messages or [] for msg in pending: self.msg(msg, options={'box': True}) self.attributes.remove("pending_messages") if self.assigned_to.filter(status=1, priority__lte=5): self.msg("{yYou have unresolved tickets assigned to you. Use @job/mine to view them.{n") self.check_motd() self.check_petitions() # in this mode we should have only one character available. We # try to auto-connect to it by calling the @ic command # (this relies on player.db._last_puppet being set) self.execute_cmd("@bbsub/quiet story updates") try: from commands.commands.bboards import get_unread_posts get_unread_posts(self) except Exception: pass try: if self.roster.frozen: self.roster.frozen = False self.roster.save() if self.roster.roster.name == "Inactive": from web.character.models import Roster try: active = Roster.objects.get(name="Active") self.roster.roster = active self.roster.save() except Roster.DoesNotExist: pass watched_by = self.char_ob.db.watched_by or [] if self.sessions.count() == 1: if not self.db.hide_from_watch: for watcher in watched_by: watcher.msg("{wA player you are watching, {c%s{w, has connected.{n" % self) self.db.afk = "" except AttributeError: pass # noinspection PyBroadException def announce_informs(self): """Lets us know if we have unread informs""" msg = "" try: unread = self.informs.filter(read_by__isnull=True).count() if unread: msg += "{w*** You have %s unread informs. Use @informs to read them. ***{n\n" % unread for org in self.current_orgs: if not org.access(self, "informs"): continue unread = org.informs.exclude(read_by=self).count() if unread: msg += "{w*** You have %s unread informs for %s. ***{n\n" % (unread, org) except Exception: pass if msg: self.msg(msg) def is_guest(self): """ Overload in guest object to return True """ return False def at_first_login(self): """ Only called once, the very first time the user logs in. """ self.execute_cmd("addcom pub=public") pass def mail(self, message, subject=None, sender=None, receivers=None): """ Sends a mail message to player. """ from django.utils import timezone sentdate = timezone.now().strftime("%x %X") mail = (sender, subject, message, sentdate, receivers) if not self.db.mails: self.db.mails = [] self.db.mails.append(mail) if sender: from_str = " from {c%s{y" % sender.capitalize() else: from_str = "" self.msg("{yYou have new mail%s. Use {w'mail %s' {yto read it.{n" % (from_str, len(self.db.mails))) self.tags.add("new_mail") def get_fancy_name(self): """Ensures that our name is capitalized""" return self.key.capitalize() # noinspection PyAttributeOutsideInit def set_name(self, value): self.key = value name = property(get_fancy_name, set_name) def send_or_queue_msg(self, message): """Sends a message to us if we're online or queues it for later""" if self.is_connected: self.msg(message, options={'box': True}) return pending = self.db.pending_messages or [] pending.append(message) self.db.pending_messages = pending def get_all_sessions(self): """Retrieves our connected sessions""" return self.sessions.all() @property def public_orgs(self): """ Return public organizations we're in. """ try: return self.Dominion.public_orgs except AttributeError: return [] @property def current_orgs(self): """Returns our current organizations we're a member of""" try: return self.Dominion.current_orgs except AttributeError: return [] @property def secret_orgs(self): """Returns any secret orgs we're a member of""" try: return self.Dominion.secret_orgs except AttributeError: return [] @property def active_memberships(self): """Returns our active memberships""" try: return self.Dominion.memberships.filter(deguilded=False) except AttributeError: return [] @property def assets(self): """Returns the holder for all our assets/prestige/etc""" return self.Dominion.assets def pay_resources(self, rtype, amt): """ Attempt to pay resources. If we don't have enough, return False. """ try: assets = self.assets current = getattr(assets, rtype) if current < amt: return False setattr(assets, rtype, current - amt) assets.save() return True except AttributeError: return False def gain_resources(self, rtype, amt): """ Attempt to gain resources. If something goes wrong, we return 0. We call pay_resources with a negative amount, and if returns true, we return the amount to show what we gained. """ if self.pay_resources(rtype, -amt): return amt return 0 def pay_materials(self, material_type, amount): """ Attempts to pay materials of the given type and amount Args: material_type (CraftingMaterialType): Material type we're paying with amount: amount we're spending Returns: False if we were able to spend, True otherwise """ from django.core.exceptions import ObjectDoesNotExist assets = self.assets try: if amount < 0: material, _ = assets.materials.get_or_create(type=material_type) else: material = assets.materials.get(type=material_type) if material.amount < amount: return False material.amount -= amount material.save() return True except ObjectDoesNotExist: return False def gain_materials(self, material_type, amount): """Similar to gain_resources, call pay_materials with negative amount to gain it""" return self.pay_materials(material_type, -amount) def pay_action_points(self, amt, can_go_over_cap=False): """ Attempt to pay action points. If we don't have enough, return False. """ try: if self.roster.action_points != self.char_ob.roster.action_points: self.roster.refresh_from_db(fields=("action_points",)) self.char_ob.roster.refresh_from_db(fields=("action_points",)) if self.roster.action_points < amt: return False self.roster.action_points -= amt if self.roster.action_points > self.roster.max_action_points and not can_go_over_cap: self.roster.action_points = self.roster.max_action_points self.roster.save() if amt > 0: verb = "use" else: verb = "gain" amt = abs(amt) self.msg("{wYou %s %s action points and have %s remaining this week.{n" % (verb, amt, self.roster.action_points)) return True except AttributeError: return False @property def retainers(self): """Returns queryset of retainer agents""" try: return self.assets.agents.filter(unique=True) except AttributeError: return [] @property def agents(self): """Returns queryset of any agents we own""" try: return self.assets.agents.all() except AttributeError: return [] def get_absolute_url(self): """Returns our absolute URL for the webpage for our character""" try: return self.char_ob.get_absolute_url() except AttributeError: pass def at_post_disconnect(self): """Called after we disconnect""" if not self.sessions.all(): watched_by = self.char_ob and self.char_ob.db.watched_by or [] if watched_by and not self.db.hide_from_watch: for watcher in watched_by: watcher.msg("{wA player you are watching, {c%s{w, has disconnected.{n" % self.key.capitalize()) self.previous_log = self.current_log self.current_log = [] self.db.lookingforrp = False temp_muted = self.db.temp_mute_list or [] for channel in temp_muted: channel.unmute(self) self.attributes.remove('temp_mute_list') def log_message(self, from_obj, text): """Logs messages if we're not in private for this session""" from evennia.utils.utils import make_iter if not self.tags.get("private_mode"): text = text.strip() from_obj = make_iter(from_obj)[0] tup = (from_obj, text) if tup not in self.current_log and from_obj != self and from_obj != self.char_ob: self.current_log.append((from_obj, text)) @property def current_log(self): """Temporary messages for this session""" if self.ndb.current_log is None: self.ndb.current_log = [] return self.ndb.current_log @current_log.setter def current_log(self, val): self.ndb.current_log = val @property def previous_log(self): """Log of our past session""" if self.db.previous_log is None: self.db.previous_log = [] return self.db.previous_log @previous_log.setter def previous_log(self, val): self.db.previous_log = val @property def flagged_log(self): """Messages flagged for GM notice""" if self.db.flagged_log is None: self.db.flagged_log = [] return self.db.flagged_log @flagged_log.setter def flagged_log(self, val): self.db.flagged_log = val def report_player(self, player): """Reports a player for GM attention""" charob = player.char_ob log = [] for line in (list(self.previous_log) + list(self.current_log)): if line[0] == charob or line[0] == player: log.append(line) self.flagged_log = log @property def allow_list(self): """List of players allowed to interact with us""" if self.db.allow_list is None: self.db.allow_list = [] return self.db.allow_list @property def block_list(self): """List of players who should not be allowed to interact with us""" if self.db.block_list is None: self.db.block_list = [] return self.db.block_list @property def clues_shared_modifier_seed(self): """Seed value for clue sharing costs""" from world.stats_and_skills import SOCIAL_SKILLS, SOCIAL_STATS seed = 0 pc = self.char_ob for stat in SOCIAL_STATS: seed += pc.attributes.get(stat) or 0 # do not be nervous. I love you. <3 seed += sum([pc.skills.get(ob, 0) for ob in SOCIAL_SKILLS]) seed += pc.skills.get("investigation", 0) * 3 return seed @property def clue_cost(self): """Total cost for clues""" return int(100.0/float(self.clues_shared_modifier_seed + 1)) + 1 @property def participated_actions(self): """Actions we participated in""" from world.dominion.models import CrisisAction from django.db.models import Q dompc = self.Dominion return CrisisAction.objects.filter(Q(assistants=dompc) | Q(dompc=dompc)).distinct() @property def past_participated_actions(self): """Actions we participated in previously""" from world.dominion.models import CrisisAction return self.participated_actions.filter(status=CrisisAction.PUBLISHED).distinct() def show_online(self, caller, check_puppet=False): """ Checks if we're online and caller has privileges to see that Args: caller: Player checking if we're online check_puppet: Whether to check if we're currently puppeting our character object Returns: True if they see us as online, False otherwise. """ if not self.char_ob: return True return self.char_ob.show_online(caller, check_puppet) @property def player_ob(self): """Maybe this should return self? Will need to think about that. Inherited from mixins""" return None @property def char_ob(self): """Returns our character object if any""" try: return self.roster.character except AttributeError: pass @property def editable_theories(self): """Theories we have permission to edit""" ids = [ob.theory.id for ob in self.theory_permissions.filter(can_edit=True)] return self.known_theories.filter(id__in=ids) @property def past_actions(self): """Actions we created that have been finished in the past""" return self.Dominion.past_actions @property def recent_actions(self): """Actions we created that have submitted recently""" return self.Dominion.recent_actions @property def recent_assists(self): """Actions we assisted recently""" return self.Dominion.recent_assists def get_current_praises_and_condemns(self): """Current praises given by this player character""" from server.utils.arx_utils import get_week return self.Dominion.praises_given.filter(week=get_week()) def check_motd(self): """Checks for a message of the day and sends it to us.""" from evennia.server.models import ServerConfig motd = ServerConfig.objects.conf(key="MESSAGE_OF_THE_DAY") msg = "" if motd: msg += "|yServer Message of the Day:|n %s\n\n" % motd for membership in self.active_memberships: org = membership.organization if not membership.has_seen_motd and org.motd: msg += "|wMessage of the Day for %s:|n %s\n" % (org, org.motd) membership.has_seen_motd = True membership.save() self.msg(msg) def check_petitions(self): """Checks if we have any unread petition posts""" try: unread = self.Dominion.petitionparticipation_set.filter(unread_posts=True) if unread: unread_ids = [str(ob.petition.id) for ob in unread] self.msg("{wThe following petitions have unread messages:{n %s" % ", ".join(unread_ids)) except AttributeError: pass
[ "evennia.utils.utils.make_iter", "evennia.server.models.ServerConfig.objects.conf" ]
[((19711, 19762), 'evennia.server.models.ServerConfig.objects.conf', 'ServerConfig.objects.conf', ([], {'key': '"""MESSAGE_OF_THE_DAY"""'}), "(key='MESSAGE_OF_THE_DAY')\n", (19736, 19762), False, 'from evennia.server.models import ServerConfig\n'), ((5720, 5742), 'commands.commands.bboards.get_unread_posts', 'get_unread_posts', (['self'], {}), '(self)\n', (5736, 5742), False, 'from commands.commands.bboards import get_unread_posts\n'), ((7890, 7904), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (7902, 7904), False, 'from django.utils import timezone\n'), ((14730, 14749), 'evennia.utils.utils.make_iter', 'make_iter', (['from_obj'], {}), '(from_obj)\n', (14739, 14749), False, 'from evennia.utils.utils import make_iter\n'), ((19536, 19546), 'server.utils.arx_utils.get_week', 'get_week', ([], {}), '()\n', (19544, 19546), False, 'from server.utils.arx_utils import get_week\n'), ((6072, 6105), 'web.character.models.Roster.objects.get', 'Roster.objects.get', ([], {'name': '"""Active"""'}), "(name='Active')\n", (6090, 6105), False, 'from web.character.models import Roster\n'), ((17486, 17505), 'django.db.models.Q', 'Q', ([], {'assistants': 'dompc'}), '(assistants=dompc)\n', (17487, 17505), False, 'from django.db.models import Q\n'), ((17508, 17522), 'django.db.models.Q', 'Q', ([], {'dompc': 'dompc'}), '(dompc=dompc)\n', (17509, 17522), False, 'from django.db.models import Q\n')]
""" Characters Characters are (by default) Objects setup to be puppeted by Accounts. They are what you "see" in game. The Character class in this module is setup to be the "default" character type created by the default creation commands. """ # from evennia import DefaultCharacter from evennia import DefaultRoom, DefaultCharacter from evennia.contrib.ingame_python.typeclasses import EventCharacter from latin.latin_declension import DeclineNoun from typeclasses.latin_noun import LatinNoun # adding next line for new at_say for the EventCharcter class from evennia.utils.utils import inherits_from # added to assign handedness import random # Commenting out and replacing DefaultCharacter so we can use ingame python # # class Character(DefaultCharacter): # # Adding next couple of lines to accommodate clothing from typeclasses import latin_clothing # Adding so that some item is created with characters from evennia.utils.create import create_object # adding for combat from world.tb_basic import TBBasicCharacter from world.tb_basic import is_in_combat import copy class Character(EventCharacter,LatinNoun,TBBasicCharacter): """ The Character defaults to reimplementing some of base Object's hook methods with the following functionality: at_basetype_setup - always assigns the DefaultCmdSet to this object type (important!)sets locks so character cannot be picked up and its commands only be called by itself, not anyone else. (to change things, use at_object_creation() instead). at_after_move(source_location) - Launches the "look" command after every move. at_post_unpuppet(account) - when Account disconnects from the Character, we store the current location in the pre_logout_location Attribute and move it to a None-location so the "unpuppeted" character object does not need to stay on grid. Echoes "Account has disconnected" to the room. at_pre_puppet - Just before Account re-connects, retrieves the character's pre_logout_location Attribute and move it back on the grid. at_post_puppet - Echoes "AccountName has entered the game" to the room. """ def at_object_creation(self): # Accommodoate and prefer the "Nomen" if self.db.nomen: gender = self.db.gender if int(self.db.gender) == 2: genitive = self.db.nomen[:-2] + 'i' else: genitive = self.db.nomen + 'e' nomen = DeclineNoun(self.db.nomen,genitive,gender) nomen_forms = nomen.make_paradigm() self.db.nom_sg = [nomen_forms[0][1]] self.db.gen_sg = [nomen_forms[1][1]] self.db.dat_sg = [nomen_forms[2][1]] self.db.acc_sg = [nomen_forms[3][1]] self.db.abl_sg = [nomen_forms[4][1]] self.db.voc_sg = [nomen_forms[5][1]] self.db.nom_pl = [nomen_forms[6][1]] self.db.gen_pl = [nomen_forms[7][1]] self.db.dat_pl = [nomen_forms[8][1]] self.db.acc_pl = [nomen_forms[9][1]] self.db.abl_pl = [nomen_forms[10][1]] self.db.voc_pl = [nomen_forms[11][1]] # Add the variant forms to aliases for easy interaction for form in nomen_forms: self.aliases.add(form[1]) praenomen = self.db.praenomen if praenomen[-1] == 'a': p_genitive = praenomen + 'e' elif praenomen[-1] == 'r': p_genitive = praenomen + 'is' elif praenomen[-2:] == 'us': p_genitive = praenomen[:-2] + 'i' else: p_genitive = praenomen + 'nis' word = DeclineNoun(praenomen,p_genitive,self.db.gender) forms = word.make_paradigm() self.db.nom_sg.append(forms[0][1]) self.db.gen_sg.append(forms[1][1]) self.db.dat_sg.append(forms[2][1]) self.db.acc_sg.append(forms[3][1]) self.db.abl_sg.append(forms[4][1]) self.db.voc_sg.append(forms[5][1]) self.db.nom_pl.append(forms[6][1]) self.db.gen_pl.append(forms[7][1]) self.db.dat_pl.append(forms[8][1]) self.db.acc_pl.append(forms[9][1]) self.db.abl_pl.append(forms[10][1]) self.db.voc_pl.append(forms[11][1]) # Add the variant forms to aliases for easy interaction for form in forms: self.aliases.add(form[1]) # add all of the case endings to attributes else: word = DeclineNoun(self.db.nom_sg[0],self.db.gen_sg[0],self.db.gender) forms = word.make_paradigm() all_forms = forms forms = forms[2:] self.db.dat_sg = [forms[0][1]] self.db.acc_sg = [forms[1][1]] self.db.abl_sg = [forms[2][1]] self.db.voc_sg = [forms[3][1]] self.db.nom_pl = [forms[4][1]] self.db.gen_pl = [forms[5][1]] self.db.dat_pl = [forms[6][1]] self.db.acc_pl = [forms[7][1]] self.db.abl_pl = [forms[8][1]] self.db.voc_pl = [forms[9][1]] # Add the variant forms to aliases for easy interaction for form in all_forms: self.aliases.add(form[1]) self.tags.add('latin') # assign handedness if random.random() >= 0.9: self.db.handedness = 'left' else: self.db.handedness = 'right' # set hands as empty self.db.right_hand = False self.db.left_hand = False # Experiment with stats if not self.db.stats: statNums = [0,0,0,0,0,0] points = 27; while points > 0: index = random.randint(0,5) if statNums[index] < 5 and points > 0: statNums[index] += 1 points -= 1 elif statNums[index] in [5,6] and points > 1: statNums[index] += 1 points -= 2 for index,value in enumerate(statNums): statNums[index] += 9 self.db.stats = {'str':statNums[0],'dex':statNums[1],'con':statNums[2],'int':statNums[3],'wis':statNums[4],'cha':statNums[5]} # first calculate the bonus bonus = self.db.stats['con'] bonus = (bonus - 11) if bonus % 2 else (bonus - 10) max_hp = (10 + bonus) if (10 + bonus) > 0 else 1 self.db.hp = {'max':max_hp,"current":max_hp} # if bonus % 2 != 0: # bonus -= 1 # bonus -= 10 # bonus /= 2 # starting_hp = 10 + int(bonus) # if starting_hp <= 0: # starting_hp = 1 # self.db.hp = {'max':starting_hp,'current':starting_hp} # lifting/carrying strength = self.db.stats['str'] self.db.lift_carry = {'lift': round(strength * 30 * 0.45,1), 'encumbered': round(strength * 5 * 0.45,1), 'v_encumbered': round(strength * 10 * 0.45,1),'current':0,'max':round(strength * 15 * 0.45,1)} # Add the following so players start with clothes underwear = create_object( typeclass = "typeclasses.latin_clothing.Clothing", key = "subligaculum", location = self.dbref, attributes=[ ('gender','3'), ('clothing_type','underpants'), ('nom_sg',['subligaculum']), ('gen_sg',['subligaculi']), ('worn',True), ('desc','Briefs'), ('physical',{'material':'linen','rigid':False,'volume':0.5,'mass':0.45}) ] ) if int(self.db.gender) == 1: bandeau = create_object( typeclass = "typeclasses.latin_clothing.Clothing", key = "strophium", location = self.dbref, attributes=[ ('gender','3'), ('clothing_type','undershirt'), ('nom_sg',['strophium']), ('gen_sg',['strophii']), ('worn',True), ('desc','A bandeau'), ('physical',{'material':'linen','rigid':False,'volume':0.5,'mass':0.45}) ] ) items_carried = self.contents mass_carried = 0 for item in items_carried: mass_carried += item.db.physical['mass'] self.db.lift_carry['current'] = mass_carried # For turn-based battle def at_before_move(self, destination): """ Called just before starting to move this object to destination. Args: destination (Object): The object we are moving to Returns: shouldmove (bool): If we should move or not. Notes: If this method returns False/None, the move is cancelled before it is even started. """ # Keep the character from moving if at 0 HP or in combat. if is_in_combat(self): self.msg("You can't exit a room while in combat!") return False # Returning false keeps the character from moving. if self.db.hp['current'] <= 0: self.msg("You can't move, you've been defeated!") return False return True #making a new get_display_name that is aware of case and not # dependent on the key of the object def get_display_name(self, looker, **kwargs): if not self.db.nom_sg: if self.locks.check_lockstring(looker, "perm(Builder)"): return "{}(#{})".format(self.key, self.id) return self.key else: if self.locks.check_lockstring(looker, "perm(Builder)"): return "{}(#{})".format(self.key, self.id) return self.key def announce_move_from(self, destination, msg=None, mapping=None): """ Called if the move is to be announced. This is called while we are still standing in the old location. Args: destination (Object): The place we are going to. msg (str, optional): a replacement message. mapping (dict, optional): additional mapping objects. You can override this method and call its parent with a message to simply change the default message. In the string, you can use the following as mappings (between braces): object: the object which is moving. exit: the exit from which the object is moving (if found). origin: the location of the object before the move. destination: the location of the object after moving. """ if not self.location: return # changing {origin} to {exit} string = msg or "{object} {exit} discessit." #, heading for {destination}." # Get the exit from location to destination location = self.location exits = [ o for o in location.contents if o.location is location and o.destination is destination ] mapping = mapping or {} mapping.update({"character": self}) if exits: exits[0].callbacks.call( "msg_leave", self, exits[0], location, destination, string, mapping ) string = exits[0].callbacks.get_variable("message") mapping = exits[0].callbacks.get_variable("mapping") # If there's no string, don't display anything # It can happen if the "message" variable in events is set to None if not string: return super().announce_move_from(destination, msg=string, mapping=mapping) def announce_move_to(self, source_location, msg=None, mapping=None): """ Called after the move if the move was not quiet. At this point we are standing in the new location. Args: source_location (Object): The place we came from msg (str, optional): the replacement message if location. mapping (dict, optional): additional mapping objects. You can override this method and call its parent with a message to simply change the default message. In the string, you can use the following as mappings (between braces): object: the object which is moving. exit: the exit from which the object is moving (if found). origin: the location of the object before the move. destination: the location of the object after moving. """ if not source_location and self.location.has_account: # This was created from nowhere and added to an account's # inventory; it's probably the result of a create command. string = "You now have %s in your possession." % self.get_display_name(self.location) self.location.msg(string) return # added the line below because origin = source_location # error checking self.location.msg(source_location) if source_location: origin = source_location.db.abl_sg[0] string = msg or f"{self.key} ab {source_location.db.abl_sg[0]} venit." else: string = "{character} venit." # adding '.db.abl_sg' to end of 'source_location' and moving from line below # up into the 'if source_location' conditional destination = self.location exits = [] mapping = mapping or {} mapping.update({"character": self}) if origin: exits = [ o for o in destination.contents if o.location is destination and o.destination is origin ] if exits: exits[0].callbacks.call( "msg_arrive", self, exits[0], origin, destination, string, mapping ) string = exits[0].callbacks.get_variable("message") mapping = exits[0].callbacks.get_variable("mapping") # If there's no string, don't display anything # It can happen if the "message" variable in events is set to None if not string: return super().announce_move_to(source_location, msg=string, mapping=mapping) # This older 'at_say' is VERY different from the new EventCharacter ones. # commenting out to see what changes. EventCharacter say implements this # before executing its own things. Will incorporate new at_say event below def at_say( self, message, msg_self=None, msg_location=None, receivers=None, msg_receivers=None, **kwargs, ): """ Display the actual say (or whisper) of self. This hook should display the actual say/whisper of the object in its location. It should both alert the object (self) and its location that some text is spoken. The overriding of messages or `mapping` allows for simple customization of the hook without re-writing it completely. Args: message (str): The message to convey. msg_self (bool or str, optional): If boolean True, echo `message` to self. If a string, return that message. If False or unset, don't echo to self. msg_location (str, optional): The message to echo to self's location. receivers (Object or iterable, optional): An eventual receiver or receivers of the message (by default only used by whispers). msg_receivers(str): Specific message to pass to the receiver(s). This will parsed with the {receiver} placeholder replaced with the given receiver. Kwargs: whisper (bool): If this is a whisper rather than a say. Kwargs can be used by other verbal commands in a similar way. mapping (dict): Pass an additional mapping to the message. Notes: Messages can contain {} markers. These are substituted against the values passed in the `mapping` argument. msg_self = 'You say: "{speech}"' msg_location = '{object} says: "{speech}"' msg_receivers = '{object} whispers: "{speech}"' Supported markers by default: {self}: text to self-reference with (default 'You') {speech}: the text spoken/whispered by self. {object}: the object speaking. {receiver}: replaced with a single receiver only for strings meant for a specific receiver (otherwise 'None'). {all_receivers}: comma-separated list of all receivers, if more than one, otherwise same as receiver {location}: the location where object is. """ # Need to split the statement into two parts if there's more than 1 word # Having a problem with displaying speaker's name; changing 'object' to 'self.key' sentence = message.strip() words = sentence.split(' ') speeches = [f'"{words[0]}" inquis.',f'{self.key} "{words[0]}" inquit.'] first = words[0] if len(words) > 1: rest = ' '.join(words[1:]) speeches = [f'"{words[0]}" inquis "{rest}"',f'{self.key} "{words[0]}" inquit "{rest}"'] # Added the above on 11/24 msg_type = "say" if kwargs.get("whisper", False): # whisper mode msg_type = "whisper" msg_self = ( '{self} whisper to {all_receivers}, "{speech}"' if msg_self is True else msg_self ) msg_receivers = msg_receivers or '{object} whispers: "{speech}"' msg_location = None else: # altering the commented out line immediately below to the line below that # msg_self = '{self} say, "{speech}"' if msg_self is True else msg_self msg_self = speeches[0] if msg_self is True else msg_self # altering the immediately below commented line # msg_location = msg_location or '{object} says, "{speech}"' msg_location = msg_location or speeches[1] msg_receivers = msg_receivers or message custom_mapping = kwargs.get("mapping", {}) receivers = make_iter(receivers) if receivers else None location = self.location if msg_self: self_mapping = { "self": "You", "object": self.get_display_name(self), "location": location.get_display_name(self) if location else None, "receiver": None, "all_receivers": ", ".join(recv.get_display_name(self) for recv in receivers) if receivers else None, "speech": message, } self_mapping.update(custom_mapping) self.msg(text=(msg_self.format(**self_mapping), {"type": msg_type}), from_obj=self) if receivers and msg_receivers: receiver_mapping = { "self": "You", "object": None, "location": None, "receiver": None, "all_receivers": None, "speech": message, } for receiver in make_iter(receivers): individual_mapping = { "object": self.get_display_name(receiver), "location": location.get_display_name(receiver), "receiver": receiver.get_display_name(receiver), "all_receivers": ", ".join(recv.get_display_name(recv) for recv in receivers) if receivers else None, } receiver_mapping.update(individual_mapping) receiver_mapping.update(custom_mapping) receiver.msg( text=(msg_receivers.format(**receiver_mapping), {"type": msg_type}), from_obj=self, ) if self.location and msg_location: location_mapping = { "self": "You", "object": self, "location": location, "all_receivers": ", ".join(str(recv) for recv in receivers) if receivers else None, "receiver": None, "speech": message, } location_mapping.update(custom_mapping) exclude = [] if msg_self: exclude.append(self) if receivers: exclude.extend(receivers) self.location.msg_contents( text=(msg_location, {"type": msg_type}), from_obj=self, exclude=exclude, mapping=location_mapping, ) location = getattr(self, "location", None) location = ( location if location and inherits_from(location, "evennia.objects.objects.DefaultRoom") else None ) if location and not kwargs.get("whisper", False): location.callbacks.call("say", self, location, message, parameters=message) # Call the other characters' "say" event presents = [ obj for obj in location.contents if obj is not self and inherits_from(obj, "evennia.objects.objects.DefaultCharacter") ] for present in presents: present.callbacks.call("say", self, present, message, parameters=message) # adding the following to accommodate clothing def return_appearance(self, looker, **kwargs): """ # Lightly editing to change "You see" to "Ecce" # and 'Exits' to 'Ad hos locos ire potes:' This formats a description. It is the hook a 'look' command should call. Args: looker (Object): Object doing the looking. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ if not looker: return "" # get and identify all objects # JI (12/7/19) Commenting out the following which probably shouldn't apply to characters. # visible = (con for con in self.contents if con != looker and con.access(looker, "view")) # exits, users, things = [], [], defaultdict(list) # for con in visible: # key = con.get_display_name(looker) # if con.destination: # exits.append(key) # elif con.has_account: # users.append("|c%s|n" % key) # else: # # things can be pluralized # things[key].append(con) # get description, build string string = "|c%s|n\n" % self.get_display_name(looker) desc = self.db.desc # JI (12/7/9) Adding the following lines to accommodate clothing worn_string_list = [] clothes_list = latin_clothing.get_worn_clothes(self, exclude_covered=True) # Append worn, uncovered clothing to the description for garment in clothes_list: # if 'worn' is True, just append the name if garment.db.worn is True: if garment.db.is_glowing: worn_string_list.append(f"|yarden{'s' if garment.db.gender == 3 else 'tem'}|n {garment.db.acc_sg[0]}") # JI (12/7/19) append the accusative name to the description, # since these will be direct objects else: worn_string_list.append(garment.db.acc_sg[0]) # Otherwise, append the name and the string value of 'worn' elif garment.db.worn: worn_string_list.append("%s %s" % (garment.name, garment.db.worn)) # get held clothes possessions = self.contents held_list = [] for possession in possessions: if possession.db.held: if possession.db.is_glowing: held_list.append(f"|y(arden{'s' if possession.db.gender == 3 else 'tem'})|n {possession.db.acc_sg[0]}") else: held_list.append(possession.db.acc_sg[0]) if desc: string += "%s" % desc # Append held items. if held_list: string += "|/|/%s tenet: %s." % (self, LatinNoun.list_to_string(held_list)) # Append worn clothes. if worn_string_list: string += "|/|/%s gerit: %s." % (self, LatinNoun.list_to_string(worn_string_list)) else: string += "|/|/%s nud%s est!" % (self, 'a' if self.db.gender == 1 else 'us') return string # Thinking that the above, added for clothing, might need to only be in the # character typeclass def at_after_move(self,source_location): super().at_after_move(source_location) # origin = source_location # destination = self.location # Room = DefaultRoom # if isinstance(origin, Room) and isinstance(destination, Room): # self.callbacks.call("move", self, origin, destination) # destination.callbacks.call("move", self, origin, destination) # # # Call the 'greet' event of characters in the location # for present in [ # o for o in destination.contents if isinstance(o, DefaultCharacter) and o is not self # ]: # present.callbacks.call("greet", present, self) # # target = self.location # self.msg((self.at_look(target), {"type": "look"}), options=None) if self.db.hp: prompt = "\n|wVita: %i/%i) |n" % (self.db.hp['current'],self.db.hp['max']) self.msg(prompt)
[ "evennia.utils.utils.inherits_from", "evennia.utils.create.create_object" ]
[((7286, 7648), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""typeclasses.latin_clothing.Clothing"""', 'key': '"""subligaculum"""', 'location': 'self.dbref', 'attributes': "[('gender', '3'), ('clothing_type', 'underpants'), ('nom_sg', [\n 'subligaculum']), ('gen_sg', ['subligaculi']), ('worn', True), ('desc',\n 'Briefs'), ('physical', {'material': 'linen', 'rigid': False, 'volume':\n 0.5, 'mass': 0.45})]"}), "(typeclass='typeclasses.latin_clothing.Clothing', key=\n 'subligaculum', location=self.dbref, attributes=[('gender', '3'), (\n 'clothing_type', 'underpants'), ('nom_sg', ['subligaculum']), ('gen_sg',\n ['subligaculi']), ('worn', True), ('desc', 'Briefs'), ('physical', {\n 'material': 'linen', 'rigid': False, 'volume': 0.5, 'mass': 0.45})])\n", (7299, 7648), False, 'from evennia.utils.create import create_object\n'), ((9288, 9306), 'world.tb_basic.is_in_combat', 'is_in_combat', (['self'], {}), '(self)\n', (9300, 9306), False, 'from world.tb_basic import is_in_combat\n'), ((23392, 23451), 'typeclasses.latin_clothing.get_worn_clothes', 'latin_clothing.get_worn_clothes', (['self'], {'exclude_covered': '(True)'}), '(self, exclude_covered=True)\n', (23423, 23451), False, 'from typeclasses import latin_clothing\n'), ((2605, 2649), 'latin.latin_declension.DeclineNoun', 'DeclineNoun', (['self.db.nomen', 'genitive', 'gender'], {}), '(self.db.nomen, genitive, gender)\n', (2616, 2649), False, 'from latin.latin_declension import DeclineNoun\n'), ((3820, 3870), 'latin.latin_declension.DeclineNoun', 'DeclineNoun', (['praenomen', 'p_genitive', 'self.db.gender'], {}), '(praenomen, p_genitive, self.db.gender)\n', (3831, 3870), False, 'from latin.latin_declension import DeclineNoun\n'), ((4705, 4770), 'latin.latin_declension.DeclineNoun', 'DeclineNoun', (['self.db.nom_sg[0]', 'self.db.gen_sg[0]', 'self.db.gender'], {}), '(self.db.nom_sg[0], self.db.gen_sg[0], self.db.gender)\n', (4716, 4770), False, 'from latin.latin_declension import DeclineNoun\n'), ((5519, 5534), 'random.random', 'random.random', ([], {}), '()\n', (5532, 5534), False, 'import random\n'), ((7926, 8283), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""typeclasses.latin_clothing.Clothing"""', 'key': '"""strophium"""', 'location': 'self.dbref', 'attributes': "[('gender', '3'), ('clothing_type', 'undershirt'), ('nom_sg', ['strophium']\n ), ('gen_sg', ['strophii']), ('worn', True), ('desc', 'A bandeau'), (\n 'physical', {'material': 'linen', 'rigid': False, 'volume': 0.5, 'mass':\n 0.45})]"}), "(typeclass='typeclasses.latin_clothing.Clothing', key=\n 'strophium', location=self.dbref, attributes=[('gender', '3'), (\n 'clothing_type', 'undershirt'), ('nom_sg', ['strophium']), ('gen_sg', [\n 'strophii']), ('worn', True), ('desc', 'A bandeau'), ('physical', {\n 'material': 'linen', 'rigid': False, 'volume': 0.5, 'mass': 0.45})])\n", (7939, 8283), False, 'from evennia.utils.create import create_object\n'), ((5918, 5938), 'random.randint', 'random.randint', (['(0)', '(5)'], {}), '(0, 5)\n', (5932, 5938), False, 'import random\n'), ((21307, 21369), 'evennia.utils.utils.inherits_from', 'inherits_from', (['location', '"""evennia.objects.objects.DefaultRoom"""'], {}), "(location, 'evennia.objects.objects.DefaultRoom')\n", (21320, 21369), False, 'from evennia.utils.utils import inherits_from\n'), ((24783, 24818), 'typeclasses.latin_noun.LatinNoun.list_to_string', 'LatinNoun.list_to_string', (['held_list'], {}), '(held_list)\n', (24807, 24818), False, 'from typeclasses.latin_noun import LatinNoun\n'), ((24931, 24973), 'typeclasses.latin_noun.LatinNoun.list_to_string', 'LatinNoun.list_to_string', (['worn_string_list'], {}), '(worn_string_list)\n', (24955, 24973), False, 'from typeclasses.latin_noun import LatinNoun\n'), ((21748, 21810), 'evennia.utils.utils.inherits_from', 'inherits_from', (['obj', '"""evennia.objects.objects.DefaultCharacter"""'], {}), "(obj, 'evennia.objects.objects.DefaultCharacter')\n", (21761, 21810), False, 'from evennia.utils.utils import inherits_from\n')]
""" Spawner The spawner takes input files containing object definitions in dictionary forms. These use a prototype architecture to define unique objects without having to make a Typeclass for each. There main function is `spawn(*prototype)`, where the `prototype` is a dictionary like this: ```python from evennia.prototypes import prototypes prot = { "prototype_key": "goblin", "typeclass": "types.objects.Monster", "key": "goblin grunt", "health": lambda: randint(20,30), "resists": ["cold", "poison"], "attacks": ["fists"], "weaknesses": ["fire", "light"] "tags": ["mob", "evil", ('greenskin','mob')] "attrs": [("weapon", "sword")] } prot = prototypes.create_prototype(prot) ``` Possible keywords are: prototype_key (str): name of this prototype. This is used when storing prototypes and should be unique. This should always be defined but for prototypes defined in modules, the variable holding the prototype dict will become the prototype_key if it's not explicitly given. prototype_desc (str, optional): describes prototype in listings prototype_locks (str, optional): locks for restricting access to this prototype. Locktypes supported are 'edit' and 'use'. prototype_tags(list, optional): List of tags or tuples (tag, category) used to group prototype in listings prototype_parent (str, tuple or callable, optional): name (prototype_key) of eventual parent prototype, or a list of parents, for multiple left-to-right inheritance. prototype: Deprecated. Same meaning as 'parent'. typeclass (str or callable, optional): if not set, will use typeclass of parent prototype or use `settings.BASE_OBJECT_TYPECLASS` key (str or callable, optional): the name of the spawned object. If not given this will set to a random hash location (obj, str or callable, optional): location of the object - a valid object or #dbref home (obj, str or callable, optional): valid object or #dbref destination (obj, str or callable, optional): only valid for exits (object or #dbref) permissions (str, list or callable, optional): which permissions for spawned object to have locks (str or callable, optional): lock-string for the spawned object aliases (str, list or callable, optional): Aliases for the spawned object exec (str or callable, optional): this is a string of python code to execute or a list of such codes. This can be used e.g. to trigger custom handlers on the object. The execution namespace contains 'evennia' for the library and 'obj'. All default spawn commands limit this functionality to Developer/superusers. Usually it's better to use callables or prototypefuncs instead of this. tags (str, tuple, list or callable, optional): string or list of strings or tuples `(tagstr, category)`. Plain strings will be result in tags with no category (default tags). attrs (tuple, list or callable, optional): tuple or list of tuples of Attributes to add. This form allows more complex Attributes to be set. Tuples at least specify `(key, value)` but can also specify up to `(key, value, category, lockstring)`. If you want to specify a lockstring but not a category, set the category to `None`. ndb_<name> (any): value of a nattribute (ndb_ is stripped) - this is of limited use. other (any): any other name is interpreted as the key of an Attribute with its value. Such Attributes have no categories. Each value can also be a callable that takes no arguments. It should return the value to enter into the field and will be called every time the prototype is used to spawn an object. Note, if you want to store a callable in an Attribute, embed it in a tuple to the `args` keyword. By specifying the "prototype_parent" key, the prototype becomes a child of the given prototype, inheritng all prototype slots it does not explicitly define itself, while overloading those that it does specify. ```python import random { "prototype_key": "goblin_wizard", "prototype_parent": GOBLIN, "key": "goblin wizard", "spells": ["fire ball", "lighting bolt"] } GOBLIN_ARCHER = { "prototype_parent": GOBLIN, "key": "goblin archer", "attack_skill": (random, (5, 10))" "attacks": ["short bow"] } ``` One can also have multiple prototypes. These are inherited from the left, with the ones further to the right taking precedence. ```python ARCHWIZARD = { "attack": ["archwizard staff", "eye of doom"] GOBLIN_ARCHWIZARD = { "key" : "goblin archwizard" "prototype_parent": (GOBLIN_WIZARD, ARCHWIZARD), } ``` The *goblin archwizard* will have some different attacks, but will otherwise have the same spells as a *goblin wizard* who in turn shares many traits with a normal *goblin*. Storage mechanism: This sets up a central storage for prototypes. The idea is to make these available in a repository for buildiers to use. Each prototype is stored in a Script so that it can be tagged for quick sorting/finding and locked for limiting access. This system also takes into consideration prototypes defined and stored in modules. Such prototypes are considered 'read-only' to the system and can only be modified in code. To replace a default prototype, add the same-name prototype in a custom module read later in the settings.PROTOTYPE_MODULES list. To remove a default prototype, override its name with an empty dict. """ import copy import hashlib import time from django.conf import settings import evennia from evennia.objects.models import ObjectDB from evennia.utils import logger from evennia.utils.utils import make_iter, is_iter from evennia.prototypes import prototypes as protlib from evennia.prototypes.prototypes import ( value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY, ) _CREATE_OBJECT_KWARGS = ("key", "location", "home", "destination") _PROTOTYPE_META_NAMES = ("prototype_key", "prototype_desc", "prototype_tags", "prototype_locks") _PROTOTYPE_ROOT_NAMES = ( "typeclass", "key", "aliases", "attrs", "tags", "locks", "permissions", "location", "home", "destination", ) _NON_CREATE_KWARGS = _CREATE_OBJECT_KWARGS + _PROTOTYPE_META_NAMES class Unset: """ Helper class representing a non-set diff element. """ def __bool__(self): return False def __str__(self): return "<Unset>" # Helper def _get_prototype(inprot, protparents, uninherited=None, _workprot=None): """ Recursively traverse a prototype dictionary, including multiple inheritance. Use validate_prototype before this, we don't check for infinite recursion here. Args: inprot (dict): Prototype dict (the individual prototype, with no inheritance included). protparents (dict): Available protparents, keyed by prototype_key. uninherited (dict): Parts of prototype to not inherit. _workprot (dict, optional): Work dict for the recursive algorithm. Returns: merged (dict): A prototype where parent's have been merged as needed (the `prototype_parent` key is removed). """ def _inherit_tags(old_tags, new_tags): old = {(tup[0], tup[1]): tup for tup in old_tags} new = {(tup[0], tup[1]): tup for tup in new_tags} old.update(new) return list(old.values()) def _inherit_attrs(old_attrs, new_attrs): old = {(tup[0], tup[2]): tup for tup in old_attrs} new = {(tup[0], tup[2]): tup for tup in new_attrs} old.update(new) return list(old.values()) _workprot = {} if _workprot is None else _workprot if "prototype_parent" in inprot: # move backwards through the inheritance for prototype in make_iter(inprot["prototype_parent"]): # Build the prot dictionary in reverse order, overloading new_prot = _get_prototype( protparents.get(prototype.lower(), {}), protparents, _workprot=_workprot ) # attrs, tags have internal structure that should be inherited separately new_prot["attrs"] = _inherit_attrs( _workprot.get("attrs", {}), new_prot.get("attrs", {}) ) new_prot["tags"] = _inherit_tags(_workprot.get("tags", {}), new_prot.get("tags", {})) _workprot.update(new_prot) # the inprot represents a higher level (a child prot), which should override parents inprot["attrs"] = _inherit_attrs(_workprot.get("attrs", {}), inprot.get("attrs", {})) inprot["tags"] = _inherit_tags(_workprot.get("tags", {}), inprot.get("tags", {})) _workprot.update(inprot) if uninherited: # put back the parts that should not be inherited _workprot.update(uninherited) _workprot.pop("prototype_parent", None) # we don't need this for spawning return _workprot def flatten_prototype(prototype, validate=False): """ Produce a 'flattened' prototype, where all prototype parents in the inheritance tree have been merged into a final prototype. Args: prototype (dict): Prototype to flatten. Its `prototype_parent` field will be parsed. validate (bool, optional): Validate for valid keys etc. Returns: flattened (dict): The final, flattened prototype. """ if prototype: prototype = protlib.homogenize_prototype(prototype) protparents = {prot["prototype_key"].lower(): prot for prot in protlib.search_prototype()} protlib.validate_prototype( prototype, None, protparents, is_prototype_base=validate, strict=validate ) return _get_prototype( prototype, protparents, uninherited={"prototype_key": prototype.get("prototype_key")} ) return {} # obj-related prototype functions def prototype_from_object(obj): """ Guess a minimal prototype from an existing object. Args: obj (Object): An object to analyze. Returns: prototype (dict): A prototype estimating the current state of the object. """ # first, check if this object already has a prototype prot = obj.tags.get(category=PROTOTYPE_TAG_CATEGORY, return_list=True) if prot: prot = protlib.search_prototype(prot[0]) if not prot or len(prot) > 1: # no unambiguous prototype found - build new prototype prot = {} prot["prototype_key"] = "From-Object-{}-{}".format( obj.key, hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:7] ) prot["prototype_desc"] = "Built from {}".format(str(obj)) prot["prototype_locks"] = "spawn:all();edit:all()" prot["prototype_tags"] = [] else: prot = prot[0] prot["key"] = obj.db_key or hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:6] prot["typeclass"] = obj.db_typeclass_path location = obj.db_location if location: prot["location"] = location.dbref home = obj.db_home if home: prot["home"] = home.dbref destination = obj.db_destination if destination: prot["destination"] = destination.dbref locks = obj.locks.all() if locks: prot["locks"] = ";".join(locks) perms = obj.permissions.get(return_list=True) if perms: prot["permissions"] = make_iter(perms) aliases = obj.aliases.get(return_list=True) if aliases: prot["aliases"] = aliases tags = sorted( [(tag.db_key, tag.db_category, tag.db_data) for tag in obj.tags.all(return_objs=True)] ) if tags: prot["tags"] = tags attrs = sorted( [ (attr.key, attr.value, attr.category, ";".join(attr.locks.all())) for attr in obj.attributes.all() ] ) if attrs: prot["attrs"] = attrs return prot def prototype_diff(prototype1, prototype2, maxdepth=2, homogenize=False, implicit_keep=False): """ A 'detailed' diff specifies differences down to individual sub-sections of the prototype, like individual attributes, permissions etc. It is used by the menu to allow a user to customize what should be kept. Args: prototype1 (dict): Original prototype. prototype2 (dict): Comparison prototype. maxdepth (int, optional): The maximum depth into the diff we go before treating the elements of iterables as individual entities to compare. This is important since a single attr/tag (for example) are represented by a tuple. homogenize (bool, optional): Auto-homogenize both prototypes for the best comparison. This is most useful for displaying. implicit_keep (bool, optional): If set, the resulting diff will assume KEEP unless the new prototype explicitly change them. That is, if a key exists in `prototype1` and not in `prototype2`, it will not be REMOVEd but set to KEEP instead. This is particularly useful for auto-generated prototypes when updating objects. Returns: diff (dict): A structure detailing how to convert prototype1 to prototype2. All nested structures are dicts with keys matching either the prototype's matching key or the first element in the tuple describing the prototype value (so for a tag tuple `(tagname, category)` the second-level key in the diff would be tagname). The the bottom level of the diff consist of tuples `(old, new, instruction)`, where instruction can be one of "REMOVE", "ADD", "UPDATE" or "KEEP". """ _unset = Unset() def _recursive_diff(old, new, depth=0): old_type = type(old) new_type = type(new) if old_type == new_type and not (old or new): # both old and new are unset, like [] or None return (None, None, "KEEP") if old_type != new_type: if old and not new: if depth < maxdepth and old_type == dict: return {key: (part, None, "REMOVE") for key, part in old.items()} elif depth < maxdepth and is_iter(old): return { part[0] if is_iter(part) else part: (part, None, "REMOVE") for part in old } if isinstance(new, Unset) and implicit_keep: # the new does not define any change, use implicit-keep return (old, None, "KEEP") return (old, new, "REMOVE") elif not old and new: if depth < maxdepth and new_type == dict: return {key: (None, part, "ADD") for key, part in new.items()} elif depth < maxdepth and is_iter(new): return {part[0] if is_iter(part) else part: (None, part, "ADD") for part in new} return (old, new, "ADD") else: # this condition should not occur in a standard diff return (old, new, "UPDATE") elif depth < maxdepth and new_type == dict: all_keys = set(list(old.keys()) + list(new.keys())) return { key: _recursive_diff(old.get(key, _unset), new.get(key, _unset), depth=depth + 1) for key in all_keys } elif depth < maxdepth and is_iter(new): old_map = {part[0] if is_iter(part) else part: part for part in old} new_map = {part[0] if is_iter(part) else part: part for part in new} all_keys = set(list(old_map.keys()) + list(new_map.keys())) return { key: _recursive_diff( old_map.get(key, _unset), new_map.get(key, _unset), depth=depth + 1 ) for key in all_keys } elif old != new: return (old, new, "UPDATE") else: return (old, new, "KEEP") prot1 = protlib.homogenize_prototype(prototype1) if homogenize else prototype1 prot2 = protlib.homogenize_prototype(prototype2) if homogenize else prototype2 diff = _recursive_diff(prot1, prot2) return diff def flatten_diff(diff): """ For spawning, a 'detailed' diff is not necessary, rather we just want instructions on how to handle each root key. Args: diff (dict): Diff produced by `prototype_diff` and possibly modified by the user. Note that also a pre-flattened diff will come out unchanged by this function. Returns: flattened_diff (dict): A flat structure detailing how to operate on each root component of the prototype. Notes: The flattened diff has the following possible instructions: UPDATE, REPLACE, REMOVE Many of the detailed diff's values can hold nested structures with their own individual instructions. A detailed diff can have the following instructions: REMOVE, ADD, UPDATE, KEEP Here's how they are translated: - All REMOVE -> REMOVE - All ADD|UPDATE -> UPDATE - All KEEP -> KEEP - Mix KEEP, UPDATE, ADD -> UPDATE - Mix REMOVE, KEEP, UPDATE, ADD -> REPLACE """ valid_instructions = ("KEEP", "REMOVE", "ADD", "UPDATE") def _get_all_nested_diff_instructions(diffpart): "Started for each root key, returns all instructions nested under it" out = [] typ = type(diffpart) if typ == tuple and len(diffpart) == 3 and diffpart[2] in valid_instructions: out = [diffpart[2]] elif typ == dict: # all other are dicts for val in diffpart.values(): out.extend(_get_all_nested_diff_instructions(val)) else: raise RuntimeError( "Diff contains non-dicts that are not on the " "form (old, new, inst): {}".format(diffpart) ) return out flat_diff = {} # flatten diff based on rules for rootkey, diffpart in diff.items(): insts = _get_all_nested_diff_instructions(diffpart) if all(inst == "KEEP" for inst in insts): rootinst = "KEEP" elif all(inst in ("ADD", "UPDATE") for inst in insts): rootinst = "UPDATE" elif all(inst == "REMOVE" for inst in insts): rootinst = "REMOVE" elif "REMOVE" in insts: rootinst = "REPLACE" else: rootinst = "UPDATE" flat_diff[rootkey] = rootinst return flat_diff def prototype_diff_from_object(prototype, obj, implicit_keep=True): """ Get a simple diff for a prototype compared to an object which may or may not already have a prototype (or has one but changed locally). For more complex migratations a manual diff may be needed. Args: prototype (dict): New prototype. obj (Object): Object to compare prototype against. Returns: diff (dict): Mapping for every prototype key: {"keyname": "REMOVE|UPDATE|KEEP", ...} obj_prototype (dict): The prototype calculated for the given object. The diff is how to convert this prototype into the new prototype. implicit_keep (bool, optional): This is usually what one wants for object updating. When set, this means the prototype diff will assume KEEP on differences between the object-generated prototype and that which is not explicitly set in the new prototype. This means e.g. that even though the object has a location, and the prototype does not specify the location, it will not be unset. Notes: The `diff` is on the following form: {"key": (old, new, "KEEP|REPLACE|UPDATE|REMOVE"), "attrs": {"attrkey": (old, new, "KEEP|REPLACE|UPDATE|REMOVE"), "attrkey": (old, new, "KEEP|REPLACE|UPDATE|REMOVE"), ...}, "aliases": {"aliasname": (old, new, "KEEP...", ...}, ... } """ obj_prototype = prototype_from_object(obj) diff = prototype_diff( obj_prototype, protlib.homogenize_prototype(prototype), implicit_keep=implicit_keep ) return diff, obj_prototype def format_diff(diff, minimal=True): """ Reformat a diff for presentation. This is a shortened version of the olc _format_diff_text_and_options without the options. Args: diff (dict): A diff as produced by `prototype_diff`. minimal (bool, optional): Only show changes (remove KEEPs) Returns: texts (str): The formatted text. """ valid_instructions = ("KEEP", "REMOVE", "ADD", "UPDATE") def _visualize(obj, rootname, get_name=False): if is_iter(obj): if not obj: return str(obj) if get_name: return obj[0] if obj[0] else "<unset>" if rootname == "attrs": return "{} |w=|n {} |w(category:|n |n{}|w, locks:|n {}|w)|n".format(*obj) elif rootname == "tags": return "{} |w(category:|n {}|w)|n".format(obj[0], obj[1]) return "{}".format(obj) def _parse_diffpart(diffpart, rootname): typ = type(diffpart) texts = [] if typ == tuple and len(diffpart) == 3 and diffpart[2] in valid_instructions: old, new, instruction = diffpart if instruction == "KEEP": if not minimal: texts.append(" |gKEEP|n: {old}".format(old=_visualize(old, rootname))) elif instruction == "ADD": texts.append(" |yADD|n: {new}".format(new=_visualize(new, rootname))) elif instruction == "REMOVE" and not new: texts.append(" |rREMOVE|n: {old}".format(old=_visualize(old, rootname))) else: vold = _visualize(old, rootname) vnew = _visualize(new, rootname) vsep = "" if len(vold) < 78 else "\n" vinst = " |rREMOVE|n" if instruction == "REMOVE" else "|y{}|n".format(instruction) varrow = "|r->|n" if instruction == "REMOVE" else "|y->|n" texts.append( " {inst}|W:|n {old} |W{varrow}|n{sep} {new}".format( inst=vinst, old=vold, varrow=varrow, sep=vsep, new=vnew ) ) else: for key in sorted(list(diffpart.keys())): subdiffpart = diffpart[key] text = _parse_diffpart(subdiffpart, rootname) texts.extend(text) return texts texts = [] for root_key in sorted(diff): diffpart = diff[root_key] text = _parse_diffpart(diffpart, root_key) if text or not minimal: heading = "- |w{}:|n\n".format(root_key) if text: text = [heading + text[0]] + text[1:] else: text = [heading] texts.extend(text) return "\n ".join(line for line in texts if line) def batch_update_objects_with_prototype(prototype, diff=None, objects=None, exact=False): """ Update existing objects with the latest version of the prototype. Args: prototype (str or dict): Either the `prototype_key` to use or the prototype dict itself. diff (dict, optional): This a diff structure that describes how to update the protototype. If not given this will be constructed from the first object found. objects (list, optional): List of objects to update. If not given, query for these objects using the prototype's `prototype_key`. exact (bool, optional): By default (`False`), keys not explicitly in the prototype will not be applied to the object, but will be retained as-is. This is usually what is expected - for example, one usually do not want to remove the object's location even if it's not set in the prototype. With `exact=True`, all un-specified properties of the objects will be removed if they exist. This will lead to a more accurate 1:1 correlation between the object and the prototype but is usually impractical. Returns: changed (int): The number of objects that had changes applied to them. """ prototype = protlib.homogenize_prototype(prototype) if isinstance(prototype, str): new_prototype = protlib.search_prototype(prototype) else: new_prototype = prototype prototype_key = new_prototype["prototype_key"] if not objects: objects = ObjectDB.objects.get_by_tag(prototype_key, category=PROTOTYPE_TAG_CATEGORY) if not objects: return 0 if not diff: diff, _ = prototype_diff_from_object(new_prototype, objects[0]) # make sure the diff is flattened diff = flatten_diff(diff) changed = 0 for obj in objects: do_save = False old_prot_key = obj.tags.get(category=PROTOTYPE_TAG_CATEGORY, return_list=True) old_prot_key = old_prot_key[0] if old_prot_key else None try: for key, directive in diff.items(): if key not in new_prototype and not exact: # we don't update the object if the prototype does not actually # contain the key (the diff will report REMOVE but we ignore it # since exact=False) continue if directive in ("UPDATE", "REPLACE"): if key in _PROTOTYPE_META_NAMES: # prototype meta keys are not stored on-object continue val = new_prototype[key] do_save = True if key == "key": obj.db_key = init_spawn_value(val, str) elif key == "typeclass": obj.db_typeclass_path = init_spawn_value(val, str) elif key == "location": obj.db_location = init_spawn_value(val, value_to_obj) elif key == "home": obj.db_home = init_spawn_value(val, value_to_obj) elif key == "destination": obj.db_destination = init_spawn_value(val, value_to_obj) elif key == "locks": if directive == "REPLACE": obj.locks.clear() obj.locks.add(init_spawn_value(val, str)) elif key == "permissions": if directive == "REPLACE": obj.permissions.clear() obj.permissions.batch_add(*(init_spawn_value(perm, str) for perm in val)) elif key == "aliases": if directive == "REPLACE": obj.aliases.clear() obj.aliases.batch_add(*(init_spawn_value(alias, str) for alias in val)) elif key == "tags": if directive == "REPLACE": obj.tags.clear() obj.tags.batch_add( *( (init_spawn_value(ttag, str), tcategory, tdata) for ttag, tcategory, tdata in val ) ) elif key == "attrs": if directive == "REPLACE": obj.attributes.clear() obj.attributes.batch_add( *( ( init_spawn_value(akey, str), init_spawn_value(aval, value_to_obj), acategory, alocks, ) for akey, aval, acategory, alocks in val ) ) elif key == "exec": # we don't auto-rerun exec statements, it would be huge security risk! pass else: obj.attributes.add(key, init_spawn_value(val, value_to_obj)) elif directive == "REMOVE": do_save = True if key == "key": obj.db_key = "" elif key == "typeclass": # fall back to default obj.db_typeclass_path = settings.BASE_OBJECT_TYPECLASS elif key == "location": obj.db_location = None elif key == "home": obj.db_home = None elif key == "destination": obj.db_destination = None elif key == "locks": obj.locks.clear() elif key == "permissions": obj.permissions.clear() elif key == "aliases": obj.aliases.clear() elif key == "tags": obj.tags.clear() elif key == "attrs": obj.attributes.clear() elif key == "exec": # we don't auto-rerun exec statements, it would be huge security risk! pass else: obj.attributes.remove(key) except Exception: logger.log_trace(f"Failed to apply prototype '{prototype_key}' to {obj}.") finally: # we must always make sure to re-add the prototype tag obj.tags.clear(category=PROTOTYPE_TAG_CATEGORY) obj.tags.add(prototype_key, category=PROTOTYPE_TAG_CATEGORY) if do_save: changed += 1 obj.save() return changed def batch_create_object(*objparams): """ This is a cut-down version of the create_object() function, optimized for speed. It does NOT check and convert various input so make sure the spawned Typeclass works before using this! Args: objsparams (tuple): Each paremter tuple will create one object instance using the parameters within. The parameters should be given in the following order: - `create_kwargs` (dict): For use as new_obj = `ObjectDB(**create_kwargs)`. - `permissions` (str): Permission string used with `new_obj.batch_add(permission)`. - `lockstring` (str): Lockstring used with `new_obj.locks.add(lockstring)`. - `aliases` (list): A list of alias strings for adding with `new_object.aliases.batch_add(*aliases)`. - `nattributes` (list): list of tuples `(key, value)` to be loop-added to add with `new_obj.nattributes.add(*tuple)`. - `attributes` (list): list of tuples `(key, value[,category[,lockstring]])` for adding with `new_obj.attributes.batch_add(*attributes)`. - `tags` (list): list of tuples `(key, category)` for adding with `new_obj.tags.batch_add(*tags)`. - `execs` (list): Code strings to execute together with the creation of each object. They will be executed with `evennia` and `obj` (the newly created object) available in the namespace. Execution will happend after all other properties have been assigned and is intended for calling custom handlers etc. Returns: objects (list): A list of created objects Notes: The `exec` list will execute arbitrary python code so don't allow this to be available to unprivileged users! """ # bulk create all objects in one go # unfortunately this doesn't work since bulk_create doesn't creates pks; # the result would be duplicate objects at the next stage, so we comment # it out for now: # dbobjs = _ObjectDB.objects.bulk_create(dbobjs) objs = [] for objparam in objparams: obj = ObjectDB(**objparam[0]) # setup obj._createdict = { "permissions": make_iter(objparam[1]), "locks": objparam[2], "aliases": make_iter(objparam[3]), "nattributes": objparam[4], "attributes": objparam[5], "tags": make_iter(objparam[6]), } # this triggers all hooks obj.save() # run eventual extra code for code in objparam[7]: if code: exec(code, {}, {"evennia": evennia, "obj": obj}) objs.append(obj) return objs # Spawner mechanism def spawn(*prototypes, **kwargs): """ Spawn a number of prototyped objects. Args: prototypes (str or dict): Each argument should either be a prototype_key (will be used to find the prototype) or a full prototype dictionary. These will be batched-spawned as one object each. Kwargs: prototype_modules (str or list): A python-path to a prototype module, or a list of such paths. These will be used to build the global protparents dictionary accessible by the input prototypes. If not given, it will instead look for modules defined by settings.PROTOTYPE_MODULES. prototype_parents (dict): A dictionary holding a custom prototype-parent dictionary. Will overload same-named prototypes from prototype_modules. return_parents (bool): Return a dict of the entire prototype-parent tree available to this prototype (no object creation happens). This is a merged result between the globally found protparents and whatever custom `prototype_parents` are given to this function. only_validate (bool): Only run validation of prototype/parents (no object creation) and return the create-kwargs. Returns: object (Object, dict or list): Spawned object(s). If `only_validate` is given, return a list of the creation kwargs to build the object(s) without actually creating it. If `return_parents` is set, instead return dict of prototype parents. """ # search string (=prototype_key) from input prototypes = [ protlib.search_prototype(prot, require_single=True)[0] if isinstance(prot, str) else prot for prot in prototypes ] # get available protparents protparents = {prot["prototype_key"].lower(): prot for prot in protlib.search_prototype()} if not kwargs.get("only_validate"): # homogenization to be more lenient about prototype format when entering the prototype manually prototypes = [protlib.homogenize_prototype(prot) for prot in prototypes] # overload module's protparents with specifically given protparents # we allow prototype_key to be the key of the protparent dict, to allow for module-level # prototype imports. We need to insert prototype_key in this case for key, protparent in kwargs.get("prototype_parents", {}).items(): key = str(key).lower() protparent["prototype_key"] = str(protparent.get("prototype_key", key)).lower() protparents[key] = protparent if "return_parents" in kwargs: # only return the parents return copy.deepcopy(protparents) objsparams = [] for prototype in prototypes: protlib.validate_prototype(prototype, None, protparents, is_prototype_base=True) prot = _get_prototype( prototype, protparents, uninherited={"prototype_key": prototype.get("prototype_key")} ) if not prot: continue # extract the keyword args we need to create the object itself. If we get a callable, # call that to get the value (don't catch errors) create_kwargs = {} # we must always add a key, so if not given we use a shortened md5 hash. There is a (small) # chance this is not unique but it should usually not be a problem. val = prot.pop( "key", "Spawned-{}".format(hashlib.md5(bytes(str(time.time()), "utf-8")).hexdigest()[:6]), ) create_kwargs["db_key"] = init_spawn_value(val, str) val = prot.pop("location", None) create_kwargs["db_location"] = init_spawn_value(val, value_to_obj) val = prot.pop("home", settings.DEFAULT_HOME) create_kwargs["db_home"] = init_spawn_value(val, value_to_obj) val = prot.pop("destination", None) create_kwargs["db_destination"] = init_spawn_value(val, value_to_obj) val = prot.pop("typeclass", settings.BASE_OBJECT_TYPECLASS) create_kwargs["db_typeclass_path"] = init_spawn_value(val, str) # extract calls to handlers val = prot.pop("permissions", []) permission_string = init_spawn_value(val, make_iter) val = prot.pop("locks", "") lock_string = init_spawn_value(val, str) val = prot.pop("aliases", []) alias_string = init_spawn_value(val, make_iter) val = prot.pop("tags", []) tags = [] for (tag, category, data) in val: tags.append((init_spawn_value(tag, str), category, data)) prototype_key = prototype.get("prototype_key", None) if prototype_key: # we make sure to add a tag identifying which prototype created this object tags.append((prototype_key, PROTOTYPE_TAG_CATEGORY)) val = prot.pop("exec", "") execs = init_spawn_value(val, make_iter) # extract ndb assignments nattributes = dict( (key.split("_", 1)[1], init_spawn_value(val, value_to_obj)) for key, val in prot.items() if key.startswith("ndb_") ) # the rest are attribute tuples (attrname, value, category, locks) val = make_iter(prot.pop("attrs", [])) attributes = [] for (attrname, value, category, locks) in val: attributes.append((attrname, init_spawn_value(value), category, locks)) simple_attributes = [] for key, value in ( (key, value) for key, value in prot.items() if not (key.startswith("ndb_")) ): # we don't support categories, nor locks for simple attributes if key in _PROTOTYPE_META_NAMES: continue else: simple_attributes.append( (key, init_spawn_value(value, value_to_obj_or_any), None, None) ) attributes = attributes + simple_attributes attributes = [tup for tup in attributes if not tup[0] in _NON_CREATE_KWARGS] # pack for call into _batch_create_object objsparams.append( ( create_kwargs, permission_string, lock_string, alias_string, nattributes, attributes, tags, execs, ) ) if kwargs.get("only_validate"): return objsparams return batch_create_object(*objsparams)
[ "evennia.prototypes.prototypes.homogenize_prototype", "evennia.utils.utils.is_iter", "evennia.utils.logger.log_trace", "evennia.utils.utils.make_iter", "evennia.prototypes.prototypes.validate_prototype", "evennia.objects.models.ObjectDB.objects.get_by_tag", "evennia.prototypes.prototypes.search_prototyp...
[((24382, 24421), 'evennia.prototypes.prototypes.homogenize_prototype', 'protlib.homogenize_prototype', (['prototype'], {}), '(prototype)\n', (24410, 24421), True, 'from evennia.prototypes import prototypes as protlib\n'), ((7803, 7840), 'evennia.utils.utils.make_iter', 'make_iter', (["inprot['prototype_parent']"], {}), "(inprot['prototype_parent'])\n", (7812, 7840), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((9404, 9443), 'evennia.prototypes.prototypes.homogenize_prototype', 'protlib.homogenize_prototype', (['prototype'], {}), '(prototype)\n', (9432, 9443), True, 'from evennia.prototypes import prototypes as protlib\n'), ((9551, 9657), 'evennia.prototypes.prototypes.validate_prototype', 'protlib.validate_prototype', (['prototype', 'None', 'protparents'], {'is_prototype_base': 'validate', 'strict': 'validate'}), '(prototype, None, protparents, is_prototype_base=\n validate, strict=validate)\n', (9577, 9657), True, 'from evennia.prototypes import prototypes as protlib\n'), ((10283, 10316), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['prot[0]'], {}), '(prot[0])\n', (10307, 10316), True, 'from evennia.prototypes import prototypes as protlib\n'), ((11363, 11379), 'evennia.utils.utils.make_iter', 'make_iter', (['perms'], {}), '(perms)\n', (11372, 11379), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((15961, 16001), 'evennia.prototypes.prototypes.homogenize_prototype', 'protlib.homogenize_prototype', (['prototype1'], {}), '(prototype1)\n', (15989, 16001), True, 'from evennia.prototypes import prototypes as protlib\n'), ((16044, 16084), 'evennia.prototypes.prototypes.homogenize_prototype', 'protlib.homogenize_prototype', (['prototype2'], {}), '(prototype2)\n', (16072, 16084), True, 'from evennia.prototypes import prototypes as protlib\n'), ((20154, 20193), 'evennia.prototypes.prototypes.homogenize_prototype', 'protlib.homogenize_prototype', (['prototype'], {}), '(prototype)\n', (20182, 20193), True, 'from evennia.prototypes import prototypes as protlib\n'), ((20767, 20779), 'evennia.utils.utils.is_iter', 'is_iter', (['obj'], {}), '(obj)\n', (20774, 20779), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((24482, 24517), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['prototype'], {}), '(prototype)\n', (24506, 24517), True, 'from evennia.prototypes import prototypes as protlib\n'), ((24653, 24728), 'evennia.objects.models.ObjectDB.objects.get_by_tag', 'ObjectDB.objects.get_by_tag', (['prototype_key'], {'category': 'PROTOTYPE_TAG_CATEGORY'}), '(prototype_key, category=PROTOTYPE_TAG_CATEGORY)\n', (24680, 24728), False, 'from evennia.objects.models import ObjectDB\n'), ((32391, 32414), 'evennia.objects.models.ObjectDB', 'ObjectDB', ([], {}), '(**objparam[0])\n', (32399, 32414), False, 'from evennia.objects.models import ObjectDB\n'), ((35679, 35705), 'copy.deepcopy', 'copy.deepcopy', (['protparents'], {}), '(protparents)\n', (35692, 35705), False, 'import copy\n'), ((35769, 35854), 'evennia.prototypes.prototypes.validate_prototype', 'protlib.validate_prototype', (['prototype', 'None', 'protparents'], {'is_prototype_base': '(True)'}), '(prototype, None, protparents, is_prototype_base=True\n )\n', (35795, 35854), True, 'from evennia.prototypes import prototypes as protlib\n'), ((36570, 36596), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'str'], {}), '(val, str)\n', (36586, 36596), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((36678, 36713), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (36694, 36713), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((36804, 36839), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (36820, 36839), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((36927, 36962), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (36943, 36962), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((37077, 37103), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'str'], {}), '(val, str)\n', (37093, 37103), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((37211, 37243), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'make_iter'], {}), '(val, make_iter)\n', (37227, 37243), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((37302, 37328), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'str'], {}), '(val, str)\n', (37318, 37328), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((37390, 37422), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'make_iter'], {}), '(val, make_iter)\n', (37406, 37422), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((37882, 37914), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'make_iter'], {}), '(val, make_iter)\n', (37898, 37914), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((32487, 32509), 'evennia.utils.utils.make_iter', 'make_iter', (['objparam[1]'], {}), '(objparam[1])\n', (32496, 32509), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((32568, 32590), 'evennia.utils.utils.make_iter', 'make_iter', (['objparam[3]'], {}), '(objparam[3])\n', (32577, 32590), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((32691, 32713), 'evennia.utils.utils.make_iter', 'make_iter', (['objparam[6]'], {}), '(objparam[6])\n', (32700, 32713), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((34875, 34901), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', ([], {}), '()\n', (34899, 34901), True, 'from evennia.prototypes import prototypes as protlib\n'), ((35070, 35104), 'evennia.prototypes.prototypes.homogenize_prototype', 'protlib.homogenize_prototype', (['prot'], {}), '(prot)\n', (35098, 35104), True, 'from evennia.prototypes import prototypes as protlib\n'), ((9515, 9541), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', ([], {}), '()\n', (9539, 9541), True, 'from evennia.prototypes import prototypes as protlib\n'), ((29725, 29799), 'evennia.utils.logger.log_trace', 'logger.log_trace', (['f"""Failed to apply prototype \'{prototype_key}\' to {obj}."""'], {}), '(f"Failed to apply prototype \'{prototype_key}\' to {obj}.")\n', (29741, 29799), False, 'from evennia.utils import logger\n'), ((34648, 34699), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['prot'], {'require_single': '(True)'}), '(prot, require_single=True)\n', (34672, 34699), True, 'from evennia.prototypes import prototypes as protlib\n'), ((15368, 15380), 'evennia.utils.utils.is_iter', 'is_iter', (['new'], {}), '(new)\n', (15375, 15380), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((37544, 37570), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['tag', 'str'], {}), '(tag, str)\n', (37560, 37570), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((38013, 38048), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (38029, 38048), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((38382, 38405), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['value'], {}), '(value)\n', (38398, 38405), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((14153, 14165), 'evennia.utils.utils.is_iter', 'is_iter', (['old'], {}), '(old)\n', (14160, 14165), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((25874, 25900), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'str'], {}), '(val, str)\n', (25890, 25900), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((38815, 38859), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['value', 'value_to_obj_or_any'], {}), '(value, value_to_obj_or_any)\n', (38831, 38859), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((14762, 14774), 'evennia.utils.utils.is_iter', 'is_iter', (['new'], {}), '(new)\n', (14769, 14774), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((15416, 15429), 'evennia.utils.utils.is_iter', 'is_iter', (['part'], {}), '(part)\n', (15423, 15429), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((15497, 15510), 'evennia.utils.utils.is_iter', 'is_iter', (['part'], {}), '(part)\n', (15504, 15510), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((25994, 26020), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'str'], {}), '(val, str)\n', (26010, 26020), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((10835, 10846), 'time.time', 'time.time', ([], {}), '()\n', (10844, 10846), False, 'import time\n'), ((14231, 14244), 'evennia.utils.utils.is_iter', 'is_iter', (['part'], {}), '(part)\n', (14238, 14244), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((26107, 26142), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (26123, 26142), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((10536, 10547), 'time.time', 'time.time', ([], {}), '()\n', (10545, 10547), False, 'import time\n'), ((14815, 14828), 'evennia.utils.utils.is_iter', 'is_iter', (['part'], {}), '(part)\n', (14822, 14828), False, 'from evennia.utils.utils import make_iter, is_iter\n'), ((26221, 26256), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (26237, 26256), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((26349, 26384), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (26365, 26384), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((36484, 36495), 'time.time', 'time.time', ([], {}), '()\n', (36493, 36495), False, 'import time\n'), ((26561, 26587), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'str'], {}), '(val, str)\n', (26577, 26587), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((26791, 26818), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['perm', 'str'], {}), '(perm, str)\n', (26807, 26818), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((27027, 27055), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['alias', 'str'], {}), '(alias, str)\n', (27043, 27055), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((28377, 28412), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['val', 'value_to_obj'], {}), '(val, value_to_obj)\n', (28393, 28412), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((27319, 27346), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['ttag', 'str'], {}), '(ttag, str)\n', (27335, 27346), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((27782, 27809), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['akey', 'str'], {}), '(akey, str)\n', (27798, 27809), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n'), ((27847, 27883), 'evennia.prototypes.prototypes.init_spawn_value', 'init_spawn_value', (['aval', 'value_to_obj'], {}), '(aval, value_to_obj)\n', (27863, 27883), False, 'from evennia.prototypes.prototypes import value_to_obj, value_to_obj_or_any, init_spawn_value, PROTOTYPE_TAG_CATEGORY\n')]
""" Pseudo-random generator and registry Evennia contribution - <NAME> 2017 This contrib can be used to generate pseudo-random strings of information with specific criteria. You could, for instance, use it to generate phone numbers, license plate numbers, validation codes, non-sensivite passwords and so on. The strings generated by the generator will be stored and won't be available again in order to avoid repetition. Here's a very simple example: ```python from evennia.contrib.random_string_generator import RandomStringGenerator # Create a generator for phone numbers phone_generator = RandomStringGenerator("phone number", r"555-[0-9]{3}-[0-9]{4}") # Generate a phone number (555-XXX-XXXX with X as numbers) number = phone_generator.get() # `number` will contain something like: "555-981-2207" # If you call `phone_generator.get`, it won't give the same anymore.phone_generator.all() # Will return a list of all currently-used phone numbers phone_generator.remove("555-981-2207") # The number can be generated again ``` To use it, you will need to: 1. Import the `RandomStringGenerator` class from the contrib. 2. Create an instance of this class taking two arguments: - The name of the gemerator (like "phone number", "license plate"...). - The regular expression representing the expected results. 3. Use the generator's `all`, `get` and `remove` methods as shown above. To understand how to read and create regular expressions, you can refer to [the documentation on the re module](https://docs.python.org/2/library/re.html). Some examples of regular expressions you could use: - `r"555-\d{3}-\d{4}"`: 555, a dash, 3 digits, another dash, 4 digits. - `r"[0-9]{3}[A-Z][0-9]{3}"`: 3 digits, a capital letter, 3 digits. - `r"[A-Za-z0-9]{8,15}"`: between 8 and 15 letters and digits. - ... Behind the scenes, a script is created to store the generated information for a single generator. The `RandomStringGenerator` object will also read the regular expression you give to it to see what information is required (letters, digits, a more restricted class, simple characters...)... More complex regular expressions (with branches for instance) might not be available. """ from random import choice, randint, seed import re import string import time from evennia import DefaultScript, ScriptDB from evennia.utils.create import create_script class RejectedRegex(RuntimeError): """The provided regular expression has been rejected. More details regarding why this error occurred will be provided in the message. The usual reason is the provided regular expression is not specific enough and could lead to inconsistent generating. """ pass class ExhaustedGenerator(RuntimeError): """The generator hasn't any available strings to generate anymore.""" pass class RandomStringGeneratorScript(DefaultScript): """ The global script to hold all generators. It will be automatically created the first time `generate` is called on a RandomStringGenerator object. """ def at_script_creation(self): """Hook called when the script is created.""" self.key = "generator_script" self.desc = "Global generator script" self.persistent = True # Permanent data to be stored self.db.generated = {} class RandomStringGenerator(object): """ A generator class to generate pseudo-random strings with a rule. The "rule" defining what the generator should provide in terms of string is given as a regular expression when creating instances of this class. You can use the `all` method to get all generated strings, the `get` method to generate a new string, the `remove` method to remove a generated string, or the `clear` method to remove all generated strings. Bear in mind, however, that while the generated strings will be stored to avoid repetition, the generator will not concern itself with how the string is stored on the object you use. You probably want to create a tag to mark this object. This is outside of the scope of this class. """ # We keep the script as a class variable to optimize querying # with multiple instandces script = None def __init__(self, name, regex): """ Create a new generator. Args: name (str): name of the generator to create. regex (str): regular expression describing the generator. Notes: `name` should be an explicit name. If you use more than one generator in your game, be sure to give them different names. This name will be used to store the generated information in the global script, and in case of errors. The regular expression should describe the generator, what it should generate: a phone number, a license plate, a password or something else. Regular expressions allow you to use pretty advanced criteria, but be aware that some regular expressions will be rejected if not specific enough. Raises: RejectedRegex: the provided regular expression couldn't be accepted as a valid generator description. """ self.name = name self.elements = [] self.total = 1 # Analyze the regex if any if regex: self._find_elements(regex) def __repr__(self): return "<evennia.contrib.random_string_generator.RandomStringGenerator for {}>".format( self.name ) def _get_script(self): """Get or create the script.""" if type(self).script: return type(self).script try: script = ScriptDB.objects.get(db_key="generator_script") except ScriptDB.DoesNotExist: script = create_script("contrib.random_string_generator.RandomStringGeneratorScript") type(self).script = script return script def _find_elements(self, regex): """ Find the elements described in the regular expression. This will analyze the provided regular expression and try to find elements. Args: regex (str): the regular expression. """ self.total = 1 self.elements = [] tree = re.sre_parse.parse(regex).data # `tree` contains a list of elements in the regular expression for element in tree: # `element` is also a list, the first element is a string name = str(element[0]).lower() desc = {"min": 1, "max": 1} # If `.`, break here if name == "any": raise RejectedRegex( "the . definition is too broad, specify what you need more precisely" ) elif name == "at": # Either the beginning or end, we ignore it continue elif name == "min_repeat": raise RejectedRegex("you have to provide a maximum number of this character class") elif name == "max_repeat": desc["min"] = element[1][0] desc["max"] = element[1][1] desc["chars"] = self._find_literal(element[1][2][0]) elif name == "in": desc["chars"] = self._find_literal(element) elif name == "literal": desc["chars"] = self._find_literal(element) else: raise RejectedRegex("unhandled regex syntax:: {}".format(repr(name))) self.elements.append(desc) self.total *= len(desc["chars"]) ** desc["max"] def _find_literal(self, element): """Find the literal corresponding to a piece of regular expression.""" name = str(element[0]).lower() chars = [] if name == "literal": chars.append(chr(element[1])) elif name == "in": negate = False if element[1][0][0] == "negate": negate = True chars = list(string.ascii_letters + string.digits) for part in element[1]: if part[0] == "negate": continue sublist = self._find_literal(part) for char in sublist: if negate: if char in chars: chars.remove(char) else: chars.append(char) elif name == "range": chars = [chr(i) for i in range(element[1][0], element[1][1] + 1)] elif name == "category": category = str(element[1]).lower() if category == "category_digit": chars = list(string.digits) elif category == "category_word": chars = list(string.letters) else: raise RejectedRegex("unknown category: {}".format(category)) else: raise RejectedRegex("cannot find the literal: {}".format(element[0])) return chars def all(self): """ Return all generated strings for this generator. Returns: strings (list of strr): the list of strings that are already used. The strings that were generated first come first in the list. """ script = self._get_script() generated = list(script.db.generated.get(self.name, [])) return generated def get(self, store=True, unique=True): """ Generate a pseudo-random string according to the regular expression. Args: store (bool, optional): store the generated string in the script. unique (bool, optional): keep on trying if the string is already used. Returns: The newly-generated string. Raises: ExhaustedGenerator: if there's no available string in this generator. Note: Unless asked explicitly, the returned string can't repeat itself. """ script = self._get_script() generated = script.db.generated.get(self.name) if generated is None: script.db.generated[self.name] = [] generated = script.db.generated[self.name] if len(generated) >= self.total: raise ExhaustedGenerator # Generate a pseudo-random string that might be used already result = "" for element in self.elements: number = randint(element["min"], element["max"]) chars = element["chars"] for index in range(number): char = choice(chars) result += char # If the string has already been generated, try again if result in generated and unique: # Change the random seed, incrementing it slowly epoch = time.time() while result in generated: epoch += 1 seed(epoch) result = self.get(store=False, unique=False) if store: generated.append(result) return result def remove(self, element): """ Remove a generated string from the list of stored strings. Args: element (str): the string to remove from the list of generated strings. Raises: ValueError: the specified value hasn't been generated and is not present. Note: The specified string has to be present in the script (so has to have been generated). It will remove this entry from the script, so this string could be generated again by calling the `get` method. """ script = self._get_script() generated = script.db.generated.get(self.name, []) if element not in generated: raise ValueError( "the string {} isn't stored as generated by the generator {}".format( element, self.name ) ) generated.remove(element) def clear(self): """ Clear the generator of all generated strings. """ script = self._get_script() generated = script.db.generated.get(self.name, []) generated[:] = []
[ "evennia.utils.create.create_script", "evennia.ScriptDB.objects.get" ]
[((5759, 5806), 'evennia.ScriptDB.objects.get', 'ScriptDB.objects.get', ([], {'db_key': '"""generator_script"""'}), "(db_key='generator_script')\n", (5779, 5806), False, 'from evennia import DefaultScript, ScriptDB\n'), ((6341, 6366), 're.sre_parse.parse', 're.sre_parse.parse', (['regex'], {}), '(regex)\n', (6359, 6366), False, 'import re\n'), ((10510, 10549), 'random.randint', 'randint', (["element['min']", "element['max']"], {}), "(element['min'], element['max'])\n", (10517, 10549), False, 'from random import choice, randint, seed\n'), ((10882, 10893), 'time.time', 'time.time', ([], {}), '()\n', (10891, 10893), False, 'import time\n'), ((5866, 5942), 'evennia.utils.create.create_script', 'create_script', (['"""contrib.random_string_generator.RandomStringGeneratorScript"""'], {}), "('contrib.random_string_generator.RandomStringGeneratorScript')\n", (5879, 5942), False, 'from evennia.utils.create import create_script\n'), ((10650, 10663), 'random.choice', 'choice', (['chars'], {}), '(chars)\n', (10656, 10663), False, 'from random import choice, randint, seed\n'), ((10976, 10987), 'random.seed', 'seed', (['epoch'], {}), '(epoch)\n', (10980, 10987), False, 'from random import choice, randint, seed\n')]
""" All available event actions. """ from django.conf import settings from evennia.utils import logger from muddery.server.utils.utils import classes_in_path from muddery.server.events.base_event_action import BaseEventAction class EventActionSet(object): """ All available event triggers. """ def __init__(self): self.dict = {} def load(self): """ Add all event actions from the path. """ # load classes for cls in classes_in_path(settings.PATH_EVENT_ACTION_BASE, BaseEventAction): key = cls.key if key: if key in self.dict: logger.log_infomsg("Event action %s is replaced by %s." % (key, cls)) self.dict[key] = cls() def get(self, key): """ Get the event action. """ return self.dict.get(key, None) def func(self, key): """ Get the function of the event action. """ action = self.dict.get(key, None) if action: return action.func def all(self): """ Get all event types. """ return self.dict.keys() def choice_all(self): """ Get all event types and names for form choice. """ return [(key, "%s (%s)" % (value.name, key)) for key, value in self.dict.items()] def repeatedly(self): """ Get all repeatedly event types. """ return [key for key, value in self.dict.items() if value.repeatedly] def choice_repeatedly(self): """ Get all repeatedly event types and names. """ return [(key, "%s (%s)" % (value.name, key)) for key, value in self.dict.items() if value.repeatedly] EVENT_ACTION_SET = EventActionSet() EVENT_ACTION_SET.load()
[ "evennia.utils.logger.log_infomsg" ]
[((488, 553), 'muddery.server.utils.utils.classes_in_path', 'classes_in_path', (['settings.PATH_EVENT_ACTION_BASE', 'BaseEventAction'], {}), '(settings.PATH_EVENT_ACTION_BASE, BaseEventAction)\n', (503, 553), False, 'from muddery.server.utils.utils import classes_in_path\n'), ((658, 727), 'evennia.utils.logger.log_infomsg', 'logger.log_infomsg', (["('Event action %s is replaced by %s.' % (key, cls))"], {}), "('Event action %s is replaced by %s.' % (key, cls))\n", (676, 727), False, 'from evennia.utils import logger\n')]
""" Commands for agents """ from django.db.models import Q from evennia.objects.models import ObjectDB # noinspection PyProtectedMember from evennia.objects.objects import _AT_SEARCH_RESULT from server.utils.arx_utils import ArxCommand, ArxPlayerCommand from server.utils.arx_utils import validate_name, caller_change_field from typeclasses.npcs.npc_types import get_npc_type, generate_default_name_and_desc from .models import Agent, Organization, AssetOwner class CmdAgents(ArxPlayerCommand): """ @agents Usage: @agents @agents <org name> @agents/guard player,<id #>,<amt> @agents/recall player,<id #>,<amt> @agents/hire <type>,<level>,<amount>=<organization> @agents/desc <ID #>,<desc> @agents/name <ID #>,name @agents/transferowner <ID #>,<new owner> Hires guards, assassins, spies, or any other form of NPC that has a presence in-game and can act on player orders. Agents are owned by an organization and are generic, while personalized agents are created and ordered by the @retainer command, which are unique individuals. To use any of the switches of this command, you must be in a space designated by GMs to be the barracks your agents report to. Switches: guard: The 'guard' switch assigns agents of the type and the amount to a given player, who can then use them via the +guard command. 'name' should be what the type of guard is named - for example, name might be 'Thrax elite guards'. recall: Recalls guards of the given type listed by 'name' and the value given by the deployment number, and the amount listed. For example, you might have 10 Grayson House Guards deployed to player name A, and 15 to player B. To recall 10 of the guards assigned to player B, you would do @agents/recall grayson house guards,B,10=grayson. hire: enter the type, level, and quantity of the agents and the org you wish to buy them for. The type will generally be 'guard' for nobles, and 'thug' for crime families and the like. Cost = (lvl+1)^5 in military resources for each agent. """ key = "@agents" locks = "cmd:all()" help_category = "Dominion" aliases = ["@agent"] @staticmethod def find_barracks(owner): """"find rooms that are tagged as being barracks for that owner""" tagname = str(owner.owner) + "_barracks" rooms = ObjectDB.objects.filter(db_tags__db_key__iexact=tagname) return list(rooms) @staticmethod def get_cost(lvl): """Gets the cost of an agent""" cost = pow((lvl + 1), 5) return cost @staticmethod def get_guard_cap(char): """Gets maximum number of guards for a character""" return char.max_guards @staticmethod def get_allowed_types_from_org(org): """Gets types of agents allowed for an org""" if org.category in ("noble", "law", "discipleship"): return ["guards"] if "crime" in org.category: return ["thugs"] return [] def func(self): """Executes agents command""" caller = self.caller personal = Agent.objects.filter(owner__player__player=caller) orgs = [org.assets for org in Organization.objects.filter(members__player=caller.Dominion) if org.access(caller, 'guards')] house = Agent.objects.filter(owner__organization_owner__members__player__player=caller, owner__organization_owner__in=[org.organization_owner for org in orgs]) agents = personal | house if not self.args: caller.msg("{WYour agents:{n\n%s" % "".join(agent.display(caller=self.caller) for agent in agents), options={'box': True}) barracks = self.find_barracks(caller.Dominion.assets) for org in orgs: barracks.extend(self.find_barracks(org)) caller.msg("{wBarracks locations:{n %s" % ", ".join(ob.key for ob in barracks)) return if not self.switches: try: org = Organization.objects.get(name__iexact=self.args, members__player=caller.Dominion) except Organization.DoesNotExist: caller.msg("You are not a member of an organization named %s." % self.args) return caller.msg(", ".join(agent.display() for agent in org.assets.agents.all()), options={'box': True}) barracks = self.find_barracks(org.assets) caller.msg("{wBarracks locations:{n %s" % ", ".join(ob.key for ob in barracks)) return try: owner_ids = [] loc = caller.character.location if loc == caller.character.home: owner_ids.append(caller.Dominion.assets.id) if loc.db.barracks_owner: owner_ids.append(loc.db.barracks_owner) if loc.db.room_owner: owner_ids.append(loc.db.room_owner) if owner_ids: owners = [ob for ob in AssetOwner.objects.filter(id__in=owner_ids) if ob == caller.Dominion.assets or ( ob.organization_owner and ob.organization_owner.access(caller, 'guards'))] if not owners: caller.msg("You do not have access to guards here.") else: self.msg("You do not have access to guards here.") return owner_ids = [ob.id for ob in owners] owner_names = ", ".join(str(ob) for ob in owners) except (AttributeError, AssetOwner.DoesNotExist, ValueError, TypeError): caller.msg("You do not have access to guards here.") return if not self.lhslist: caller.msg("Must provide arguments separated by commas.") return if 'guard' in self.switches: try: player, pid, amt = self.lhslist amt = int(amt) if amt < 1: self.msg("Must assign a positive number.") return pid = int(pid) targ = caller.search(player) if not targ: caller.msg("Could not find player by name %s." % player) return avail_agent = Agent.objects.get(id=pid, owner_id__in=owner_ids) if avail_agent.quantity < amt: caller.msg("You tried to assign %s, but only have %s available." % (amt, avail_agent.quantity)) return try: # assigning it to their character targ = targ.db.char_ob if not targ: caller.msg("They have no character to assign to.") return cap = self.get_guard_cap(targ) if targ.num_guards + amt > cap: caller.msg("They can only have %s guards assigned to them." % cap) return avail_agent.assign(targ, amt) if avail_agent.unique: self.msg("Assigned %s to %s." % (avail_agent, targ)) else: caller.msg("Assigned %s %s to %s." % (amt, avail_agent.name, targ)) return except ValueError as err: caller.msg(err) return except Agent.DoesNotExist: caller.msg("%s owns no agents by that name." % owner_names) agents = Agent.objects.filter(owner_id__in=owner_ids) caller.msg("{wAgents:{n %s" % ", ".join("%s (#%s)" % (agent.name, agent.id) for agent in agents)) return except ValueError: caller.msg("Invalid usage: provide player, ID, and amount, separated by commas.") return if 'recall' in self.switches: try: pname, pid, amt = self.lhslist player = caller.search(pname) if not player: caller.msg("No player found by %s." % pname) return amt = int(amt) pid = int(pid) if amt < 1: raise ValueError agent = Agent.objects.get(id=pid) if agent.owner.id not in owner_ids: self.msg("They are owned by %s, and must be recalled from their barracks." % agent.owner) return # look through our agent actives for a dbobj assigned to player agentob = agent.find_assigned(player) if not agentob: caller.msg("No agents assigned to %s by %s." % (player, owner_names)) return num = agentob.recall(amt) if agent.unique: caller.msg("You have recalled %s from %s." % (agent, player)) else: caller.msg("You have recalled %s from %s. They have %s left." % (num, player, agentob.quantity)) return except Agent.DoesNotExist: caller.msg("No agents found for those arguments.") return except ValueError: caller.msg("Amount and ID must be positive numbers.") return if 'hire' in self.switches: try: org = caller.Dominion.current_orgs.get(name__iexact=self.rhs) owner = org.assets except (AttributeError, Organization.DoesNotExist): caller.msg("You are not in an organization by that name.") return try: gtype, level, amt = self.lhslist[0], int(self.lhslist[1]), int(self.lhslist[2]) except (IndexError, TypeError, ValueError): caller.msg("Please give the type, level, and amount of agents to buy.") return if not org.access(caller, 'agents'): caller.msg("You do not have permission to hire agents for %s." % org) return types = self.get_allowed_types_from_org(org) if gtype not in types: caller.msg("%s is not a type %s is allowed to hire." % (gtype, org)) caller.msg("You can buy: %s" % ", ".join(types)) return if level < 0 or amt < 1: self.msg("Level and amt must be positive.") return gtype_num = get_npc_type(gtype) cost = self.get_cost(level) cost *= amt if owner.military < cost: caller.msg("%s does not enough military resources. Cost was %s." % (owner, cost)) return owner.military -= cost owner.save() # get or create agents of the appropriate type try: agent = owner.agents.get(quality=level, type=gtype_num) except Agent.DoesNotExist: gname, gdesc = generate_default_name_and_desc(gtype_num, level, org) agent = owner.agents.create(quality=level, type=gtype_num, name=gname, desc=gdesc) except Agent.MultipleObjectsReturned: agent = owner.agents.filter(quality=level, type=gtype_num)[0] agent.quantity += amt agent.save() caller.msg("You bought %s, and now have %s." % (amt, agent)) return if 'desc' in self.switches or 'name' in self.switches or 'transferowner' in self.switches: try: agent = Agent.objects.get(id=int(self.lhslist[0])) strval = self.rhs if not agent.access(caller, 'agents'): caller.msg("No access.") return if 'desc' in self.switches: attr = 'desc' strval = strval or ", ".join(self.lhslist[1:]) agent.desc = strval elif 'name' in self.switches: strval = strval or ", ".join(self.lhslist[1:]) name = strval if not validate_name(name): self.msg("That is not a valid name.") return agent.set_name(name) self.msg("Name changed to %s" % name) return elif 'transferowner' in self.switches: attr = 'owner' strval = self.lhslist[1] try: agent.owner = AssetOwner.objects.get(Q(player__player__username__iexact=self.lhslist[1]) | Q(organization_owner__name__iexact=self.lhslist[1])) if agent.unique: agent.dbobj.unassign() try: char = agent.owner.player.player.db.char_ob agent.assign(char, 1) except AttributeError: pass except AssetOwner.DoesNotExist: self.msg("No owner found by that name to transfer to.") return else: self.msg("Invalid attr") return agent.save() # do we need to do any refresh_from_db calls here to prevent sync errors with stale foreignkeys? caller.msg("Changed %s to %s." % (attr, strval)) if attr == 'owner': agent.owner.inform_owner("You have been transferred ownership of %s from %s." % (agent, caller), category="agents") return except IndexError: self.msg("Wrong number of arguments.") except (TypeError, ValueError): self.msg("Wrong type of arguments.") except Agent.DoesNotExist: caller.msg("No agent found by that number.") return self.msg("Unrecognized switch.") class CmdRetainers(ArxPlayerCommand): """ @retainers Usage: @retainers @retainers/create <name>,<type> @retainers/train <owner>=<retainer name> @retainers/transferxp <id #>=<xp>[,retainer ID] @retainers/buyability <id #>=<ability> @retainers/buyskill <id #>=<skill> @retainers/buylevel <id #>=<field> @retainers/buystat <id #>=<stat> @retainers/upgradeweapon <id #>=<field> @retainers/changeweaponskill <id #>=<skill> @retainers/upgradearmor <id #> @retainers/desc <id #>=<new description> @retainers/name <id #>=<new name> @retainers/customize <id #>=<trait name>,<value> @retainers/viewstats <id #> @retainers/cost <id #>=<attribute>,<category> @retainer/delete <id #> Allows you to create and train unique agents that serve you, called retainers. They are still agents, and use the @agents command to set their name and description. They can be summoned in-game through the use of the +guards command while in your home. Retainers may be five types: champion, assistant, spy, animal, or small animal. Small animals are essentially pets that may be trained to perform tasks such as carrying messages, but no combat ability. Champions are guards and protectors. Non-small animals are assumed to be any large animal that can serve as a guardian or a mount. Assistants provide personal assistance in everyday tasks and adventures outside of combat. Spies may assist in criminal or sneaky activities. @retainers are upgraded through transfer of XP and the expenditure of resources. XP transferred to @retainers is multiplied by three, making it far easier (but much more expensive) to have skilled retainers. Changing the name, desc, or cosmetic traits of a retainer is free. The cost of a new retainer is 100 resources, with champions and large animals requiring military, assistants using economic, and spies requiring social. Small animals, due to their limited use, only cost 25 social resources. /delete will remove a retainer that you own forever. """ key = "@retainers" aliases = ["@retainer"] locks = "cmd:all()" help_category = "Dominion" # cost of a new retainer in resources new_retainer_cost = 100 retainer_types = ("champion", "assistant", "spy", "animal", "small animal") valid_traits = ("species", "gender", "age", "haircolor", "eyecolor", "skintone", "height") valid_categories = ("skill", "stat", "ability", "level", "armor", "weapon") def get_agent_from_args(self, args): """Get our retainer's Agent model from an ID number in args""" if args.isdigit(): return self.caller.retainers.get(id=args) return self.caller.retainers.get(agent_objects__dbobj__db_key__iexact=args) def display_retainers(self): """ Displays retainers the player owns """ agents = self.caller.retainers self.msg("{WYour retainers:{n\n%s" % "".join(agent.display(caller=self.caller) for agent in agents), options={'box': True}) return def view_stats(self, agent): """Views the stats for a retainer""" char = agent.dbobj self.msg(agent.display()) char.view_stats(self.caller, combat=True) def create_new_retainer(self): """ Create a new retainer that will be attached to the assetowner object of the caller. The cost will be in resources determined by the type passed by arguments. """ caller = self.caller try: aname, atype = self.lhslist[0], self.lhslist[1] except IndexError: caller.msg("You must provide both a name and a type for your new retainer.") return atype = atype.lower() if atype not in self.retainer_types: caller.msg("The type of retainer must be one of the following: %s" % ", ".join(self.retainer_types)) return cost = self.new_retainer_cost if atype == "champion" or atype == "animal": rtype = "military" elif atype == "spy" or atype == "small animal": rtype = "social" if atype == "small animal": cost /= 4 elif atype == "assistant": rtype = "economic" else: rtype = "military" if not caller.pay_resources(rtype, cost): caller.msg("You do not have enough %s resources." % rtype) return # all checks passed, and we've paid the cost. Create a new agent npc_type = get_npc_type(atype) desc = "An agent belonging to %s." % caller agent = caller.Dominion.assets.agents.create(type=npc_type, quality=0, name=aname, quantity=1, unique=True, desc=desc) caller.msg("You have created a new %s named %s." % (atype, aname)) agent.assign(caller.db.char_ob, 1) caller.msg("Assigning %s to you." % aname) self.msg("You now have a new agent. You can return to your home to summon them with the +guard command.") # sets its name and saves it agent.set_name(aname) return def train_retainer(self): """ Trains a retainer belonging to a player """ self.caller.execute_cmd("train/retainer %s" % self.args) def transfer_xp(self, agent): """ Transfers xp to a retainer. All retainer upgrades cost xp and resources. XP transferred to a retainer is multiplied to make it appealing to dump xp on them rather than spend it personally. """ if len(self.rhslist) < 2: char = self.caller.db.char_ob xp_multiplier = 3 else: try: char = self.get_agent_from_args(self.rhslist[1]) xp_multiplier = 1 except (Agent.DoesNotExist, ValueError): self.msg("Could not find an agent by those args.") return try: amt = int(self.rhslist[0]) if amt < 1: raise ValueError except (TypeError, ValueError): self.msg("You must specify a positive xp value to transfer to your retainer.") return if char.xp < amt: self.msg("You want to transfer %s xp, but only have %s." % (amt, char.xp)) return if hasattr(char, 'xp_transfer_cap'): if amt > char.xp_transfer_cap: self.msg("You are trying to transfer %s xp and their transfer cap is %s." % (amt, char.xp_transfer_cap)) return self.adjust_transfer_cap(char, -amt) char.adjust_xp(-amt) self.msg("%s has %s xp remaining." % (char, char.xp)) amt *= xp_multiplier agent.adjust_xp(amt) self.adjust_transfer_cap(agent, amt) self.msg("%s now has %s xp to spend." % (agent, agent.xp)) return def adjust_transfer_cap(self, agent, amt): """Changes the xp transfer cap for an agent""" agent.xp_transfer_cap += amt self.msg("%s's xp transfer cap is now %s." % (agent, agent.xp_transfer_cap)) # ------ Helper methods for performing pre-purchase checks ------------- def check_categories(self, category): """Helper method for displaying categories""" if category not in self.valid_categories: self.msg("%s is not a valid choice. It must be one of the following: %s" % (category, ", ".join(self.valid_categories))) return False return True def get_attr_from_args(self, agent, category="stat"): """ Helper method that returns the attr that the player is buying or displays a failure message and returns None. """ from world.stats_and_skills import VALID_SKILLS, VALID_STATS if not self.check_categories(category): return rhs = self.rhs if category == "level" and not rhs: rhs = agent.type_str if not rhs: if category == "ability": self.msg("Ability must be one of the following: %s" % ", ".join(agent.buyable_abilities)) return self.msg("You must provide the name of what you want to purchase.") return attr = rhs.lower() if category == "stat": if attr not in VALID_STATS: self.msg("When buying a stat, it must be one of the following: %s" % ", ".join(VALID_STATS)) return return attr if category == "skill": if attr not in VALID_SKILLS: self.msg("When buying a skill, it must be one of the following: %s" % ", ".join(VALID_SKILLS)) return return attr if category == "ability": if attr not in agent.buyable_abilities: self.msg("Ability must be one of the following: %s" % ", ".join(agent.buyable_abilities)) return return attr if category == "level": if attr not in self.retainer_types: self.msg("The type of level to buy must be one of the following: %s" % ", ".join(self.retainer_types)) return return "%s_level" % attr if category == "armor": return "armor" if category == "weapon": try: cats = ("weapon_damage", "difficulty_mod") attr = self.rhslist[0] if attr not in cats: self.msg("Must specify one of the following: %s" % ", ".join(cats)) return except IndexError: self.msg("Must specify a weapon field, and the weapon category.") return return attr def pay_resources(self, res_cost, res_type): """Attempts to pay resources""" if not self.caller.pay_resources(res_type, res_cost): self.msg("You do not have enough %s resources. You need %s." % (res_type, res_cost)) return False return True def pay_xp_and_resources(self, agent, xp_cost, res_cost, res_type): """Attempts to pay xp and resource costs""" if xp_cost > agent.xp: self.msg("Cost is %s and they only have %s xp." % (xp_cost, agent.xp)) return False if not self.pay_resources(res_cost, res_type): return False agent.xp -= xp_cost agent.save() self.msg("You pay %s %s resources and %s %s's xp." % (res_cost, res_type, xp_cost, agent)) return True def check_max_for_attr(self, agent, attr, category): """Checks the maximum allowed for an agent's traits""" a_max = agent.get_attr_maximum(attr, category) current = self.get_attr_current_value(agent, attr, category) if current >= a_max: self.msg("Their level in %s is currently %s, the maximum is %s." % (attr, current, a_max)) return False return True def get_attr_current_value(self, agent, attr, category): """Checks the current value for an agent's trait""" if not self.check_categories(category): return if category == "level": current = agent.dbobj.attributes.get(attr) or 0 elif category == "armor": current = agent.dbobj.db.armor_class elif category == "stat": current = agent.dbobj.attributes.get(attr) elif category == "skill": current = agent.dbobj.db.skills.get(attr, 0) elif category == "weapon": current = agent.dbobj.fakeweapon.get(attr, 0) elif category == "ability": if agent.dbobj.db.abilities is None: agent.dbobj.db.abilities = {} current = agent.dbobj.db.abilities.get(attr, 0) else: raise ValueError("Undefined category") return current def get_attr_cost(self, agent, attrname, category, current=None): """ Determines the xp cost, resource cost, and type of resources based on the type of attribute we're trying to raise. """ atype = agent.type_str xpcost = 0 rescost = 0 restype = "military" if current is None: current = self.get_attr_current_value(agent, attrname, category) newrating = current + 1 if category == "level": base = (newrating * newrating * 5) + 25 # increase the cost if not raising our primary type if atype not in attrname: base *= 2 xpcost = base rescost = base if atype == self.retainer_types[1]: # assistant restype = "economic" if atype == self.retainer_types[2]: # spy restype = "social" if category == "skill": xpcost, rescost, restype = agent.get_skill_cost(attrname) if category == "stat": xpcost, rescost, restype = agent.get_stat_cost(attrname) if category == "ability": xpcost, rescost, restype = agent.get_ability_cost(attrname) if category == "armor": xpcost = newrating rescost = newrating if category == "weapon": if attrname == 'weapon_damage': xpcost = newrating * newrating * 10 rescost = newrating * newrating * 20 elif attrname == 'difficulty_mod': xpcost = newrating * 50 rescost = newrating * 100 return xpcost, rescost, restype # ----- Upgrade methods that use the purchase checks ------------------- def buy_ability(self, agent): """ Buys a command/ability for a retainer. Available commands are limited by the levels we have in the different categories available. """ attr = self.get_attr_from_args(agent, category="ability") if not attr: return if not self.check_max_for_attr(agent, attr, category="ability"): return current = agent.dbobj.db.abilities.get(attr, 0) xp_cost, res_cost, res_type = self.get_attr_cost(agent, attr, "ability", current) if not self.pay_xp_and_resources(agent, xp_cost, res_cost, res_type): return newval = current + 1 agent.dbobj.db.abilities[attr] = newval self.msg("You have increased %s to %s." % (attr, newval)) def buy_skill(self, agent): """ Increase one of the retainer's skills. Maximum is determined by our level in one of the categories available. """ attr = self.get_attr_from_args(agent, category="skill") if not attr: return if not self.check_max_for_attr(agent, attr, category="skill"): return current = agent.dbobj.db.skills.get(attr, 0) xp_cost, res_cost, res_type = self.get_attr_cost(agent, attr, "skill", current) if not self.pay_xp_and_resources(agent, xp_cost, res_cost, res_type): return newval = current + 1 agent.dbobj.db.skills[attr] = newval self.msg("You have increased %s to %s." % (attr, newval)) def buy_stat(self, agent): """ Increase one of the retainer's stats. Maximum is determined by our quality level. """ attr = self.get_attr_from_args(agent) if not attr: return if not self.check_max_for_attr(agent, attr, category="stat"): return current = agent.dbobj.attributes.get(attr) or 0 xp_cost, res_cost, res_type = self.get_attr_cost(agent, attr, "stat", current) if not self.pay_xp_and_resources(agent, xp_cost, res_cost, res_type): return newval = current + 1 agent.dbobj.attributes.add(attr, newval) self.msg("You have increased %s to %s." % (attr, newval)) def buy_level(self, agent): """ Increases one of the retainer's levels. If its our main category, raise our rating. """ attrname = self.get_attr_from_args(agent, category="level") if not attrname: return if not self.check_max_for_attr(agent, attrname, category="level"): return current = agent.dbobj.attributes.get(attrname) or 0 # check and pay costs xp_cost, res_cost, res_type = self.get_attr_cost(agent, attrname, "level", current) if not self.pay_xp_and_resources(agent, xp_cost, res_cost, res_type): return # all checks passed, increase it and raise quality if it was our main category agent.dbobj.attributes.add(attrname, current + 1) if agent.type_str in attrname: agent.quality += 1 agent.save() self.msg("You have raised %s to %s" % (attrname, current + 1)) def upgrade_weapon(self, agent): """ Upgrade/buy a fake weapon for the agent. Should be significantly cheaper than using resources to buy the same sort of weapon for a player. """ fields = ('weapon_damage', 'difficulty_mod') if self.rhs not in fields: self.msg("You must specify one of the following: %s" % ", ".join(fields)) return fake = agent.dbobj.fakeweapon current = fake.get(self.rhs, 0) if self.rhs == 'difficulty_mod': current *= -1 if current < 0: current = 0 if not self.check_max_for_attr(agent, self.rhs, category="weapon"): return xp_cost, res_cost, res_type = self.get_attr_cost(agent, self.rhs, "weapon", current) if not self.pay_xp_and_resources(agent, xp_cost, res_cost, res_type): return newval = current + 1 if self.rhs == 'difficulty_mod': newval *= -1 fake[self.rhs] = newval agent.dbobj.fakeweapon = fake agent.dbobj.combat.setup_weapon(fake) self.msg("You have raised %s's %s to %s." % (agent, self.rhs, newval)) return def change_weapon_skill(self, agent): """ Changes the weapon skill of agent's dbobj's fakeweapon Args: agent: Agent to modify """ valid_skills = ('small wpn', 'medium wpn', 'huge wpn', 'archery', 'brawl') if self.rhs not in valid_skills: self.msg("Weapon skill must be one of following: %s" % ", ".join(valid_skills)) return fake = agent.dbobj.fakeweapon fake['attack_skill'] = self.rhs agent.dbobj.fakeweapon = fake self.msg("%s will now use %s as their weapon skill." % (agent, self.rhs)) def upgrade_armor(self, agent): """ Upgrade/buy fake armor for the agent. Significantly cheaper than the same sort of armor would be for a real character. They can only raise 1 point of armor at a time, which is kind of tedious but allows us to easily have increasing costs. """ current = agent.dbobj.db.armor_class if not self.check_max_for_attr(agent, "armor", category="armor"): return xp_cost, res_cost, res_type = self.get_attr_cost(agent, "armor", "armor", current) if not self.pay_xp_and_resources(agent, xp_cost, res_cost, res_type): return agent.dbobj.db.armor_class = current + 1 self.msg("You have raised %s's armor to %s." % (agent, current+1)) return # Cosmetic methods def change_desc(self, agent): """Changes description field of agent""" caller_change_field(self.caller, agent, "desc", self.rhs) return def change_name(self, agent): """Changes an agent's name""" old = agent.name name = self.rhs if not validate_name(name): self.msg("That is not a valid name.") return agent.set_name(name) self.caller.msg("Name changed from %s to %s." % (old, self.rhs)) return def customize(self, agent): """Changes other cosmetic attributes for agent""" try: attr, val = self.rhslist[0], self.rhslist[1] except (TypeError, ValueError, IndexError): self.msg("Please provide an attribute and a value.") self.msg("Valid attributes: %s" % ", ".join(self.valid_traits)) return if attr not in self.valid_traits: self.msg("Trait to customize must be one of the following: %s" % ", ".join(self.valid_traits)) return agent.dbobj.attributes.add(attr, val) self.msg("%s's %s set to %s." % (agent, attr, val)) def delete(self, agent): """Deletes an agent""" if not self.caller.ndb.remove_agent_forever == agent: self.caller.ndb.remove_agent_forever = agent self.msg("You wish to remove %s forever. Use the command again to confirm." % agent) return dbobj = agent.dbobj dbobj.softdelete() dbobj.unassign() agent.owner = None agent.save() self.msg("%s has gone to live with a nice farm family." % dbobj) def func(self): """Executes retainer command""" caller = self.caller if not self.args: self.display_retainers() return if "create" in self.switches: self.create_new_retainer() return if "train" in self.switches: self.train_retainer() return # methods that require an agent below try: agent = self.get_agent_from_args(self.lhs) except (Agent.DoesNotExist, ValueError, TypeError): caller.msg("No agent found that matches %s." % self.lhs) self.msg("Your current retainers:") self.display_retainers() return if "transferxp" in self.switches: self.transfer_xp(agent) return if "buyability" in self.switches: self.buy_ability(agent) return if "buyskill" in self.switches: self.buy_skill(agent) return if "buylevel" in self.switches: self.buy_level(agent) return if "buystat" in self.switches: self.buy_stat(agent) return if "upgradeweapon" in self.switches: self.upgrade_weapon(agent) return if "changeweaponskill" in self.switches: self.change_weapon_skill(agent) return if "upgradearmor" in self.switches: self.upgrade_armor(agent) return if "desc" in self.switches: self.change_desc(agent) return if "name" in self.switches: self.change_name(agent) return if "customize" in self.switches: self.customize(agent) return if "viewstats" in self.switches or "sheet" in self.switches: self.view_stats(agent) return if "cost" in self.switches: if len(self.rhslist) != 2: self.msg("@retainers/cost <agent ID>=<attribute>,<category>") self.check_categories("") return category = self.rhslist[1] if not self.check_categories(category): return # noinspection PyAttributeOutsideInit self.rhs = self.rhslist[0] attr = self.get_attr_from_args(agent, category) if not attr: return current = self.get_attr_current_value(agent, attr, category) xpcost, rescost, restype = self.get_attr_cost(agent, attr, category, current) self.msg("Raising %s would cost %s xp, %s %s resources." % (attr, xpcost, rescost, restype)) return if "delete" in self.switches: self.delete(agent) return caller.msg("Invalid switch.") class CmdGuards(ArxCommand): """ +guards Usage: +guards +guards/summon <name> +guards/dismiss <name> +guards/attack <guard>=<victim> +guards/kill <guard>=<victim> +guards/stop <guard> +guards/follow <guard>=<person to follow> +guards/passive <guard> +guard/get <guard>=<object> +guard/give <guard>=<object> to <receiver> +guard/inventory <guard> +guard/discreet <guard> Controls summoned guards or retainers. Guards that belong to a player may be summoned from their home, while guards belonging to an organization may be summoned from their barracks. Dismissing them will cause the guards to temporarily leave, and they may be resummoned from close to that location. Guards will automatically attempt to protect their owner unless they are marked as passive, which may be toggled with the /passive switch. Some types of agents, such as small animals or assistants, are passive by default. Guards that are docked in your room from being dismissed or having logged out in that location will be automatically resummoned upon login unless the /discreet flag is set. """ key = "+guards" locks = "cmd:all()" help_category = "Dominion" aliases = ["@guards", "guards", "+guard", "@guard", "guard"] def func(self): """Executes guard command""" caller = self.caller guards = caller.db.assigned_guards or [] if not guards: caller.msg("You have no guards assigned to you.") return if not self.args and not self.switches: self.msg("{WYour guards:{n\n%s" % "".join(guard.agent.display() if guard.agent.unique else guard.display() for guard in guards), options={'box': True}) return if self.args: guard = ObjectDB.objects.object_search(self.lhs, candidates=guards, exact=False) if not guard: try: guard = self.caller.player_ob.retainers.get(id=int(self.lhs)).dbobj except (Agent.DoesNotExist, ValueError, AttributeError): _AT_SEARCH_RESULT(guard, caller, self.lhs) return else: guard = guard[0] else: if len(guards) > 1: caller.msg("You must specify which guards.") for guard in guards: caller.msg(guard.display()) return guard = guards[0] if not self.switches: guard.display() return if 'summon' in self.switches: if guard.location == caller.location: caller.msg("They are already here.") return # check maximum guards and how many we have current = caller.num_armed_guards + guard.num_armed_guards g_max = caller.max_guards if current > g_max: self.msg("You are only permitted to have %s guards, and summoning them would give you %s." % (g_max, current)) return if caller.location.db.docked_guards and guard in caller.location.db.docked_guards: guard.summon() return tagname = str(guard.agentob.agent_class.owner.owner) + "_barracks" barracks = ObjectDB.objects.filter(db_tags__db_key__iexact=tagname) if caller.location in barracks: guard.summon() return # if they're only one square away loc = guard.location or guard.db.docked if not guard.db.guarding: self.msg("They are unassigned.") return if loc and caller.location == loc: guard.summon() return if loc and caller.location.locations_set.filter(db_destination_id=loc.id): guard.summon() return if caller.location == caller.home: guard.summon() return caller.msg("Your guards aren't close enough to summon. They are at %s." % loc) return # after this point, need guards to be with us. if guard.location != caller.location: caller.msg("Your guards are not here to receive commands. You must summon them to you first.") return if 'dismiss' in self.switches: guard.dismiss() caller.msg("You dismiss %s." % guard.name) return if 'stop' in self.switches: guard.stop() caller.msg("You order your guards to stop what they're doing.") return if 'passive' in self.switches: current = guard.passive if current: guard.passive = False self.msg("%s will now actively protect you." % guard.name) return guard.passive = True self.msg("%s will no longer actively protect you." % guard.name) return if 'discreet' in self.switches: current = guard.discreet if current: guard.discreet = False self.msg("%s will now be automatically summoned upon login if they are in your space." % guard.name) return guard.discreet = True self.msg("%s will no longer be automatically summoned upon login if they are in your space." % guard.name) return if 'inventory' in self.switches: objects = guard.contents self.msg("{c%s's {winventory:{n %s" % (guard, ", ".join(ob.name for ob in objects))) return if "give" in self.switches: self.msg("You order %s to give %s." % (guard, self.rhs)) guard.execute_cmd("give %s" % self.rhs) return if 'get' in self.switches: self.msg("You order %s to get %s." % (guard, self.rhs)) guard.execute_cmd("get %s" % self.rhs) return targ = caller.search(self.rhs) if not targ: return if 'attack' in self.switches: guard.attack(targ) caller.msg("You order %s to attack %s." % (guard.name, targ.name)) return if 'kill' in self.switches: guard.attack(targ, kill=True) caller.msg("You order %s to kill %s." % (guard.name, targ.name)) return if 'follow' in self.switches: guard.stop_follow(dismiss=False) guard.follow(targ) caller.msg("You order %s to follow %s." % (guard.name, targ.name)) return
[ "evennia.objects.models.ObjectDB.objects.object_search", "evennia.objects.objects._AT_SEARCH_RESULT", "evennia.objects.models.ObjectDB.objects.filter" ]
[((2439, 2495), 'evennia.objects.models.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'db_tags__db_key__iexact': 'tagname'}), '(db_tags__db_key__iexact=tagname)\n', (2462, 2495), False, 'from evennia.objects.models import ObjectDB\n'), ((19181, 19200), 'typeclasses.npcs.npc_types.get_npc_type', 'get_npc_type', (['atype'], {}), '(atype)\n', (19193, 19200), False, 'from typeclasses.npcs.npc_types import get_npc_type, generate_default_name_and_desc\n'), ((34274, 34331), 'server.utils.arx_utils.caller_change_field', 'caller_change_field', (['self.caller', 'agent', '"""desc"""', 'self.rhs'], {}), "(self.caller, agent, 'desc', self.rhs)\n", (34293, 34331), False, 'from server.utils.arx_utils import validate_name, caller_change_field\n'), ((10737, 10756), 'typeclasses.npcs.npc_types.get_npc_type', 'get_npc_type', (['gtype'], {}), '(gtype)\n', (10749, 10756), False, 'from typeclasses.npcs.npc_types import get_npc_type, generate_default_name_and_desc\n'), ((34484, 34503), 'server.utils.arx_utils.validate_name', 'validate_name', (['name'], {}), '(name)\n', (34497, 34503), False, 'from server.utils.arx_utils import validate_name, caller_change_field\n'), ((40602, 40674), 'evennia.objects.models.ObjectDB.objects.object_search', 'ObjectDB.objects.object_search', (['self.lhs'], {'candidates': 'guards', 'exact': '(False)'}), '(self.lhs, candidates=guards, exact=False)\n', (40632, 40674), False, 'from evennia.objects.models import ObjectDB\n'), ((42218, 42274), 'evennia.objects.models.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'db_tags__db_key__iexact': 'tagname'}), '(db_tags__db_key__iexact=tagname)\n', (42241, 42274), False, 'from evennia.objects.models import ObjectDB\n'), ((11258, 11311), 'typeclasses.npcs.npc_types.generate_default_name_and_desc', 'generate_default_name_and_desc', (['gtype_num', 'level', 'org'], {}), '(gtype_num, level, org)\n', (11288, 11311), False, 'from typeclasses.npcs.npc_types import get_npc_type, generate_default_name_and_desc\n'), ((40903, 40945), 'evennia.objects.objects._AT_SEARCH_RESULT', '_AT_SEARCH_RESULT', (['guard', 'caller', 'self.lhs'], {}), '(guard, caller, self.lhs)\n', (40920, 40945), False, 'from evennia.objects.objects import _AT_SEARCH_RESULT\n'), ((12437, 12456), 'server.utils.arx_utils.validate_name', 'validate_name', (['name'], {}), '(name)\n', (12450, 12456), False, 'from server.utils.arx_utils import validate_name, caller_change_field\n'), ((12898, 12949), 'django.db.models.Q', 'Q', ([], {'player__player__username__iexact': 'self.lhslist[1]'}), '(player__player__username__iexact=self.lhslist[1])\n', (12899, 12949), False, 'from django.db.models import Q\n'), ((13013, 13064), 'django.db.models.Q', 'Q', ([], {'organization_owner__name__iexact': 'self.lhslist[1]'}), '(organization_owner__name__iexact=self.lhslist[1])\n', (13014, 13064), False, 'from django.db.models import Q\n')]
""" Simple turn-based combat system with items and status effects Contrib - <NAME> 2017 This is a version of the 'turnbattle' combat system that includes conditions and usable items, which can instill these conditions, cure them, or do just about anything else. Conditions are stored on characters as a dictionary, where the key is the name of the condition and the value is a list of two items: an integer representing the number of turns left until the condition runs out, and the character upon whose turn the condition timer is ticked down. Unlike most combat-related attributes, conditions aren't wiped once combat ends - if out of combat, they tick down in real time instead. This module includes a number of example conditions: Regeneration: Character recovers HP every turn Poisoned: Character loses HP every turn Accuracy Up: +25 to character's attack rolls Accuracy Down: -25 to character's attack rolls Damage Up: +5 to character's damage Damage Down: -5 to character's damage Defense Up: +15 to character's defense Defense Down: -15 to character's defense Haste: +1 action per turn Paralyzed: No actions per turn Frightened: Character can't use the 'attack' command Since conditions can have a wide variety of effects, their code is scattered throughout the other functions wherever they may apply. Items aren't given any sort of special typeclass - instead, whether or not an object counts as an item is determined by its attributes. To make an object into an item, it must have the attribute 'item_func', with the value given as a callable - this is the function that will be called when an item is used. Other properties of the item, such as how many uses it has, whether it's destroyed when its uses are depleted, and such can be specified on the item as well, but they are optional. To install and test, import this module's TBItemsCharacter object into your game's character.py module: from evennia.contrib.turnbattle.tb_items import TBItemsCharacter And change your game's character typeclass to inherit from TBItemsCharacter instead of the default: class Character(TBItemsCharacter): Next, import this module into your default_cmdsets.py module: from evennia.contrib.turnbattle import tb_items And add the battle command set to your default command set: # # any commands you add below will overload the default ones. # self.add(tb_items.BattleCmdSet()) This module is meant to be heavily expanded on, so you may want to copy it to your game's 'world' folder and modify it there rather than importing it in your game and using it as-is. """ from random import randint from evennia import DefaultCharacter, Command, default_cmds, DefaultScript from evennia.commands.default.muxcommand import MuxCommand from evennia.commands.default.help import CmdHelp from evennia.prototypes.spawner import spawn from evennia import TICKER_HANDLER as tickerhandler """ ---------------------------------------------------------------------------- OPTIONS ---------------------------------------------------------------------------- """ TURN_TIMEOUT = 30 # Time before turns automatically end, in seconds ACTIONS_PER_TURN = 1 # Number of actions allowed per turn NONCOMBAT_TURN_TIME = 30 # Time per turn count out of combat # Condition options start here. # If you need to make changes to how your conditions work later, # it's best to put the easily tweakable values all in one place! REGEN_RATE = (4, 8) # Min and max HP regen for Regeneration POISON_RATE = (4, 8) # Min and max damage for Poisoned ACC_UP_MOD = 25 # Accuracy Up attack roll bonus ACC_DOWN_MOD = -25 # Accuracy Down attack roll penalty DMG_UP_MOD = 5 # Damage Up damage roll bonus DMG_DOWN_MOD = -5 # Damage Down damage roll penalty DEF_UP_MOD = 15 # Defense Up defense bonus DEF_DOWN_MOD = -15 # Defense Down defense penalty """ ---------------------------------------------------------------------------- COMBAT FUNCTIONS START HERE ---------------------------------------------------------------------------- """ def roll_init(character): """ Rolls a number between 1-1000 to determine initiative. Args: character (obj): The character to determine initiative for Returns: initiative (int): The character's place in initiative - higher numbers go first. Notes: By default, does not reference the character and simply returns a random integer from 1 to 1000. Since the character is passed to this function, you can easily reference a character's stats to determine an initiative roll - for example, if your character has a 'dexterity' attribute, you can use it to give that character an advantage in turn order, like so: return (randint(1,20)) + character.db.dexterity This way, characters with a higher dexterity will go first more often. """ return randint(1, 1000) def get_attack(attacker, defender): """ Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whether an attack hits or misses. Notes: This is where conditions affecting attack rolls are applied, as well. Accuracy Up and Accuracy Down are also accounted for in itemfunc_attack(), so that attack items' accuracy is affected as well. """ # For this example, just return a random integer up to 100. attack_value = randint(1, 100) # Add to the roll if the attacker has the "Accuracy Up" condition. if "Accuracy Up" in attacker.db.conditions: attack_value += ACC_UP_MOD # Subtract from the roll if the attack has the "Accuracy Down" condition. if "Accuracy Down" in attacker.db.conditions: attack_value += ACC_DOWN_MOD return attack_value def get_defense(attacker, defender): """ Returns a value for defense, which an attack roll must equal or exceed in order for an attack to hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: defense_value (int): Defense value, compared against an attack roll to determine whether an attack hits or misses. Notes: This is where conditions affecting defense are accounted for. """ # For this example, just return 50, for about a 50/50 chance of hit. defense_value = 50 # Add to defense if the defender has the "Defense Up" condition. if "Defense Up" in defender.db.conditions: defense_value += DEF_UP_MOD # Subtract from defense if the defender has the "Defense Down" condition. if "Defense Down" in defender.db.conditions: defense_value += DEF_DOWN_MOD return defense_value def get_damage(attacker, defender): """ Returns a value for damage to be deducted from the defender's HP after abilities successful hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being damaged Returns: damage_value (int): Damage value, which is to be deducted from the defending character's HP. Notes: This is where conditions affecting damage are accounted for. Since attack items roll their own damage in itemfunc_attack(), their damage is unaffected by any conditions. """ # For this example, just generate a number between 15 and 25. damage_value = randint(15, 25) # Add to damage roll if attacker has the "Damage Up" condition. if "Damage Up" in attacker.db.conditions: damage_value += DMG_UP_MOD # Subtract from the roll if the attacker has the "Damage Down" condition. if "Damage Down" in attacker.db.conditions: damage_value += DMG_DOWN_MOD return damage_value def apply_damage(defender, damage): """ Applies damage to a target, reducing their HP by the damage amount to a minimum of 0. Args: defender (obj): Character taking damage damage (int): Amount of damage being taken """ defender.db.hp -= damage # Reduce defender's HP by the damage dealt. # If this reduces it to 0 or less, set HP to 0. if defender.db.hp <= 0: defender.db.hp = 0 def at_defeat(defeated): """ Announces the defeat of a fighter in combat. Args: defeated (obj): Fighter that's been defeated. Notes: All this does is announce a defeat message by default, but if you want anything else to happen to defeated fighters (like putting them into a dying state or something similar) then this is the place to do it. """ defeated.location.msg_contents("%s has been defeated!" % defeated) def resolve_attack( attacker, defender, attack_value=None, defense_value=None, damage_value=None, inflict_condition=[], ): """ Resolves an attack and outputs the result. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Options: attack_value (int): Override for attack roll defense_value (int): Override for defense value damage_value (int): Override for damage value inflict_condition (list): Conditions to inflict upon hit, a list of tuples formated as (condition(str), duration(int)) Notes: This function is called by normal attacks as well as attacks made with items. """ # Get an attack roll from the attacker. if not attack_value: attack_value = get_attack(attacker, defender) # Get a defense value from the defender. if not defense_value: defense_value = get_defense(attacker, defender) # If the attack value is lower than the defense value, miss. Otherwise, hit. if attack_value < defense_value: attacker.location.msg_contents("%s's attack misses %s!" % (attacker, defender)) else: if not damage_value: damage_value = get_damage(attacker, defender) # Calculate damage value. # Announce damage dealt and apply damage. attacker.location.msg_contents( "%s hits %s for %i damage!" % (attacker, defender, damage_value) ) apply_damage(defender, damage_value) # Inflict conditions on hit, if any specified for condition in inflict_condition: add_condition(defender, attacker, condition[0], condition[1]) # If defender HP is reduced to 0 or less, call at_defeat. if defender.db.hp <= 0: at_defeat(defender) def combat_cleanup(character): """ Cleans up all the temporary combat-related attributes on a character. Args: character (obj): Character to have their combat attributes removed Notes: Any attribute whose key begins with 'combat_' is temporary and no longer needed once a fight ends. """ for attr in character.attributes.all(): if attr.key[:7] == "combat_": # If the attribute name starts with 'combat_'... character.attributes.remove(key=attr.key) # ...then delete it! def is_in_combat(character): """ Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat """ return bool(character.db.combat_turnhandler) def is_turn(character): """ Returns true if it's currently the given character's turn in combat. Args: character (obj): Character to determine if it is their turn or not Returns: (bool): True if it is their turn or False otherwise """ turnhandler = character.db.combat_turnhandler currentchar = turnhandler.db.fighters[turnhandler.db.turn] return bool(character == currentchar) def spend_action(character, actions, action_name=None): """ Spends a character's available combat actions and checks for end of turn. Args: character (obj): Character spending the action actions (int) or 'all': Number of actions to spend, or 'all' to spend all actions Keyword Args: action_name (str or None): If a string is given, sets character's last action in combat to provided string """ if action_name: character.db.combat_lastaction = action_name if actions == "all": # If spending all actions character.db.combat_actionsleft = 0 # Set actions to 0 else: character.db.combat_actionsleft -= actions # Use up actions. if character.db.combat_actionsleft < 0: character.db.combat_actionsleft = 0 # Can't have fewer than 0 actions character.db.combat_turnhandler.turn_end_check(character) # Signal potential end of turn. def spend_item_use(item, user): """ Spends one use on an item with limited uses. Args: item (obj): Item being used user (obj): Character using the item Notes: If item.db.item_consumable is 'True', the item is destroyed if it runs out of uses - if it's a string instead of 'True', it will also spawn a new object as residue, using the value of item.db.item_consumable as the name of the prototype to spawn. """ item.db.item_uses -= 1 # Spend one use if item.db.item_uses > 0: # Has uses remaining # Inform the player user.msg("%s has %i uses remaining." % (item.key.capitalize(), item.db.item_uses)) else: # All uses spent if not item.db.item_consumable: # Item isn't consumable # Just inform the player that the uses are gone user.msg("%s has no uses remaining." % item.key.capitalize()) else: # If item is consumable if item.db.item_consumable == True: # If the value is 'True', just destroy the item user.msg("%s has been consumed." % item.key.capitalize()) item.delete() # Delete the spent item else: # If a string, use value of item_consumable to spawn an object in its place residue = spawn({"prototype": item.db.item_consumable})[0] # Spawn the residue residue.location = item.location # Move the residue to the same place as the item user.msg("After using %s, you are left with %s." % (item, residue)) item.delete() # Delete the spent item def use_item(user, item, target): """ Performs the action of using an item. Args: user (obj): Character using the item item (obj): Item being used target (obj): Target of the item use """ # If item is self only and no target given, set target to self. if item.db.item_selfonly and target == None: target = user # If item is self only, abort use if used on others. if item.db.item_selfonly and user != target: user.msg("%s can only be used on yourself." % item) return # Set kwargs to pass to item_func kwargs = {} if item.db.item_kwargs: kwargs = item.db.item_kwargs # Match item_func string to function try: item_func = ITEMFUNCS[item.db.item_func] except KeyError: # If item_func string doesn't match to a function in ITEMFUNCS user.msg("ERROR: %s not defined in ITEMFUNCS" % item.db.item_func) return # Call the item function - abort if it returns False, indicating an error. # This performs the actual action of using the item. # Regardless of what the function returns (if anything), it's still executed. if item_func(item, user, target, **kwargs) == False: return # If we haven't returned yet, we assume the item was used successfully. # Spend one use if item has limited uses if item.db.item_uses: spend_item_use(item, user) # Spend an action if in combat if is_in_combat(user): spend_action(user, 1, action_name="item") def condition_tickdown(character, turnchar): """ Ticks down the duration of conditions on a character at the start of a given character's turn. Args: character (obj): Character to tick down the conditions of turnchar (obj): Character whose turn it currently is Notes: In combat, this is called on every fighter at the start of every character's turn. Out of combat, it's instead called when a character's at_update() hook is called, which is every 30 seconds by default. """ for key in character.db.conditions: # The first value is the remaining turns - the second value is whose turn to count down on. condition_duration = character.db.conditions[key][0] condition_turnchar = character.db.conditions[key][1] # If the duration is 'True', then the condition doesn't tick down - it lasts indefinitely. if not condition_duration is True: # Count down if the given turn character matches the condition's turn character. if condition_turnchar == turnchar: character.db.conditions[key][0] -= 1 if character.db.conditions[key][0] <= 0: # If the duration is brought down to 0, remove the condition and inform everyone. character.location.msg_contents( "%s no longer has the '%s' condition." % (str(character), str(key)) ) del character.db.conditions[key] def add_condition(character, turnchar, condition, duration): """ Adds a condition to a fighter. Args: character (obj): Character to give the condition to turnchar (obj): Character whose turn to tick down the condition on in combat condition (str): Name of the condition duration (int or True): Number of turns the condition lasts, or True for indefinite """ # The first value is the remaining turns - the second value is whose turn to count down on. character.db.conditions.update({condition: [duration, turnchar]}) # Tell everyone! character.location.msg_contents("%s gains the '%s' condition." % (character, condition)) """ ---------------------------------------------------------------------------- CHARACTER TYPECLASS ---------------------------------------------------------------------------- """ class TBItemsCharacter(DefaultCharacter): """ A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands. """ def at_object_creation(self): """ Called once, when this object is first created. This is the normal hook to overload for most object types. """ self.db.max_hp = 100 # Set maximum HP to 100 self.db.hp = self.db.max_hp # Set current HP to maximum self.db.conditions = {} # Set empty dict for conditions # Subscribe character to the ticker handler tickerhandler.add(NONCOMBAT_TURN_TIME, self.at_update, idstring="update") """ Adds attributes for a character's current and maximum HP. We're just going to set this value at '100' by default. An empty dictionary is created to store conditions later, and the character is subscribed to the Ticker Handler, which will call at_update() on the character, with the interval specified by NONCOMBAT_TURN_TIME above. This is used to tick down conditions out of combat. You may want to expand this to include various 'stats' that can be changed at creation and factor into combat calculations. """ def at_pre_move(self, destination): """ Called just before starting to move this object to destination. Args: destination (Object): The object we are moving to Returns: shouldmove (bool): If we should move or not. Notes: If this method returns False/None, the move is cancelled before it is even started. """ # Keep the character from moving if at 0 HP or in combat. if is_in_combat(self): self.msg("You can't exit a room while in combat!") return False # Returning false keeps the character from moving. if self.db.HP <= 0: self.msg("You can't move, you've been defeated!") return False return True def at_turn_start(self): """ Hook called at the beginning of this character's turn in combat. """ # Prompt the character for their turn and give some information. self.msg("|wIt's your turn! You have %i HP remaining.|n" % self.db.hp) # Apply conditions that fire at the start of each turn. self.apply_turn_conditions() def apply_turn_conditions(self): """ Applies the effect of conditions that occur at the start of each turn in combat, or every 30 seconds out of combat. """ # Regeneration: restores 4 to 8 HP at the start of character's turn if "Regeneration" in self.db.conditions: to_heal = randint(REGEN_RATE[0], REGEN_RAGE[1]) # Restore HP if self.db.hp + to_heal > self.db.max_hp: to_heal = self.db.max_hp - self.db.hp # Cap healing to max HP self.db.hp += to_heal self.location.msg_contents("%s regains %i HP from Regeneration." % (self, to_heal)) # Poisoned: does 4 to 8 damage at the start of character's turn if "Poisoned" in self.db.conditions: to_hurt = randint(POISON_RATE[0], POISON_RATE[1]) # Deal damage apply_damage(self, to_hurt) self.location.msg_contents("%s takes %i damage from being Poisoned." % (self, to_hurt)) if self.db.hp <= 0: # Call at_defeat if poison defeats the character at_defeat(self) # Haste: Gain an extra action in combat. if is_in_combat(self) and "Haste" in self.db.conditions: self.db.combat_actionsleft += 1 self.msg("You gain an extra action this turn from Haste!") # Paralyzed: Have no actions in combat. if is_in_combat(self) and "Paralyzed" in self.db.conditions: self.db.combat_actionsleft = 0 self.location.msg_contents("%s is Paralyzed, and can't act this turn!" % self) self.db.combat_turnhandler.turn_end_check(self) def at_update(self): """ Fires every 30 seconds. """ if not is_in_combat(self): # Not in combat # Change all conditions to update on character's turn. for key in self.db.conditions: self.db.conditions[key][1] = self # Apply conditions that fire every turn self.apply_turn_conditions() # Tick down condition durations condition_tickdown(self, self) class TBItemsCharacterTest(TBItemsCharacter): """ Just like the TBItemsCharacter, but doesn't subscribe to the TickerHandler. This makes it easier to run unit tests on. """ def at_object_creation(self): self.db.max_hp = 100 # Set maximum HP to 100 self.db.hp = self.db.max_hp # Set current HP to maximum self.db.conditions = {} # Set empty dict for conditions """ ---------------------------------------------------------------------------- SCRIPTS START HERE ---------------------------------------------------------------------------- """ class TBItemsTurnHandler(DefaultScript): """ This is the script that handles the progression of combat through turns. On creation (when a fight is started) it adds all combat-ready characters to its roster and then sorts them into a turn order. There can only be one fight going on in a single room at a time, so the script is assigned to a room as its object. Fights persist until only one participant is left with any HP or all remaining participants choose to end the combat with the 'disengage' command. """ def at_script_creation(self): """ Called once, when the script is created. """ self.key = "Combat Turn Handler" self.interval = 5 # Once every 5 seconds self.persistent = True self.db.fighters = [] # Add all fighters in the room with at least 1 HP to the combat." for thing in self.obj.contents: if thing.db.hp: self.db.fighters.append(thing) # Initialize each fighter for combat for fighter in self.db.fighters: self.initialize_for_combat(fighter) # Add a reference to this script to the room self.obj.db.combat_turnhandler = self # Roll initiative and sort the list of fighters depending on who rolls highest to determine turn order. # The initiative roll is determined by the roll_init function and can be customized easily. ordered_by_roll = sorted(self.db.fighters, key=roll_init, reverse=True) self.db.fighters = ordered_by_roll # Announce the turn order. self.obj.msg_contents("Turn order is: %s " % ", ".join(obj.key for obj in self.db.fighters)) # Start first fighter's turn. self.start_turn(self.db.fighters[0]) # Set up the current turn and turn timeout delay. self.db.turn = 0 self.db.timer = TURN_TIMEOUT # Set timer to turn timeout specified in options def at_stop(self): """ Called at script termination. """ for fighter in self.db.fighters: combat_cleanup(fighter) # Clean up the combat attributes for every fighter. self.obj.db.combat_turnhandler = None # Remove reference to turn handler in location def at_repeat(self): """ Called once every self.interval seconds. """ currentchar = self.db.fighters[ self.db.turn ] # Note the current character in the turn order. self.db.timer -= self.interval # Count down the timer. if self.db.timer <= 0: # Force current character to disengage if timer runs out. self.obj.msg_contents("%s's turn timed out!" % currentchar) spend_action( currentchar, "all", action_name="disengage" ) # Spend all remaining actions. return elif self.db.timer <= 10 and not self.db.timeout_warning_given: # 10 seconds left # Warn the current character if they're about to time out. currentchar.msg("WARNING: About to time out!") self.db.timeout_warning_given = True def initialize_for_combat(self, character): """ Prepares a character for combat when starting or entering a fight. Args: character (obj): Character to initialize for combat. """ combat_cleanup(character) # Clean up leftover combat attributes beforehand, just in case. character.db.combat_actionsleft = ( 0 # Actions remaining - start of turn adds to this, turn ends when it reaches 0 ) character.db.combat_turnhandler = ( self # Add a reference to this turn handler script to the character ) character.db.combat_lastaction = "null" # Track last action taken in combat def start_turn(self, character): """ Readies a character for the start of their turn by replenishing their available actions and notifying them that their turn has come up. Args: character (obj): Character to be readied. Notes: Here, you only get one action per turn, but you might want to allow more than one per turn, or even grant a number of actions based on a character's attributes. You can even add multiple different kinds of actions, I.E. actions separated for movement, by adding "character.db.combat_movesleft = 3" or something similar. """ character.db.combat_actionsleft = ACTIONS_PER_TURN # Replenish actions # Call character's at_turn_start() hook. character.at_turn_start() def next_turn(self): """ Advances to the next character in the turn order. """ # Check to see if every character disengaged as their last action. If so, end combat. disengage_check = True for fighter in self.db.fighters: if ( fighter.db.combat_lastaction != "disengage" ): # If a character has done anything but disengage disengage_check = False if disengage_check: # All characters have disengaged self.obj.msg_contents("All fighters have disengaged! Combat is over!") self.stop() # Stop this script and end combat. return # Check to see if only one character is left standing. If so, end combat. defeated_characters = 0 for fighter in self.db.fighters: if fighter.db.HP == 0: defeated_characters += 1 # Add 1 for every fighter with 0 HP left (defeated) if defeated_characters == ( len(self.db.fighters) - 1 ): # If only one character isn't defeated for fighter in self.db.fighters: if fighter.db.HP != 0: LastStanding = fighter # Pick the one fighter left with HP remaining self.obj.msg_contents("Only %s remains! Combat is over!" % LastStanding) self.stop() # Stop this script and end combat. return # Cycle to the next turn. currentchar = self.db.fighters[self.db.turn] self.db.turn += 1 # Go to the next in the turn order. if self.db.turn > len(self.db.fighters) - 1: self.db.turn = 0 # Go back to the first in the turn order once you reach the end. newchar = self.db.fighters[self.db.turn] # Note the new character self.db.timer = TURN_TIMEOUT + self.time_until_next_repeat() # Reset the timer. self.db.timeout_warning_given = False # Reset the timeout warning. self.obj.msg_contents("%s's turn ends - %s's turn begins!" % (currentchar, newchar)) self.start_turn(newchar) # Start the new character's turn. # Count down condition timers. for fighter in self.db.fighters: condition_tickdown(fighter, newchar) def turn_end_check(self, character): """ Tests to see if a character's turn is over, and cycles to the next turn if it is. Args: character (obj): Character to test for end of turn """ if not character.db.combat_actionsleft: # Character has no actions remaining self.next_turn() return def join_fight(self, character): """ Adds a new character to a fight already in progress. Args: character (obj): Character to be added to the fight. """ # Inserts the fighter to the turn order, right behind whoever's turn it currently is. self.db.fighters.insert(self.db.turn, character) # Tick the turn counter forward one to compensate. self.db.turn += 1 # Initialize the character like you do at the start. self.initialize_for_combat(character) """ ---------------------------------------------------------------------------- COMMANDS START HERE ---------------------------------------------------------------------------- """ class CmdFight(Command): """ Starts a fight with everyone in the same room as you. Usage: fight When you start a fight, everyone in the room who is able to fight is added to combat, and a turn order is randomly rolled. When it's your turn, you can attack other characters. """ key = "fight" help_category = "combat" def func(self): """ This performs the actual command. """ here = self.caller.location fighters = [] if not self.caller.db.hp: # If you don't have any hp self.caller.msg("You can't start a fight if you've been defeated!") return if is_in_combat(self.caller): # Already in a fight self.caller.msg("You're already in a fight!") return for thing in here.contents: # Test everything in the room to add it to the fight. if thing.db.HP: # If the object has HP... fighters.append(thing) # ...then add it to the fight. if len(fighters) <= 1: # If you're the only able fighter in the room self.caller.msg("There's nobody here to fight!") return if here.db.combat_turnhandler: # If there's already a fight going on... here.msg_contents("%s joins the fight!" % self.caller) here.db.combat_turnhandler.join_fight(self.caller) # Join the fight! return here.msg_contents("%s starts a fight!" % self.caller) # Add a turn handler script to the room, which starts combat. here.scripts.add("contrib.turnbattle.tb_items.TBItemsTurnHandler") # Remember you'll have to change the path to the script if you copy this code to your own modules! class CmdAttack(Command): """ Attacks another character. Usage: attack <target> When in a fight, you may attack another character. The attack has a chance to hit, and if successful, will deal damage. """ key = "attack" help_category = "combat" def func(self): "This performs the actual command." "Set the attacker to the caller and the defender to the target." if not is_in_combat(self.caller): # If not in combat, can't attack. self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # If it's not your turn, can't attack. self.caller.msg("You can only do that on your turn.") return if not self.caller.db.hp: # Can't attack if you have no HP. self.caller.msg("You can't attack, you've been defeated.") return if "Frightened" in self.caller.db.conditions: # Can't attack if frightened self.caller.msg("You're too frightened to attack!") return attacker = self.caller defender = self.caller.search(self.args) if not defender: # No valid target given. return if not defender.db.hp: # Target object has no HP left or to begin with self.caller.msg("You can't fight that!") return if attacker == defender: # Target and attacker are the same self.caller.msg("You can't attack yourself!") return "If everything checks out, call the attack resolving function." resolve_attack(attacker, defender) spend_action(self.caller, 1, action_name="attack") # Use up one action. class CmdPass(Command): """ Passes on your turn. Usage: pass When in a fight, you can use this command to end your turn early, even if there are still any actions you can take. """ key = "pass" aliases = ["wait", "hold"] help_category = "combat" def func(self): """ This performs the actual command. """ if not is_in_combat(self.caller): # Can only pass a turn in combat. self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # Can only pass if it's your turn. self.caller.msg("You can only do that on your turn.") return self.caller.location.msg_contents( "%s takes no further action, passing the turn." % self.caller ) spend_action(self.caller, "all", action_name="pass") # Spend all remaining actions. class CmdDisengage(Command): """ Passes your turn and attempts to end combat. Usage: disengage Ends your turn early and signals that you're trying to end the fight. If all participants in a fight disengage, the fight ends. """ key = "disengage" aliases = ["spare"] help_category = "combat" def func(self): """ This performs the actual command. """ if not is_in_combat(self.caller): # If you're not in combat self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # If it's not your turn self.caller.msg("You can only do that on your turn.") return self.caller.location.msg_contents("%s disengages, ready to stop fighting." % self.caller) spend_action(self.caller, "all", action_name="disengage") # Spend all remaining actions. """ The action_name kwarg sets the character's last action to "disengage", which is checked by the turn handler script to see if all fighters have disengaged. """ class CmdRest(Command): """ Recovers damage. Usage: rest Resting recovers your HP to its maximum, but you can only rest if you're not in a fight. """ key = "rest" help_category = "combat" def func(self): "This performs the actual command." if is_in_combat(self.caller): # If you're in combat self.caller.msg("You can't rest while you're in combat.") return self.caller.db.hp = self.caller.db.max_hp # Set current HP to maximum self.caller.location.msg_contents("%s rests to recover HP." % self.caller) """ You'll probably want to replace this with your own system for recovering HP. """ class CmdCombatHelp(CmdHelp): """ View help or a list of topics Usage: help <topic or command> help list help all This will search for help on commands and other topics related to the game. """ # Just like the default help command, but will give quick # tips on combat when used in a fight with no arguments. def func(self): if is_in_combat(self.caller) and not self.args: # In combat and entered 'help' alone self.caller.msg( "Available combat commands:|/" + "|wAttack:|n Attack a target, attempting to deal damage.|/" + "|wPass:|n Pass your turn without further action.|/" + "|wDisengage:|n End your turn and attempt to end combat.|/" + "|wUse:|n Use an item you're carrying." ) else: super(CmdCombatHelp, self).func() # Call the default help command class CmdUse(MuxCommand): """ Use an item. Usage: use <item> [= target] An item can have various function - looking at the item may provide information as to its effects. Some items can be used to attack others, and as such can only be used in combat. """ key = "use" help_category = "combat" def func(self): """ This performs the actual command. """ # Search for item item = self.caller.search(self.lhs, candidates=self.caller.contents) if not item: return # Search for target, if any is given target = None if self.rhs: target = self.caller.search(self.rhs) if not target: return # If in combat, can only use items on your turn if is_in_combat(self.caller): if not is_turn(self.caller): self.caller.msg("You can only use items on your turn.") return if not item.db.item_func: # Object has no item_func, not usable self.caller.msg("'%s' is not a usable item." % item.key.capitalize()) return if item.attributes.has("item_uses"): # Item has limited uses if item.db.item_uses <= 0: # Limited uses are spent self.caller.msg("'%s' has no uses remaining." % item.key.capitalize()) return # If everything checks out, call the use_item function use_item(self.caller, item, target) class BattleCmdSet(default_cmds.CharacterCmdSet): """ This command set includes all the commmands used in the battle system. """ key = "DefaultCharacter" def at_cmdset_creation(self): """ Populates the cmdset """ self.add(CmdFight()) self.add(CmdAttack()) self.add(CmdRest()) self.add(CmdPass()) self.add(CmdDisengage()) self.add(CmdCombatHelp()) self.add(CmdUse()) """ ---------------------------------------------------------------------------- ITEM FUNCTIONS START HERE ---------------------------------------------------------------------------- These functions carry out the action of using an item - every item should contain a db entry "item_func", with its value being a string that is matched to one of these functions in the ITEMFUNCS dictionary below. Every item function must take the following arguments: item (obj): The item being used user (obj): The character using the item target (obj): The target of the item use Item functions must also accept **kwargs - these keyword arguments can be used to define how different items that use the same function can have different effects (for example, different attack items doing different amounts of damage). Each function below contains a description of what kwargs the function will take and the effect they have on the result. """ def itemfunc_heal(item, user, target, **kwargs): """ Item function that heals HP. kwargs: min_healing(int): Minimum amount of HP recovered max_healing(int): Maximum amount of HP recovered """ if not target: target = user # Target user if none specified if not target.attributes.has("max_hp"): # Has no HP to speak of user.msg("You can't use %s on that." % item) return False # Returning false aborts the item use if target.db.hp >= target.db.max_hp: user.msg("%s is already at full health." % target) return False min_healing = 20 max_healing = 40 # Retrieve healing range from kwargs, if present if "healing_range" in kwargs: min_healing = kwargs["healing_range"][0] max_healing = kwargs["healing_range"][1] to_heal = randint(min_healing, max_healing) # Restore 20 to 40 hp if target.db.hp + to_heal > target.db.max_hp: to_heal = target.db.max_hp - target.db.hp # Cap healing to max HP target.db.hp += to_heal user.location.msg_contents("%s uses %s! %s regains %i HP!" % (user, item, target, to_heal)) def itemfunc_add_condition(item, user, target, **kwargs): """ Item function that gives the target one or more conditions. kwargs: conditions (list): Conditions added by the item formatted as a list of tuples: (condition (str), duration (int or True)) Notes: Should mostly be used for beneficial conditions - use itemfunc_attack for an item that can give an enemy a harmful condition. """ conditions = [("Regeneration", 5)] if not target: target = user # Target user if none specified if not target.attributes.has("max_hp"): # Is not a fighter user.msg("You can't use %s on that." % item) return False # Returning false aborts the item use # Retrieve condition / duration from kwargs, if present if "conditions" in kwargs: conditions = kwargs["conditions"] user.location.msg_contents("%s uses %s!" % (user, item)) # Add conditions to the target for condition in conditions: add_condition(target, user, condition[0], condition[1]) def itemfunc_cure_condition(item, user, target, **kwargs): """ Item function that'll remove given conditions from a target. kwargs: to_cure(list): List of conditions (str) that the item cures when used """ to_cure = ["Poisoned"] if not target: target = user # Target user if none specified if not target.attributes.has("max_hp"): # Is not a fighter user.msg("You can't use %s on that." % item) return False # Returning false aborts the item use # Retrieve condition(s) to cure from kwargs, if present if "to_cure" in kwargs: to_cure = kwargs["to_cure"] item_msg = "%s uses %s! " % (user, item) for key in target.db.conditions: if key in to_cure: # If condition specified in to_cure, remove it. item_msg += "%s no longer has the '%s' condition. " % (str(target), str(key)) del target.db.conditions[key] user.location.msg_contents(item_msg) def itemfunc_attack(item, user, target, **kwargs): """ Item function that attacks a target. kwargs: min_damage(int): Minimum damage dealt by the attack max_damage(int): Maximum damage dealth by the attack accuracy(int): Bonus / penalty to attack accuracy roll inflict_condition(list): List of conditions inflicted on hit, formatted as a (str, int) tuple containing condition name and duration. Notes: Calls resolve_attack at the end. """ if not is_in_combat(user): user.msg("You can only use that in combat.") return False # Returning false aborts the item use if not target: user.msg("You have to specify a target to use %s! (use <item> = <target>)" % item) return False if target == user: user.msg("You can't attack yourself!") return False if not target.db.hp: # Has no HP user.msg("You can't use %s on that." % item) return False min_damage = 20 max_damage = 40 accuracy = 0 inflict_condition = [] # Retrieve values from kwargs, if present if "damage_range" in kwargs: min_damage = kwargs["damage_range"][0] max_damage = kwargs["damage_range"][1] if "accuracy" in kwargs: accuracy = kwargs["accuracy"] if "inflict_condition" in kwargs: inflict_condition = kwargs["inflict_condition"] # Roll attack and damage attack_value = randint(1, 100) + accuracy damage_value = randint(min_damage, max_damage) # Account for "Accuracy Up" and "Accuracy Down" conditions if "Accuracy Up" in user.db.conditions: attack_value += 25 if "Accuracy Down" in user.db.conditions: attack_value -= 25 user.location.msg_contents("%s attacks %s with %s!" % (user, target, item)) resolve_attack( user, target, attack_value=attack_value, damage_value=damage_value, inflict_condition=inflict_condition, ) # Match strings to item functions here. We can't store callables on # prototypes, so we store a string instead, matching that string to # a callable in this dictionary. ITEMFUNCS = { "heal": itemfunc_heal, "attack": itemfunc_attack, "add_condition": itemfunc_add_condition, "cure_condition": itemfunc_cure_condition, } """ ---------------------------------------------------------------------------- PROTOTYPES START HERE ---------------------------------------------------------------------------- You can paste these prototypes into your game's prototypes.py module in your /world/ folder, and use the spawner to create them - they serve as examples of items you can make and a handy way to demonstrate the system for conditions as well. Items don't have any particular typeclass - any object with a db entry "item_func" that references one of the functions given above can be used as an item with the 'use' command. Only "item_func" is required, but item behavior can be further modified by specifying any of the following: item_uses (int): If defined, item has a limited number of uses item_selfonly (bool): If True, user can only use the item on themself item_consumable(True or str): If True, item is destroyed when it runs out of uses. If a string is given, the item will spawn a new object as it's destroyed, with the string specifying what prototype to spawn. item_kwargs (dict): Keyword arguments to pass to the function defined in item_func. Unique to each function, and can be used to make multiple items using the same function work differently. """ MEDKIT = { "key": "a medical kit", "aliases": ["medkit"], "desc": "A standard medical kit. It can be used a few times to heal wounds.", "item_func": "heal", "item_uses": 3, "item_consumable": True, "item_kwargs": {"healing_range": (15, 25)}, } GLASS_BOTTLE = {"key": "a glass bottle", "desc": "An empty glass bottle."} HEALTH_POTION = { "key": "a health potion", "desc": "A glass bottle full of a mystical potion that heals wounds when used.", "item_func": "heal", "item_uses": 1, "item_consumable": "GLASS_BOTTLE", "item_kwargs": {"healing_range": (35, 50)}, } REGEN_POTION = { "key": "a regeneration potion", "desc": "A glass bottle full of a mystical potion that regenerates wounds over time.", "item_func": "add_condition", "item_uses": 1, "item_consumable": "GLASS_BOTTLE", "item_kwargs": {"conditions": [("Regeneration", 10)]}, } HASTE_POTION = { "key": "a haste potion", "desc": "A glass bottle full of a mystical potion that hastens its user.", "item_func": "add_condition", "item_uses": 1, "item_consumable": "GLASS_BOTTLE", "item_kwargs": {"conditions": [("Haste", 10)]}, } BOMB = { "key": "a rotund bomb", "desc": "A large black sphere with a fuse at the end. Can be used on enemies in combat.", "item_func": "attack", "item_uses": 1, "item_consumable": True, "item_kwargs": {"damage_range": (25, 40), "accuracy": 25}, } POISON_DART = { "key": "a poison dart", "desc": "A thin dart coated in deadly poison. Can be used on enemies in combat", "item_func": "attack", "item_uses": 1, "item_consumable": True, "item_kwargs": { "damage_range": (5, 10), "accuracy": 25, "inflict_condition": [("Poisoned", 10)], }, } TASER = { "key": "a taser", "desc": "A device that can be used to paralyze enemies in combat.", "item_func": "attack", "item_kwargs": { "damage_range": (10, 20), "accuracy": 0, "inflict_condition": [("Paralyzed", 1)], }, } GHOST_GUN = { "key": "a ghost gun", "desc": "A gun that fires scary ghosts at people. Anyone hit by a ghost becomes frightened.", "item_func": "attack", "item_uses": 6, "item_kwargs": { "damage_range": (5, 10), "accuracy": 15, "inflict_condition": [("Frightened", 1)], }, } ANTIDOTE_POTION = { "key": "an antidote potion", "desc": "A glass bottle full of a mystical potion that cures poison when used.", "item_func": "cure_condition", "item_uses": 1, "item_consumable": "GLASS_BOTTLE", "item_kwargs": {"to_cure": ["Poisoned"]}, } AMULET_OF_MIGHT = { "key": "The Amulet of Might", "desc": "The one who holds this amulet can call upon its power to gain great strength.", "item_func": "add_condition", "item_selfonly": True, "item_kwargs": {"conditions": [("Damage Up", 3), ("Accuracy Up", 3), ("Defense Up", 3)]}, } AMULET_OF_WEAKNESS = { "key": "The Amulet of Weakness", "desc": "The one who holds this amulet can call upon its power to gain great weakness. It's not a terribly useful artifact.", "item_func": "add_condition", "item_selfonly": True, "item_kwargs": {"conditions": [("Damage Down", 3), ("Accuracy Down", 3), ("Defense Down", 3)]}, }
[ "evennia.prototypes.spawner.spawn", "evennia.TICKER_HANDLER.add" ]
[((4950, 4966), 'random.randint', 'randint', (['(1)', '(1000)'], {}), '(1, 1000)\n', (4957, 4966), False, 'from random import randint\n'), ((5644, 5659), 'random.randint', 'randint', (['(1)', '(100)'], {}), '(1, 100)\n', (5651, 5659), False, 'from random import randint\n'), ((7641, 7656), 'random.randint', 'randint', (['(15)', '(25)'], {}), '(15, 25)\n', (7648, 7656), False, 'from random import randint\n'), ((42780, 42813), 'random.randint', 'randint', (['min_healing', 'max_healing'], {}), '(min_healing, max_healing)\n', (42787, 42813), False, 'from random import randint\n'), ((46660, 46691), 'random.randint', 'randint', (['min_damage', 'max_damage'], {}), '(min_damage, max_damage)\n', (46667, 46691), False, 'from random import randint\n'), ((19134, 19207), 'evennia.TICKER_HANDLER.add', 'tickerhandler.add', (['NONCOMBAT_TURN_TIME', 'self.at_update'], {'idstring': '"""update"""'}), "(NONCOMBAT_TURN_TIME, self.at_update, idstring='update')\n", (19151, 19207), True, 'from evennia import TICKER_HANDLER as tickerhandler\n'), ((46614, 46629), 'random.randint', 'randint', (['(1)', '(100)'], {}), '(1, 100)\n', (46621, 46629), False, 'from random import randint\n'), ((21329, 21366), 'random.randint', 'randint', (['REGEN_RATE[0]', 'REGEN_RAGE[1]'], {}), '(REGEN_RATE[0], REGEN_RAGE[1])\n', (21336, 21366), False, 'from random import randint\n'), ((21784, 21823), 'random.randint', 'randint', (['POISON_RATE[0]', 'POISON_RATE[1]'], {}), '(POISON_RATE[0], POISON_RATE[1])\n', (21791, 21823), False, 'from random import randint\n'), ((14305, 14350), 'evennia.prototypes.spawner.spawn', 'spawn', (["{'prototype': item.db.item_consumable}"], {}), "({'prototype': item.db.item_consumable})\n", (14310, 14350), False, 'from evennia.prototypes.spawner import spawn\n')]
""" Slow Exit typeclass Contribution - Griatch 2014 This is an example of an Exit-type that delays its traversal.This simulates slow movement, common in many different types of games. The contrib also contains two commands, CmdSetSpeed and CmdStop for changing the movement speed and abort an ongoing traversal, respectively. To try out an exit of this type, you could connect two existing rooms using something like this: @open north:contrib.slow_exit.SlowExit = <destination> Installation: To make all new exits of this type, add the following line to your settings: BASE_EXIT_TYPECLASS = "contrib.slow_exit.SlowExit" To get the ability to change your speed and abort your movement, simply import and add CmdSetSpeed and CmdStop from this module to your default cmdset (see tutorials on how to do this if you are unsure). Notes: This implementation is efficient but not persistent; so incomplete movement will be lost in a server reload. This is acceptable for most game types - to simulate longer travel times (more than the couple of seconds assumed here), a more persistent variant using Scripts or the TickerHandler might be better. """ from evennia import DefaultExit, utils, Command MOVE_DELAY = {"stroll": 6, "walk": 4, "run": 2, "sprint": 1} class SlowExit(DefaultExit): """ This overloads the way moving happens. """ def at_traverse(self, traversing_object, target_location): """ Implements the actual traversal, using utils.delay to delay the move_to. """ # if the traverser has an Attribute move_speed, use that, # otherwise default to "walk" speed move_speed = traversing_object.db.move_speed or "walk" move_delay = MOVE_DELAY.get(move_speed, 4) def move_callback(): "This callback will be called by utils.delay after move_delay seconds." source_location = traversing_object.location if traversing_object.move_to(target_location): self.at_after_traverse(traversing_object, source_location) else: if self.db.err_traverse: # if exit has a better error message, let's use it. self.caller.msg(self.db.err_traverse) else: # No shorthand error message. Call hook. self.at_failed_traverse(traversing_object) traversing_object.msg("You start moving %s at a %s." % (self.key, move_speed)) # create a delayed movement deferred = utils.delay(move_delay, callback=move_callback) # we store the deferred on the character, this will allow us # to abort the movement. We must use an ndb here since # deferreds cannot be pickled. traversing_object.ndb.currently_moving = deferred # # set speed - command # SPEED_DESCS = {"stroll": "strolling", "walk": "walking", "run": "running", "sprint": "sprinting"} class CmdSetSpeed(Command): """ set your movement speed Usage: setspeed stroll|walk|run|sprint This will set your movement speed, determining how long time it takes to traverse exits. If no speed is set, 'walk' speed is assumed. """ key = "setspeed" def func(self): """ Simply sets an Attribute used by the SlowExit above. """ speed = self.args.lower().strip() if speed not in SPEED_DESCS: self.caller.msg("Usage: setspeed stroll|walk|run|sprint") elif self.caller.db.move_speed == speed: self.caller.msg("You are already %s." % SPEED_DESCS[speed]) else: self.caller.db.move_speed = speed self.caller.msg("You are now %s." % SPEED_DESCS[speed]) # # stop moving - command # class CmdStop(Command): """ stop moving Usage: stop Stops the current movement, if any. """ key = "stop" def func(self): """ This is a very simple command, using the stored deferred from the exit traversal above. """ currently_moving = self.caller.ndb.currently_moving if currently_moving: currently_moving.cancel() self.caller.msg("You stop moving.") else: self.caller.msg("You are not moving.")
[ "evennia.utils.delay" ]
[((2574, 2621), 'evennia.utils.delay', 'utils.delay', (['move_delay'], {'callback': 'move_callback'}), '(move_delay, callback=move_callback)\n', (2585, 2621), False, 'from evennia import DefaultExit, utils, Command\n')]
""" Commands for flashbacks and other scene management stuff in the Character app. Flashbacks are for the Arx equivalent of play-by-post: players can create a flashback of a scene that happened in the past with a clear summary and end-goal in mind, and then invite others to RP about it. """ from django.db.models import Q from server.utils.arx_utils import ArxPlayerCommand from web.character.models import Flashback class CmdFlashback(ArxPlayerCommand): """ Create, read, or participate in a flashback Usage: flashback flashback <ID #>[=<number of last posts to display] flashback/catchup <ID #> flashback/create <title>[=<summary>] flashback/title <ID #>=<new title> flashback/summary <ID #>=<new summary> flashback/invite <ID #>=<player> flashback/uninvite <ID #>=<player> flashback/post <ID #>=<message> Flashbacks are a way in which you can flesh out scenes that happened in the past in story form, inviting other players to participate. All flashbacks are private to the players involved and staff, and are assumed to be IC scenes that occurred some time in the past. New posts will inform the characters involved in the flashback. If you wish to no longer be informed or participate, you can uninvite yourself from a flashback. Catchup will summarize all display unread posts a given flashback. Posts can also be made from the webpage, linked from your character page. """ key = "flashback" aliases = ["flashbacks"] locks = "cmd:all()" help_category = "scenes" player_switches = ("invite", "uninvite") change_switches = ("title", "summary") requires_owner = ("invite",) + change_switches @property def roster_entry(self): return self.caller.roster @property def accessible_flashbacks(self): return Flashback.objects.filter(Q(owner=self.roster_entry) | Q(allowed=self.roster_entry)).distinct() def func(self): if not self.switches and not self.args: return self.list_flashbacks() if "create" in self.switches: return self.create_flashback() flashback = self.get_flashback() if not flashback: return if not self.switches: return self.view_flashback(flashback) if "catchup" in self.switches: return self.read_new_posts(flashback) if "post" in self.switches: return self.post_message(flashback) if not self.check_can_use_switch(flashback): return if self.check_switches(self.player_switches): return self.manage_invites(flashback) if self.check_switches(self.change_switches): return self.update_flashback(flashback) self.msg("Invalid switch.") def list_flashbacks(self): from evennia.utils.evtable import EvTable table = EvTable("ID", "Title", "Owner", "New Posts", width=78, border="cells") for flashback in self.accessible_flashbacks: table.add_row(flashback.id, flashback.title, flashback.owner, len(flashback.get_new_posts(self.roster_entry))) self.msg(str(table)) def create_flashback(self): title = self.lhs summary = self.rhs or "" if Flashback.objects.filter(title__iexact=title).exists(): self.msg("There is already a flashback with that title. Please choose another.") return flashback = self.roster_entry.created_flashbacks.create(title=title, summary=summary) self.msg("You have created a new flashback with the ID of #%s." % flashback.id) def get_flashback(self): try: return self.accessible_flashbacks.get(id=int(self.lhs)) except (Flashback.DoesNotExist, ValueError): self.msg("No flashback by that ID number.") self.list_flashbacks() def view_flashback(self, flashback): try: post_limit = int(self.rhs) except (TypeError, ValueError): post_limit = None self.msg(flashback.display(post_limit=post_limit)) def read_new_posts(self, flashback): new_posts = flashback.get_new_posts(self.roster_entry) if not new_posts: msg = "No new posts for #%s." % flashback.id else: msg = "New posts for #%s\n" % flashback.id for post in new_posts: msg += "%s\n" % post.display() post.read_by.add(self.roster_entry) self.msg(msg) def manage_invites(self, flashback): targ = self.caller.search(self.rhs) if not targ: return if "invite" in self.switches: self.invite_target(flashback, targ) else: # uninvite self.uninvite_target(flashback, targ) def invite_target(self, flashback, target): if flashback.allowed.filter(id=target.roster.id).exists(): self.msg("They are already invited to this flashback.") return self.msg("You have invited %s to participate in this flashback." % target) flashback.allowed.add(target.roster) target.inform("You have been invited by %s to participate in flashback #%s: '%s'." % (self.caller, flashback.id, flashback), category="Flashbacks") def uninvite_target(self, flashback, target): if not flashback.allowed.filter(id=target.roster.id).exists(): self.msg("They are already not invited to this flashback.") return self.msg("You have uninvited %s from this flashback." % target) flashback.allowed.remove(target.roster) target.inform("You have been removed from flashback #%s." % flashback.id, category="Flashbacks") def post_message(self, flashback): if not self.rhs: self.msg("You must include a message.") return flashback.add_post(self.rhs, self.roster_entry) self.msg("You have posted a new message to %s: %s" % (flashback, self.rhs)) def check_can_use_switch(self, flashback): if not self.check_switches(self.requires_owner): return True if self.roster_entry != flashback.owner: self.msg("Only the flashback's owner may use that switch.") return False return True def update_flashback(self, flashback): if "title" in self.switches: field = "title" else: field = "summary" setattr(flashback, field, self.rhs) flashback.save() self.msg("%s set to: %s." % (field, self.rhs))
[ "evennia.utils.evtable.EvTable" ]
[((3005, 3075), 'evennia.utils.evtable.EvTable', 'EvTable', (['"""ID"""', '"""Title"""', '"""Owner"""', '"""New Posts"""'], {'width': '(78)', 'border': '"""cells"""'}), "('ID', 'Title', 'Owner', 'New Posts', width=78, border='cells')\n", (3012, 3075), False, 'from evennia.utils.evtable import EvTable\n'), ((3413, 3458), 'web.character.models.Flashback.objects.filter', 'Flashback.objects.filter', ([], {'title__iexact': 'title'}), '(title__iexact=title)\n', (3437, 3458), False, 'from web.character.models import Flashback\n'), ((1935, 1961), 'django.db.models.Q', 'Q', ([], {'owner': 'self.roster_entry'}), '(owner=self.roster_entry)\n', (1936, 1961), False, 'from django.db.models import Q\n'), ((2005, 2033), 'django.db.models.Q', 'Q', ([], {'allowed': 'self.roster_entry'}), '(allowed=self.roster_entry)\n', (2006, 2033), False, 'from django.db.models import Q\n')]
from django.db.models import Q, Manager class OrganizationManager(Manager): def get_public_org(self, org_name, caller): org = None try: try: name_or_id = Q(id=int(org_name)) except (ValueError, TypeError): name_or_id = Q(name__iexact=org_name) org = self.get(name_or_id & Q(secret=False)) except (self.model.DoesNotExist): caller.msg("Could not find public org '%s'." % org_name) except self.model.MultipleObjectsReturned: orgs = self.filter(Q(name__iexact=org_name) & Q(secret=False)) caller.msg("Too many options: %s" % ", ".join(ob for ob in orgs)) return org class CrisisManager(Manager): """Methods for accessing different Plot collections or viewing groups of Plots.""" def viewable_by_player(self, player): if not player or not player.is_authenticated(): return self.filter(public=True) if player.check_permstring("builders") or player.is_staff: qs = self.all() else: qs = self.filter(Q(public=True) | Q(required_clue__in=player.roster.clues.all())) return qs def view_plots_table(self, old=False): """Returns an EvTable chock full of spicy Plots.""" from evennia.utils.evtable import EvTable qs = self.filter(resolved=old).exclude(Q(usage=self.model.CRISIS) | Q(parent_plot__isnull=False)).distinct() alt_header = "Resolved " if old else "" table = EvTable("{w#{n", "{w%sPlot (owner){n" % alt_header, "{Summary{n", width=78, border="cells") for plot in qs: def get_plot_name_and_owner(plotmato): owner = (" (%s)" % plotmato.first_owner) if plotmato.first_owner else "" return "%s%s" % (str(plotmato), owner) def add_subplots_rows(subplot, color_num): sub_name = get_plot_name_and_owner(subplot) table.add_row("|%s35%s|n" % (color_num, subplot.id), sub_name, subplot.headline) color_num += 1 if color_num > 5: color_num = 0 for subplotmato in subplot.subplots.filter(resolved=old): add_subplots_rows(subplotmato, color_num) plot_name = get_plot_name_and_owner(plot) table.add_row(plot.id, plot_name, plot.headline) for subploterino in plot.subplots.filter(resolved=old): add_subplots_rows(subploterino, color_num=0) table.reformat_column(0, width=7) table.reformat_column(1, width=25) table.reformat_column(2, width=46) return table class LandManager(Manager): def land_by_coord(self, x, y): qs = self.filter(Q(x_coord=x) & Q(y_coord=y)) return qs
[ "evennia.utils.evtable.EvTable" ]
[((1530, 1625), 'evennia.utils.evtable.EvTable', 'EvTable', (['"""{w#{n"""', "('{w%sPlot (owner){n' % alt_header)", '"""{Summary{n"""'], {'width': '(78)', 'border': '"""cells"""'}), "('{w#{n', '{w%sPlot (owner){n' % alt_header, '{Summary{n', width=78,\n border='cells')\n", (1537, 1625), False, 'from evennia.utils.evtable import EvTable\n'), ((2773, 2785), 'django.db.models.Q', 'Q', ([], {'x_coord': 'x'}), '(x_coord=x)\n', (2774, 2785), False, 'from django.db.models import Q, Manager\n'), ((2788, 2800), 'django.db.models.Q', 'Q', ([], {'y_coord': 'y'}), '(y_coord=y)\n', (2789, 2800), False, 'from django.db.models import Q, Manager\n'), ((297, 321), 'django.db.models.Q', 'Q', ([], {'name__iexact': 'org_name'}), '(name__iexact=org_name)\n', (298, 321), False, 'from django.db.models import Q, Manager\n'), ((362, 377), 'django.db.models.Q', 'Q', ([], {'secret': '(False)'}), '(secret=False)\n', (363, 377), False, 'from django.db.models import Q, Manager\n'), ((1112, 1126), 'django.db.models.Q', 'Q', ([], {'public': '(True)'}), '(public=True)\n', (1113, 1126), False, 'from django.db.models import Q, Manager\n'), ((572, 596), 'django.db.models.Q', 'Q', ([], {'name__iexact': 'org_name'}), '(name__iexact=org_name)\n', (573, 596), False, 'from django.db.models import Q, Manager\n'), ((599, 614), 'django.db.models.Q', 'Q', ([], {'secret': '(False)'}), '(secret=False)\n', (600, 614), False, 'from django.db.models import Q, Manager\n'), ((1396, 1422), 'django.db.models.Q', 'Q', ([], {'usage': 'self.model.CRISIS'}), '(usage=self.model.CRISIS)\n', (1397, 1422), False, 'from django.db.models import Q, Manager\n'), ((1425, 1453), 'django.db.models.Q', 'Q', ([], {'parent_plot__isnull': '(False)'}), '(parent_plot__isnull=False)\n', (1426, 1453), False, 'from django.db.models import Q, Manager\n')]
""" Readable/Writable objects """ from typeclasses.objects import Object from evennia import CmdSet from commands.base import ArxCommand from world.templates.mixins import TemplateMixins class Readable(Object): """ Class for objects that can be written/named """ def at_object_creation(self): """ Run at Place creation. """ self.db.written = False self.desc = "Nothing has been written on this yet. '{whelp write{n'" self.db.num_instances = 1 self.db.can_stack = True self.db.do_not_format_desc = True self.at_init() def at_after_move(self, source_location, **kwargs): if self.db.num_instances > 1 and not self.db.written: self.setup_multiname() location = self.location # first, remove ourself from the source location's places, if it exists if source_location and source_location.is_room: if source_location.db.places and self in source_location.db.places: source_location.db.places.remove(self) # if location is a room, add cmdset if location and location.is_character: if self.db.written: self.cmdset.add_default(SignCmdSet, permanent=True) else: self.cmdset.add_default(WriteCmdSet, permanent=True) else: self.cmdset.delete_default() def return_appearance(self, *args, **kwargs): msg = Object.return_appearance(self, *args, **kwargs) if self.db.signed and not self.db.can_stack: sigs = ", ".join(str(ob) for ob in self.db.signed) msg += "\nSigned by: %s" % sigs return msg # noinspection PyAttributeOutsideInit def setup_multiname(self): if self.db.num_instances > 1: self.key = "%s books" % self.db.num_instances self.save() else: self.key = "a book" def set_num(self, value): self.db.num_instances = value self.setup_multiname() @property def junkable(self): """A check for this object's plot connections.""" return not self.is_plot_related def do_junkout(self, caller): """Junks us as if we were a crafted item.""" caller.msg("You destroy %s." % self) self.softdelete() return class WriteCmdSet(CmdSet): key = "WriteCmd" priority = 0 duplicates = True def at_cmdset_creation(self): """Init the cmdset""" self.add(CmdWrite()) class SignCmdSet(CmdSet): key = "SignCmd" priority = 0 duplicates = True def at_cmdset_creation(self): self.add(CmdSign()) class CmdSign(ArxCommand): """ Signs a document Usage: sign Places your signature on a document. """ key = "sign" locks = "cmd:all()" def func(self): caller = self.caller obj = self.obj sigs = obj.db.signed or [] if caller in sigs: caller.msg("You already signed this document.") return sigs.append(caller) caller.msg("You sign your name on %s." % obj.name) obj.db.signed = sigs return class CmdWrite(ArxCommand, TemplateMixins): """ Write upon a scroll/book/letter. Usage: write <description> write/title <title> write/proof write/translated_text <language>=<text> write/finish Writes upon a given scroll/letter/book or other object to give it a description set to the body of the text you write and set its name to the title you specify. For example, to rename 'a scroll' into 'Furen's Book of Wisdom', use 'write/title Furen's Book of Wisdom'. To write in other languages, use /translated_text to show what the material actually says. Check your changes with /proof, and then finalize changes with /finish. Once set, no further changes can be made. """ key = "write" locks = "cmd:all()" def display(self): obj = self.obj title = obj.ndb.title or obj.name desc = obj.ndb.desc or obj.desc msg = "{wName:{n %s\n" % title msg += "{wDesc:{n\n%s" % desc transtext = obj.ndb.transtext or {} for lang in transtext: msg += "\n{wWritten in {c%s:{n\n%s\n" % (lang.capitalize(), transtext[lang]) return msg def func(self): """Look for object in inventory that matches args to wear""" caller = self.caller obj = self.obj if not self.args and not self.switches: self.switches.append("proof") if not self.switches or 'desc' in self.switches: if not self.can_apply_templates(caller, self.args): return obj.ndb.desc = self.args caller.msg("Desc set to:\n%s" % self.args) return if "title" in self.switches: obj.ndb.title = self.args caller.msg("Name set to: %s" % self.args) return if "translated_text" in self.switches: transtext = obj.ndb.transtext or {} if not self.rhs: self.msg("Must have text.") lhs = self.lhs.lower() if lhs not in self.caller.languages.known_languages: self.msg("You cannot speak that language.") return transtext[lhs] = self.rhs obj.ndb.transtext = transtext self.msg(self.display()) return if "proof" in self.switches: msg = self.display() caller.msg(msg, options={'box': True}) return if "finish" in self.switches: name = obj.ndb.title desc = obj.ndb.desc if not name: caller.msg("Still needs a title set.") return if not desc: caller.msg("Still needs a description set.") return if obj.db.num_instances > 1: from evennia.utils.create import create_object remain = obj.db.num_instances - 1 newobj = create_object(typeclass="typeclasses.readable.readable.Readable", key='book', location=caller, home=caller) newobj.set_num(remain) obj.db.num_instances = 1 obj.name = name obj.desc = desc if obj.ndb.transtext: obj.db.translation = obj.ndb.transtext obj.save() self.apply_templates_to(obj) caller.msg("You have written on %s." % obj.name) obj.attributes.remove("quality_level") obj.attributes.remove("can_stack") obj.db.author = caller obj.db.written = True obj.cmdset.delete_default() obj.cmdset.add_default(SignCmdSet, permanent=True) obj.aliases.add("book") return caller.msg("Unrecognized syntax for write.")
[ "evennia.utils.create.create_object" ]
[((1466, 1513), 'typeclasses.objects.Object.return_appearance', 'Object.return_appearance', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (1490, 1513), False, 'from typeclasses.objects import Object\n'), ((6146, 6258), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""typeclasses.readable.readable.Readable"""', 'key': '"""book"""', 'location': 'caller', 'home': 'caller'}), "(typeclass='typeclasses.readable.readable.Readable', key=\n 'book', location=caller, home=caller)\n", (6159, 6258), False, 'from evennia.utils.create import create_object\n')]
import datetime from evennia import logger from evennia.utils.ansi import strip_ansi from evennia.utils.validatorfuncs import _TZ_DICT from evennia.utils.utils import crop from evennia.utils import validatorfuncs class BaseOption(object): """ Abstract Class to deal with encapsulating individual Options. An Option has a name/key, a description to display in relevant commands and menus, and a default value. It saves to the owner's Attributes using its Handler's save category. Designed to be extremely overloadable as some options can be cantankerous. Properties: valid: Shortcut to the loaded VALID_HANDLER. validator_key (str): The key of the Validator this uses. """ def __str__(self): return "<Option {key}: {value}>".format(key=self.key, value=crop(str(self.value), width=10)) def __repr__(self): return str(self) def __init__(self, handler, key, description, default): """ Args: handler (OptionHandler): The OptionHandler that 'owns' this Option. key (str): The name this will be used for storage in a dictionary. Must be unique per OptionHandler. description (str): What this Option's text will show in commands and menus. default: A default value for this Option. """ self.handler = handler self.key = key self.default_value = default self.description = description # Value Storage contains None until the Option is loaded. self.value_storage = None # And it's not loaded until it's called upon to spit out its contents. self.loaded = False @property def changed(self): return self.value_storage != self.default_value @property def default(self): return self.default_value @property def value(self): if not self.loaded: self.load() if self.loaded: return self.value_storage else: return self.default @value.setter def value(self, value): self.set(value) def set(self, value, **kwargs): """ Takes user input and stores appropriately. This method allows for passing extra instructions into the validator. Args: value (str): The new value of this Option. kwargs (any): Any kwargs will be passed into `self.validate(value, **kwargs)` and `self.save(**kwargs)`. """ final_value = self.validate(value, **kwargs) self.value_storage = final_value self.loaded = True self.save(**kwargs) def load(self): """ Takes the provided save data, validates it, and gets this Option ready to use. Returns: Boolean: Whether loading was successful. """ loadfunc = self.handler.loadfunc load_kwargs = self.handler.load_kwargs try: self.value_storage = self.deserialize( loadfunc(self.key, default=self.default_value, **load_kwargs) ) except Exception: logger.log_trace() return False self.loaded = True return True def save(self, **kwargs): """ Stores the current value using .handler.save_handler(self.key, value, **kwargs) where kwargs are a combination of those passed into this function and the ones specified by the OptionHandler. Kwargs: any (any): Not used by default. These are passed in from self.set and allows the option to let the caller customize saving by overriding or extend the default save kwargs """ value = self.serialize() save_kwargs = {**self.handler.save_kwargs, **kwargs} savefunc = self.handler.savefunc savefunc(self.key, value=value, **save_kwargs) def deserialize(self, save_data): """ Perform sanity-checking on the save data as it is loaded from storage. This isn't the same as what validator-functions provide (those work on user input). For example, save data might be a timedelta or a list or some other object. Args: save_data: The data to check. Returns: any (any): Whatever the Option needs to track, like a string or a datetime. The display hook is responsible for what is actually displayed to user. """ return save_data def serialize(self): """ Serializes the save data for Attribute storage. Returns: any (any): Whatever is best for storage. """ return self.value_storage def validate(self, value, **kwargs): """ Validate user input, which is presumed to be a string. Args: value (str): User input. account (AccountDB): The Account that is performing the validation. This is necessary because of other settings which may affect the check, such as an Account's timezone affecting how their datetime entries are processed. Returns: any (any): The results of the validation. Raises: ValidationError: If input value failed validation. """ return validatorfuncs.text(value, option_key=self.key, **kwargs) def display(self, **kwargs): """ Renders the Option's value as something pretty to look at. Kwargs: any (any): These are options passed by the caller to potentially customize display dynamically. Returns: str: How the stored value should be projected to users (e.g. a raw timedelta is pretty ugly). """ return self.value # Option classes class Text(BaseOption): def deserialize(self, save_data): got_data = str(save_data) if not got_data: raise ValueError(f"{self.key} expected Text data, got '{save_data}'") return got_data class Email(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.email(value, option_key=self.key, **kwargs) def deserialize(self, save_data): got_data = str(save_data) if not got_data: raise ValueError(f"{self.key} expected String data, got '{save_data}'") return got_data class Boolean(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.boolean(value, option_key=self.key, **kwargs) def display(self, **kwargs): if self.value: return "1 - On/True" return "0 - Off/False" def serialize(self): return self.value def deserialize(self, save_data): if not isinstance(save_data, bool): raise ValueError(f"{self.key} expected Boolean, got '{save_data}'") return save_data class Color(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.color(value, option_key=self.key, **kwargs) def display(self, **kwargs): return f"{self.value} - |{self.value}this|n" def deserialize(self, save_data): if not save_data or len(strip_ansi(f"|{save_data}|n")) > 0: raise ValueError(f"{self.key} expected Color Code, got '{save_data}'") return save_data class Timezone(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.timezone(value, option_key=self.key, **kwargs) @property def default(self): return _TZ_DICT[self.default_value] def deserialize(self, save_data): if save_data not in _TZ_DICT: raise ValueError(f"{self.key} expected Timezone Data, got '{save_data}'") return _TZ_DICT[save_data] def serialize(self): return str(self.value_storage) class UnsignedInteger(BaseOption): validator_key = "unsigned_integer" def validate(self, value, **kwargs): return validatorfuncs.unsigned_integer(value, option_key=self.key, **kwargs) def deserialize(self, save_data): if isinstance(save_data, int) and save_data >= 0: return save_data raise ValueError(f"{self.key} expected Whole Number 0+, got '{save_data}'") class SignedInteger(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.signed_integer(value, option_key=self.key, **kwargs) def deserialize(self, save_data): if isinstance(save_data, int): return save_data raise ValueError(f"{self.key} expected Whole Number, got '{save_data}'") class PositiveInteger(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.positive_integer(value, option_key=self.key, **kwargs) def deserialize(self, save_data): if isinstance(save_data, int) and save_data > 0: return save_data raise ValueError(f"{self.key} expected Whole Number 1+, got '{save_data}'") class Duration(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.duration(value, option_key=self.key, **kwargs) def deserialize(self, save_data): if isinstance(save_data, int): return datetime.timedelta(0, save_data, 0, 0, 0, 0, 0) raise ValueError(f"{self.key} expected Timedelta in seconds, got '{save_data}'") def serialize(self): return self.value_storage.seconds class Datetime(BaseOption): def validate(self, value, **kwargs): return validatorfuncs.datetime(value, option_key=self.key, **kwargs) def deserialize(self, save_data): if isinstance(save_data, int): return datetime.datetime.utcfromtimestamp(save_data) raise ValueError(f"{self.key} expected UTC Datetime in EPOCH format, got '{save_data}'") def serialize(self): return int(self.value_storage.strftime("%s")) class Future(Datetime): def validate(self, value, **kwargs): return validatorfuncs.future(value, option_key=self.key, **kwargs) class Lock(Text): def validate(self, value, **kwargs): return validatorfuncs.lock(value, option_key=self.key, **kwargs)
[ "evennia.utils.validatorfuncs.unsigned_integer", "evennia.utils.validatorfuncs.datetime", "evennia.utils.validatorfuncs.timezone", "evennia.utils.validatorfuncs.email", "evennia.utils.ansi.strip_ansi", "evennia.utils.validatorfuncs.color", "evennia.utils.validatorfuncs.duration", "evennia.utils.valida...
[((5397, 5454), 'evennia.utils.validatorfuncs.text', 'validatorfuncs.text', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (5416, 5454), False, 'from evennia.utils import validatorfuncs\n'), ((6219, 6277), 'evennia.utils.validatorfuncs.email', 'validatorfuncs.email', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (6239, 6277), False, 'from evennia.utils import validatorfuncs\n'), ((6569, 6629), 'evennia.utils.validatorfuncs.boolean', 'validatorfuncs.boolean', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (6591, 6629), False, 'from evennia.utils import validatorfuncs\n'), ((7074, 7132), 'evennia.utils.validatorfuncs.color', 'validatorfuncs.color', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (7094, 7132), False, 'from evennia.utils import validatorfuncs\n'), ((7521, 7582), 'evennia.utils.validatorfuncs.timezone', 'validatorfuncs.timezone', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (7544, 7582), False, 'from evennia.utils import validatorfuncs\n'), ((8061, 8130), 'evennia.utils.validatorfuncs.unsigned_integer', 'validatorfuncs.unsigned_integer', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (8092, 8130), False, 'from evennia.utils import validatorfuncs\n'), ((8432, 8499), 'evennia.utils.validatorfuncs.signed_integer', 'validatorfuncs.signed_integer', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (8461, 8499), False, 'from evennia.utils import validatorfuncs\n'), ((8781, 8850), 'evennia.utils.validatorfuncs.positive_integer', 'validatorfuncs.positive_integer', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (8812, 8850), False, 'from evennia.utils import validatorfuncs\n'), ((9146, 9207), 'evennia.utils.validatorfuncs.duration', 'validatorfuncs.duration', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (9169, 9207), False, 'from evennia.utils import validatorfuncs\n'), ((9596, 9657), 'evennia.utils.validatorfuncs.datetime', 'validatorfuncs.datetime', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (9619, 9657), False, 'from evennia.utils import validatorfuncs\n'), ((10060, 10119), 'evennia.utils.validatorfuncs.future', 'validatorfuncs.future', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (10081, 10119), False, 'from evennia.utils import validatorfuncs\n'), ((10196, 10253), 'evennia.utils.validatorfuncs.lock', 'validatorfuncs.lock', (['value'], {'option_key': 'self.key'}), '(value, option_key=self.key, **kwargs)\n', (10215, 10253), False, 'from evennia.utils import validatorfuncs\n'), ((9305, 9352), 'datetime.timedelta', 'datetime.timedelta', (['(0)', 'save_data', '(0)', '(0)', '(0)', '(0)', '(0)'], {}), '(0, save_data, 0, 0, 0, 0, 0)\n', (9323, 9352), False, 'import datetime\n'), ((9755, 9800), 'datetime.datetime.utcfromtimestamp', 'datetime.datetime.utcfromtimestamp', (['save_data'], {}), '(save_data)\n', (9789, 9800), False, 'import datetime\n'), ((3154, 3172), 'evennia.logger.log_trace', 'logger.log_trace', ([], {}), '()\n', (3170, 3172), False, 'from evennia import logger\n'), ((7291, 7320), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['f"""|{save_data}|n"""'], {}), "(f'|{save_data}|n')\n", (7301, 7320), False, 'from evennia.utils.ansi import strip_ansi\n')]
""" At_initial_setup module template Custom at_initial_setup method. This allows you to hook special modifications to the initial server startup process. Note that this will only be run once - when the server starts up for the very first time! It is called last in the startup process and can thus be used to overload things that happened before it. The module must contain a global function at_initial_setup(). This will be called without arguments. Note that tracebacks in this module will be QUIETLY ignored, so make sure to check it well to make sure it does what you expect it to. """ from evennia.utils import search, dedent def at_initial_setup(): limbo = search.objects('Limbo')[0] # limbo.db.desc = dedent(""" # Welcome to |mCelestiaMUD|n, a game of crewing spaceships and stations! # The project is still in early development, and we welcome your contributions. # |YDeveloper/Builder Resources|n # * Issue tracking: https://github.com/evennia/ainneve/issues # * Discussion list: https://groups.google.com/forum/?fromgroups#!categories/evennia/ainneve # * Ainneve Wiki: https://github.com/evennia/ainneve/wiki # * Evennia Developer IRC: http://webchat.freenode.net/?channels=evennia # |YGetting Started|n # As Account #1 you can use the |w@batchcmd|n or |w@batchcode|n commands to # build components of Ainneve, or the entire world (once it has been created). # Build scripts are in the |wworld/content/{area name}/|n directories and have |w*.ev|n or |w*.py|n extensions. # """) limbo.db.desc = dedent(""" Welcome to |mCelestiaMUD|n, a game of crewing spaceships and stations! The project is still in early development, |YGetting Started|n TODO: Character screen here """)
[ "evennia.utils.search.objects", "evennia.utils.dedent" ]
[((1681, 1932), 'evennia.utils.dedent', 'dedent', (['"""\n Welcome to |mCelestiaMUD|n, a game of crewing spaceships and stations!\n The project is still in early development,\n |YGetting Started|n\n TODO: Character screen here\n """'], {}), '(\n """\n Welcome to |mCelestiaMUD|n, a game of crewing spaceships and stations!\n The project is still in early development,\n |YGetting Started|n\n TODO: Character screen here\n """\n )\n', (1687, 1932), False, 'from evennia.utils import search, dedent\n'), ((674, 697), 'evennia.utils.search.objects', 'search.objects', (['"""Limbo"""'], {}), "('Limbo')\n", (688, 697), False, 'from evennia.utils import search, dedent\n')]
# Generated by Django 2.2.16 on 2021-04-18 17:15 from django.db import migrations, models import django.db.models.deletion from django.core.exceptions import ObjectDoesNotExist from evennia.utils.ansi import parse_ansi from server.utils.arx_utils import sub_old_ansi OLD_BASE_DESC = "Nothing has been written on this yet. '{whelp write{n'" def convert_descs_to_written_works(apps, schema_editor): """ This iterates over all the Readable typeclassed objects we have, and tries to convert their descriptions into WrittenWorks. In cases where their descs are built up of templates or translated texts, those are converted to WrittenWorks first, and then the BookChapters are created to associate the works with the book. For descs, a WrittenWork is created, which we'll compare future descs against to see if there's duplicates. """ ObjectDB = apps.get_model("objects", "ObjectDB") WrittenWork = apps.get_model("templates", "WrittenWork") BookChapter = apps.get_model("templates", "BookChapter") ChapterSignature = apps.get_model("templates", "ChapterSignature") readable = ObjectDB.objects.filter( db_typeclass_path="typeclasses.readable.readable.Readable" ) # different mappings desc_to_work = {} template_to_work = {} authors = {} def get_author(book_object): try: author_tuple = book_object.db_attributes.get(db_key="author").db_value return get_dbobj_from_tuple(author_tuple) except (ObjectDoesNotExist, TypeError, IndexError): return None def get_dbobj_from_tuple(obj_tuple): try: obj_pk = obj_tuple[-1] if obj_pk in authors: return authors[obj_pk] else: author_obj = ObjectDB.objects.get(id=obj_pk) authors[obj_pk] = author_obj return author_obj except (ObjectDoesNotExist, TypeError, IndexError): return None def get_desc(book_object): try: desc_attr = book_object.db_attributes.get(db_key="desc") except ObjectDoesNotExist: # if they have no desc, it's an empty book. skip it return # if its desc was that it's a blank book, delete the attribute and skip it if desc_attr.db_value == OLD_BASE_DESC: desc_attr.delete() return return desc_attr def get_signers(book_object): try: signed_attr = book_object.db_attributes.get(db_key="signed") signers_objects = [] for tup in signed_attr.db_value: obj = get_dbobj_from_tuple(tup) if obj: signers_objects.append(obj) signed_attr.delete() return signers_objects except (ObjectDoesNotExist, ValueError, TypeError): return [] def add_work_and_chapter_for_desc(book_object, desc_attr, chapter_num, author_obj): # check if work already exists body = desc_attr.db_value if body in desc_to_work: work_obj = desc_to_work[body] else: work_title = book_object.db_key num_matches = WrittenWork.objects.filter( title__startswith=book_object.db_key ).count() if num_matches: work_title += f" {num_matches + 1}" # create the work_obj for the body work_obj = WrittenWork.objects.create( body=desc_attr.db_value, title=work_title, author=author_obj ) desc_to_work[body] = work_obj # create chapter return BookChapter.objects.get_or_create( defaults=dict(number=chapter_num), written_work=work_obj, objectdb=book_object, )[0] def get_max_chapter_num(book_object): agg = book_object.book_chapters.aggregate(max_chapter=models.Max("number")) return agg.get("max_chapter", 0) or 0 readable.update(db_cmdset_storage=None) for book in readable: chapter_number = 1 desc = get_desc(book) if not desc: continue templates = book.template_set.all() if templates: # if we have templates, the desc is assumed it just be a list of templates # we'll convert templates to WrittenWorks and add chapters for them print(f"Processing templates for {book.db_key} (ID #{book.id})") for template in templates: if template.id in template_to_work: new_work = template_to_work[template.id] elif template.desc in desc_to_work: new_work = desc_to_work[template.desc] else: colored_title = sub_old_ansi(template.title) title = parse_ansi(colored_title, strip_ansi=True) if colored_title == title: colored_title = "" # try to get author author = get_author(book) # check for unique title title_matches = WrittenWork.objects.filter( title__startswith=title ).count() if title_matches: title += f" {title_matches + 1}" colored_title += f" {title_matches + 1}" new_work = WrittenWork.objects.create( body=template.desc, title=title, colored_title=colored_title, owner=template.owner, author=author, ) template_to_work[template.id] = new_work desc_to_work[template.desc] = new_work # add work to chapters for the book BookChapter.objects.get_or_create( defaults=dict(number=chapter_number), written_work=new_work, objectdb=book, ) chapter_number += 1 # get rid of old desc and move on desc.delete() continue # convert books with translated descs translations = book.translations.all() if translations: print(f"Processing translations for {book.db_key} (ID #{book.id})") base_title = book.db_key chapter_number = get_max_chapter_num(book) + 1 # desc should be first chapter author = get_author(book) add_work_and_chapter_for_desc(book, desc, chapter_number, author) for translation in translations: chapter_number += 1 if translation.description in desc_to_work: work = desc_to_work[translation.description] else: # convert translations into WrittenWorks of appropriate language title = base_title if chapter_number > 1: title += f" Chapter {chapter_number}" work = WrittenWork.objects.create( language=translation.language, body=translation.description, title=title, author=author, ) desc_to_work[translation.description] = work # add bookchapter for each converted translation BookChapter.objects.get_or_create( defaults=dict(number=chapter_number), written_work=work, objectdb=book, ) # get rid of old translation translation.delete() desc.delete() continue print(f"Processing book {book.db_key} (ID #{book.id})") author = get_author(book) chapter = add_work_and_chapter_for_desc(book, desc, 1, author) desc.delete() signers = get_signers(book) for signer in signers: ChapterSignature.objects.create(book_chapter=chapter, signer=signer) class Migration(migrations.Migration): dependencies = [ ("character", "0002_fix_character_dependencies"), ("templates", "0003_auto_20191228_1417"), ] operations = [ migrations.CreateModel( name="BookChapter", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("number", models.PositiveSmallIntegerField(default=1)), ( "objectdb", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="book_chapters", to="objects.ObjectDB", ), ), ], options={ "verbose_name_plural": "Book Chapters", "ordering": ("number",), }, ), migrations.CreateModel( name="WrittenWork", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("title", models.CharField(max_length=255)), ("colored_title", models.TextField(blank=True)), ("body", models.TextField()), ("language", models.CharField(blank=True, max_length=255)), ( "author", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="authored_works", to="objects.ObjectDB", ), ), ( "books", models.ManyToManyField( related_name="contained_written_works", through="templates.BookChapter", to="objects.ObjectDB", ), ), ( "owner", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name="written_works", to="character.PlayerAccount", ), ), ], options={ "verbose_name_plural": "Written Works", }, ), migrations.CreateModel( name="ChapterSignature", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "book_chapter", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="signatures", to="templates.BookChapter", ), ), ( "signer", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="signatures", to="objects.ObjectDB", ), ), ], options={ "abstract": False, }, ), migrations.AddField( model_name="bookchapter", name="signers", field=models.ManyToManyField( related_name="signed_chapters", through="templates.ChapterSignature", to="objects.ObjectDB", ), ), migrations.AddField( model_name="bookchapter", name="written_work", field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="templates.WrittenWork" ), ), migrations.AlterUniqueTogether( name="bookchapter", unique_together={("objectdb", "number"), ("objectdb", "written_work")}, ), migrations.RunPython( convert_descs_to_written_works, migrations.RunPython.noop, elidable=True ), ]
[ "evennia.utils.ansi.parse_ansi" ]
[((12767, 12894), 'django.db.migrations.AlterUniqueTogether', 'migrations.AlterUniqueTogether', ([], {'name': '"""bookchapter"""', 'unique_together': "{('objectdb', 'number'), ('objectdb', 'written_work')}"}), "(name='bookchapter', unique_together={(\n 'objectdb', 'number'), ('objectdb', 'written_work')})\n", (12797, 12894), False, 'from django.db import migrations, models\n'), ((12934, 13033), 'django.db.migrations.RunPython', 'migrations.RunPython', (['convert_descs_to_written_works', 'migrations.RunPython.noop'], {'elidable': '(True)'}), '(convert_descs_to_written_works, migrations.RunPython.\n noop, elidable=True)\n', (12954, 13033), False, 'from django.db import migrations, models\n'), ((3945, 3965), 'django.db.models.Max', 'models.Max', (['"""number"""'], {}), "('number')\n", (3955, 3965), False, 'from django.db import migrations, models\n'), ((12317, 12437), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_name': '"""signed_chapters"""', 'through': '"""templates.ChapterSignature"""', 'to': '"""objects.ObjectDB"""'}), "(related_name='signed_chapters', through=\n 'templates.ChapterSignature', to='objects.ObjectDB')\n", (12339, 12437), False, 'from django.db import migrations, models\n'), ((12626, 12721), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""templates.WrittenWork"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'templates.WrittenWork')\n", (12643, 12721), False, 'from django.db import migrations, models\n'), ((4815, 4843), 'server.utils.arx_utils.sub_old_ansi', 'sub_old_ansi', (['template.title'], {}), '(template.title)\n', (4827, 4843), False, 'from server.utils.arx_utils import sub_old_ansi\n'), ((4872, 4914), 'evennia.utils.ansi.parse_ansi', 'parse_ansi', (['colored_title'], {'strip_ansi': '(True)'}), '(colored_title, strip_ansi=True)\n', (4882, 4914), False, 'from evennia.utils.ansi import parse_ansi\n'), ((8562, 8655), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (8578, 8655), False, 'from django.db import migrations, models\n'), ((8818, 8861), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'default': '(1)'}), '(default=1)\n', (8850, 8861), False, 'from django.db import migrations, models\n'), ((8934, 9054), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""book_chapters"""', 'to': '"""objects.ObjectDB"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='book_chapters', to='objects.ObjectDB')\n", (8951, 9054), False, 'from django.db import migrations, models\n'), ((9474, 9567), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (9490, 9567), False, 'from django.db import migrations, models\n'), ((9729, 9761), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (9745, 9761), False, 'from django.db import migrations, models\n'), ((9798, 9826), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)'}), '(blank=True)\n', (9814, 9826), False, 'from django.db import migrations, models\n'), ((9854, 9872), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (9870, 9872), False, 'from django.db import migrations, models\n'), ((9904, 9948), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(255)'}), '(blank=True, max_length=255)\n', (9920, 9948), False, 'from django.db import migrations, models\n'), ((10019, 10164), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'related_name': '"""authored_works"""', 'to': '"""objects.ObjectDB"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.SET_NULL, related_name='authored_works', to='objects.ObjectDB')\n", (10036, 10164), False, 'from django.db import migrations, models\n'), ((10390, 10513), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_name': '"""contained_written_works"""', 'through': '"""templates.BookChapter"""', 'to': '"""objects.ObjectDB"""'}), "(related_name='contained_written_works', through=\n 'templates.BookChapter', to='objects.ObjectDB')\n", (10412, 10513), False, 'from django.db import migrations, models\n'), ((10691, 10847), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'related_name': '"""written_works"""', 'to': '"""character.PlayerAccount"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.SET_NULL, related_name='written_works', to=\n 'character.PlayerAccount')\n", (10708, 10847), False, 'from django.db import migrations, models\n'), ((11274, 11367), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (11290, 11367), False, 'from django.db import migrations, models\n'), ((11577, 11699), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""signatures"""', 'to': '"""templates.BookChapter"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='signatures', to='templates.BookChapter')\n", (11594, 11699), False, 'from django.db import migrations, models\n'), ((11878, 11995), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""signatures"""', 'to': '"""objects.ObjectDB"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='signatures', to='objects.ObjectDB')\n", (11895, 11995), False, 'from django.db import migrations, models\n')]
from evennia import create_object from typeclasses import exits, rooms from .ships import * def build_bridge(x, y, **kwargs): # If on anything other than the first iteration - Do nothing. if kwargs["iteration"] > 0: return None room = create_object(rooms.Room, key="bridge" + str(x) + str(y)) room.db.desc = "Bridge of the ship." # Send a message to the account kwargs["caller"].msg(room.key + " " + room.dbref) captains_chair = create_object(key="Chair", location=room) captains_chair.db.desc = "The captain's chair." stations = ["navigation", "weapons", "engineering", "communications", "science"] for station in stations: chair = create_object(key="Chair", location=room) chair.db.desc = "Chair for " + station console = create_object(key="Console: " + station) console.db.desc = "Console for " + station # Mandatory, usually return room def build_common(x, y, **kwargs): # If on anything other than the first iteration - Do nothing. if kwargs["iteration"] > 0: return None room = create_object(rooms.Room, key="common" + str(x) + str(y)) room.db.desc = "Common room found on smaller ship. A combination of galley, dining, and rec room." # Send a message to the account kwargs["caller"].msg(room.key + " " + room.dbref) table = create_object(key="Table", location=room) table.db.desc = "A simple table with outstanding, outdated, Swedish mass produced minimalistic design." for i in range(0, 2): chair = create_object(key="Chair", location=room) chair.db.desc = "A simple dented metallic chair. Worn sleeping pillows provide ample padding for ample seats." # Mandatory, usually return room def build_vertical_exit(x, y, **kwargs): """Creates two exits to and from the two rooms north and south.""" if kwargs["iteration"] == 0: return north_room = kwargs["room_dict"][(x, y - 1)] south_room = kwargs["room_dict"][(x, y + 1)] # create exits in the rooms create_object(exits.Exit, key="south", aliases=["s"], location=north_room, destination=south_room) create_object(exits.Exit, key="north", aliases=["n"], location=south_room, destination=north_room) kwargs["caller"].msg("Connected: " + north_room.key + " & " + south_room.key) def build_horizontal_exit(x, y, **kwargs): """Creates two exits to and from the two rooms east and west.""" # If on the first iteration - Do nothing. if kwargs["iteration"] == 0: return west_room = kwargs["room_dict"][(x - 1, y)] east_room = kwargs["room_dict"][(x + 1, y)] create_object(exits.Exit, key="east", aliases=["e"], location=west_room, destination=east_room) create_object(exits.Exit, key="west", aliases=["w"], location=east_room, destination=west_room) kwargs["caller"].msg("Connected: " + west_room.key + " & " + east_room.key) LEGEND = {("|"): build_vertical_exit, ("-"): build_horizontal_exit, ("B"): build_bridge, ("C"): build_common}
[ "evennia.create_object" ]
[((471, 512), 'evennia.create_object', 'create_object', ([], {'key': '"""Chair"""', 'location': 'room'}), "(key='Chair', location=room)\n", (484, 512), False, 'from evennia import create_object\n'), ((1368, 1409), 'evennia.create_object', 'create_object', ([], {'key': '"""Table"""', 'location': 'room'}), "(key='Table', location=room)\n", (1381, 1409), False, 'from evennia import create_object\n'), ((2060, 2162), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""south"""', 'aliases': "['s']", 'location': 'north_room', 'destination': 'south_room'}), "(exits.Exit, key='south', aliases=['s'], location=north_room,\n destination=south_room)\n", (2073, 2162), False, 'from evennia import create_object\n'), ((2200, 2302), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""north"""', 'aliases': "['n']", 'location': 'south_room', 'destination': 'north_room'}), "(exits.Exit, key='north', aliases=['n'], location=south_room,\n destination=north_room)\n", (2213, 2302), False, 'from evennia import create_object\n'), ((2753, 2852), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""east"""', 'aliases': "['e']", 'location': 'west_room', 'destination': 'east_room'}), "(exits.Exit, key='east', aliases=['e'], location=west_room,\n destination=east_room)\n", (2766, 2852), False, 'from evennia import create_object\n'), ((2890, 2989), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""west"""', 'aliases': "['w']", 'location': 'east_room', 'destination': 'west_room'}), "(exits.Exit, key='west', aliases=['w'], location=east_room,\n destination=west_room)\n", (2903, 2989), False, 'from evennia import create_object\n'), ((696, 737), 'evennia.create_object', 'create_object', ([], {'key': '"""Chair"""', 'location': 'room'}), "(key='Chair', location=room)\n", (709, 737), False, 'from evennia import create_object\n'), ((803, 843), 'evennia.create_object', 'create_object', ([], {'key': "('Console: ' + station)"}), "(key='Console: ' + station)\n", (816, 843), False, 'from evennia import create_object\n'), ((1560, 1601), 'evennia.create_object', 'create_object', ([], {'key': '"""Chair"""', 'location': 'room'}), "(key='Chair', location=room)\n", (1573, 1601), False, 'from evennia import create_object\n')]
""" Turnbattle tests. """ from mock import patch, MagicMock from evennia.commands.default.tests import BaseEvenniaCommandTest from evennia.utils.create import create_object from evennia.utils.test_resources import BaseEvenniaTest from evennia.objects.objects import DefaultRoom from . import tb_basic, tb_equip, tb_range, tb_items, tb_magic class TestTurnBattleBasicCmd(BaseEvenniaCommandTest): # Test basic combat commands def test_turnbattlecmd(self): self.call(tb_basic.CmdFight(), "", "You can't start a fight if you've been defeated!") self.call(tb_basic.CmdAttack(), "", "You can only do that in combat. (see: help fight)") self.call(tb_basic.CmdPass(), "", "You can only do that in combat. (see: help fight)") self.call(tb_basic.CmdDisengage(), "", "You can only do that in combat. (see: help fight)") self.call(tb_basic.CmdRest(), "", "Char rests to recover HP.") class TestTurnBattleEquipCmd(BaseEvenniaCommandTest): def setUp(self): super(TestTurnBattleEquipCmd, self).setUp() self.testweapon = create_object(tb_equip.TBEWeapon, key="test weapon") self.testarmor = create_object(tb_equip.TBEArmor, key="test armor") self.testweapon.move_to(self.char1) self.testarmor.move_to(self.char1) # Test equipment commands def test_turnbattleequipcmd(self): # Start with equip module specific commands. self.call(tb_equip.CmdWield(), "weapon", "Char wields test weapon.") self.call(tb_equip.CmdUnwield(), "", "Char lowers test weapon.") self.call(tb_equip.CmdDon(), "armor", "Char dons test armor.") self.call(tb_equip.CmdDoff(), "", "Char removes test armor.") # Also test the commands that are the same in the basic module self.call(tb_equip.CmdFight(), "", "You can't start a fight if you've been defeated!") self.call(tb_equip.CmdAttack(), "", "You can only do that in combat. (see: help fight)") self.call(tb_equip.CmdPass(), "", "You can only do that in combat. (see: help fight)") self.call(tb_equip.CmdDisengage(), "", "You can only do that in combat. (see: help fight)") self.call(tb_equip.CmdRest(), "", "Char rests to recover HP.") class TestTurnBattleRangeCmd(BaseEvenniaCommandTest): # Test range commands def test_turnbattlerangecmd(self): # Start with range module specific commands. self.call(tb_range.CmdShoot(), "", "You can only do that in combat. (see: help fight)") self.call(tb_range.CmdApproach(), "", "You can only do that in combat. (see: help fight)") self.call(tb_range.CmdWithdraw(), "", "You can only do that in combat. (see: help fight)") self.call(tb_range.CmdStatus(), "", "HP Remaining: 100 / 100") # Also test the commands that are the same in the basic module self.call(tb_range.CmdFight(), "", "There's nobody here to fight!") self.call(tb_range.CmdAttack(), "", "You can only do that in combat. (see: help fight)") self.call(tb_range.CmdPass(), "", "You can only do that in combat. (see: help fight)") self.call(tb_range.CmdDisengage(), "", "You can only do that in combat. (see: help fight)") self.call(tb_range.CmdRest(), "", "Char rests to recover HP.") class TestTurnBattleItemsCmd(BaseEvenniaCommandTest): def setUp(self): super(TestTurnBattleItemsCmd, self).setUp() self.testitem = create_object(key="test item") self.testitem.move_to(self.char1) # Test item commands def test_turnbattleitemcmd(self): self.call(tb_items.CmdUse(), "item", "'Test item' is not a usable item.") # Also test the commands that are the same in the basic module self.call(tb_items.CmdFight(), "", "You can't start a fight if you've been defeated!") self.call(tb_items.CmdAttack(), "", "You can only do that in combat. (see: help fight)") self.call(tb_items.CmdPass(), "", "You can only do that in combat. (see: help fight)") self.call(tb_items.CmdDisengage(), "", "You can only do that in combat. (see: help fight)") self.call(tb_items.CmdRest(), "", "Char rests to recover HP.") class TestTurnBattleMagicCmd(BaseEvenniaCommandTest): # Test magic commands def test_turnbattlemagiccmd(self): self.call(tb_magic.CmdStatus(), "", "You have 100 / 100 HP and 20 / 20 MP.") self.call(tb_magic.CmdLearnSpell(), "test spell", "There is no spell with that name.") self.call(tb_magic.CmdCast(), "", "Usage: cast <spell name> = <target>, <target2>") # Also test the commands that are the same in the basic module self.call(tb_magic.CmdFight(), "", "There's nobody here to fight!") self.call(tb_magic.CmdAttack(), "", "You can only do that in combat. (see: help fight)") self.call(tb_magic.CmdPass(), "", "You can only do that in combat. (see: help fight)") self.call(tb_magic.CmdDisengage(), "", "You can only do that in combat. (see: help fight)") self.call(tb_magic.CmdRest(), "", "Char rests to recover HP and MP.") class TestTurnBattleBasicFunc(BaseEvenniaTest): def setUp(self): super(TestTurnBattleBasicFunc, self).setUp() self.testroom = create_object(DefaultRoom, key="Test Room") self.attacker = create_object( tb_basic.TBBasicCharacter, key="Attacker", location=self.testroom ) self.defender = create_object( tb_basic.TBBasicCharacter, key="Defender", location=self.testroom ) self.joiner = create_object(tb_basic.TBBasicCharacter, key="Joiner", location=None) def tearDown(self): super(TestTurnBattleBasicFunc, self).tearDown() self.turnhandler.stop() self.testroom.delete() self.attacker.delete() self.defender.delete() self.joiner.delete() # Test combat functions def test_tbbasicfunc(self): # Initiative roll initiative = tb_basic.roll_init(self.attacker) self.assertTrue(initiative >= 0 and initiative <= 1000) # Attack roll attack_roll = tb_basic.get_attack(self.attacker, self.defender) self.assertTrue(attack_roll >= 0 and attack_roll <= 100) # Defense roll defense_roll = tb_basic.get_defense(self.attacker, self.defender) self.assertTrue(defense_roll == 50) # Damage roll damage_roll = tb_basic.get_damage(self.attacker, self.defender) self.assertTrue(damage_roll >= 15 and damage_roll <= 25) # Apply damage self.defender.db.hp = 10 tb_basic.apply_damage(self.defender, 3) self.assertTrue(self.defender.db.hp == 7) # Resolve attack self.defender.db.hp = 40 tb_basic.resolve_attack(self.attacker, self.defender, attack_value=20, defense_value=10) self.assertTrue(self.defender.db.hp < 40) # Combat cleanup self.attacker.db.Combat_attribute = True tb_basic.combat_cleanup(self.attacker) self.assertFalse(self.attacker.db.combat_attribute) # Is in combat self.assertFalse(tb_basic.is_in_combat(self.attacker)) # Set up turn handler script for further tests self.attacker.location.scripts.add(tb_basic.TBBasicTurnHandler) self.turnhandler = self.attacker.db.combat_TurnHandler self.assertTrue(self.attacker.db.combat_TurnHandler) # Set the turn handler's interval very high to keep it from repeating during tests. self.turnhandler.interval = 10000 # Force turn order self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 # Test is turn self.assertTrue(tb_basic.is_turn(self.attacker)) # Spend actions self.attacker.db.Combat_ActionsLeft = 1 tb_basic.spend_action(self.attacker, 1, action_name="Test") self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "Test") # Initialize for combat self.attacker.db.Combat_ActionsLeft = 983 self.turnhandler.initialize_for_combat(self.attacker) self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "null") # Start turn self.defender.db.Combat_ActionsLeft = 0 self.turnhandler.start_turn(self.defender) self.assertTrue(self.defender.db.Combat_ActionsLeft == 1) # Next turn self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.next_turn() self.assertTrue(self.turnhandler.db.turn == 1) # Turn end check self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.attacker.db.Combat_ActionsLeft = 0 self.turnhandler.turn_end_check(self.attacker) self.assertTrue(self.turnhandler.db.turn == 1) # Join fight self.joiner.location = self.testroom self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.join_fight(self.joiner) self.assertTrue(self.turnhandler.db.turn == 1) self.assertTrue(self.turnhandler.db.fighters == [self.joiner, self.attacker, self.defender]) class TestTurnBattleEquipFunc(BaseEvenniaTest): def setUp(self): super(TestTurnBattleEquipFunc, self).setUp() self.testroom = create_object(DefaultRoom, key="Test Room") self.attacker = create_object( tb_equip.TBEquipCharacter, key="Attacker", location=self.testroom ) self.defender = create_object( tb_equip.TBEquipCharacter, key="Defender", location=self.testroom ) self.joiner = create_object(tb_equip.TBEquipCharacter, key="Joiner", location=None) def tearDown(self): super(TestTurnBattleEquipFunc, self).tearDown() self.turnhandler.stop() self.testroom.delete() self.attacker.delete() self.defender.delete() self.joiner.delete() # Test the combat functions in tb_equip too. They work mostly the same. def test_tbequipfunc(self): # Initiative roll initiative = tb_equip.roll_init(self.attacker) self.assertTrue(initiative >= 0 and initiative <= 1000) # Attack roll attack_roll = tb_equip.get_attack(self.attacker, self.defender) self.assertTrue(attack_roll >= -50 and attack_roll <= 150) # Defense roll defense_roll = tb_equip.get_defense(self.attacker, self.defender) self.assertTrue(defense_roll == 50) # Damage roll damage_roll = tb_equip.get_damage(self.attacker, self.defender) self.assertTrue(damage_roll >= 0 and damage_roll <= 50) # Apply damage self.defender.db.hp = 10 tb_equip.apply_damage(self.defender, 3) self.assertTrue(self.defender.db.hp == 7) # Resolve attack self.defender.db.hp = 40 tb_equip.resolve_attack(self.attacker, self.defender, attack_value=20, defense_value=10) self.assertTrue(self.defender.db.hp < 40) # Combat cleanup self.attacker.db.Combat_attribute = True tb_equip.combat_cleanup(self.attacker) self.assertFalse(self.attacker.db.combat_attribute) # Is in combat self.assertFalse(tb_equip.is_in_combat(self.attacker)) # Set up turn handler script for further tests self.attacker.location.scripts.add(tb_equip.TBEquipTurnHandler) self.turnhandler = self.attacker.db.combat_TurnHandler self.assertTrue(self.attacker.db.combat_TurnHandler) # Set the turn handler's interval very high to keep it from repeating during tests. self.turnhandler.interval = 10000 # Force turn order self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 # Test is turn self.assertTrue(tb_equip.is_turn(self.attacker)) # Spend actions self.attacker.db.Combat_ActionsLeft = 1 tb_equip.spend_action(self.attacker, 1, action_name="Test") self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "Test") # Initialize for combat self.attacker.db.Combat_ActionsLeft = 983 self.turnhandler.initialize_for_combat(self.attacker) self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "null") # Start turn self.defender.db.Combat_ActionsLeft = 0 self.turnhandler.start_turn(self.defender) self.assertTrue(self.defender.db.Combat_ActionsLeft == 1) # Next turn self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.next_turn() self.assertTrue(self.turnhandler.db.turn == 1) # Turn end check self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.attacker.db.Combat_ActionsLeft = 0 self.turnhandler.turn_end_check(self.attacker) self.assertTrue(self.turnhandler.db.turn == 1) # Join fight self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.join_fight(self.joiner) self.assertTrue(self.turnhandler.db.turn == 1) self.assertTrue(self.turnhandler.db.fighters == [self.joiner, self.attacker, self.defender]) class TestTurnBattleRangeFunc(BaseEvenniaTest): def setUp(self): super(TestTurnBattleRangeFunc, self).setUp() self.testroom = create_object(DefaultRoom, key="Test Room") self.attacker = create_object( tb_range.TBRangeCharacter, key="Attacker", location=self.testroom ) self.defender = create_object( tb_range.TBRangeCharacter, key="Defender", location=self.testroom ) self.joiner = create_object(tb_range.TBRangeCharacter, key="Joiner", location=self.testroom) def tearDown(self): super(TestTurnBattleRangeFunc, self).tearDown() self.turnhandler.stop() self.testroom.delete() self.attacker.delete() self.defender.delete() self.joiner.delete() # Test combat functions in tb_range too. def test_tbrangefunc(self): # Initiative roll initiative = tb_range.roll_init(self.attacker) self.assertTrue(initiative >= 0 and initiative <= 1000) # Attack roll attack_roll = tb_range.get_attack(self.attacker, self.defender, "test") self.assertTrue(attack_roll >= 0 and attack_roll <= 100) # Defense roll defense_roll = tb_range.get_defense(self.attacker, self.defender, "test") self.assertTrue(defense_roll == 50) # Damage roll damage_roll = tb_range.get_damage(self.attacker, self.defender) self.assertTrue(damage_roll >= 15 and damage_roll <= 25) # Apply damage self.defender.db.hp = 10 tb_range.apply_damage(self.defender, 3) self.assertTrue(self.defender.db.hp == 7) # Resolve attack self.defender.db.hp = 40 tb_range.resolve_attack( self.attacker, self.defender, "test", attack_value=20, defense_value=10 ) self.assertTrue(self.defender.db.hp < 40) # Combat cleanup self.attacker.db.Combat_attribute = True tb_range.combat_cleanup(self.attacker) self.assertFalse(self.attacker.db.combat_attribute) # Is in combat self.assertFalse(tb_range.is_in_combat(self.attacker)) # Set up turn handler script for further tests self.attacker.location.scripts.add(tb_range.TBRangeTurnHandler) self.turnhandler = self.attacker.db.combat_TurnHandler self.assertTrue(self.attacker.db.combat_TurnHandler) # Set the turn handler's interval very high to keep it from repeating during tests. self.turnhandler.interval = 10000 # Force turn order self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 # Test is turn self.assertTrue(tb_range.is_turn(self.attacker)) # Spend actions self.attacker.db.Combat_ActionsLeft = 1 tb_range.spend_action(self.attacker, 1, action_name="Test") self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "Test") # Initialize for combat self.attacker.db.Combat_ActionsLeft = 983 self.turnhandler.initialize_for_combat(self.attacker) self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "null") # Set up ranges again, since initialize_for_combat clears them self.attacker.db.combat_range = {} self.attacker.db.combat_range[self.attacker] = 0 self.attacker.db.combat_range[self.defender] = 1 self.defender.db.combat_range = {} self.defender.db.combat_range[self.defender] = 0 self.defender.db.combat_range[self.attacker] = 1 # Start turn self.defender.db.Combat_ActionsLeft = 0 self.turnhandler.start_turn(self.defender) self.assertTrue(self.defender.db.Combat_ActionsLeft == 2) # Next turn self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.next_turn() self.assertTrue(self.turnhandler.db.turn == 1) # Turn end check self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.attacker.db.Combat_ActionsLeft = 0 self.turnhandler.turn_end_check(self.attacker) self.assertTrue(self.turnhandler.db.turn == 1) # Join fight self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.join_fight(self.joiner) self.assertTrue(self.turnhandler.db.turn == 1) self.assertTrue(self.turnhandler.db.fighters == [self.joiner, self.attacker, self.defender]) # Now, test for approach/withdraw functions self.assertTrue(tb_range.get_range(self.attacker, self.defender) == 1) # Approach tb_range.approach(self.attacker, self.defender) self.assertTrue(tb_range.get_range(self.attacker, self.defender) == 0) # Withdraw tb_range.withdraw(self.attacker, self.defender) self.assertTrue(tb_range.get_range(self.attacker, self.defender) == 1) class TestTurnBattleItemsFunc(BaseEvenniaTest): @patch("evennia.contrib.game_systems.turnbattle.tb_items.tickerhandler", new=MagicMock()) def setUp(self): super(TestTurnBattleItemsFunc, self).setUp() self.testroom = create_object(DefaultRoom, key="Test Room") self.attacker = create_object( tb_items.TBItemsCharacter, key="Attacker", location=self.testroom ) self.defender = create_object( tb_items.TBItemsCharacter, key="Defender", location=self.testroom ) self.joiner = create_object(tb_items.TBItemsCharacter, key="Joiner", location=self.testroom) self.user = create_object(tb_items.TBItemsCharacter, key="User", location=self.testroom) self.test_healpotion = create_object(key="healing potion") self.test_healpotion.db.item_func = "heal" self.test_healpotion.db.item_uses = 3 def tearDown(self): super(TestTurnBattleItemsFunc, self).tearDown() self.turnhandler.stop() self.testroom.delete() self.attacker.delete() self.defender.delete() self.joiner.delete() self.user.delete() # Test functions in tb_items. def test_tbitemsfunc(self): # Initiative roll initiative = tb_items.roll_init(self.attacker) self.assertTrue(initiative >= 0 and initiative <= 1000) # Attack roll attack_roll = tb_items.get_attack(self.attacker, self.defender) self.assertTrue(attack_roll >= 0 and attack_roll <= 100) # Defense roll defense_roll = tb_items.get_defense(self.attacker, self.defender) self.assertTrue(defense_roll == 50) # Damage roll damage_roll = tb_items.get_damage(self.attacker, self.defender) self.assertTrue(damage_roll >= 15 and damage_roll <= 25) # Apply damage self.defender.db.hp = 10 tb_items.apply_damage(self.defender, 3) self.assertTrue(self.defender.db.hp == 7) # Resolve attack self.defender.db.hp = 40 tb_items.resolve_attack(self.attacker, self.defender, attack_value=20, defense_value=10) self.assertTrue(self.defender.db.hp < 40) # Combat cleanup self.attacker.db.Combat_attribute = True tb_items.combat_cleanup(self.attacker) self.assertFalse(self.attacker.db.combat_attribute) # Is in combat self.assertFalse(tb_items.is_in_combat(self.attacker)) # Set up turn handler script for further tests self.attacker.location.scripts.add(tb_items.TBItemsTurnHandler) self.turnhandler = self.attacker.db.combat_TurnHandler self.assertTrue(self.attacker.db.combat_TurnHandler) # Set the turn handler's interval very high to keep it from repeating during tests. self.turnhandler.interval = 10000 # Force turn order self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 # Test is turn self.assertTrue(tb_items.is_turn(self.attacker)) # Spend actions self.attacker.db.Combat_ActionsLeft = 1 tb_items.spend_action(self.attacker, 1, action_name="Test") self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "Test") # Initialize for combat self.attacker.db.Combat_ActionsLeft = 983 self.turnhandler.initialize_for_combat(self.attacker) self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "null") # Start turn self.defender.db.Combat_ActionsLeft = 0 self.turnhandler.start_turn(self.defender) self.assertTrue(self.defender.db.Combat_ActionsLeft == 1) # Next turn self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.next_turn() self.assertTrue(self.turnhandler.db.turn == 1) # Turn end check self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.attacker.db.Combat_ActionsLeft = 0 self.turnhandler.turn_end_check(self.attacker) self.assertTrue(self.turnhandler.db.turn == 1) # Join fight self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.join_fight(self.joiner) self.assertTrue(self.turnhandler.db.turn == 1) self.assertTrue(self.turnhandler.db.fighters == [self.joiner, self.attacker, self.defender]) # Now time to test item stuff. # Spend item use tb_items.spend_item_use(self.test_healpotion, self.user) self.assertTrue(self.test_healpotion.db.item_uses == 2) # Use item self.user.db.hp = 2 tb_items.use_item(self.user, self.test_healpotion, self.user) self.assertTrue(self.user.db.hp > 2) # Add contition tb_items.add_condition(self.user, self.user, "Test", 5) self.assertTrue(self.user.db.conditions == {"Test": [5, self.user]}) # Condition tickdown tb_items.condition_tickdown(self.user, self.user) self.assertTrue(self.user.db.conditions == {"Test": [4, self.user]}) # Test item functions now! # Item heal self.user.db.hp = 2 tb_items.itemfunc_heal(self.test_healpotion, self.user, self.user) # Item add condition self.user.db.conditions = {} tb_items.itemfunc_add_condition(self.test_healpotion, self.user, self.user) self.assertTrue(self.user.db.conditions == {"Regeneration": [5, self.user]}) # Item cure condition self.user.db.conditions = {"Poisoned": [5, self.user]} tb_items.itemfunc_cure_condition(self.test_healpotion, self.user, self.user) self.assertTrue(self.user.db.conditions == {}) class TestTurnBattleMagicFunc(BaseEvenniaTest): def setUp(self): super(TestTurnBattleMagicFunc, self).setUp() self.testroom = create_object(DefaultRoom, key="Test Room") self.attacker = create_object( tb_magic.TBMagicCharacter, key="Attacker", location=self.testroom ) self.defender = create_object( tb_magic.TBMagicCharacter, key="Defender", location=self.testroom ) self.joiner = create_object(tb_magic.TBMagicCharacter, key="Joiner", location=self.testroom) def tearDown(self): super(TestTurnBattleMagicFunc, self).tearDown() self.turnhandler.stop() self.testroom.delete() self.attacker.delete() self.defender.delete() self.joiner.delete() # Test combat functions in tb_magic. def test_tbbasicfunc(self): # Initiative roll initiative = tb_magic.roll_init(self.attacker) self.assertTrue(initiative >= 0 and initiative <= 1000) # Attack roll attack_roll = tb_magic.get_attack(self.attacker, self.defender) self.assertTrue(attack_roll >= 0 and attack_roll <= 100) # Defense roll defense_roll = tb_magic.get_defense(self.attacker, self.defender) self.assertTrue(defense_roll == 50) # Damage roll damage_roll = tb_magic.get_damage(self.attacker, self.defender) self.assertTrue(damage_roll >= 15 and damage_roll <= 25) # Apply damage self.defender.db.hp = 10 tb_magic.apply_damage(self.defender, 3) self.assertTrue(self.defender.db.hp == 7) # Resolve attack self.defender.db.hp = 40 tb_magic.resolve_attack(self.attacker, self.defender, attack_value=20, defense_value=10) self.assertTrue(self.defender.db.hp < 40) # Combat cleanup self.attacker.db.Combat_attribute = True tb_magic.combat_cleanup(self.attacker) self.assertFalse(self.attacker.db.combat_attribute) # Is in combat self.assertFalse(tb_magic.is_in_combat(self.attacker)) # Set up turn handler script for further tests self.attacker.location.scripts.add(tb_magic.TBMagicTurnHandler) self.turnhandler = self.attacker.db.combat_TurnHandler self.assertTrue(self.attacker.db.combat_TurnHandler) # Set the turn handler's interval very high to keep it from repeating during tests. self.turnhandler.interval = 10000 # Force turn order self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 # Test is turn self.assertTrue(tb_magic.is_turn(self.attacker)) # Spend actions self.attacker.db.Combat_ActionsLeft = 1 tb_magic.spend_action(self.attacker, 1, action_name="Test") self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "Test") # Initialize for combat self.attacker.db.Combat_ActionsLeft = 983 self.turnhandler.initialize_for_combat(self.attacker) self.assertTrue(self.attacker.db.Combat_ActionsLeft == 0) self.assertTrue(self.attacker.db.Combat_LastAction == "null") # Start turn self.defender.db.Combat_ActionsLeft = 0 self.turnhandler.start_turn(self.defender) self.assertTrue(self.defender.db.Combat_ActionsLeft == 1) # Next turn self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.next_turn() self.assertTrue(self.turnhandler.db.turn == 1) # Turn end check self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.attacker.db.Combat_ActionsLeft = 0 self.turnhandler.turn_end_check(self.attacker) self.assertTrue(self.turnhandler.db.turn == 1) # Join fight self.turnhandler.db.fighters = [self.attacker, self.defender] self.turnhandler.db.turn = 0 self.turnhandler.join_fight(self.joiner) self.assertTrue(self.turnhandler.db.turn == 1) self.assertTrue(self.turnhandler.db.fighters == [self.joiner, self.attacker, self.defender])
[ "evennia.utils.create.create_object" ]
[((1080, 1132), 'evennia.utils.create.create_object', 'create_object', (['tb_equip.TBEWeapon'], {'key': '"""test weapon"""'}), "(tb_equip.TBEWeapon, key='test weapon')\n", (1093, 1132), False, 'from evennia.utils.create import create_object\n'), ((1158, 1208), 'evennia.utils.create.create_object', 'create_object', (['tb_equip.TBEArmor'], {'key': '"""test armor"""'}), "(tb_equip.TBEArmor, key='test armor')\n", (1171, 1208), False, 'from evennia.utils.create import create_object\n'), ((3441, 3471), 'evennia.utils.create.create_object', 'create_object', ([], {'key': '"""test item"""'}), "(key='test item')\n", (3454, 3471), False, 'from evennia.utils.create import create_object\n'), ((5248, 5291), 'evennia.utils.create.create_object', 'create_object', (['DefaultRoom'], {'key': '"""Test Room"""'}), "(DefaultRoom, key='Test Room')\n", (5261, 5291), False, 'from evennia.utils.create import create_object\n'), ((5316, 5401), 'evennia.utils.create.create_object', 'create_object', (['tb_basic.TBBasicCharacter'], {'key': '"""Attacker"""', 'location': 'self.testroom'}), "(tb_basic.TBBasicCharacter, key='Attacker', location=self.testroom\n )\n", (5329, 5401), False, 'from evennia.utils.create import create_object\n'), ((5443, 5528), 'evennia.utils.create.create_object', 'create_object', (['tb_basic.TBBasicCharacter'], {'key': '"""Defender"""', 'location': 'self.testroom'}), "(tb_basic.TBBasicCharacter, key='Defender', location=self.testroom\n )\n", (5456, 5528), False, 'from evennia.utils.create import create_object\n'), ((5568, 5637), 'evennia.utils.create.create_object', 'create_object', (['tb_basic.TBBasicCharacter'], {'key': '"""Joiner"""', 'location': 'None'}), "(tb_basic.TBBasicCharacter, key='Joiner', location=None)\n", (5581, 5637), False, 'from evennia.utils.create import create_object\n'), ((9540, 9583), 'evennia.utils.create.create_object', 'create_object', (['DefaultRoom'], {'key': '"""Test Room"""'}), "(DefaultRoom, key='Test Room')\n", (9553, 9583), False, 'from evennia.utils.create import create_object\n'), ((9608, 9693), 'evennia.utils.create.create_object', 'create_object', (['tb_equip.TBEquipCharacter'], {'key': '"""Attacker"""', 'location': 'self.testroom'}), "(tb_equip.TBEquipCharacter, key='Attacker', location=self.testroom\n )\n", (9621, 9693), False, 'from evennia.utils.create import create_object\n'), ((9735, 9820), 'evennia.utils.create.create_object', 'create_object', (['tb_equip.TBEquipCharacter'], {'key': '"""Defender"""', 'location': 'self.testroom'}), "(tb_equip.TBEquipCharacter, key='Defender', location=self.testroom\n )\n", (9748, 9820), False, 'from evennia.utils.create import create_object\n'), ((9860, 9929), 'evennia.utils.create.create_object', 'create_object', (['tb_equip.TBEquipCharacter'], {'key': '"""Joiner"""', 'location': 'None'}), "(tb_equip.TBEquipCharacter, key='Joiner', location=None)\n", (9873, 9929), False, 'from evennia.utils.create import create_object\n'), ((13836, 13879), 'evennia.utils.create.create_object', 'create_object', (['DefaultRoom'], {'key': '"""Test Room"""'}), "(DefaultRoom, key='Test Room')\n", (13849, 13879), False, 'from evennia.utils.create import create_object\n'), ((13904, 13989), 'evennia.utils.create.create_object', 'create_object', (['tb_range.TBRangeCharacter'], {'key': '"""Attacker"""', 'location': 'self.testroom'}), "(tb_range.TBRangeCharacter, key='Attacker', location=self.testroom\n )\n", (13917, 13989), False, 'from evennia.utils.create import create_object\n'), ((14031, 14116), 'evennia.utils.create.create_object', 'create_object', (['tb_range.TBRangeCharacter'], {'key': '"""Defender"""', 'location': 'self.testroom'}), "(tb_range.TBRangeCharacter, key='Defender', location=self.testroom\n )\n", (14044, 14116), False, 'from evennia.utils.create import create_object\n'), ((14156, 14234), 'evennia.utils.create.create_object', 'create_object', (['tb_range.TBRangeCharacter'], {'key': '"""Joiner"""', 'location': 'self.testroom'}), "(tb_range.TBRangeCharacter, key='Joiner', location=self.testroom)\n", (14169, 14234), False, 'from evennia.utils.create import create_object\n'), ((19073, 19116), 'evennia.utils.create.create_object', 'create_object', (['DefaultRoom'], {'key': '"""Test Room"""'}), "(DefaultRoom, key='Test Room')\n", (19086, 19116), False, 'from evennia.utils.create import create_object\n'), ((19141, 19226), 'evennia.utils.create.create_object', 'create_object', (['tb_items.TBItemsCharacter'], {'key': '"""Attacker"""', 'location': 'self.testroom'}), "(tb_items.TBItemsCharacter, key='Attacker', location=self.testroom\n )\n", (19154, 19226), False, 'from evennia.utils.create import create_object\n'), ((19268, 19353), 'evennia.utils.create.create_object', 'create_object', (['tb_items.TBItemsCharacter'], {'key': '"""Defender"""', 'location': 'self.testroom'}), "(tb_items.TBItemsCharacter, key='Defender', location=self.testroom\n )\n", (19281, 19353), False, 'from evennia.utils.create import create_object\n'), ((19393, 19471), 'evennia.utils.create.create_object', 'create_object', (['tb_items.TBItemsCharacter'], {'key': '"""Joiner"""', 'location': 'self.testroom'}), "(tb_items.TBItemsCharacter, key='Joiner', location=self.testroom)\n", (19406, 19471), False, 'from evennia.utils.create import create_object\n'), ((19492, 19568), 'evennia.utils.create.create_object', 'create_object', (['tb_items.TBItemsCharacter'], {'key': '"""User"""', 'location': 'self.testroom'}), "(tb_items.TBItemsCharacter, key='User', location=self.testroom)\n", (19505, 19568), False, 'from evennia.utils.create import create_object\n'), ((19600, 19635), 'evennia.utils.create.create_object', 'create_object', ([], {'key': '"""healing potion"""'}), "(key='healing potion')\n", (19613, 19635), False, 'from evennia.utils.create import create_object\n'), ((24933, 24976), 'evennia.utils.create.create_object', 'create_object', (['DefaultRoom'], {'key': '"""Test Room"""'}), "(DefaultRoom, key='Test Room')\n", (24946, 24976), False, 'from evennia.utils.create import create_object\n'), ((25001, 25086), 'evennia.utils.create.create_object', 'create_object', (['tb_magic.TBMagicCharacter'], {'key': '"""Attacker"""', 'location': 'self.testroom'}), "(tb_magic.TBMagicCharacter, key='Attacker', location=self.testroom\n )\n", (25014, 25086), False, 'from evennia.utils.create import create_object\n'), ((25128, 25213), 'evennia.utils.create.create_object', 'create_object', (['tb_magic.TBMagicCharacter'], {'key': '"""Defender"""', 'location': 'self.testroom'}), "(tb_magic.TBMagicCharacter, key='Defender', location=self.testroom\n )\n", (25141, 25213), False, 'from evennia.utils.create import create_object\n'), ((25253, 25331), 'evennia.utils.create.create_object', 'create_object', (['tb_magic.TBMagicCharacter'], {'key': '"""Joiner"""', 'location': 'self.testroom'}), "(tb_magic.TBMagicCharacter, key='Joiner', location=self.testroom)\n", (25266, 25331), False, 'from evennia.utils.create import create_object\n'), ((18962, 18973), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (18971, 18973), False, 'from mock import patch, MagicMock\n')]
from django.conf import settings from evennia.utils.utils import class_from_module from athanor.gamedb.characters import AthanorPlayerCharacter from athanor_entity.entities.base import BaseGameEntity MIXINS = [class_from_module(mixin) for mixin in settings.MIXINS["ENTITY_CHARACTER"]] MIXINS.sort(key=lambda x: getattr(x, "mixin_priority", 0)) class EntityPlayerCharacter(*MIXINS, BaseGameEntity, AthanorPlayerCharacter): persistent = True @property def contents(self): """ This must return a list for commands to work properly. Returns: items (list) """ return self.items.all()
[ "evennia.utils.utils.class_from_module" ]
[((211, 235), 'evennia.utils.utils.class_from_module', 'class_from_module', (['mixin'], {}), '(mixin)\n', (228, 235), False, 'from evennia.utils.utils import class_from_module\n')]
""" Channel The channel class represents the out-of-character chat-room usable by Players in-game. It is mostly overloaded to change its appearance, but channels can be used to implement many different forms of message distribution systems. Note that sending data to channels are handled via the CMD_CHANNEL syscommand (see evennia.syscmds). The sending should normally not need to be modified. """ from evennia.comms.models import TempMsg from evennia.comms.comms import DefaultChannel from evennia.utils.utils import make_iter from muddery.server.utils.localized_strings_handler import _ from muddery.server.utils.defines import ConversationType class MudderyChannel(DefaultChannel): """ Working methods: at_channel_creation() - called once, when the channel is created has_connection(player) - check if the given player listens to this channel connect(player) - connect player to this channel disconnect(player) - disconnect player from channel access(access_obj, access_type='listen', default=False) - check the access on this channel (default access_type is listen) delete() - delete this channel message_transform(msg, emit=False, prefix=True, sender_strings=None, external=False) - called by the comm system and triggers the hooks below msg(msgobj, header=None, senders=None, sender_strings=None, persistent=None, online=False, emit=False, external=False) - main send method, builds and sends a new message to channel. tempmsg(msg, header=None, senders=None) - wrapper for sending non-persistent messages. distribute_message(msg, online=False) - send a message to all connected players on channel, optionally sending only to players that are currently online (optimized for very large sends) Useful hooks: channel_prefix(msg, emit=False) - how the channel should be prefixed when returning to user. Returns a string format_senders(senders) - should return how to display multiple senders to a channel pose_transform(msg, sender_string) - should detect if the sender is posing, and if so, modify the string format_external(msg, senders, emit=False) - format messages sent from outside the game, like from IRC format_message(msg, emit=False) - format the message body before displaying it to the user. 'emit' generally means that the message should not be displayed with the sender's name. pre_join_channel(joiner) - if returning False, abort join post_join_channel(joiner) - called right after successful join pre_leave_channel(leaver) - if returning False, abort leave post_leave_channel(leaver) - called right after successful leave pre_send_message(msg) - runs just before a message is sent to channel post_send_message(msg) - called just after message was sent to channel """ def channel_prefix(self, msg=None, emit=False, **kwargs): """ Hook method. How the channel should prefix itself for users. Args: msg (str, optional): Prefix text emit (bool, optional): Switches to emit mode, which usually means to not prefix the channel's info. Returns: prefix (str): The created channel prefix. """ return '' if emit else '[%s] ' % _(self.key, category="channels") def get_message(self, caller, message): """ Receive a message from a character. :param caller: talker. :param message: content. """ if not self.access(caller, "send"): caller.msg(_("You can not talk in this channel.")) return output = { "conversation": { "type": ConversationType.CHANNEL.value, "channel": _(self.key, category="channels"), "from_id": caller.get_id(), "from_name": caller.get_name(), "msg": message, } } msgobj = TempMsg(message=output, channels=[self]) self.msg(msgobj, emit=True) def msg( self, msgobj, header=None, senders=None, sender_strings=None, keep_log=None, online=False, emit=False, external=False, ): """ Send the given message to all accounts connected to channel. Note that no permission-checking is done here; it is assumed to have been done before calling this method. The optional keywords are not used if persistent is False. Args: msgobj (Msg, TempMsg or str): If a Msg/TempMsg, the remaining keywords will be ignored (since the Msg/TempMsg object already has all the data). If a string, this will either be sent as-is (if persistent=False) or it will be used together with `header` and `senders` keywords to create a Msg instance on the fly. header (str, optional): A header for building the message. senders (Object, Account or list, optional): Optional if persistent=False, used to build senders for the message. sender_strings (list, optional): Name strings of senders. Used for external connections where the sender is not an account or object. When this is defined, external will be assumed. keep_log (bool or None, optional): This allows to temporarily change the logging status of this channel message. If `None`, the Channel's `keep_log` Attribute will be used. If `True` or `False`, that logging status will be used for this message only (note that for unlogged channels, a `True` value here will create a new log file only for this message). online (bool, optional) - If this is set true, only messages people who are online. Otherwise, messages all accounts connected. This can make things faster, but may not trigger listeners on accounts that are offline. emit (bool, optional) - Signals to the message formatter that this message is not to be directly associated with a name. external (bool, optional): Treat this message as being agnostic of its sender. Returns: success (bool): Returns `True` if message sending was successful, `False` otherwise. """ senders = make_iter(senders) if senders else [] if isinstance(msgobj, str): # given msgobj is a string - convert to msgobject (always TempMsg) msgobj = TempMsg(senders=senders, header=header, message=msgobj, channels=[self]) # we store the logging setting for use in distribute_message() msgobj.keep_log = keep_log if keep_log is not None else self.db.keep_log # start the sending msgobj = self.pre_send_message(msgobj) if not msgobj: return False msgobj = self.message_transform( msgobj, emit=emit, prefix=False, sender_strings=sender_strings, external=external ) self.distribute_message(msgobj, online=online) self.post_send_message(msgobj) return True
[ "evennia.utils.utils.make_iter", "evennia.comms.models.TempMsg" ]
[((4252, 4292), 'evennia.comms.models.TempMsg', 'TempMsg', ([], {'message': 'output', 'channels': '[self]'}), '(message=output, channels=[self])\n', (4259, 4292), False, 'from evennia.comms.models import TempMsg\n'), ((6780, 6798), 'evennia.utils.utils.make_iter', 'make_iter', (['senders'], {}), '(senders)\n', (6789, 6798), False, 'from evennia.utils.utils import make_iter\n'), ((6954, 7026), 'evennia.comms.models.TempMsg', 'TempMsg', ([], {'senders': 'senders', 'header': 'header', 'message': 'msgobj', 'channels': '[self]'}), '(senders=senders, header=header, message=msgobj, channels=[self])\n', (6961, 7026), False, 'from evennia.comms.models import TempMsg\n'), ((3583, 3615), 'muddery.server.utils.localized_strings_handler._', '_', (['self.key'], {'category': '"""channels"""'}), "(self.key, category='channels')\n", (3584, 3615), False, 'from muddery.server.utils.localized_strings_handler import _\n'), ((3861, 3899), 'muddery.server.utils.localized_strings_handler._', '_', (['"""You can not talk in this channel."""'], {}), "('You can not talk in this channel.')\n", (3862, 3899), False, 'from muddery.server.utils.localized_strings_handler import _\n'), ((4053, 4085), 'muddery.server.utils.localized_strings_handler._', '_', (['self.key'], {'category': '"""channels"""'}), "(self.key, category='channels')\n", (4054, 4085), False, 'from muddery.server.utils.localized_strings_handler import _\n')]
""" In-Game Mail system Evennia Contribution - grungies1138 2016 A simple Brandymail style @mail system that uses the Msg class from Evennia Core. It has two Commands, both of which can be used on their own: - CmdMail - this should sit on the Account cmdset and makes the @mail command available both IC and OOC. Mails will always go to Accounts (other players). - CmdMailCharacter - this should sit on the Character cmdset and makes the @mail command ONLY available when puppeting a character. Mails will be sent to other Characters only and will not be available when OOC. - If adding *both* commands to their respective cmdsets, you'll get two separate IC and OOC mailing systems, with different lists of mail for IC and OOC modes. Installation: Install one or both of the following (see above): - CmdMail (IC + OOC mail, sent between players) # mygame/commands/default_cmds.py from evennia.contrib import mail # in AccountCmdSet.at_cmdset_creation: self.add(mail.CmdMail()) - CmdMailCharacter (optional, IC only mail, sent between characters) # mygame/commands/default_cmds.py from evennia.contrib import mail # in CharacterCmdSet.at_cmdset_creation: self.add(mail.CmdMailCharacter()) Once installed, use `help mail` in game for help with the mail command. Use @ic/@ooc to switch in and out of IC/OOC modes. """ import re from evennia import ObjectDB, AccountDB from evennia import default_cmds from evennia.utils import create, evtable, make_iter, inherits_from, datetime_format from evennia.comms.models import Msg _HEAD_CHAR = "|015-|n" _SUB_HEAD_CHAR = "-" _WIDTH = 78 class CmdMail(default_cmds.MuxAccountCommand): """ Communicate with others by sending mail. Usage: @mail - Displays all the mail an account has in their mailbox @mail <#> - Displays a specific message @mail <accounts>=<subject>/<message> - Sends a message to the comma separated list of accounts. @mail/delete <#> - Deletes a specific message @mail/forward <account list>=<#>[/<Message>] - Forwards an existing message to the specified list of accounts, original message is delivered with optional Message prepended. @mail/reply <#>=<message> - Replies to a message #. Prepends message to the original message text. Switches: delete - deletes a message forward - forward a received message to another object with an optional message attached. reply - Replies to a received message, appending the original message to the bottom. Examples: @mail 2 @mail Griatch=New mail/Hey man, I am sending you a message! @mail/delete 6 @mail/forward feend78 Griatch=4/You guys should read this. @mail/reply 9=Thanks for the info! """ key = "@mail" aliases = ["mail"] lock = "cmd:all()" help_category = "General" 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 search_targets(self, namelist): """ Search a list of targets of the same type as caller. Args: caller (Object or Account): The type of object to search. namelist (list): List of strings for objects to search for. Returns: targetlist (Queryset): Any target matches. """ nameregex = r"|".join(r"^%s$" % re.escape(name) for name in make_iter(namelist)) if self.caller_is_account: matches = AccountDB.objects.filter(username__iregex=nameregex) else: matches = ObjectDB.objects.filter(db_key__iregex=nameregex) return matches def get_all_mail(self): """ Returns a list of all the messages where the caller is a recipient. These are all messages tagged with tags of the `mail` category. Returns: messages (QuerySet): Matching Msg objects. """ if self.caller_is_account: return Msg.objects.get_by_tag(category="mail").filter(db_receivers_accounts=self.caller) else: return Msg.objects.get_by_tag(category="mail").filter(db_receivers_objects=self.caller) def send_mail(self, recipients, subject, message, caller): """ Function for sending new mail. Also useful for sending notifications from objects or systems. Args: recipients (list): list of Account or Character objects to receive the newly created mails. subject (str): The header or subject of the message to be delivered. message (str): The body of the message being sent. caller (obj): The object (or Account or Character) that is sending the message. """ for recipient in recipients: recipient.msg("You have received a new @mail from %s" % caller) new_message = create.create_message(self.caller, message, receivers=recipient, header=subject) new_message.tags.add("new", category="mail") if recipients: caller.msg("You sent your message.") return else: caller.msg("No valid target(s) found. Cannot send message.") return def func(self): """ Do the main command functionality """ subject = "" body = "" if self.switches or self.args: if "delete" in self.switches or "del" in self.switches: try: if not self.lhs: self.caller.msg("No Message ID given. Unable to delete.") return else: all_mail = self.get_all_mail() mind_max = max(0, all_mail.count() - 1) mind = max(0, min(mind_max, int(self.lhs) - 1)) if all_mail[mind]: mail = all_mail[mind] question = "Delete message {} ({}) [Y]/N?".format(mind + 1, mail.header) ret = yield(question) # handle not ret, it will be None during unit testing if not ret or ret.strip().upper() not in ("N", "No"): all_mail[mind].delete() self.caller.msg("Message %s deleted" % (mind + 1,)) else: self.caller.msg("Message not deleted.") else: raise IndexError except IndexError: self.caller.msg("That message does not exist.") except ValueError: self.caller.msg("Usage: @mail/delete <message ID>") elif "forward" in self.switches or "fwd" in self.switches: try: if not self.rhs: self.caller.msg("Cannot forward a message without a target list. " "Please try again.") return elif not self.lhs: self.caller.msg("You must define a message to forward.") return else: all_mail = self.get_all_mail() mind_max = max(0, all_mail.count() - 1) if "/" in self.rhs: message_number, message = self.rhs.split("/", 1) mind = max(0, min(mind_max, int(message_number) - 1)) if all_mail[mind]: old_message = all_mail[mind] self.send_mail(self.search_targets(self.lhslist), "FWD: " + old_message.header, message + "\n---- Original Message ----\n" + old_message.message, self.caller) self.caller.msg("Message forwarded.") else: raise IndexError else: mind = max(0, min(mind_max, int(self.rhs) - 1)) if all_mail[mind]: old_message = all_mail[mind] self.send_mail(self.search_targets(self.lhslist), "FWD: " + old_message.header, "\n---- Original Message ----\n" + old_message.message, self.caller) self.caller.msg("Message forwarded.") old_message.tags.remove("new", category="mail") old_message.tags.add("fwd", category="mail") else: raise IndexError except IndexError: self.caller.msg("Message does not exixt.") except ValueError: self.caller.msg("Usage: @mail/forward <account list>=<#>[/<Message>]") elif "reply" in self.switches or "rep" in self.switches: try: if not self.rhs: self.caller.msg("You must define a message to reply to.") return elif not self.lhs: self.caller.msg("You must supply a reply message") return else: all_mail = self.get_all_mail() mind_max = max(0, all_mail.count() - 1) mind = max(0, min(mind_max, int(self.lhs) - 1)) if all_mail[mind]: old_message = all_mail[mind] self.send_mail(old_message.senders, "RE: " + old_message.header, self.rhs + "\n---- Original Message ----\n" + old_message.message, self.caller) old_message.tags.remove("new", category="mail") old_message.tags.add("-", category="mail") return else: raise IndexError except IndexError: self.caller.msg("Message does not exist.") except ValueError: self.caller.msg("Usage: @mail/reply <#>=<message>") else: # normal send if self.rhs: if "/" in self.rhs: subject, body = self.rhs.split("/", 1) else: body = self.rhs self.send_mail(self.search_targets(self.lhslist), subject, body, self.caller) else: all_mail = self.get_all_mail() mind_max = max(0, all_mail.count() - 1) try: mind = max(0, min(mind_max, int(self.lhs) - 1)) message = all_mail[mind] except (ValueError, IndexError): self.caller.msg("'%s' is not a valid mail id." % self.lhs) return messageForm = [] if message: messageForm.append(_HEAD_CHAR * _WIDTH) messageForm.append("|wFrom:|n %s" % (message.senders[0].get_display_name(self.caller))) messageForm.append("|wSent:|n %s" % message.db_date_created.strftime("%b %-d, %Y - %H:%M:%S")) messageForm.append("|wSubject:|n %s" % message.header) messageForm.append(_SUB_HEAD_CHAR * _WIDTH) messageForm.append(message.message) messageForm.append(_HEAD_CHAR * _WIDTH) self.caller.msg("\n".join(messageForm)) message.tags.remove("new", category="mail") message.tags.add("-", category="mail") else: # list messages messages = self.get_all_mail() if messages: table = evtable.EvTable("|wID|n", "|wFrom|n", "|wSubject|n", "|wArrived|n", "", table=None, border="header", header_line_char=_SUB_HEAD_CHAR, width=_WIDTH) index = 1 for message in messages: status = str(message.db_tags.last().db_key.upper()) if status == "NEW": status = "|gNEW|n" table.add_row(index, message.senders[0].get_display_name(self.caller), message.header, datetime_format(message.db_date_created), status) index += 1 table.reformat_column(0, width=6) table.reformat_column(1, width=18) table.reformat_column(2, width=34) table.reformat_column(3, width=13) table.reformat_column(4, width=7) self.caller.msg(_HEAD_CHAR * _WIDTH) self.caller.msg(str(table)) self.caller.msg(_HEAD_CHAR * _WIDTH) else: self.caller.msg("There are no messages in your inbox.") # character - level version of the command class CmdMailCharacter(CmdMail): account_caller = False
[ "evennia.ObjectDB.objects.filter", "evennia.utils.inherits_from", "evennia.utils.make_iter", "evennia.comms.models.Msg.objects.get_by_tag", "evennia.AccountDB.objects.filter", "evennia.utils.datetime_format", "evennia.utils.create.create_message", "evennia.utils.evtable.EvTable" ]
[((3227, 3297), 'evennia.utils.inherits_from', 'inherits_from', (['self.caller', '"""evennia.accounts.accounts.DefaultAccount"""'], {}), "(self.caller, 'evennia.accounts.accounts.DefaultAccount')\n", (3240, 3297), False, 'from evennia.utils import create, evtable, make_iter, inherits_from, datetime_format\n'), ((3854, 3906), 'evennia.AccountDB.objects.filter', 'AccountDB.objects.filter', ([], {'username__iregex': 'nameregex'}), '(username__iregex=nameregex)\n', (3878, 3906), False, 'from evennia import ObjectDB, AccountDB\n'), ((3943, 3992), 'evennia.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'db_key__iregex': 'nameregex'}), '(db_key__iregex=nameregex)\n', (3966, 3992), False, 'from evennia import ObjectDB, AccountDB\n'), ((5255, 5340), 'evennia.utils.create.create_message', 'create.create_message', (['self.caller', 'message'], {'receivers': 'recipient', 'header': 'subject'}), '(self.caller, message, receivers=recipient, header=subject\n )\n', (5276, 5340), False, 'from evennia.utils import create, evtable, make_iter, inherits_from, datetime_format\n'), ((12710, 12861), 'evennia.utils.evtable.EvTable', 'evtable.EvTable', (['"""|wID|n"""', '"""|wFrom|n"""', '"""|wSubject|n"""', '"""|wArrived|n"""', '""""""'], {'table': 'None', 'border': '"""header"""', 'header_line_char': '_SUB_HEAD_CHAR', 'width': '_WIDTH'}), "('|wID|n', '|wFrom|n', '|wSubject|n', '|wArrived|n', '',\n table=None, border='header', header_line_char=_SUB_HEAD_CHAR, width=_WIDTH)\n", (12725, 12861), False, 'from evennia.utils import create, evtable, make_iter, inherits_from, datetime_format\n'), ((3748, 3763), 're.escape', 're.escape', (['name'], {}), '(name)\n', (3757, 3763), False, 'import re\n'), ((3776, 3795), 'evennia.utils.make_iter', 'make_iter', (['namelist'], {}), '(namelist)\n', (3785, 3795), False, 'from evennia.utils import create, evtable, make_iter, inherits_from, datetime_format\n'), ((4349, 4388), 'evennia.comms.models.Msg.objects.get_by_tag', 'Msg.objects.get_by_tag', ([], {'category': '"""mail"""'}), "(category='mail')\n", (4371, 4388), False, 'from evennia.comms.models import Msg\n'), ((4464, 4503), 'evennia.comms.models.Msg.objects.get_by_tag', 'Msg.objects.get_by_tag', ([], {'category': '"""mail"""'}), "(category='mail')\n", (4486, 4503), False, 'from evennia.comms.models import Msg\n'), ((13377, 13417), 'evennia.utils.datetime_format', 'datetime_format', (['message.db_date_created'], {}), '(message.db_date_created)\n', (13392, 13417), False, 'from evennia.utils import create, evtable, make_iter, inherits_from, datetime_format\n')]
""" This model translates default strings into localized strings. """ from django.conf import settings from django.contrib.admin.forms import forms from evennia.utils import logger from muddery.server.utils.utils import classes_in_path class FormSet(object): """ All available elements. """ def __init__(self): self.dict = {} self.load() def load(self): """ Add all forms from the form path. """ # load classes for cls in classes_in_path(settings.PATH_DATA_FORMS_BASE, forms.ModelForm): if hasattr(cls, "Meta") and hasattr(cls.Meta, "model"): model = cls.Meta.model model_name = model.__name__ if model_name in self.dict: logger.log_infomsg("Form %s is replaced by %s." % (model_name, cls)) self.dict[model_name] = cls def get(self, model_name): """ Get a form. Args: model_name: (string) model's name """ return self.dict[model_name] FORM_SET = FormSet()
[ "evennia.utils.logger.log_infomsg" ]
[((510, 573), 'muddery.server.utils.utils.classes_in_path', 'classes_in_path', (['settings.PATH_DATA_FORMS_BASE', 'forms.ModelForm'], {}), '(settings.PATH_DATA_FORMS_BASE, forms.ModelForm)\n', (525, 573), False, 'from muddery.server.utils.utils import classes_in_path\n'), ((791, 859), 'evennia.utils.logger.log_infomsg', 'logger.log_infomsg', (["('Form %s is replaced by %s.' % (model_name, cls))"], {}), "('Form %s is replaced by %s.' % (model_name, cls))\n", (809, 859), False, 'from evennia.utils import logger\n')]
""" Tests of create functions """ from django.test import TestCase from evennia.utils.test_resources import EvenniaTest from evennia.scripts.scripts import DefaultScript from evennia.utils import create class TestCreateScript(EvenniaTest): def test_create_script(self): class TestScriptA(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.persistent = False script = create.create_script(TestScriptA, key="test_script") assert script is not None assert script.interval == 10 assert script.key == "test_script" script.stop() def test_create_script_w_repeats_equal_1(self): class TestScriptB(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 1 self.persistent = False # script should still exist even though repeats=1, start_delay=False script = create.create_script(TestScriptB, key="test_script") assert script # but the timer should be inactive now assert not script.is_active def test_create_script_w_repeats_equal_1_persisted(self): class TestScriptB1(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 1 self.persistent = True # script is already stopped (interval=1, start_delay=False) script = create.create_script(TestScriptB1, key="test_script") assert script assert not script.is_active def test_create_script_w_repeats_equal_2(self): class TestScriptC(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.repeats = 2 self.persistent = False script = create.create_script(TestScriptC, key="test_script") assert script is not None assert script.interval == 10 assert script.repeats == 2 assert script.key == "test_script" script.stop() def test_create_script_w_repeats_equal_1_and_delayed(self): class TestScriptD(DefaultScript): def at_script_creation(self): self.key = "test_script" self.interval = 10 self.start_delay = True self.repeats = 1 self.persistent = False script = create.create_script(TestScriptD, key="test_script") assert script is not None assert script.interval == 10 assert script.repeats == 1 assert script.key == "test_script" script.stop() class TestCreateHelpEntry(TestCase): help_entry = """ Qui laborum voluptas quis commodi ipsum quo temporibus eum. Facilis assumenda facilis architecto in corrupti. Est placeat eum amet qui beatae reiciendis. Accusamus vel aspernatur ab ex. Quam expedita sed expedita consequuntur est dolorum non exercitationem. Ipsa vel ut dolorem voluptatem adipisci velit. Sit odit temporibus mollitia illum ipsam placeat. Rem et ipsum dolor. Hic eum tempore excepturi qui veniam magni. Excepturi quam repellendus inventore excepturi fugiat quo quasi molestias. Nostrum ut assumenda enim a. Repellat quis omnis est officia accusantium. Fugit facere qui aperiam. Perspiciatis commodi dolores ipsam nemo consequatur quisquam qui non. Adipisci et molestias voluptatum est sed fugiat facere. """ def test_create_help_entry__simple(self): entry = create.create_help_entry("testentry", self.help_entry, category="Testing") self.assertEqual(entry.key, "testentry") self.assertEqual(entry.entrytext, self.help_entry) self.assertEqual(entry.help_category, "Testing") # creating same-named entry should not work (must edit existing) self.assertFalse(create.create_help_entry("testentry", "testtext")) def test_create_help_entry__complex(self): locks = "foo:false();bar:true()" aliases = ["foo", "bar", "tst"] tags = [("tag1", "help"), ("tag2", "help"), ("tag3", "help")] entry = create.create_help_entry( "testentry", self.help_entry, category="Testing", locks=locks, aliases=aliases, tags=tags, ) self.assertTrue(all(lock in entry.locks.all() for lock in locks.split(";"))) self.assertEqual(list(entry.aliases.all()).sort(), aliases.sort()) self.assertEqual(entry.tags.all(return_key_and_category=True), tags) class TestCreateMessage(EvenniaTest): msgtext = """ Qui laborum voluptas quis commodi ipsum quo temporibus eum. Facilis assumenda facilis architecto in corrupti. Est placeat eum amet qui beatae reiciendis. Accusamus vel aspernatur ab ex. Quam expedita sed expedita consequuntur est dolorum non exercitationem. """ def test_create_msg__simple(self): # from evennia import set_trace;set_trace() msg = create.create_message(self.char1, self.msgtext, header="TestHeader") msg.senders = "ExternalSender" msg.receivers = self.char2 msg.receivers = "ExternalReceiver" self.assertEqual(msg.message, self.msgtext) self.assertEqual(msg.header, "TestHeader") self.assertEqual(msg.senders, [self.char1, "ExternalSender"]) self.assertEqual(msg.receivers, [self.char2, "ExternalReceiver"]) def test_create_msg__custom(self): locks = "foo:false();bar:true()" tags = ["tag1", "tag2", "tag3"] msg = create.create_message( self.char1, self.msgtext, header="TestHeader", receivers=[self.char1, self.char2, "ExternalReceiver"], locks=locks, tags=tags, ) self.assertEqual(set(msg.receivers), set([self.char1, self.char2, "ExternalReceiver"])) self.assertTrue(all(lock in msg.locks.all() for lock in locks.split(";"))) self.assertEqual(msg.tags.all(), tags) class TestCreateChannel(TestCase): def test_create_channel__simple(self): chan = create.create_channel("TestChannel1", desc="Testing channel") self.assertEqual(chan.key, "TestChannel1") self.assertEqual(chan.db.desc, "Testing channel") def test_create_channel__complex(self): locks = "foo:false();bar:true()" tags = ["tag1", "tag2", "tag3"] aliases = ["foo", "bar", "tst"] chan = create.create_channel( "TestChannel2", desc="Testing channel", aliases=aliases, locks=locks, tags=tags ) self.assertTrue(all(lock in chan.locks.all() for lock in locks.split(";"))) self.assertEqual(chan.tags.all(), tags) self.assertEqual(list(chan.aliases.all()).sort(), aliases.sort())
[ "evennia.utils.create.create_script", "evennia.utils.create.create_channel", "evennia.utils.create.create_message", "evennia.utils.create.create_help_entry" ]
[((496, 548), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptA'], {'key': '"""test_script"""'}), "(TestScriptA, key='test_script')\n", (516, 548), False, 'from evennia.utils import create\n'), ((1066, 1118), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptB'], {'key': '"""test_script"""'}), "(TestScriptB, key='test_script')\n", (1086, 1118), False, 'from evennia.utils import create\n'), ((1606, 1659), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptB1'], {'key': '"""test_script"""'}), "(TestScriptB1, key='test_script')\n", (1626, 1659), False, 'from evennia.utils import create\n'), ((2023, 2075), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptC'], {'key': '"""test_script"""'}), "(TestScriptC, key='test_script')\n", (2043, 2075), False, 'from evennia.utils import create\n'), ((2603, 2655), 'evennia.utils.create.create_script', 'create.create_script', (['TestScriptD'], {'key': '"""test_script"""'}), "(TestScriptD, key='test_script')\n", (2623, 2655), False, 'from evennia.utils import create\n'), ((3726, 3800), 'evennia.utils.create.create_help_entry', 'create.create_help_entry', (['"""testentry"""', 'self.help_entry'], {'category': '"""Testing"""'}), "('testentry', self.help_entry, category='Testing')\n", (3750, 3800), False, 'from evennia.utils import create\n'), ((4332, 4451), 'evennia.utils.create.create_help_entry', 'create.create_help_entry', (['"""testentry"""', 'self.help_entry'], {'category': '"""Testing"""', 'locks': 'locks', 'aliases': 'aliases', 'tags': 'tags'}), "('testentry', self.help_entry, category='Testing',\n locks=locks, aliases=aliases, tags=tags)\n", (4356, 4451), False, 'from evennia.utils import create\n'), ((5215, 5283), 'evennia.utils.create.create_message', 'create.create_message', (['self.char1', 'self.msgtext'], {'header': '"""TestHeader"""'}), "(self.char1, self.msgtext, header='TestHeader')\n", (5236, 5283), False, 'from evennia.utils import create\n'), ((5783, 5939), 'evennia.utils.create.create_message', 'create.create_message', (['self.char1', 'self.msgtext'], {'header': '"""TestHeader"""', 'receivers': "[self.char1, self.char2, 'ExternalReceiver']", 'locks': 'locks', 'tags': 'tags'}), "(self.char1, self.msgtext, header='TestHeader',\n receivers=[self.char1, self.char2, 'ExternalReceiver'], locks=locks,\n tags=tags)\n", (5804, 5939), False, 'from evennia.utils import create\n'), ((6336, 6397), 'evennia.utils.create.create_channel', 'create.create_channel', (['"""TestChannel1"""'], {'desc': '"""Testing channel"""'}), "('TestChannel1', desc='Testing channel')\n", (6357, 6397), False, 'from evennia.utils import create\n'), ((6689, 6796), 'evennia.utils.create.create_channel', 'create.create_channel', (['"""TestChannel2"""'], {'desc': '"""Testing channel"""', 'aliases': 'aliases', 'locks': 'locks', 'tags': 'tags'}), "('TestChannel2', desc='Testing channel', aliases=\n aliases, locks=locks, tags=tags)\n", (6710, 6796), False, 'from evennia.utils import create\n'), ((4065, 4114), 'evennia.utils.create.create_help_entry', 'create.create_help_entry', (['"""testentry"""', '"""testtext"""'], {}), "('testentry', 'testtext')\n", (4089, 4114), False, 'from evennia.utils import create\n')]
""" Special building tools like inside->wilderness connections and tunnel with translated directions. """ from contrib.wilderness import WildernessRoom from evennia.utils import create from evennia import default_cmds class CmdTunnel(default_cmds.CmdTunnel): """ create new rooms in cardinal directions only Usage: tunnel[/switch] <direction>[:typeclass] [= <roomname>[;alias;alias;...][:typeclass]] Switches: oneway - do not create an exit back to the current location tel - teleport to the newly created room Example: tunnel n tunnel n = house;mike's place;green building This is a simple way to build using pre-defined directions: |wn,ne,e,se,s,sw,w,nw|n (north, northeast etc) |wu,d|n (up and down) |wi,o|n (in and out) The full names (north, in, southwest, etc) will always be put as main name for the exit, using the abbreviation as an alias (so an exit will always be able to be used with both "north" as well as "n" for example). Opposite directions will automatically be created back from the new room unless the /oneway switch is given. For more flexibility and power in creating rooms, use dig. """ key = "tunnel" aliases = ["tun"] switch_options = ("oneway", "tel") locks = "cmd: (perm(tunnel) or perm(Builder)) and not wild()" help_category = "Building" # store the direction, full name and its opposite directions = { "n": ("nord", "s"), "ne": ("nordest", "so"), "e": ("est", "o"), "se": ("sudest", "no"), "s": ("sud", "n"), "so": ("sudovest", "ne"), "o": ("ovest", "e"), "no": ("nordovest", "se"), "a": ("alto", "b"), "b": ("basso", "a"), "d": ("dentro", "f"), "f": ("fuori", "d"), } class CmdPortal(default_cmds.CmdOpen): """ Open a special kind of exit that connects to a specific pair of coordinates in a specified wilderness. Usage: portal <new exit>[;alias;alias..] = <coordinates in the form: (x,y)> """ key = "portal" aliases = ["por"] locks = "cmd:perm(portal) or perm(Builder)" help_category = "Building" new_obj_lockstring = ( "control:id({id}) or perm(Admin);delete:id({id}) or perm(Admin)" ) # a custom member method to chug out exits and do checks def create_exit(self, exit_name, location, attributes, exit_aliases=None): """ Helper function to avoid code duplication. At this point we know destination is a valid location """ caller = self.caller string = "" # check if this exit object already exists at the location. # we need to ignore errors (so no automatic feedback)since we # have to know the result of the search to decide what to do. exit_obj = caller.search(exit_name, location=location, quiet=True, exact=True) if len(exit_obj) > 1: # give error message and return caller.search(exit_name, location=location, exact=True) return None if exit_obj: string = "'%s' already exists!" caller.msg(string % exit_name) return None else: # exit does not exist before. Create a new one. lockstring = self.new_obj_lockstring.format(id=caller.id) typeclass = "exits.Portal" exit_obj = create.create_object( typeclass, key=exit_name, location=location, aliases=exit_aliases, locks=lockstring, report_to=caller, attributes=attributes, ) if exit_obj: # storing a destination is what makes it an exit! string = ( "" if not exit_aliases else " (aliases: %s)" % (", ".join([str(e) for e in exit_aliases])) ) string = "Created new Exit '%s' from %s to %s%s." % ( exit_name, location.name, attributes[0][1], string, ) else: string = "Error: Exit '%s' not created." % exit_name # emit results caller.msg(string) return exit_obj def func(self): """ This is where the processing starts. Uses the ObjManipCommand.parser() for pre-processing as well as the self.create_exit() method. """ caller = self.caller if not self.args or not self.rhs: string = "Usage: por <new exit>[;alias...] " string += "= <wilderness,x,y>" caller.msg(string) return # We must have a location to open an exit location = caller.location if not location: caller.msg("You cannot create an exit from a None-location.") return # This command mustn't be used in the wilderness if type(location) == WildernessRoom: caller.msg("You can't use this while still in the wilderness.") return # obtain needed info from cmdline exit_name = self.lhs_objs[0]["name"] exit_aliases = self.lhs_objs[0]["aliases"] dest_name = self.rhs.split(",") if len(dest_name) != 3: string = "Bad destination. It should be in the format: <wilderness,x,y>." caller.msg(string) return try: coordinates = (int(dest_name[1]), int(dest_name[2])) except ValueError: string = "Wrong format. Coordinates should be of type: Tuple(int,int)." caller.msg(string) return attributes = [("wilderness", dest_name[0]), ("coordinates", coordinates)] # Create exit ok = self.create_exit(exit_name, location, attributes, exit_aliases) if not ok: # an error; the exit was not created, so we quit. return
[ "evennia.utils.create.create_object" ]
[((3440, 3591), 'evennia.utils.create.create_object', 'create.create_object', (['typeclass'], {'key': 'exit_name', 'location': 'location', 'aliases': 'exit_aliases', 'locks': 'lockstring', 'report_to': 'caller', 'attributes': 'attributes'}), '(typeclass, key=exit_name, location=location, aliases=\n exit_aliases, locks=lockstring, report_to=caller, attributes=attributes)\n', (3460, 3591), False, 'from evennia.utils import create\n')]
""" Unit tests for the prototypes and spawner """ from random import randint import mock from anything import Something from django.test.utils import override_settings from evennia.utils.test_resources import EvenniaTest from evennia.utils.tests.test_evmenu import TestEvMenu from evennia.prototypes import spawner, prototypes as protlib from evennia.prototypes import menus as olc_menus from evennia.prototypes import protfuncs as protofuncs from evennia.prototypes.prototypes import _PROTOTYPE_TAG_META_CATEGORY _PROTPARENTS = { "NOBODY": {}, "GOBLIN": { "prototype_key": "GOBLIN", "typeclass": "evennia.objects.objects.DefaultObject", "key": "goblin grunt", "health": lambda: randint(1, 1), "resists": ["cold", "poison"], "attacks": ["fists"], "weaknesses": ["fire", "light"] }, "GOBLIN_WIZARD": { "prototype_parent": "GOBLIN", "key": "goblin wizard", "spells": ["fire ball", "lighting bolt"] }, "GOBLIN_ARCHER": { "prototype_parent": "GOBLIN", "key": "goblin archer", "attacks": ["short bow"] }, "ARCHWIZARD": { "prototype_parent": "GOBLIN", "attacks": ["archwizard staff"], }, "GOBLIN_ARCHWIZARD": { "key": "goblin archwizard", "prototype_parent": ("GOBLIN_WIZARD", "ARCHWIZARD") } } class TestSpawner(EvenniaTest): def setUp(self): super(TestSpawner, self).setUp() self.prot1 = {"prototype_key": "testprototype", "typeclass": "evennia.objects.objects.DefaultObject"} def test_spawn_from_prot(self): obj1 = spawner.spawn(self.prot1) # check spawned objects have the right tag self.assertEqual(list(protlib.search_objects_with_prototype("testprototype")), obj1) self.assertEqual([o.key for o in spawner.spawn( _PROTPARENTS["GOBLIN"], _PROTPARENTS["GOBLIN_ARCHWIZARD"], prototype_parents=_PROTPARENTS)], ['goblin grunt', 'goblin archwizard']) def test_spawn_from_str(self): protlib.save_prototype(self.prot1) obj1 = spawner.spawn(self.prot1['prototype_key']) self.assertEqual(list(protlib.search_objects_with_prototype("testprototype")), obj1) self.assertEqual([o.key for o in spawner.spawn( _PROTPARENTS["GOBLIN"], _PROTPARENTS["GOBLIN_ARCHWIZARD"], prototype_parents=_PROTPARENTS)], ['goblin grunt', 'goblin archwizard']) class TestUtils(EvenniaTest): def test_prototype_from_object(self): self.maxDiff = None self.obj1.attributes.add("test", "testval") self.obj1.tags.add('foo') new_prot = spawner.prototype_from_object(self.obj1) self.assertEqual( {'attrs': [('test', 'testval', None, '')], 'home': Something, 'key': 'Obj', 'location': Something, 'locks': ";".join([ 'call:true()', 'control:perm(Developer)', 'delete:perm(Admin)', 'drop:holds()', 'edit:perm(Admin)', 'examine:perm(Builder)', 'get:all()', 'puppet:pperm(Developer)', 'tell:perm(Admin)', 'view:all()']), 'prototype_desc': 'Built from Obj', 'prototype_key': Something, 'prototype_locks': 'spawn:all();edit:all()', 'prototype_tags': [], 'tags': [('foo', None, None)], 'typeclass': 'evennia.objects.objects.DefaultObject'}, new_prot) def test_update_objects_from_prototypes(self): self.maxDiff = None self.obj1.attributes.add('oldtest', 'to_keep') old_prot = spawner.prototype_from_object(self.obj1) # modify object away from prototype self.obj1.attributes.add('test', 'testval') self.obj1.attributes.add('desc', 'changed desc') self.obj1.aliases.add('foo') self.obj1.tags.add('footag', 'foocategory') # modify prototype old_prot['new'] = 'new_val' old_prot['test'] = 'testval_changed' old_prot['permissions'] = ['Builder'] # this will not update, since we don't update the prototype on-disk old_prot['prototype_desc'] = 'New version of prototype' old_prot['attrs'] += (("fooattr", "fooattrval", None, ''),) # diff obj/prototype old_prot_copy = old_prot.copy() pdiff, obj_prototype = spawner.prototype_diff_from_object(old_prot, self.obj1) self.assertEqual(old_prot_copy, old_prot) self.assertEqual(obj_prototype, {'aliases': ['foo'], 'attrs': [('desc', 'changed desc', None, ''), ('oldtest', 'to_keep', None, ''), ('test', 'testval', None, '')], 'key': 'Obj', 'home': Something, 'location': Something, 'locks': 'call:true();control:perm(Developer);delete:perm(Admin);' 'drop:holds();' 'edit:perm(Admin);examine:perm(Builder);get:all();' 'puppet:pperm(Developer);tell:perm(Admin);view:all()', 'prototype_desc': 'Built from Obj', 'prototype_key': Something, 'prototype_locks': 'spawn:all();edit:all()', 'prototype_tags': [], 'tags': [('footag', 'foocategory', None)], 'typeclass': 'evennia.objects.objects.DefaultObject'}) self.assertEqual(old_prot, {'attrs': [('oldtest', 'to_keep', None, ''), ('fooattr', 'fooattrval', None, '')], 'home': Something, 'key': 'Obj', 'location': Something, 'locks': 'call:true();control:perm(Developer);delete:perm(Admin);' 'drop:holds();' 'edit:perm(Admin);examine:perm(Builder);get:all();' 'puppet:pperm(Developer);tell:perm(Admin);view:all()', 'new': 'new_val', 'permissions': ['Builder'], 'prototype_desc': 'New version of prototype', 'prototype_key': Something, 'prototype_locks': 'spawn:all();edit:all()', 'prototype_tags': [], 'test': 'testval_changed', 'typeclass': 'evennia.objects.objects.DefaultObject'}) self.assertEqual( pdiff, {'home': (Something, Something, 'KEEP'), 'prototype_locks': ('spawn:all();edit:all()', 'spawn:all();edit:all()', 'KEEP'), 'prototype_key': (Something, Something, 'UPDATE'), 'location': (Something, Something, 'KEEP'), 'locks': ('call:true();control:perm(Developer);delete:perm(Admin);' 'drop:holds();edit:perm(Admin);examine:perm(Builder);' 'get:all();puppet:pperm(Developer);tell:perm(Admin);view:all()', 'call:true();control:perm(Developer);delete:perm(Admin);drop:holds();' 'edit:perm(Admin);examine:perm(Builder);get:all();' 'puppet:pperm(Developer);tell:perm(Admin);view:all()', 'KEEP'), 'prototype_tags': {}, 'attrs': {'oldtest': (('oldtest', 'to_keep', None, ''), ('oldtest', 'to_keep', None, ''), 'KEEP'), 'test': (('test', 'testval', None, ''), None, 'REMOVE'), 'desc': (('desc', 'changed desc', None, ''), None, 'REMOVE'), 'fooattr': (None, ('fooattr', 'fooattrval', None, ''), 'ADD'), 'test': (('test', 'testval', None, ''), ('test', 'testval_changed', None, ''), 'UPDATE'), 'new': (None, ('new', 'new_val', None, ''), 'ADD')}, 'key': ('Obj', 'Obj', 'KEEP'), 'typeclass': ('evennia.objects.objects.DefaultObject', 'evennia.objects.objects.DefaultObject', 'KEEP'), 'aliases': {'foo': ('foo', None, 'REMOVE')}, 'tags': {'footag': (('footag', 'foocategory', None), None, 'REMOVE')}, 'prototype_desc': ('Built from Obj', 'New version of prototype', 'UPDATE'), 'permissions': {"Builder": (None, 'Builder', 'ADD')} }) self.assertEqual( spawner.flatten_diff(pdiff), {'aliases': 'REMOVE', 'attrs': 'REPLACE', 'home': 'KEEP', 'key': 'KEEP', 'location': 'KEEP', 'locks': 'KEEP', 'permissions': 'UPDATE', 'prototype_desc': 'UPDATE', 'prototype_key': 'UPDATE', 'prototype_locks': 'KEEP', 'prototype_tags': 'KEEP', 'tags': 'REMOVE', 'typeclass': 'KEEP'} ) # apply diff count = spawner.batch_update_objects_with_prototype( old_prot, diff=pdiff, objects=[self.obj1]) self.assertEqual(count, 1) new_prot = spawner.prototype_from_object(self.obj1) self.assertEqual({'attrs': [('fooattr', 'fooattrval', None, ''), ('new', 'new_val', None, ''), ('oldtest', 'to_keep', None, ''), ('test', 'testval_changed', None, '')], 'home': Something, 'key': 'Obj', 'location': Something, 'locks': ";".join([ 'call:true()', 'control:perm(Developer)', 'delete:perm(Admin)', 'drop:holds()', 'edit:perm(Admin)', 'examine:perm(Builder)', 'get:all()', 'puppet:pperm(Developer)', 'tell:perm(Admin)', 'view:all()']), 'permissions': ['builder'], 'prototype_desc': 'Built from Obj', 'prototype_key': Something, 'prototype_locks': 'spawn:all();edit:all()', 'prototype_tags': [], 'typeclass': 'evennia.objects.objects.DefaultObject'}, new_prot) class TestProtLib(EvenniaTest): def setUp(self): super(TestProtLib, self).setUp() self.obj1.attributes.add("testattr", "testval") self.prot = spawner.prototype_from_object(self.obj1) def test_prototype_to_str(self): prstr = protlib.prototype_to_str(self.prot) self.assertTrue(prstr.startswith("|cprototype-key:|n")) def test_check_permission(self): pass def test_save_prototype(self): result = protlib.save_prototype(self.prot) self.assertEqual(result, self.prot) # faulty self.prot['prototype_key'] = None self.assertRaises(protlib.ValidationError, protlib.save_prototype, self.prot) def test_search_prototype(self): protlib.save_prototype(self.prot) match = protlib.search_prototype("NotFound") self.assertFalse(match) match = protlib.search_prototype() self.assertTrue(match) match = protlib.search_prototype(self.prot['prototype_key']) self.assertEqual(match, [self.prot]) @override_settings(PROT_FUNC_MODULES=['evennia.prototypes.protfuncs'], CLIENT_DEFAULT_WIDTH=20) class TestProtFuncs(EvenniaTest): def setUp(self): super(TestProtFuncs, self).setUp() self.prot = {"prototype_key": "test_prototype", "prototype_desc": "testing prot", "key": "ExampleObj"} @mock.patch("evennia.prototypes.protfuncs.base_random", new=mock.MagicMock(return_value=0.5)) @mock.patch("evennia.prototypes.protfuncs.base_randint", new=mock.MagicMock(return_value=5)) def test_protfuncs(self): self.assertEqual(protlib.protfunc_parser("$random()"), 0.5) self.assertEqual(protlib.protfunc_parser("$randint(1, 10)"), 5) self.assertEqual(protlib.protfunc_parser("$left_justify( foo )"), "foo ") self.assertEqual(protlib.protfunc_parser("$right_justify( foo )"), " foo") self.assertEqual(protlib.protfunc_parser("$center_justify(foo )"), " foo ") self.assertEqual(protlib.protfunc_parser( "$full_justify(foo bar moo too)"), 'foo bar moo too') self.assertEqual( protlib.protfunc_parser("$right_justify( foo )", testing=True), ('unexpected indent (<unknown>, line 1)', ' foo')) test_prot = {"key1": "value1", "key2": 2} self.assertEqual(protlib.protfunc_parser( "$protkey(key1)", testing=True, prototype=test_prot), (None, "value1")) self.assertEqual(protlib.protfunc_parser( "$protkey(key2)", testing=True, prototype=test_prot), (None, 2)) self.assertEqual(protlib.protfunc_parser("$add(1, 2)"), 3) self.assertEqual(protlib.protfunc_parser("$add(10, 25)"), 35) self.assertEqual(protlib.protfunc_parser( "$add('''[1,2,3]''', '''[4,5,6]''')"), [1, 2, 3, 4, 5, 6]) self.assertEqual(protlib.protfunc_parser("$add(foo, bar)"), "foo bar") self.assertEqual(protlib.protfunc_parser("$sub(5, 2)"), 3) self.assertRaises(TypeError, protlib.protfunc_parser, "$sub(5, test)") self.assertEqual(protlib.protfunc_parser("$mult(5, 2)"), 10) self.assertEqual(protlib.protfunc_parser("$mult( 5 , 10)"), 50) self.assertEqual(protlib.protfunc_parser("$mult('foo',3)"), "foofoofoo") self.assertEqual(protlib.protfunc_parser("$mult(foo,3)"), "foofoofoo") self.assertRaises(TypeError, protlib.protfunc_parser, "$mult(foo, foo)") self.assertEqual(protlib.protfunc_parser("$toint(5.3)"), 5) self.assertEqual(protlib.protfunc_parser("$div(5, 2)"), 2.5) self.assertEqual(protlib.protfunc_parser("$toint($div(5, 2))"), 2) self.assertEqual(protlib.protfunc_parser("$sub($add(5, 3), $add(10, 2))"), -4) self.assertEqual(protlib.protfunc_parser("$eval('2')"), '2') self.assertEqual(protlib.protfunc_parser( "$eval(['test', 1, '2', 3.5, \"foo\"])"), ['test', 1, '2', 3.5, 'foo']) self.assertEqual(protlib.protfunc_parser( "$eval({'test': '1', 2:3, 3: $toint(3.5)})"), {'test': '1', 2: 3, 3: 3}) # no object search odbref = self.obj1.dbref with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("obj({})".format(odbref), session=self.session), 'obj({})'.format(odbref)) mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("dbref({})".format(odbref), session=self.session), 'dbref({})'.format(odbref)) mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("stone(#12345)", session=self.session), 'stone(#12345)') mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser(odbref, session=self.session), odbref) mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("#12345", session=self.session), '#12345') mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("nothing({})".format(odbref), session=self.session), 'nothing({})'.format(odbref)) mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("(#12345)", session=self.session), '(#12345)') mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("obj(Char)", session=self.session), 'obj(Char)') mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("objlist({})".format(odbref), session=self.session), 'objlist({})'.format(odbref)) mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("dbref(Char)", session=self.session), 'dbref(Char)') mocked__obj_search.assert_not_called() # obj search happens with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("$objlist({})".format(odbref), session=self.session), [odbref]) mocked__obj_search.assert_called_once() assert (odbref,) == mocked__obj_search.call_args[0] with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("$obj({})".format(odbref), session=self.session), odbref) mocked__obj_search.assert_called_once() assert (odbref,) == mocked__obj_search.call_args[0] with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("$dbref({})".format(odbref), session=self.session), odbref) mocked__obj_search.assert_called_once() assert (odbref,) == mocked__obj_search.call_args[0] cdbref = self.char1.dbref with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("$obj(Char)", session=self.session), cdbref) mocked__obj_search.assert_called_once() assert ('Char',) == mocked__obj_search.call_args[0] # bad invocation with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertEqual(protlib.protfunc_parser("$badfunc(#112345)", session=self.session), '<UNKNOWN>') mocked__obj_search.assert_not_called() with mock.patch("evennia.prototypes.protfuncs._obj_search", wraps=protofuncs._obj_search) as mocked__obj_search: self.assertRaises(ValueError, protlib.protfunc_parser, "$dbref(Char)") mocked__obj_search.assert_not_called() self.assertEqual(protlib.value_to_obj( protlib.protfunc_parser(cdbref, session=self.session)), self.char1) self.assertEqual(protlib.value_to_obj_or_any( protlib.protfunc_parser(cdbref, session=self.session)), self.char1) self.assertEqual(protlib.value_to_obj_or_any( protlib.protfunc_parser("[1,2,3,'{}',5]".format(cdbref), session=self.session)), [1, 2, 3, self.char1, 5]) class TestPrototypeStorage(EvenniaTest): def setUp(self): super(TestPrototypeStorage, self).setUp() self.maxDiff = None self.prot1 = spawner.prototype_from_object(self.obj1) self.prot1['prototype_key'] = 'testprototype1' self.prot1['prototype_desc'] = 'testdesc1' self.prot1['prototype_tags'] = [('foo1', _PROTOTYPE_TAG_META_CATEGORY)] self.prot2 = self.prot1.copy() self.prot2['prototype_key'] = 'testprototype2' self.prot2['prototype_desc'] = 'testdesc2' self.prot2['prototype_tags'] = [('foo1', _PROTOTYPE_TAG_META_CATEGORY)] self.prot3 = self.prot2.copy() self.prot3['prototype_key'] = 'testprototype3' self.prot3['prototype_desc'] = 'testdesc3' self.prot3['prototype_tags'] = [('foo1', _PROTOTYPE_TAG_META_CATEGORY)] def test_prototype_storage(self): # from evennia import set_trace;set_trace(term_size=(180, 50)) prot1 = protlib.create_prototype(self.prot1) self.assertTrue(bool(prot1)) self.assertEqual(prot1, self.prot1) self.assertEqual(prot1['prototype_desc'], "testdesc1") self.assertEqual(prot1['prototype_tags'], [("foo1", _PROTOTYPE_TAG_META_CATEGORY)]) self.assertEqual( protlib.DbPrototype.objects.get_by_tag( "foo1", _PROTOTYPE_TAG_META_CATEGORY)[0].db.prototype, prot1) prot2 = protlib.create_prototype(self.prot2) self.assertEqual( [pobj.db.prototype for pobj in protlib.DbPrototype.objects.get_by_tag( "foo1", _PROTOTYPE_TAG_META_CATEGORY)], [prot1, prot2]) # add to existing prototype prot1b = protlib.create_prototype( {"prototype_key": 'testprototype1', "foo": 'bar', "prototype_tags": ['foo2']}) self.assertEqual( [pobj.db.prototype for pobj in protlib.DbPrototype.objects.get_by_tag( "foo2", _PROTOTYPE_TAG_META_CATEGORY)], [prot1b]) self.assertEqual(list(protlib.search_prototype("testprototype2")), [prot2]) self.assertNotEqual(list(protlib.search_prototype("testprototype1")), [prot1]) self.assertEqual(list(protlib.search_prototype("testprototype1")), [prot1b]) prot3 = protlib.create_prototype(self.prot3) # partial match with mock.patch("evennia.prototypes.prototypes._MODULE_PROTOTYPES", {}): self.assertEqual(list(protlib.search_prototype("prot")), [prot1b, prot2, prot3]) self.assertEqual(list(protlib.search_prototype(tags="foo1")), [prot1b, prot2, prot3]) self.assertTrue(str(str(protlib.list_prototypes(self.char1)))) class _MockMenu(object): pass class TestMenuModule(EvenniaTest): maxDiff = None def setUp(self): super(TestMenuModule, self).setUp() # set up fake store self.caller = self.char1 menutree = _MockMenu() self.caller.ndb._menutree = menutree self.test_prot = {"prototype_key": "test_prot", "typeclass": "evennia.objects.objects.DefaultObject", "prototype_locks": "edit:all();spawn:all()"} def test_helpers(self): caller = self.caller # general helpers self.assertEqual(olc_menus._get_menu_prototype(caller), {}) self.assertEqual(olc_menus._is_new_prototype(caller), True) self.assertEqual(olc_menus._set_menu_prototype(caller, {}), {}) self.assertEqual( olc_menus._set_prototype_value(caller, "key", "TestKey"), {"key": "TestKey"}) self.assertEqual(olc_menus._get_menu_prototype(caller), {"key": "TestKey"}) self.assertEqual(olc_menus._format_option_value( "key", required=True, prototype=olc_menus._get_menu_prototype(caller)), " (TestKey|n)") self.assertEqual(olc_menus._format_option_value( [1, 2, 3, "foo"], required=True), ' (1, 2, 3, foo|n)') self.assertEqual(olc_menus._set_property( caller, "ChangedKey", prop="key", processor=str, next_node="foo"), "foo") self.assertEqual(olc_menus._get_menu_prototype(caller), {"key": "ChangedKey"}) self.assertEqual(olc_menus._wizard_options( "ThisNode", "PrevNode", "NextNode"), [{'goto': 'node_PrevNode', 'key': ('|wB|Wack', 'b'), 'desc': '|W(PrevNode)|n'}, {'goto': 'node_NextNode', 'key': ('|wF|Worward', 'f'), 'desc': '|W(NextNode)|n'}, {'goto': 'node_index', 'key': ('|wI|Wndex', 'i')}, {'goto': ('node_validate_prototype', {'back': 'ThisNode'}), 'key': ('|wV|Walidate prototype', 'validate', 'v')}]) self.assertEqual(olc_menus._validate_prototype(self.test_prot), (False, Something)) self.assertEqual(olc_menus._validate_prototype( {"prototype_key": "testthing", "key": "mytest"}), (True, Something)) choices = ["test1", "test2", "test3", "test4"] actions = (("examine", "e", "l"), ("add", "a"), ("foo", "f")) self.assertEqual(olc_menus._default_parse("l4", choices, *actions), ('test4', 'examine')) self.assertEqual(olc_menus._default_parse("add 2", choices, *actions), ('test2', 'add')) self.assertEqual(olc_menus._default_parse("foo3", choices, *actions), ('test3', 'foo')) self.assertEqual(olc_menus._default_parse("f3", choices, *actions), ('test3', 'foo')) self.assertEqual(olc_menus._default_parse("f5", choices, *actions), (None, None)) def test_node_helpers(self): caller = self.caller with mock.patch("evennia.prototypes.menus.protlib.search_prototype", new=mock.MagicMock(return_value=[self.test_prot])): # prototype_key helpers self.assertEqual(olc_menus._check_prototype_key(caller, "test_prot"), None) caller.ndb._menutree.olc_new = True self.assertEqual(olc_menus._check_prototype_key(caller, "test_prot"), "node_index") # prototype_parent helpers self.assertEqual(olc_menus._all_prototype_parents(caller), ['test_prot']) # self.assertEqual(olc_menus._prototype_parent_parse( # caller, 'test_prot'), # "|cprototype key:|n test_prot, |ctags:|n None, |clocks:|n edit:all();spawn:all() " # "\n|cdesc:|n None \n|cprototype:|n " # "{\n 'typeclass': 'evennia.objects.objects.DefaultObject', \n}") with mock.patch("evennia.prototypes.menus.protlib.search_prototype", new=mock.MagicMock(return_value=[_PROTPARENTS['GOBLIN']])): self.assertEqual(olc_menus._prototype_parent_select(caller, "goblin"), "node_prototype_parent") self.assertEqual(olc_menus._get_menu_prototype(caller), {'prototype_key': 'test_prot', 'prototype_locks': 'edit:all();spawn:all()', 'prototype_parent': 'goblin', 'typeclass': 'evennia.objects.objects.DefaultObject'}) # typeclass helpers with mock.patch("evennia.utils.utils.get_all_typeclasses", new=mock.MagicMock(return_value={"foo": None, "bar": None})): self.assertEqual(olc_menus._all_typeclasses(caller), ["bar", "foo"]) self.assertEqual(olc_menus._typeclass_select( caller, "evennia.objects.objects.DefaultObject"), None) # prototype_parent should be popped off here self.assertEqual(olc_menus._get_menu_prototype(caller), {'prototype_key': 'test_prot', 'prototype_locks': 'edit:all();spawn:all()', 'prototype_parent': 'goblin', 'typeclass': 'evennia.objects.objects.DefaultObject'}) # attr helpers self.assertEqual(olc_menus._caller_attrs(caller), []) self.assertEqual(olc_menus._add_attr(caller, "test1=foo1"), Something) self.assertEqual(olc_menus._add_attr(caller, "test2;cat1=foo2"), Something) self.assertEqual(olc_menus._add_attr(caller, "test3;cat2;edit:false()=foo3"), Something) self.assertEqual(olc_menus._add_attr(caller, "test4;cat3;set:true();edit:false()=foo4"), Something) self.assertEqual(olc_menus._add_attr(caller, "test5;cat4;set:true();edit:false()=123"), Something) self.assertEqual(olc_menus._add_attr(caller, "test1=foo1_changed"), Something) self.assertEqual(olc_menus._get_menu_prototype(caller)['attrs'], [("test1", "foo1_changed", None, ''), ("test2", "foo2", "cat1", ''), ("test3", "foo3", "cat2", "edit:false()"), ("test4", "foo4", "cat3", "set:true();edit:false()"), ("test5", '123', "cat4", "set:true();edit:false()")]) # tag helpers self.assertEqual(olc_menus._caller_tags(caller), []) self.assertEqual(olc_menus._add_tag(caller, "foo1"), Something) self.assertEqual(olc_menus._add_tag(caller, "foo2;cat1"), Something) self.assertEqual(olc_menus._add_tag(caller, "foo3;cat2;dat1"), Something) self.assertEqual(olc_menus._caller_tags(caller), ['foo1', 'foo2', 'foo3']) self.assertEqual(olc_menus._get_menu_prototype(caller)['tags'], [('foo1', None, ""), ('foo2', 'cat1', ""), ('foo3', 'cat2', "dat1")]) self.assertEqual(olc_menus._add_tag(caller, "foo1", delete=True), "Removed Tag 'foo1'.") self.assertEqual(olc_menus._get_menu_prototype(caller)['tags'], [('foo2', 'cat1', ""), ('foo3', 'cat2', "dat1")]) self.assertEqual(olc_menus._display_tag(olc_menus._get_menu_prototype(caller)['tags'][0]), Something) self.assertEqual(olc_menus._caller_tags(caller), ["foo2", "foo3"]) protlib.save_prototype(self.test_prot) # locks helpers self.assertEqual(olc_menus._lock_add(caller, "foo:false()"), "Added lock 'foo:false()'.") self.assertEqual(olc_menus._lock_add(caller, "foo2:false()"), "Added lock 'foo2:false()'.") self.assertEqual(olc_menus._lock_add(caller, "foo2:true()"), "Lock with locktype 'foo2' updated.") self.assertEqual(olc_menus._get_menu_prototype(caller)["locks"], "foo:false();foo2:true()") # perm helpers self.assertEqual(olc_menus._add_perm(caller, "foo"), "Added Permission 'foo'") self.assertEqual(olc_menus._add_perm(caller, "foo2"), "Added Permission 'foo2'") self.assertEqual(olc_menus._get_menu_prototype(caller)["permissions"], ["foo", "foo2"]) # prototype_tags helpers self.assertEqual(olc_menus._add_prototype_tag(caller, "foo"), "Added Prototype-Tag 'foo'.") self.assertEqual(olc_menus._add_prototype_tag(caller, "foo2"), "Added Prototype-Tag 'foo2'.") self.assertEqual(olc_menus._get_menu_prototype(caller)["prototype_tags"], ["foo", "foo2"]) # spawn helpers with mock.patch("evennia.prototypes.menus.protlib.search_prototype", new=mock.MagicMock(return_value=[_PROTPARENTS['GOBLIN']])): self.assertEqual(olc_menus._spawn(caller, prototype=self.test_prot), Something) obj = caller.contents[0] self.assertEqual(obj.typeclass_path, "evennia.objects.objects.DefaultObject") self.assertEqual(obj.tags.get(category=spawner._PROTOTYPE_TAG_CATEGORY), self.test_prot['prototype_key']) # update helpers self.assertEqual(olc_menus._apply_diff( caller, prototype=self.test_prot, back_node="foo", objects=[obj]), 'foo') # no changes to apply self.test_prot['key'] = "updated key" # change prototype self.assertEqual(olc_menus._apply_diff( caller, prototype=self.test_prot, objects=[obj], back_node='foo'), 'foo') # apply change to the one obj # load helpers self.assertEqual(olc_menus._prototype_load_select(caller, self.test_prot['prototype_key']), ('node_examine_entity', {'text': '|gLoaded prototype test_prot.|n', 'back': 'index'}) ) # diff helpers obj_diff = { 'attrs': { 'desc': (('desc', 'This is User #1.', None, ''), ('desc', 'This is User #1.', None, ''), 'KEEP'), 'foo': (None, ('foo', 'bar', None, ''), 'ADD'), 'prelogout_location': (('prelogout_location', "#2", None, ''), ('prelogout_location', "#2", None, ''), 'KEEP')}, 'home': ('#2', '#2', 'KEEP'), 'key': ('TestChar', 'TestChar', 'KEEP'), 'locks': ('boot:false();call:false();control:perm(Developer);delete:false();' 'edit:false();examine:perm(Developer);get:false();msg:all();' 'puppet:false();tell:perm(Admin);view:all()', 'boot:false();call:false();control:perm(Developer);delete:false();' 'edit:false();examine:perm(Developer);get:false();msg:all();' 'puppet:false();tell:perm(Admin);view:all()', 'KEEP'), 'permissions': {'developer': ('developer', 'developer', 'KEEP')}, 'prototype_desc': ('Testobject build', None, 'REMOVE'), 'prototype_key': ('TestDiffKey', 'TestDiffKey', 'KEEP'), 'prototype_locks': ('spawn:all();edit:all()', 'spawn:all();edit:all()', 'KEEP'), 'prototype_tags': {}, 'tags': {'foo': (None, ('foo', None, ''), 'ADD')}, 'typeclass': ('typeclasses.characters.Character', 'typeclasses.characters.Character', 'KEEP')} texts, options = olc_menus._format_diff_text_and_options(obj_diff) self.assertEqual( "\n".join(texts), '- |wattrs:|n \n' ' |gKEEP|W:|n desc |W=|n This is User #1. |W(category:|n None|W, locks:|n |W)|n\n' ' |c[1] |yADD|n|W:|n None |W->|n foo |W=|n bar |W(category:|n None|W, locks:|n |W)|n\n' ' |gKEEP|W:|n prelogout_location |W=|n #2 |W(category:|n None|W, locks:|n |W)|n\n' '- |whome:|n |gKEEP|W:|n #2\n' '- |wkey:|n |gKEEP|W:|n TestChar\n' '- |wlocks:|n |gKEEP|W:|n boot:false();call:false();control:perm(Developer);delete:false();edit:false();examine:perm(Developer);get:false();msg:all();puppet:false();tell:perm(Admin);view:all()\n' '- |wpermissions:|n \n' ' |gKEEP|W:|n developer\n' '- |wprototype_desc:|n |c[2] |rREMOVE|n|W:|n Testobject build |W->|n None\n' '- |wprototype_key:|n |gKEEP|W:|n TestDiffKey\n' '- |wprototype_locks:|n |gKEEP|W:|n spawn:all();edit:all()\n' '- |wprototype_tags:|n \n' '- |wtags:|n \n' ' |c[3] |yADD|n|W:|n None |W->|n foo |W(category:|n None|W)|n\n' '- |wtypeclass:|n |gKEEP|W:|n typeclasses.characters.Character') self.assertEqual( options, [{'goto': (Something, Something), 'key': '1', 'desc': '|gKEEP|n (attrs) None'}, {'goto': (Something, Something), 'key': '2', 'desc': '|gKEEP|n (prototype_desc) Testobject build'}, {'goto': (Something, Something), 'key': '3', 'desc': '|gKEEP|n (tags) None'}]) @mock.patch("evennia.prototypes.menus.protlib.search_prototype", new=mock.MagicMock( return_value=[{"prototype_key": "TestPrototype", "typeclass": "TypeClassTest", "key": "TestObj"}])) @mock.patch("evennia.utils.utils.get_all_typeclasses", new=mock.MagicMock( return_value={"TypeclassTest": None})) class TestOLCMenu(TestEvMenu): maxDiff = None menutree = "evennia.prototypes.menus" startnode = "node_index" # debug_output = True expect_all_nodes = True expected_node_texts = { "node_index": "|c --- Prototype wizard --- |n" } expected_tree = ['node_index', ['node_prototype_key', ['node_index', 'node_index', 'node_index', 'node_validate_prototype', ['node_index', 'node_index', 'node_index'], 'node_index'], 'node_prototype_parent', ['node_prototype_parent', 'node_prototype_key', 'node_prototype_parent', 'node_index', 'node_validate_prototype', 'node_index'], 'node_typeclass', ['node_typeclass', 'node_prototype_parent', 'node_typeclass', 'node_index', 'node_validate_prototype', 'node_index'], 'node_key', ['node_typeclass', 'node_key', 'node_index', 'node_validate_prototype', 'node_index'], 'node_aliases', ['node_key', 'node_aliases', 'node_index', 'node_validate_prototype', 'node_index'], 'node_attrs', ['node_aliases', 'node_attrs', 'node_index', 'node_validate_prototype', 'node_index'], 'node_tags', ['node_attrs', 'node_tags', 'node_index', 'node_validate_prototype', 'node_index'], 'node_locks', ['node_tags', 'node_locks', 'node_index', 'node_validate_prototype', 'node_index'], 'node_permissions', ['node_locks', 'node_permissions', 'node_index', 'node_validate_prototype', 'node_index'], 'node_location', ['node_permissions', 'node_location', 'node_index', 'node_validate_prototype', 'node_index', 'node_index'], 'node_home', ['node_location', 'node_home', 'node_index', 'node_validate_prototype', 'node_index', 'node_index'], 'node_destination', ['node_home', 'node_destination', 'node_index', 'node_validate_prototype', 'node_index', 'node_index'], 'node_prototype_desc', ['node_prototype_key', 'node_prototype_parent', 'node_index', 'node_validate_prototype', 'node_index'], 'node_prototype_tags', ['node_prototype_desc', 'node_prototype_tags', 'node_index', 'node_validate_prototype', 'node_index'], 'node_prototype_locks', ['node_prototype_tags', 'node_prototype_locks', 'node_index', 'node_validate_prototype', 'node_index'], 'node_validate_prototype', 'node_index', 'node_prototype_spawn', ['node_index', 'node_index', 'node_validate_prototype'], 'node_index', 'node_search_object', ['node_index', 'node_index', 'node_index']]]
[ "evennia.prototypes.menus._set_prototype_value", "evennia.prototypes.menus._add_attr", "evennia.prototypes.menus._validate_prototype", "evennia.prototypes.menus._all_typeclasses", "evennia.prototypes.menus._default_parse", "evennia.prototypes.spawner.spawn", "evennia.prototypes.menus._format_option_valu...
[((12359, 12457), 'django.test.utils.override_settings', 'override_settings', ([], {'PROT_FUNC_MODULES': "['evennia.prototypes.protfuncs']", 'CLIENT_DEFAULT_WIDTH': '(20)'}), "(PROT_FUNC_MODULES=['evennia.prototypes.protfuncs'],\n CLIENT_DEFAULT_WIDTH=20)\n", (12376, 12457), False, 'from django.test.utils import override_settings\n'), ((1654, 1679), 'evennia.prototypes.spawner.spawn', 'spawner.spawn', (['self.prot1'], {}), '(self.prot1)\n', (1667, 1679), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((2108, 2142), 'evennia.prototypes.prototypes.save_prototype', 'protlib.save_prototype', (['self.prot1'], {}), '(self.prot1)\n', (2130, 2142), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((2158, 2200), 'evennia.prototypes.spawner.spawn', 'spawner.spawn', (["self.prot1['prototype_key']"], {}), "(self.prot1['prototype_key'])\n", (2171, 2200), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((2742, 2782), 'evennia.prototypes.spawner.prototype_from_object', 'spawner.prototype_from_object', (['self.obj1'], {}), '(self.obj1)\n', (2771, 2782), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((3884, 3924), 'evennia.prototypes.spawner.prototype_from_object', 'spawner.prototype_from_object', (['self.obj1'], {}), '(self.obj1)\n', (3913, 3924), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((4633, 4688), 'evennia.prototypes.spawner.prototype_diff_from_object', 'spawner.prototype_diff_from_object', (['old_prot', 'self.obj1'], {}), '(old_prot, self.obj1)\n', (4667, 4688), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((9680, 9771), 'evennia.prototypes.spawner.batch_update_objects_with_prototype', 'spawner.batch_update_objects_with_prototype', (['old_prot'], {'diff': 'pdiff', 'objects': '[self.obj1]'}), '(old_prot, diff=pdiff, objects=[\n self.obj1])\n', (9723, 9771), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((9835, 9875), 'evennia.prototypes.spawner.prototype_from_object', 'spawner.prototype_from_object', (['self.obj1'], {}), '(self.obj1)\n', (9864, 9875), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((11480, 11520), 'evennia.prototypes.spawner.prototype_from_object', 'spawner.prototype_from_object', (['self.obj1'], {}), '(self.obj1)\n', (11509, 11520), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((11576, 11611), 'evennia.prototypes.prototypes.prototype_to_str', 'protlib.prototype_to_str', (['self.prot'], {}), '(self.prot)\n', (11600, 11611), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((11780, 11813), 'evennia.prototypes.prototypes.save_prototype', 'protlib.save_prototype', (['self.prot'], {}), '(self.prot)\n', (11802, 11813), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((12049, 12082), 'evennia.prototypes.prototypes.save_prototype', 'protlib.save_prototype', (['self.prot'], {}), '(self.prot)\n', (12071, 12082), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((12099, 12135), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['"""NotFound"""'], {}), "('NotFound')\n", (12123, 12135), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((12184, 12210), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', ([], {}), '()\n', (12208, 12210), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((12258, 12310), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (["self.prot['prototype_key']"], {}), "(self.prot['prototype_key'])\n", (12282, 12310), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((21091, 21131), 'evennia.prototypes.spawner.prototype_from_object', 'spawner.prototype_from_object', (['self.obj1'], {}), '(self.obj1)\n', (21120, 21131), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((21897, 21933), 'evennia.prototypes.prototypes.create_prototype', 'protlib.create_prototype', (['self.prot1'], {}), '(self.prot1)\n', (21921, 21933), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((22346, 22382), 'evennia.prototypes.prototypes.create_prototype', 'protlib.create_prototype', (['self.prot2'], {}), '(self.prot2)\n', (22370, 22382), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((22644, 22751), 'evennia.prototypes.prototypes.create_prototype', 'protlib.create_prototype', (["{'prototype_key': 'testprototype1', 'foo': 'bar', 'prototype_tags': ['foo2']}"], {}), "({'prototype_key': 'testprototype1', 'foo': 'bar',\n 'prototype_tags': ['foo2']})\n", (22668, 22751), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((23237, 23273), 'evennia.prototypes.prototypes.create_prototype', 'protlib.create_prototype', (['self.prot3'], {}), '(self.prot3)\n', (23261, 23273), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((30838, 30876), 'evennia.prototypes.prototypes.save_prototype', 'protlib.save_prototype', (['self.test_prot'], {}), '(self.test_prot)\n', (30860, 30876), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((34832, 34881), 'evennia.prototypes.menus._format_diff_text_and_options', 'olc_menus._format_diff_text_and_options', (['obj_diff'], {}), '(obj_diff)\n', (34871, 34881), True, 'from evennia.prototypes import menus as olc_menus\n'), ((36608, 36725), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': "[{'prototype_key': 'TestPrototype', 'typeclass': 'TypeClassTest', 'key':\n 'TestObj'}]"}), "(return_value=[{'prototype_key': 'TestPrototype', 'typeclass':\n 'TypeClassTest', 'key': 'TestObj'}])\n", (36622, 36725), False, 'import mock\n'), ((36804, 36856), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': "{'TypeclassTest': None}"}), "(return_value={'TypeclassTest': None})\n", (36818, 36856), False, 'import mock\n'), ((723, 736), 'random.randint', 'randint', (['(1)', '(1)'], {}), '(1, 1)\n', (730, 736), False, 'from random import randint\n'), ((9162, 9189), 'evennia.prototypes.spawner.flatten_diff', 'spawner.flatten_diff', (['pdiff'], {}), '(pdiff)\n', (9182, 9189), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((12957, 12993), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$random()"""'], {}), "('$random()')\n", (12980, 12993), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13025, 13067), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$randint(1, 10)"""'], {}), "('$randint(1, 10)')\n", (13048, 13067), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13097, 13146), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$left_justify( foo )"""'], {}), "('$left_justify( foo )')\n", (13120, 13146), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13197, 13246), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$right_justify( foo )"""'], {}), "('$right_justify( foo )')\n", (13220, 13246), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13297, 13346), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$center_justify(foo )"""'], {}), "('$center_justify(foo )')\n", (13320, 13346), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13397, 13454), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$full_justify(foo bar moo too)"""'], {}), "('$full_justify(foo bar moo too)')\n", (13420, 13454), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13531, 13594), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$right_justify( foo )"""'], {'testing': '(True)'}), "('$right_justify( foo )', testing=True)\n", (13554, 13594), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13773, 13849), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$protkey(key1)"""'], {'testing': '(True)', 'prototype': 'test_prot'}), "('$protkey(key1)', testing=True, prototype=test_prot)\n", (13796, 13849), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((13907, 13983), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$protkey(key2)"""'], {'testing': '(True)', 'prototype': 'test_prot'}), "('$protkey(key2)', testing=True, prototype=test_prot)\n", (13930, 13983), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14035, 14072), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$add(1, 2)"""'], {}), "('$add(1, 2)')\n", (14058, 14072), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14102, 14141), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$add(10, 25)"""'], {}), "('$add(10, 25)')\n", (14125, 14141), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14172, 14233), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$add(\'\'\'[1,2,3]\'\'\', \'\'\'[4,5,6]\'\'\')"""'], {}), '("$add(\'\'\'[1,2,3]\'\'\', \'\'\'[4,5,6]\'\'\')")\n', (14195, 14233), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14293, 14334), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$add(foo, bar)"""'], {}), "('$add(foo, bar)')\n", (14316, 14334), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14373, 14410), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$sub(5, 2)"""'], {}), "('$sub(5, 2)')\n", (14396, 14410), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14520, 14558), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$mult(5, 2)"""'], {}), "('$mult(5, 2)')\n", (14543, 14558), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14589, 14633), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$mult( 5 , 10)"""'], {}), "('$mult( 5 , 10)')\n", (14612, 14633), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14664, 14705), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$mult(\'foo\',3)"""'], {}), '("$mult(\'foo\',3)")\n', (14687, 14705), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14745, 14784), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$mult(foo,3)"""'], {}), "('$mult(foo,3)')\n", (14768, 14784), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14906, 14944), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$toint(5.3)"""'], {}), "('$toint(5.3)')\n", (14929, 14944), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((14975, 15012), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$div(5, 2)"""'], {}), "('$div(5, 2)')\n", (14998, 15012), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((15044, 15089), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$toint($div(5, 2))"""'], {}), "('$toint($div(5, 2))')\n", (15067, 15089), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((15119, 15175), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$sub($add(5, 3), $add(10, 2))"""'], {}), "('$sub($add(5, 3), $add(10, 2))')\n", (15142, 15175), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((15207, 15244), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$eval(\'2\')"""'], {}), '("$eval(\'2\')")\n', (15230, 15244), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((15277, 15343), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$eval([\'test\', 1, \'2\', 3.5, "foo"])"""'], {}), '(\'$eval([\\\'test\\\', 1, \\\'2\\\', 3.5, "foo"])\')\n', (15300, 15343), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((15411, 15479), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$eval({\'test\': \'1\', 2:3, 3: $toint(3.5)})"""'], {}), '("$eval({\'test\': \'1\', 2:3, 3: $toint(3.5)})")\n', (15434, 15479), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((15597, 15686), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (15607, 15686), False, 'import mock\n'), ((15898, 15987), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (15908, 15987), False, 'import mock\n'), ((16203, 16292), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (16213, 16292), False, 'import mock\n'), ((16486, 16575), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (16496, 16575), False, 'import mock\n'), ((16751, 16840), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (16761, 16840), False, 'import mock\n'), ((17020, 17109), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (17030, 17109), False, 'import mock\n'), ((17329, 17418), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (17339, 17418), False, 'import mock\n'), ((17602, 17691), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (17612, 17691), False, 'import mock\n'), ((17877, 17966), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (17887, 17966), False, 'import mock\n'), ((18186, 18275), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (18196, 18275), False, 'import mock\n'), ((18496, 18585), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (18506, 18585), False, 'import mock\n'), ((18851, 18940), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (18861, 18940), False, 'import mock\n'), ((19200, 19289), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (19210, 19289), False, 'import mock\n'), ((19586, 19675), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (19596, 19675), False, 'import mock\n'), ((19949, 20038), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (19959, 20038), False, 'import mock\n'), ((20232, 20321), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.protfuncs._obj_search"""'], {'wraps': 'protofuncs._obj_search'}), "('evennia.prototypes.protfuncs._obj_search', wraps=protofuncs.\n _obj_search)\n", (20242, 20321), False, 'import mock\n'), ((12771, 12803), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': '(0.5)'}), '(return_value=0.5)\n', (12785, 12803), False, 'import mock\n'), ((12870, 12900), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': '(5)'}), '(return_value=5)\n', (12884, 12900), False, 'import mock\n'), ((23312, 23378), 'mock.patch', 'mock.patch', (['"""evennia.prototypes.prototypes._MODULE_PROTOTYPES"""', '{}'], {}), "('evennia.prototypes.prototypes._MODULE_PROTOTYPES', {})\n", (23322, 23378), False, 'import mock\n'), ((24260, 24297), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (24289, 24297), True, 'from evennia.prototypes import menus as olc_menus\n'), ((24328, 24363), 'evennia.prototypes.menus._is_new_prototype', 'olc_menus._is_new_prototype', (['caller'], {}), '(caller)\n', (24355, 24363), True, 'from evennia.prototypes import menus as olc_menus\n'), ((24397, 24438), 'evennia.prototypes.menus._set_menu_prototype', 'olc_menus._set_menu_prototype', (['caller', '{}'], {}), '(caller, {})\n', (24426, 24438), True, 'from evennia.prototypes import menus as olc_menus\n'), ((24483, 24539), 'evennia.prototypes.menus._set_prototype_value', 'olc_menus._set_prototype_value', (['caller', '"""key"""', '"""TestKey"""'], {}), "(caller, 'key', 'TestKey')\n", (24513, 24539), True, 'from evennia.prototypes import menus as olc_menus\n'), ((24586, 24623), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (24615, 24623), True, 'from evennia.prototypes import menus as olc_menus\n'), ((24828, 24891), 'evennia.prototypes.menus._format_option_value', 'olc_menus._format_option_value', (["[1, 2, 3, 'foo']"], {'required': '(True)'}), "([1, 2, 3, 'foo'], required=True)\n", (24858, 24891), True, 'from evennia.prototypes import menus as olc_menus\n'), ((24953, 25046), 'evennia.prototypes.menus._set_property', 'olc_menus._set_property', (['caller', '"""ChangedKey"""'], {'prop': '"""key"""', 'processor': 'str', 'next_node': '"""foo"""'}), "(caller, 'ChangedKey', prop='key', processor=str,\n next_node='foo')\n", (24976, 25046), True, 'from evennia.prototypes import menus as olc_menus\n'), ((25089, 25126), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (25118, 25126), True, 'from evennia.prototypes import menus as olc_menus\n'), ((25177, 25238), 'evennia.prototypes.menus._wizard_options', 'olc_menus._wizard_options', (['"""ThisNode"""', '"""PrevNode"""', '"""NextNode"""'], {}), "('ThisNode', 'PrevNode', 'NextNode')\n", (25202, 25238), True, 'from evennia.prototypes import menus as olc_menus\n'), ((25674, 25719), 'evennia.prototypes.menus._validate_prototype', 'olc_menus._validate_prototype', (['self.test_prot'], {}), '(self.test_prot)\n', (25703, 25719), True, 'from evennia.prototypes import menus as olc_menus\n'), ((25766, 25844), 'evennia.prototypes.menus._validate_prototype', 'olc_menus._validate_prototype', (["{'prototype_key': 'testthing', 'key': 'mytest'}"], {}), "({'prototype_key': 'testthing', 'key': 'mytest'})\n", (25795, 25844), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26041, 26090), 'evennia.prototypes.menus._default_parse', 'olc_menus._default_parse', (['"""l4"""', 'choices', '*actions'], {}), "('l4', choices, *actions)\n", (26065, 26090), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26139, 26191), 'evennia.prototypes.menus._default_parse', 'olc_menus._default_parse', (['"""add 2"""', 'choices', '*actions'], {}), "('add 2', choices, *actions)\n", (26163, 26191), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26236, 26287), 'evennia.prototypes.menus._default_parse', 'olc_menus._default_parse', (['"""foo3"""', 'choices', '*actions'], {}), "('foo3', choices, *actions)\n", (26260, 26287), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26332, 26381), 'evennia.prototypes.menus._default_parse', 'olc_menus._default_parse', (['"""f3"""', 'choices', '*actions'], {}), "('f3', choices, *actions)\n", (26356, 26381), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26426, 26475), 'evennia.prototypes.menus._default_parse', 'olc_menus._default_parse', (['"""f5"""', 'choices', '*actions'], {}), "('f5', choices, *actions)\n", (26450, 26475), True, 'from evennia.prototypes import menus as olc_menus\n'), ((27745, 27782), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (27774, 27782), True, 'from evennia.prototypes import menus as olc_menus\n'), ((28338, 28414), 'evennia.prototypes.menus._typeclass_select', 'olc_menus._typeclass_select', (['caller', '"""evennia.objects.objects.DefaultObject"""'], {}), "(caller, 'evennia.objects.objects.DefaultObject')\n", (28365, 28414), True, 'from evennia.prototypes import menus as olc_menus\n'), ((28513, 28550), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (28542, 28550), True, 'from evennia.prototypes import menus as olc_menus\n'), ((28865, 28896), 'evennia.prototypes.menus._caller_attrs', 'olc_menus._caller_attrs', (['caller'], {}), '(caller)\n', (28888, 28896), True, 'from evennia.prototypes import menus as olc_menus\n'), ((28927, 28968), 'evennia.prototypes.menus._add_attr', 'olc_menus._add_attr', (['caller', '"""test1=foo1"""'], {}), "(caller, 'test1=foo1')\n", (28946, 28968), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29006, 29052), 'evennia.prototypes.menus._add_attr', 'olc_menus._add_attr', (['caller', '"""test2;cat1=foo2"""'], {}), "(caller, 'test2;cat1=foo2')\n", (29025, 29052), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29090, 29149), 'evennia.prototypes.menus._add_attr', 'olc_menus._add_attr', (['caller', '"""test3;cat2;edit:false()=foo3"""'], {}), "(caller, 'test3;cat2;edit:false()=foo3')\n", (29109, 29149), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29187, 29257), 'evennia.prototypes.menus._add_attr', 'olc_menus._add_attr', (['caller', '"""test4;cat3;set:true();edit:false()=foo4"""'], {}), "(caller, 'test4;cat3;set:true();edit:false()=foo4')\n", (29206, 29257), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29295, 29364), 'evennia.prototypes.menus._add_attr', 'olc_menus._add_attr', (['caller', '"""test5;cat4;set:true();edit:false()=123"""'], {}), "(caller, 'test5;cat4;set:true();edit:false()=123')\n", (29314, 29364), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29402, 29451), 'evennia.prototypes.menus._add_attr', 'olc_menus._add_attr', (['caller', '"""test1=foo1_changed"""'], {}), "(caller, 'test1=foo1_changed')\n", (29421, 29451), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29869, 29899), 'evennia.prototypes.menus._caller_tags', 'olc_menus._caller_tags', (['caller'], {}), '(caller)\n', (29891, 29899), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29930, 29964), 'evennia.prototypes.menus._add_tag', 'olc_menus._add_tag', (['caller', '"""foo1"""'], {}), "(caller, 'foo1')\n", (29948, 29964), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30002, 30041), 'evennia.prototypes.menus._add_tag', 'olc_menus._add_tag', (['caller', '"""foo2;cat1"""'], {}), "(caller, 'foo2;cat1')\n", (30020, 30041), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30079, 30123), 'evennia.prototypes.menus._add_tag', 'olc_menus._add_tag', (['caller', '"""foo3;cat2;dat1"""'], {}), "(caller, 'foo3;cat2;dat1')\n", (30097, 30123), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30161, 30191), 'evennia.prototypes.menus._caller_tags', 'olc_menus._caller_tags', (['caller'], {}), '(caller)\n', (30183, 30191), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30424, 30471), 'evennia.prototypes.menus._add_tag', 'olc_menus._add_tag', (['caller', '"""foo1"""'], {'delete': '(True)'}), "(caller, 'foo1', delete=True)\n", (30442, 30471), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30779, 30809), 'evennia.prototypes.menus._caller_tags', 'olc_menus._caller_tags', (['caller'], {}), '(caller)\n', (30801, 30809), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30927, 30969), 'evennia.prototypes.menus._lock_add', 'olc_menus._lock_add', (['caller', '"""foo:false()"""'], {}), "(caller, 'foo:false()')\n", (30946, 30969), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31025, 31068), 'evennia.prototypes.menus._lock_add', 'olc_menus._lock_add', (['caller', '"""foo2:false()"""'], {}), "(caller, 'foo2:false()')\n", (31044, 31068), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31125, 31167), 'evennia.prototypes.menus._lock_add', 'olc_menus._lock_add', (['caller', '"""foo2:true()"""'], {}), "(caller, 'foo2:true()')\n", (31144, 31167), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31356, 31390), 'evennia.prototypes.menus._add_perm', 'olc_menus._add_perm', (['caller', '"""foo"""'], {}), "(caller, 'foo')\n", (31375, 31390), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31443, 31478), 'evennia.prototypes.menus._add_perm', 'olc_menus._add_perm', (['caller', '"""foo2"""'], {}), "(caller, 'foo2')\n", (31462, 31478), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31662, 31705), 'evennia.prototypes.menus._add_prototype_tag', 'olc_menus._add_prototype_tag', (['caller', '"""foo"""'], {}), "(caller, 'foo')\n", (31690, 31705), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31762, 31806), 'evennia.prototypes.menus._add_prototype_tag', 'olc_menus._add_prototype_tag', (['caller', '"""foo2"""'], {}), "(caller, 'foo2')\n", (31790, 31806), True, 'from evennia.prototypes import menus as olc_menus\n'), ((32501, 32592), 'evennia.prototypes.menus._apply_diff', 'olc_menus._apply_diff', (['caller'], {'prototype': 'self.test_prot', 'back_node': '"""foo"""', 'objects': '[obj]'}), "(caller, prototype=self.test_prot, back_node='foo',\n objects=[obj])\n", (32522, 32592), True, 'from evennia.prototypes import menus as olc_menus\n'), ((32724, 32815), 'evennia.prototypes.menus._apply_diff', 'olc_menus._apply_diff', (['caller'], {'prototype': 'self.test_prot', 'objects': '[obj]', 'back_node': '"""foo"""'}), "(caller, prototype=self.test_prot, objects=[obj],\n back_node='foo')\n", (32745, 32815), True, 'from evennia.prototypes import menus as olc_menus\n'), ((32913, 32986), 'evennia.prototypes.menus._prototype_load_select', 'olc_menus._prototype_load_select', (['caller', "self.test_prot['prototype_key']"], {}), "(caller, self.test_prot['prototype_key'])\n", (32945, 32986), True, 'from evennia.prototypes import menus as olc_menus\n'), ((1761, 1815), 'evennia.prototypes.prototypes.search_objects_with_prototype', 'protlib.search_objects_with_prototype', (['"""testprototype"""'], {}), "('testprototype')\n", (1798, 1815), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((2231, 2285), 'evennia.prototypes.prototypes.search_objects_with_prototype', 'protlib.search_objects_with_prototype', (['"""testprototype"""'], {}), "('testprototype')\n", (2268, 2285), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((16340, 16402), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""stone(#12345)"""'], {'session': 'self.session'}), "('stone(#12345)', session=self.session)\n", (16363, 16402), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((16623, 16676), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['odbref'], {'session': 'self.session'}), '(odbref, session=self.session)\n', (16646, 16676), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((16888, 16943), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""#12345"""'], {'session': 'self.session'}), "('#12345', session=self.session)\n", (16911, 16943), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((17466, 17523), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""(#12345)"""'], {'session': 'self.session'}), "('(#12345)', session=self.session)\n", (17489, 17523), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((17739, 17797), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""obj(Char)"""'], {'session': 'self.session'}), "('obj(Char)', session=self.session)\n", (17762, 17797), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((18323, 18383), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""dbref(Char)"""'], {'session': 'self.session'}), "('dbref(Char)', session=self.session)\n", (18346, 18383), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((19723, 19782), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$obj(Char)"""'], {'session': 'self.session'}), "('$obj(Char)', session=self.session)\n", (19746, 19782), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((20086, 20152), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['"""$badfunc(#112345)"""'], {'session': 'self.session'}), "('$badfunc(#112345)', session=self.session)\n", (20109, 20152), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((20535, 20588), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['cdbref'], {'session': 'self.session'}), '(cdbref, session=self.session)\n', (20558, 20588), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((20669, 20722), 'evennia.prototypes.prototypes.protfunc_parser', 'protlib.protfunc_parser', (['cdbref'], {'session': 'self.session'}), '(cdbref, session=self.session)\n', (20692, 20722), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((22994, 23036), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['"""testprototype2"""'], {}), "('testprototype2')\n", (23018, 23036), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((23081, 23123), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['"""testprototype1"""'], {}), "('testprototype1')\n", (23105, 23123), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((23165, 23207), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['"""testprototype1"""'], {}), "('testprototype1')\n", (23189, 23207), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((26774, 26825), 'evennia.prototypes.menus._check_prototype_key', 'olc_menus._check_prototype_key', (['caller', '"""test_prot"""'], {}), "(caller, 'test_prot')\n", (26804, 26825), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26910, 26961), 'evennia.prototypes.menus._check_prototype_key', 'olc_menus._check_prototype_key', (['caller', '"""test_prot"""'], {}), "(caller, 'test_prot')\n", (26940, 26961), True, 'from evennia.prototypes import menus as olc_menus\n'), ((27046, 27086), 'evennia.prototypes.menus._all_prototype_parents', 'olc_menus._all_prototype_parents', (['caller'], {}), '(caller)\n', (27078, 27086), True, 'from evennia.prototypes import menus as olc_menus\n'), ((27640, 27692), 'evennia.prototypes.menus._prototype_parent_select', 'olc_menus._prototype_parent_select', (['caller', '"""goblin"""'], {}), "(caller, 'goblin')\n", (27674, 27692), True, 'from evennia.prototypes import menus as olc_menus\n'), ((28259, 28293), 'evennia.prototypes.menus._all_typeclasses', 'olc_menus._all_typeclasses', (['caller'], {}), '(caller)\n', (28285, 28293), True, 'from evennia.prototypes import menus as olc_menus\n'), ((29489, 29526), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (29518, 29526), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30244, 30281), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (30273, 30281), True, 'from evennia.prototypes import menus as olc_menus\n'), ((30521, 30558), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (30550, 30558), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31232, 31269), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (31261, 31269), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31532, 31569), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (31561, 31569), True, 'from evennia.prototypes import menus as olc_menus\n'), ((31864, 31901), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (31893, 31901), True, 'from evennia.prototypes import menus as olc_menus\n'), ((32153, 32203), 'evennia.prototypes.menus._spawn', 'olc_menus._spawn', (['caller'], {'prototype': 'self.test_prot'}), '(caller, prototype=self.test_prot)\n', (32169, 32203), True, 'from evennia.prototypes import menus as olc_menus\n'), ((1865, 1973), 'evennia.prototypes.spawner.spawn', 'spawner.spawn', (["_PROTPARENTS['GOBLIN']", "_PROTPARENTS['GOBLIN_ARCHWIZARD']"], {'prototype_parents': '_PROTPARENTS'}), "(_PROTPARENTS['GOBLIN'], _PROTPARENTS['GOBLIN_ARCHWIZARD'],\n prototype_parents=_PROTPARENTS)\n", (1878, 1973), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((2335, 2443), 'evennia.prototypes.spawner.spawn', 'spawner.spawn', (["_PROTPARENTS['GOBLIN']", "_PROTPARENTS['GOBLIN_ARCHWIZARD']"], {'prototype_parents': '_PROTPARENTS'}), "(_PROTPARENTS['GOBLIN'], _PROTPARENTS['GOBLIN_ARCHWIZARD'],\n prototype_parents=_PROTPARENTS)\n", (2348, 2443), False, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((22465, 22541), 'evennia.prototypes.prototypes.DbPrototype.objects.get_by_tag', 'protlib.DbPrototype.objects.get_by_tag', (['"""foo1"""', '_PROTOTYPE_TAG_META_CATEGORY'], {}), "('foo1', _PROTOTYPE_TAG_META_CATEGORY)\n", (22503, 22541), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((22844, 22920), 'evennia.prototypes.prototypes.DbPrototype.objects.get_by_tag', 'protlib.DbPrototype.objects.get_by_tag', (['"""foo2"""', '_PROTOTYPE_TAG_META_CATEGORY'], {}), "('foo2', _PROTOTYPE_TAG_META_CATEGORY)\n", (22882, 22920), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((23414, 23446), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', (['"""prot"""'], {}), "('prot')\n", (23438, 23446), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((23507, 23544), 'evennia.prototypes.prototypes.search_prototype', 'protlib.search_prototype', ([], {'tags': '"""foo1"""'}), "(tags='foo1')\n", (23531, 23544), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((23604, 23639), 'evennia.prototypes.prototypes.list_prototypes', 'protlib.list_prototypes', (['self.char1'], {}), '(self.char1)\n', (23627, 23639), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((24747, 24784), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (24776, 24784), True, 'from evennia.prototypes import menus as olc_menus\n'), ((26661, 26706), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': '[self.test_prot]'}), '(return_value=[self.test_prot])\n', (26675, 26706), False, 'import mock\n'), ((27555, 27608), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': "[_PROTPARENTS['GOBLIN']]"}), "(return_value=[_PROTPARENTS['GOBLIN']])\n", (27569, 27608), False, 'import mock\n'), ((28172, 28227), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': "{'foo': None, 'bar': None}"}), "(return_value={'foo': None, 'bar': None})\n", (28186, 28227), False, 'import mock\n'), ((32068, 32121), 'mock.MagicMock', 'mock.MagicMock', ([], {'return_value': "[_PROTPARENTS['GOBLIN']]"}), "(return_value=[_PROTPARENTS['GOBLIN']])\n", (32082, 32121), False, 'import mock\n'), ((22211, 22287), 'evennia.prototypes.prototypes.DbPrototype.objects.get_by_tag', 'protlib.DbPrototype.objects.get_by_tag', (['"""foo1"""', '_PROTOTYPE_TAG_META_CATEGORY'], {}), "('foo1', _PROTOTYPE_TAG_META_CATEGORY)\n", (22249, 22287), True, 'from evennia.prototypes import spawner, prototypes as protlib\n'), ((30692, 30729), 'evennia.prototypes.menus._get_menu_prototype', 'olc_menus._get_menu_prototype', (['caller'], {}), '(caller)\n', (30721, 30729), True, 'from evennia.prototypes import menus as olc_menus\n')]
""" Disguises and Masks """ from typeclasses.wearable.wearable import Wearable, EquipError from typeclasses.consumable.consumable import Consumable class Mask(Wearable): """ Wearable mask that replaces name with 'Someone wearing <short desc> mask'. Also grants a temp_desc. Charges equal to quality, loses a charge when worn. """ def at_object_creation(self): """ Run at Wearable creation. """ self.is_worn = False def at_post_remove(self, wearer): """Hook called after removing succeeds.""" self.remove_mask(wearer) super(Mask, self).at_post_remove(wearer) def at_pre_wear(self, wearer): """Hook called before wearing for any checks.""" super(Mask, self).at_pre_wear(wearer) if self.db.quality_level == 0: raise EquipError("needs repair") def at_post_wear(self, wearer): """Hook called after wearing succeeds.""" self.wear_mask(wearer) self.degrade_mask() if wearer.additional_desc: wearer.msg("{yYou currently have a +tempdesc set, which you may want to remove with +tempdesc.{n") super(Mask, self).at_post_wear(wearer) def degrade_mask(self): """Mirrormasks and GM masks don't need repairs, but others will.""" if not self.tags.get("mirrormask"): # set attr if it's not set to avoid errors if self.db.quality_level is None: self.db.quality_level = 0 # Negative quality level or above 10 are infinite-use elif 0 < self.db.quality_level < 11: self.db.quality_level -= 1 def wear_mask(self, wearer): """Change the visible identity of our wearer.""" wearer.db.mask = self wearer.fakename = "Someone wearing %s" % self wearer.temp_desc = self.db.maskdesc def remove_mask(self, wearer): """Restore the visible identity of our wearer.""" wearer.attributes.remove("mask") del wearer.fakename del wearer.temp_desc wearer.msg("%s is no longer altering your identity or description." % self) class DisguiseKit(Consumable): """ morestoof """ def check_target(self, target, caller): """ Determines if a target is valid. """ from evennia.utils.utils import inherits_from return inherits_from(target, self.valid_typeclass_path)
[ "evennia.utils.utils.inherits_from" ]
[((2389, 2437), 'evennia.utils.utils.inherits_from', 'inherits_from', (['target', 'self.valid_typeclass_path'], {}), '(target, self.valid_typeclass_path)\n', (2402, 2437), False, 'from evennia.utils.utils import inherits_from\n'), ((837, 863), 'typeclasses.wearable.wearable.EquipError', 'EquipError', (['"""needs repair"""'], {}), "('needs repair')\n", (847, 863), False, 'from typeclasses.wearable.wearable import Wearable, EquipError\n')]
""" Test eveditor """ from mock import MagicMock from django.test import TestCase from evennia.utils import eveditor from evennia.commands.default.tests import CommandTest class TestEvEditor(CommandTest): def test_eveditor_view_cmd(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":h", msg="<txt> - any non-command is appended to the end of the buffer.", ) # empty buffer self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) # input a string self.call( eveditor.CmdLineInput(), "First test line", raw_string="First test line", msg="01First test line", ) self.call( eveditor.CmdLineInput(), "Second test line", raw_string="Second test line", msg="02Second test line", ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "First test line\nSecond test line") self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", # view buffer msg="Line Editor []\n01First test line\n" "02Second test line\n[l:02 w:006 c:0032](:h for help)", ) self.call( eveditor.CmdEditorGroup(), "", cmdstring="::", # view buffer, no linenums msg="Line Editor []\nFirst test line\n" "Second test line\n[l:02 w:006 c:0032](:h for help)", ) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":::", # add single : alone on row msg="Single ':' added to buffer.", ) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01First test line\n" "02Second test line\n03:\n[l:03 w:007 c:0034](:h for help)", ) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":dd", msg="Deleted line 3." # delete line ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "First test line\nSecond test line") self.call(eveditor.CmdEditorGroup(), "", cmdstring=":u", msg="Undid one step.") # undo self.assertEqual( self.char1.ndb._eveditor.get_buffer(), "First test line\nSecond test line\n:" ) self.call(eveditor.CmdEditorGroup(), "", cmdstring=":uu", msg="Redid one step.") # redo self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "First test line\nSecond test line") self.call(eveditor.CmdEditorGroup(), "", cmdstring=":u", msg="Undid one step.") # undo self.assertEqual( self.char1.ndb._eveditor.get_buffer(), "First test line\nSecond test line\n:" ) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01First test line\n" "02Second test line\n03:\n[l:03 w:007 c:0034](:h for help)", ) self.call( eveditor.CmdEditorGroup(), "Second", cmdstring=":dw", # delete by word msg="Removed Second for lines 1-4.", ) self.call(eveditor.CmdEditorGroup(), "", cmdstring=":u", msg="Undid one step.") # undo self.call( eveditor.CmdEditorGroup(), "2 Second", cmdstring=":dw", # delete by word/line msg="Removed Second for line 2.", ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "First test line\n test line\n:") self.call( eveditor.CmdEditorGroup(), "2", cmdstring=":p", msg="Copy buffer is empty." # paste ) self.call( eveditor.CmdEditorGroup(), "2", cmdstring=":y", # yank msg="Line 2, [' test line'] yanked.", ) self.call( eveditor.CmdEditorGroup(), "2", cmdstring=":p", # paste msg="Pasted buffer [' test line'] to line 2.", ) self.assertEqual( self.char1.ndb._eveditor.get_buffer(), "First test line\n test line\n test line\n:" ) self.call( eveditor.CmdEditorGroup(), "3", cmdstring=":x", msg="Line 3, [' test line'] cut." # cut ) self.call( eveditor.CmdEditorGroup(), "2 New Second line", cmdstring=":i", # insert msg="Inserted 1 new line(s) at line 2.", ) self.call( eveditor.CmdEditorGroup(), "2 New Replaced Second line", # replace cmdstring=":r", msg="Replaced 1 line(s) at line 2.", ) self.call( eveditor.CmdEditorGroup(), "2 Inserted-", # insert beginning line cmdstring=":I", msg="Inserted text at beginning of line 2.", ) self.call( eveditor.CmdEditorGroup(), "2 -End", # append end line cmdstring=":A", msg="Appended text to end of line 2.", ) self.assertEqual( self.char1.ndb._eveditor.get_buffer(), "First test line\nInserted-New Replaced Second line-End\n test line\n:", ) def test_eveditor_COLON_UU(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) self.call( eveditor.CmdLineInput(), 'First test "line".', raw_string='First test "line".', msg='01First test "line" .', ) self.call( eveditor.CmdLineInput(), "Second 'line'.", raw_string="Second 'line'.", msg="02Second 'line' .", ) self.assertEqual( self.char1.ndb._eveditor.get_buffer(), "First test \"line\".\nSecond 'line'." ) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":UU", msg="Reverted all changes to the buffer back to original state.", ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "") def test_eveditor_search_and_replace(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) self.call(eveditor.CmdLineInput(), "line 1.", raw_string="line 1.", msg="01line 1.") self.call(eveditor.CmdLineInput(), "line 2.", raw_string="line 2.", msg="02line 2.") self.call(eveditor.CmdLineInput(), "line 3.", raw_string="line 3.", msg="03line 3.") self.call( eveditor.CmdEditorGroup(), "2:3", cmdstring=":", msg="Line Editor []\n02line 2.\n03line 3.\n[l:02 w:004 c:0015](:h for help)", ) self.call( eveditor.CmdEditorGroup(), "1:2 line LINE", cmdstring=":s", msg="Search-replaced line -> LINE for lines 1-2.", ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "LINE 1.\nLINE 2.\nline 3.") self.call( eveditor.CmdEditorGroup(), "line MINE", cmdstring=":s", msg="Search-replaced line -> MINE for lines 1-3.", ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "LINE 1.\nLINE 2.\nMINE 3.") def test_eveditor_COLON_DD(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) self.call(eveditor.CmdLineInput(), "line 1.", raw_string="line 1.", msg="01line 1.") self.call(eveditor.CmdLineInput(), "line 2.", raw_string="line 2.", msg="02line 2.") self.call(eveditor.CmdLineInput(), "line 3.", raw_string="line 3.", msg="03line 3.") self.call( eveditor.CmdEditorGroup(), "", cmdstring=":DD", msg="Cleared 3 lines from buffer." ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "") def test_eveditor_COLON_F(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) self.call(eveditor.CmdLineInput(), "line 1", raw_string="line 1", msg="01line 1") self.call(eveditor.CmdEditorGroup(), "1:2", cmdstring=":f", msg="Flood filled lines 1-2.") self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "line 1") def test_eveditor_COLON_J(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) self.call(eveditor.CmdLineInput(), "line 1", raw_string="line 1", msg="01line 1") self.call(eveditor.CmdLineInput(), "l 2", raw_string="l 2", msg="02l 2") self.call(eveditor.CmdLineInput(), "l 3", raw_string="l 3", msg="03l 3") self.call(eveditor.CmdLineInput(), "l 4", raw_string="l 4", msg="04l 4") self.call(eveditor.CmdEditorGroup(), "2 r", cmdstring=":j", msg="Right-justified line 2.") self.call(eveditor.CmdEditorGroup(), "3 c", cmdstring=":j", msg="Center-justified line 3.") self.call(eveditor.CmdEditorGroup(), "4 f", cmdstring=":j", msg="Full-justified line 4.") l1, l2, l3, l4 = tuple(self.char1.ndb._eveditor.get_buffer().split("\n")) self.assertEqual(l1, "line 1") self.assertEqual(l2, " " * 75 + "l 2") self.assertEqual(l3, " " * 37 + "l 3" + " " * 38) self.assertEqual(l4, "l" + " " * 76 + "4") def test_eveditor_bad_commands(self): eveditor.EvEditor(self.char1) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":", msg="Line Editor []\n01\n[l:01 w:000 c:0000](:h for help)", ) self.call(eveditor.CmdLineInput(), "line 1.", raw_string="line 1.", msg="01line 1.") self.call( eveditor.CmdEditorGroup(), "", cmdstring=":dw", msg="You must give a search word to delete.", ) # self.call( # eveditor.CmdEditorGroup(), # raw_string="", # cmdstring=":i", # msg="You need to enter a new line and where to insert it.", # ) # self.call( # eveditor.CmdEditorGroup(), # "", # cmdstring=":I", # msg="You need to enter text to insert.", # ) # self.call( # eveditor.CmdEditorGroup(), # "", # cmdstring=":r", # msg="You need to enter a replacement string.", # ) self.call( eveditor.CmdEditorGroup(), "", cmdstring=":s", msg="You must give a search word and something to replace it with.", ) # self.call( # eveditor.CmdEditorGroup(), # "", # cmdstring=":f", # msg="Valid justifications are [f]ull (default), [c]enter, [r]right or [l]eft" # ) self.assertEqual(self.char1.ndb._eveditor.get_buffer(), "line 1.")
[ "evennia.utils.eveditor.CmdEditorGroup", "evennia.utils.eveditor.EvEditor", "evennia.utils.eveditor.CmdLineInput" ]
[((255, 284), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (272, 284), False, 'from evennia.utils import eveditor\n'), ((5525, 5554), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (5542, 5554), False, 'from evennia.utils import eveditor\n'), ((6540, 6569), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (6557, 6569), False, 'from evennia.utils import eveditor\n'), ((7841, 7870), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (7858, 7870), False, 'from evennia.utils import eveditor\n'), ((8571, 8600), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (8588, 8600), False, 'from evennia.utils import eveditor\n'), ((9093, 9122), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (9110, 9122), False, 'from evennia.utils import eveditor\n'), ((10264, 10293), 'evennia.utils.eveditor.EvEditor', 'eveditor.EvEditor', (['self.char1'], {}), '(self.char1)\n', (10281, 10293), False, 'from evennia.utils import eveditor\n'), ((316, 341), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (339, 341), False, 'from evennia.utils import eveditor\n'), ((533, 558), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (556, 558), False, 'from evennia.utils import eveditor\n'), ((741, 764), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (762, 764), False, 'from evennia.utils import eveditor\n'), ((917, 940), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (938, 940), False, 'from evennia.utils import eveditor\n'), ((1198, 1223), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (1221, 1223), False, 'from evennia.utils import eveditor\n'), ((1446, 1471), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (1469, 1471), False, 'from evennia.utils import eveditor\n'), ((1704, 1729), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (1727, 1729), False, 'from evennia.utils import eveditor\n'), ((1893, 1918), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (1916, 1918), False, 'from evennia.utils import eveditor\n'), ((2132, 2157), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (2155, 2157), False, 'from evennia.utils import eveditor\n'), ((2346, 2371), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (2369, 2371), False, 'from evennia.utils import eveditor\n'), ((2568, 2593), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (2591, 2593), False, 'from evennia.utils import eveditor\n'), ((2766, 2791), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (2789, 2791), False, 'from evennia.utils import eveditor\n'), ((3001, 3026), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (3024, 3026), False, 'from evennia.utils import eveditor\n'), ((3240, 3265), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (3263, 3265), False, 'from evennia.utils import eveditor\n'), ((3413, 3438), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (3436, 3438), False, 'from evennia.utils import eveditor\n'), ((3522, 3547), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (3545, 3547), False, 'from evennia.utils import eveditor\n'), ((3811, 3836), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (3834, 3836), False, 'from evennia.utils import eveditor\n'), ((3937, 3962), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (3960, 3962), False, 'from evennia.utils import eveditor\n'), ((4108, 4133), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (4131, 4133), False, 'from evennia.utils import eveditor\n'), ((4422, 4447), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (4445, 4447), False, 'from evennia.utils import eveditor\n'), ((4553, 4578), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (4576, 4578), False, 'from evennia.utils import eveditor\n'), ((4745, 4770), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (4768, 4770), False, 'from evennia.utils import eveditor\n'), ((4943, 4968), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (4966, 4968), False, 'from evennia.utils import eveditor\n'), ((5148, 5173), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (5171, 5173), False, 'from evennia.utils import eveditor\n'), ((5586, 5611), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (5609, 5611), False, 'from evennia.utils import eveditor\n'), ((5769, 5792), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (5790, 5792), False, 'from evennia.utils import eveditor\n'), ((5955, 5978), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (5976, 5978), False, 'from evennia.utils import eveditor\n'), ((6255, 6280), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (6278, 6280), False, 'from evennia.utils import eveditor\n'), ((6601, 6626), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (6624, 6626), False, 'from evennia.utils import eveditor\n'), ((6771, 6794), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (6792, 6794), False, 'from evennia.utils import eveditor\n'), ((6864, 6887), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (6885, 6887), False, 'from evennia.utils import eveditor\n'), ((6957, 6980), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (6978, 6980), False, 'from evennia.utils import eveditor\n'), ((7063, 7088), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (7086, 7088), False, 'from evennia.utils import eveditor\n'), ((7267, 7292), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (7290, 7292), False, 'from evennia.utils import eveditor\n'), ((7548, 7573), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (7571, 7573), False, 'from evennia.utils import eveditor\n'), ((7902, 7927), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (7925, 7927), False, 'from evennia.utils import eveditor\n'), ((8072, 8095), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (8093, 8095), False, 'from evennia.utils import eveditor\n'), ((8165, 8188), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (8186, 8188), False, 'from evennia.utils import eveditor\n'), ((8258, 8281), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (8279, 8281), False, 'from evennia.utils import eveditor\n'), ((8364, 8389), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (8387, 8389), False, 'from evennia.utils import eveditor\n'), ((8632, 8657), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (8655, 8657), False, 'from evennia.utils import eveditor\n'), ((8802, 8825), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (8823, 8825), False, 'from evennia.utils import eveditor\n'), ((8892, 8917), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (8915, 8917), False, 'from evennia.utils import eveditor\n'), ((9154, 9179), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (9177, 9179), False, 'from evennia.utils import eveditor\n'), ((9324, 9347), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (9345, 9347), False, 'from evennia.utils import eveditor\n'), ((9414, 9437), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (9435, 9437), False, 'from evennia.utils import eveditor\n'), ((9495, 9518), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (9516, 9518), False, 'from evennia.utils import eveditor\n'), ((9576, 9599), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (9597, 9599), False, 'from evennia.utils import eveditor\n'), ((9657, 9682), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (9680, 9682), False, 'from evennia.utils import eveditor\n'), ((9756, 9781), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (9779, 9781), False, 'from evennia.utils import eveditor\n'), ((9856, 9881), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (9879, 9881), False, 'from evennia.utils import eveditor\n'), ((10325, 10350), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (10348, 10350), False, 'from evennia.utils import eveditor\n'), ((10495, 10518), 'evennia.utils.eveditor.CmdLineInput', 'eveditor.CmdLineInput', ([], {}), '()\n', (10516, 10518), False, 'from evennia.utils import eveditor\n'), ((10601, 10626), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (10624, 10626), False, 'from evennia.utils import eveditor\n'), ((11339, 11364), 'evennia.utils.eveditor.CmdEditorGroup', 'eveditor.CmdEditorGroup', ([], {}), '()\n', (11362, 11364), False, 'from evennia.utils import eveditor\n')]
""" All available requests. """ from django.conf import settings from evennia.utils import logger from muddery.server.utils.exception import MudderyError from muddery.server.utils.utils import classes_in_path from muddery.worldeditor.controllers.base_request_processer import BaseRequestProcesser class RequestSet(object): """ All available requests. """ def __init__(self): self.dict = {} self.load() def load(self): """ Add all forms from the form path. """ # load classes for cls in classes_in_path(settings.PATH_REQUEST_PROCESSERS_BASE, BaseRequestProcesser): path = cls.path name = cls.name if not path and not name: logger.log_errmsg("Missing request's path and name.") continue if path[0] != "/": path = "/" + path if name is None: name = "" if (path, name,) in self.dict: logger.log_infomsg("Request %s-%s is replaced by %s." % (path, name, cls)) self.dict[(path, name,)] = cls() def get(self, path, name): """ Get the processer responds to the request. """ return self.dict.get((path, name,), None) REQUEST_SET = RequestSet()
[ "evennia.utils.logger.log_errmsg", "evennia.utils.logger.log_infomsg" ]
[((566, 642), 'muddery.server.utils.utils.classes_in_path', 'classes_in_path', (['settings.PATH_REQUEST_PROCESSERS_BASE', 'BaseRequestProcesser'], {}), '(settings.PATH_REQUEST_PROCESSERS_BASE, BaseRequestProcesser)\n', (581, 642), False, 'from muddery.server.utils.utils import classes_in_path\n'), ((755, 808), 'evennia.utils.logger.log_errmsg', 'logger.log_errmsg', (['"""Missing request\'s path and name."""'], {}), '("Missing request\'s path and name.")\n', (772, 808), False, 'from evennia.utils import logger\n'), ((1016, 1090), 'evennia.utils.logger.log_infomsg', 'logger.log_infomsg', (["('Request %s-%s is replaced by %s.' % (path, name, cls))"], {}), "('Request %s-%s is replaced by %s.' % (path, name, cls))\n", (1034, 1090), False, 'from evennia.utils import logger\n')]
import math, datetime from django.conf import settings import evennia from evennia.utils.utils import time_format, class_from_module COMMAND_DEFAULT_CLASS = class_from_module(settings.COMMAND_DEFAULT_CLASS) JOB_COLUMNS = f"* ID Submitter Title Claimed Due Lst" class JobCmd(COMMAND_DEFAULT_CLASS): account_caller = True system_name = "JOBS" help_category = "Job System / Issue Tracker" def display_job(self, lhs): admin = False job = evennia.GLOBAL_SCRIPTS.jobs.find_job(self.account, self.lhs) if job.bucket.access(self.account, 'admin') or job.links.filter(link_type=2, account_stub=self.account.stub): admin = True message = list() message.append(self.styled_header(f'{job.bucket} Job {job.id} - {job.status_word()}')) message.append(f"|hTitle:|n {job.title}") message.append(f'|hHandlers:|n {job.handler_names()}') message.append(f'|hHelpers:|n {job.helper_names()}') comments = job.comments() if not admin: comments = comments.exclude(is_private=True) for com in comments: message.append(self.styled_separator()) message.append(com.display(self.account, admin)) message.append(self.styled_footer(f"Due: {self.account.display_time(job.due_date)}")) job.update_read(self.account) self.msg('\n'.join(message)) def display_buckets(self): message = list() message.append(self.styled_header('Job Buckets')) col_color = self.account.options.column_names_color message.append(f"|{col_color}Name Description Pen App Dny Cnc Over Due Anon|n") message.append(self.styled_separator()) for bucket in evennia.GLOBAL_SCRIPTS.jobs.visible_buckets(self.account): bkey = bucket.key[:8].ljust(8) description = bucket.description if not description: description = "" pending = str(bucket.jobs.filter(status=0).count()).rjust(3).ljust(4) approved = str(bucket.jobs.filter(status=1).count()).rjust(3).ljust(4) denied = str(bucket.jobs.filter(status=2).count()).rjust(3).ljust(4) canceled = str(bucket.jobs.filter(status=3).count()).rjust(3).ljust(4) anon = 'No' now = datetime.datetime.utcnow() overdue = str(bucket.jobs.filter(status=0, due_date__lt=now).count()).rjust(3).ljust(4) due = time_format(bucket.due.total_seconds(), style=1).rjust(3) message.append(f"{bkey} {description[:34].ljust(34)} {pending} {approved} {denied} {canceled} {overdue} {due} {anon}") message.append(self.styled_footer()) self.msg('\n'.join(str(l) for l in message)) def display_bucket(self, bucket, old=False): page = 1 if '/' in bucket: bucket, page = bucket.split('/', 1) if page.isdigit(): page = int(page) else: page = 1 bucket = evennia.GLOBAL_SCRIPTS.jobs.find_bucket(self.account, bucket) admin = bucket.access(self.account, "admin") if not admin: raise ValueError("Permission denied.") if old: jobs = bucket.old() else: jobs = bucket.active() jobs_count = len(jobs) if not jobs_count: raise ValueError("No jobs to display!") pages = float(jobs_count) / 30.0 pages = int(math.ceil(pages)) if page > pages: page = pages if page < 1: page = 1 message = list() message.append(self.styled_header(f"{'Old' if old else 'Active'} Jobs - {bucket}")) message.append(JOB_COLUMNS) message.append(self.styled_separator()) for job in jobs: message.append(job.display_line(self.account, admin)) message.append(self.styled_footer(f'< Page {page} of {pages} >')) self.msg("\n".join(str(l) for l in message)) def switch_main(self): if self.args: if self.lhs.isdigit(): self.display_job(self.lhs) else: self.display_bucket(self.lhs) else: self.display_buckets() class CmdJBucket(JobCmd): key = '+jbucket' aliases = ['+jbuckets', ] locks = 'cmd:perm(Admin) or perm(Job_Admin)' switch_options = ['create', 'delete', 'rename', 'lock', 'due', 'describe'] def switch_create(self): evennia.GLOBAL_SCRIPTS.jobs.create_bucket(self.account, self.lhs, self.rhs) def switch_delete(self): evennia.GLOBAL_SCRIPTS.jobs.delete_bucket(self.account, self.args) def switch_rename(self): evennia.GLOBAL_SCRIPTS.jobs.rename_bucket(self.account, self.lhs, self.rhs) def switch_lock(self): evennia.GLOBAL_SCRIPTS.jobs.lock_bucket(self.account, self.lhs, self.rhs) def switch_due(self): evennia.GLOBAL_SCRIPTS.jobs.due_bucket(self.account, self.lhs, self.rhs) def switch_describe(self): evennia.GLOBAL_SCRIPTS.jobs.describe_bucket(self.account, self.lhs, self.rhs) def switch_main(self): self.display_buckets() class CmdJobAdmin(JobCmd): key = "+jadmin" switch_options = ['addhandler', 'remhandler', 'addhelper', 'remhelper', 'move', 'due', 'approve', 'deny', 'cancel', 'revive', 'claim', 'unclaim'] def switch_claim(self): self.switch_addhandler() def switch_unclaim(self): self.switch_remhandler() def switch_addhandler(self): if self.rhs: handler = self.account.search(self.rhs) else: handler = self.account evennia.GLOBAL_SCRIPTS.jobs.promote_account(self.account, self.lhs, handler, show_word="Handler", rank=2, start_type=0) def switch_remhandler(self): if self.rhs: handler = self.account.search(self.rhs) else: handler = self.account evennia.GLOBAL_SCRIPTS.jobs.demote_account(self.account, self.lhs, handler, show_word="Handler", rank=0, start_type=2) def switch_addhelper(self): if self.rhs: handler = self.account.search(self.rhs) else: handler = self.account evennia.GLOBAL_SCRIPTS.jobs.promote_account(self.account, self.lhs, handler, show_word="Helper", rank=1, start_type=0) def switch_remhelper(self): if self.rhs: handler = self.account.search(self.rhs) else: handler = self.account evennia.GLOBAL_SCRIPTS.jobs.demote_account(self.account, self.lhs, handler, show_word="Helper", rank=0, start_type=1) def switch_approve(self): pass def switch_deny(self): pass def switch_cancel(self): pass def switch_revive(self): pass def switch_due(self): pass def switch_move(self): evennia.GLOBAL_SCRIPTS.jobs.move_job(self.account, self.lhs, self.rhs) class CmdJobList(JobCmd): key = "+jlist" switch_options = ['old', 'pending', 'brief', 'search', 'scan', 'next'] def switch_pending(self): if self.lhs: buckets = [bucket for bucket in [evennia.GLOBAL_SCRIPTS.jobs.find_bucket(self.account, self.lhs), ] if bucket.jobs.filter(status=0).count() and bucket.access(self.account, "admin")] else: buckets = [bucket for bucket in evennia.GLOBAL_SCRIPTS.jobs.visible_buckets(self.account) if bucket.jobs.filter(status=0).count() and bucket.access(self.account, "admin")] if not buckets: raise ValueError("No visible Pending jobs for applicable Job Buckets.") message = list() message.append(self.styled_header("Pending Jobs")) message.append(JOB_COLUMNS) for bucket in buckets: message.append(self.styled_separator(f"Pending for: {bucket} - {bucket.jobs.filter(status=0).count()} Total")) for j in bucket.jobs.filter(status=0).reverse()[:20]: message.append(j.display_line(self.account, admin=True)) message.append(self.styled_footer(())) self.msg('\n'.join(message)) def switch_scan(self): buckets = [bucket for bucket in evennia.GLOBAL_SCRIPTS.jobs.visible_buckets(self.account) if bucket.access(self.account, "admin")] message = list() all_buckets = list() for bucket in buckets: pen_jobs = bucket.new(self.account) if pen_jobs: all_buckets.append((bucket, pen_jobs)) if not all_buckets: raise ValueError("Nothing new to show!") for bucket, jobs in all_buckets: message.append(self.styled_separator(f'Job Activity - {bucket}')) for j in jobs: message.append(j.display_line(self.account, admin=True)) message.append(self.styled_footer()) self.msg('\n'.join(message)) def switch_next(self): buckets = [bucket for bucket in evennia.GLOBAL_SCRIPTS.jobs.visible_buckets(self.account) if bucket.access(self.account, "admin")] job = None for bucket in buckets: job = bucket.new(self.account).first() if job: break if not job: raise ValueError("Nothing new to show!") self.display_job(str(job.id)) def switch_old(self): self.display_bucket(self.lhs, old=True) def switch_brief(self): pass def switch_search(self): pass class CmdJob(JobCmd): key = '+job' aliases = ['+jobs', ] switch_options = ['reply', 'comment'] def switch_reply(self): evennia.GLOBAL_SCRIPTS.jobs.create_comment(self.account, self.lhs, comment_text=self.rhs, comment_type=1) def switch_comment(self): evennia.GLOBAL_SCRIPTS.jobs.create_comment(self.account, self.lhs, comment_text=self.rhs, comment_type=2) class CmdJRequest(JobCmd): key = '+jrequest' system_name = 'REQUEST' def switch_main(self): if not self.lhs: raise ValueError("No Bucket or Subject entered!") if '/' not in self.lhs: raise ValueError("Usage: +request <bucket>/<subject>=<text>") bucket, subject = self.lhs.split('/', 1) evennia.GLOBAL_SCRIPTS.jobs.create_job(self.account, bucket, subject, self.rhs) class CmdMyJob(CmdJob): key = '+myjob' aliases = ['+myjobs'] switch_options = ['reply', 'old', 'approve', 'deny', 'cancel', 'revive', 'comment', 'due', 'claim', 'unclaim', 'addhelper', 'remhelper'] JOB_COMMANDS = [CmdJBucket, CmdJob, CmdJobAdmin, CmdJobList, CmdMyJob, CmdJRequest]
[ "evennia.utils.utils.class_from_module", "evennia.GLOBAL_SCRIPTS.jobs.rename_bucket", "evennia.GLOBAL_SCRIPTS.jobs.promote_account", "evennia.GLOBAL_SCRIPTS.jobs.move_job", "evennia.GLOBAL_SCRIPTS.jobs.due_bucket", "evennia.GLOBAL_SCRIPTS.jobs.create_job", "evennia.GLOBAL_SCRIPTS.jobs.demote_account", ...
[((158, 207), 'evennia.utils.utils.class_from_module', 'class_from_module', (['settings.COMMAND_DEFAULT_CLASS'], {}), '(settings.COMMAND_DEFAULT_CLASS)\n', (175, 207), False, 'from evennia.utils.utils import time_format, class_from_module\n'), ((513, 573), 'evennia.GLOBAL_SCRIPTS.jobs.find_job', 'evennia.GLOBAL_SCRIPTS.jobs.find_job', (['self.account', 'self.lhs'], {}), '(self.account, self.lhs)\n', (549, 573), False, 'import evennia\n'), ((1800, 1857), 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', (['self.account'], {}), '(self.account)\n', (1843, 1857), False, 'import evennia\n'), ((3081, 3142), 'evennia.GLOBAL_SCRIPTS.jobs.find_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.find_bucket', (['self.account', 'bucket'], {}), '(self.account, bucket)\n', (3120, 3142), False, 'import evennia\n'), ((4552, 4627), 'evennia.GLOBAL_SCRIPTS.jobs.create_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.create_bucket', (['self.account', 'self.lhs', 'self.rhs'], {}), '(self.account, self.lhs, self.rhs)\n', (4593, 4627), False, 'import evennia\n'), ((4666, 4732), 'evennia.GLOBAL_SCRIPTS.jobs.delete_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.delete_bucket', (['self.account', 'self.args'], {}), '(self.account, self.args)\n', (4707, 4732), False, 'import evennia\n'), ((4779, 4854), 'evennia.GLOBAL_SCRIPTS.jobs.rename_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.rename_bucket', (['self.account', 'self.lhs', 'self.rhs'], {}), '(self.account, self.lhs, self.rhs)\n', (4820, 4854), False, 'import evennia\n'), ((4891, 4964), 'evennia.GLOBAL_SCRIPTS.jobs.lock_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.lock_bucket', (['self.account', 'self.lhs', 'self.rhs'], {}), '(self.account, self.lhs, self.rhs)\n', (4930, 4964), False, 'import evennia\n'), ((5000, 5072), 'evennia.GLOBAL_SCRIPTS.jobs.due_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.due_bucket', (['self.account', 'self.lhs', 'self.rhs'], {}), '(self.account, self.lhs, self.rhs)\n', (5038, 5072), False, 'import evennia\n'), ((5113, 5190), 'evennia.GLOBAL_SCRIPTS.jobs.describe_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.describe_bucket', (['self.account', 'self.lhs', 'self.rhs'], {}), '(self.account, self.lhs, self.rhs)\n', (5156, 5190), False, 'import evennia\n'), ((5761, 5884), 'evennia.GLOBAL_SCRIPTS.jobs.promote_account', 'evennia.GLOBAL_SCRIPTS.jobs.promote_account', (['self.account', 'self.lhs', 'handler'], {'show_word': '"""Handler"""', 'rank': '(2)', 'start_type': '(0)'}), "(self.account, self.lhs, handler,\n show_word='Handler', rank=2, start_type=0)\n", (5804, 5884), False, 'import evennia\n'), ((6097, 6219), 'evennia.GLOBAL_SCRIPTS.jobs.demote_account', 'evennia.GLOBAL_SCRIPTS.jobs.demote_account', (['self.account', 'self.lhs', 'handler'], {'show_word': '"""Handler"""', 'rank': '(0)', 'start_type': '(2)'}), "(self.account, self.lhs, handler,\n show_word='Handler', rank=0, start_type=2)\n", (6139, 6219), False, 'import evennia\n'), ((6430, 6552), 'evennia.GLOBAL_SCRIPTS.jobs.promote_account', 'evennia.GLOBAL_SCRIPTS.jobs.promote_account', (['self.account', 'self.lhs', 'handler'], {'show_word': '"""Helper"""', 'rank': '(1)', 'start_type': '(0)'}), "(self.account, self.lhs, handler,\n show_word='Helper', rank=1, start_type=0)\n", (6473, 6552), False, 'import evennia\n'), ((6764, 6885), 'evennia.GLOBAL_SCRIPTS.jobs.demote_account', 'evennia.GLOBAL_SCRIPTS.jobs.demote_account', (['self.account', 'self.lhs', 'handler'], {'show_word': '"""Helper"""', 'rank': '(0)', 'start_type': '(1)'}), "(self.account, self.lhs, handler,\n show_word='Helper', rank=0, start_type=1)\n", (6806, 6885), False, 'import evennia\n'), ((7180, 7250), 'evennia.GLOBAL_SCRIPTS.jobs.move_job', 'evennia.GLOBAL_SCRIPTS.jobs.move_job', (['self.account', 'self.lhs', 'self.rhs'], {}), '(self.account, self.lhs, self.rhs)\n', (7216, 7250), False, 'import evennia\n'), ((9972, 10081), 'evennia.GLOBAL_SCRIPTS.jobs.create_comment', 'evennia.GLOBAL_SCRIPTS.jobs.create_comment', (['self.account', 'self.lhs'], {'comment_text': 'self.rhs', 'comment_type': '(1)'}), '(self.account, self.lhs,\n comment_text=self.rhs, comment_type=1)\n', (10014, 10081), False, 'import evennia\n'), ((10117, 10226), 'evennia.GLOBAL_SCRIPTS.jobs.create_comment', 'evennia.GLOBAL_SCRIPTS.jobs.create_comment', (['self.account', 'self.lhs'], {'comment_text': 'self.rhs', 'comment_type': '(2)'}), '(self.account, self.lhs,\n comment_text=self.rhs, comment_type=2)\n', (10159, 10226), False, 'import evennia\n'), ((10580, 10659), 'evennia.GLOBAL_SCRIPTS.jobs.create_job', 'evennia.GLOBAL_SCRIPTS.jobs.create_job', (['self.account', 'bucket', 'subject', 'self.rhs'], {}), '(self.account, bucket, subject, self.rhs)\n', (10618, 10659), False, 'import evennia\n'), ((2383, 2409), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (2407, 2409), False, 'import math, datetime\n'), ((3537, 3553), 'math.ceil', 'math.ceil', (['pages'], {}), '(pages)\n', (3546, 3553), False, 'import math, datetime\n'), ((8513, 8570), 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', (['self.account'], {}), '(self.account)\n', (8556, 8570), False, 'import evennia\n'), ((9294, 9351), 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', (['self.account'], {}), '(self.account)\n', (9337, 9351), False, 'import evennia\n'), ((7677, 7734), 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', 'evennia.GLOBAL_SCRIPTS.jobs.visible_buckets', (['self.account'], {}), '(self.account)\n', (7720, 7734), False, 'import evennia\n'), ((7470, 7533), 'evennia.GLOBAL_SCRIPTS.jobs.find_bucket', 'evennia.GLOBAL_SCRIPTS.jobs.find_bucket', (['self.account', 'self.lhs'], {}), '(self.account, self.lhs)\n', (7509, 7533), False, 'import evennia\n')]
# Test weapons (and weapon racks). from evennia import create_object from evennia.commands.default.tests import CommandTest from typeclasses.weapons import edged as druedged from typeclasses.weapons import rack as drurack from twisted.trial.unittest import TestCase as TwistedTestCase class TestWeapons(TwistedTestCase, CommandTest): def test_weapon(self): weapon = create_object(druedged.Weapon, key="sword", location=self.char1) self.call( druedged.CmdAttack(), "Char", "You stab with sword.", obj=weapon, cmdstring="stab" ) self.call( druedged.CmdAttack(), "Char", "You slash with sword.", obj=weapon, cmdstring="slash" ) def test_weaponrack(self): rack = create_object(drurack.WeaponRack, key="rack", location=self.room1) rack.db.available_weapons = ["sword"] self.call(drurack.CmdGetWeapon(), "", "You find Rusty sword.", obj=rack)
[ "evennia.create_object" ]
[((384, 448), 'evennia.create_object', 'create_object', (['druedged.Weapon'], {'key': '"""sword"""', 'location': 'self.char1'}), "(druedged.Weapon, key='sword', location=self.char1)\n", (397, 448), False, 'from evennia import create_object\n'), ((746, 812), 'evennia.create_object', 'create_object', (['drurack.WeaponRack'], {'key': '"""rack"""', 'location': 'self.room1'}), "(drurack.WeaponRack, key='rack', location=self.room1)\n", (759, 812), False, 'from evennia import create_object\n'), ((480, 500), 'typeclasses.weapons.edged.CmdAttack', 'druedged.CmdAttack', ([], {}), '()\n', (498, 500), True, 'from typeclasses.weapons import edged as druedged\n'), ((604, 624), 'typeclasses.weapons.edged.CmdAttack', 'druedged.CmdAttack', ([], {}), '()\n', (622, 624), True, 'from typeclasses.weapons import edged as druedged\n'), ((877, 899), 'typeclasses.weapons.rack.CmdGetWeapon', 'drurack.CmdGetWeapon', ([], {}), '()\n', (897, 899), True, 'from typeclasses.weapons import rack as drurack\n')]
from evennia.prototypes.spawner import spawn from evennia.utils.create import create_object from evennia.utils.utils import variable_from_module from misc import general_mechanics as gen_mec from misc import coin ''' This handler decides functions related to items, such as get, put, stacking, etc. ''' class ItemHandler(): def __init__(self, owner): self.owner = owner self.items_dict = variable_from_module("items.items", variable='items') def group_objects(self, objects, obj_loc): """ Takes a list of objects and groups them based on 3 categories: Coin objects that have a coin dictionary. Quantity objects that are identical in both key and attributes. All other objects that have unique attribute values and are grouped into a pile, which behaves like a container. Arguments: objects (list): This is the list of objects passed in from the grouping command. obj_loc (object): This is a reference to the object that houses the listed objects. This is often times a room or the player's character. Returns: msg (string): The resulting string of the grouping action, which is sent back to the caller of the command. """ msg = '' coin_msg = None qty_msg = None inv_msg = None groupables = [] coin_groupables = [] qty_groupables = [] inv_groupables = [] #==[Parse the objects into appropriate lists.]==# # Filter ungroupables from the list. for obj in objects: if obj.tags.get(category='groupable'): groupables.append(obj) else: # Generate error strings for each object not able to be grouped. msg = f"{msg}{obj} is not able to be grouped.\n" if len(groupables) < 2: # Only one of the objects was groupable. Method requires at least 2 objects to group. msg = f"{msg}|rNot enough objects to group. Request aborted!|n" return msg # Sort objects into quantity or inventory group type lists. for obj in groupables: if obj.tags.get('coin', category='groupable'): coin_groupables.append(obj) elif obj.tags.get('quantity', category='groupable'): qty_groupables.append(obj) elif obj.tags.get('inventory', category='groupable'): inv_groupables.append(obj) #==[Execute the grouping and generate result strings.]==# # Coin Groupables if len(coin_groupables) > 1: coin_msg, coin_group_obj = self._group_coins(coin_groupables, obj_loc) msg = f"{msg}{coin_msg}" # Reset the coin groupables and add the new coin object to the list. # This will be used to evaluate if the coins should be grouped with the inventory logic. coin_groupables.clear() coin_groupables.append(coin_group_obj) # Quantity Groupables if len(qty_groupables) > 1: # Merge and filter the list of quantity objects. qty_groupables, qty_names = self._group_quantity_objects(qty_groupables) obj_names = gen_mec.comma_separated_string_list(qty_names) qty_msg = f"You combine {obj_names}." if coin_msg is not None: msg = f"{msg}\n" msg = f"{msg}{qty_msg}" # Inventory Groupables # Decide if there are enough objects to group, including coin and quantity results. # Inventory groupales must still be at least 1 + 1 from either coin or quantity to execute. if len(inv_groupables) > 1 or len(inv_groupables) + len(coin_groupables) > 1 \ or len(inv_groupables) + len(qty_groupables) > 1: inv_groupables.extend(coin_groupables) inv_groupables.extend(qty_groupables) inv_msg = self._group_inventory_objects(inv_groupables, obj_loc) if qty_msg is not None or coin_msg is not None: msg = f"{msg}\n" msg = f"{msg}{inv_msg}" return msg def _group_coins(self, coin_groupables, obj_loc): """ Creates a pile of coins. Arguments: coin_groupables (list): The coin objects to be grouped. obj_loc (object): The object that contains these groupable objects. Their location. Returns: coin_msg (string): The resulting string of the grouping action, which is sent back to the caller of the command. coin_group_obj (object): The new coin pile produced by this grouping. """ coin_names = gen_mec.comma_separated_string_list(gen_mec.objects_to_strings(coin_groupables)) total_copper = 0 for obj in coin_groupables: total_copper += coin.coin_dict_to_copper(obj.db.coin) for obj in coin_groupables: obj.delete() coin_obj = coin.generate_coin_object(copper=total_copper) coin_obj.location = obj_loc coin_msg = f"You combine {coin_names}." return coin_msg, coin_obj def _group_quantity_objects(self, qty_groupables): """ Combines objects that have no unique attributes into a single object. Adds the quantity value of duplicate objects to the first object found and then deletes any duplicates. Arguments: qty_groupables (list): The list of objects to iterate over and combine. Returns: qty_groupables (list): The filtered list of combined objects. qty_names (list): The quantity and name of each final object, used in the final string that is sent back to the caller of the grouping command. """ qty_names = [] qty_dict = {} # Spawn a new list to iterate over, while manipulating the qty_groupables list. test_list = list(qty_groupables) for obj in test_list: # Homogenize the name of the objects being combined. Account for groupings already # included for this object. obj_key = obj.db.singular_key if qty_dict.get(obj_key, None) is not None: # This is a duplicate of an already found object. # Add its quantity to the original object and delete the duplicate. qty_dict[obj_key].db.quantity += obj.db.quantity qty_groupables.remove(obj) obj.delete() else: # Generate a new dictionary key and assign the first object encountered. # Preserving the first object found also preserves the common properties assigned to # this object. Such as tags, etc. qty_dict[obj_key] = obj # Iterate over the list of final objects and modify the keys of grouped objects. for obj in qty_groupables: if obj.db.quantity > 1: obj.key = f"a pile of {obj.db.plural_key}" qty_names.append(f"{obj.db.quantity} {obj.db.plural_key}") return qty_groupables, qty_names def _group_inventory_objects(self, inv_groupables, obj_loc): """ Groups together objects with unique properties by generating a group object and placing the groupable objects into its inventory. If all objects have the same key, a pile is generated with the key of the objects being grouped. Arguments: inv_groupables (list): A list of groupable objects to be placed in the inventory. obj_loc (object): The object that contains these groupable objects. Their location. Returns: inv_msg: The resulting string that is sent back to the caller that executed the grouping command. """ inv_msg = '' inv_quantity = 0 group_groupables = [] # Separate out objects that are already groups, for additional parsing. temp_list = list(inv_groupables) for obj in temp_list: if obj.is_typeclass("items.objects.InventoryGroup", exact=True): group_groupables.append(obj) inv_groupables.remove(obj) # Generate a string to inform the user they are combining groups. # Dump the contents of each group into the inv_groupables for normal combining operations. if len(group_groupables) > 0: group_str_list = gen_mec.comma_separated_string_list(gen_mec.objects_to_strings(group_groupables)) inv_msg = f"{inv_msg}You combine the contents of {group_str_list}.\n" for group in group_groupables: inv_groupables.extend(group.contents) group.delete() # Check if all objects in the inv_groupables list have the same name. same_name = gen_mec.all_same(gen_mec.objects_to_strings(inv_groupables)) if same_name: # Create a pile of the same name of the groupable objects. inv_group_obj = create_object(key=f'a pile of {inv_groupables[0].db.plural_key}', typeclass='items.objects.InventoryGroup', location=obj_loc) inv_msg = f"{inv_msg}You group together some {inv_groupables[0].db.plural_key}." else: # Items have various names and the pile should be generic. item_str_list = gen_mec.comma_separated_string_list(gen_mec.objects_to_strings(inv_groupables)) inv_group_obj = create_object(key=f"a pile of various items", typeclass='items.objects.InventoryGroup', location=obj_loc) inv_msg = f"{inv_msg}You group together {item_str_list}." # Pile object is generated, time to move groupables into its inventory. for obj in inv_groupables: obj.move_to(inv_group_obj, quiet=True, move_hooks=False) inv_quantity += 1 inv_group_obj.db.quantity = inv_quantity return inv_msg def ungroup_objects(self, group_obj, obj_loc): """ Ungroups grouped objects. Arguments: group_obj (object): The group object to ungroup. obj_loc (object): The object that contains these groupable objects. Their location. Returns: msg (string): The resulting message that will be sent back to the caller that executed the ungroup command. """ delete_group_obj = False # Coin Groupable if group_obj.tags.get('coin', category='groupable'): msg, delete_group_obj = self._ungroup_coins(group_obj, obj_loc) # Quantity Groupable elif group_obj.tags.get('quantity', category='groupable'): msg = "You cannot ungroup a homogenized group. Use the split command instead." # Inventory Groupable elif group_obj.is_typeclass('items.objects.InventoryGroup'): group_contents = list(group_obj.contents) for x in group_contents: x.move_to(obj_loc, quiet=True, move_hooks=False) msg = (f"You ungroup {group_obj.name}, producing " f"{gen_mec.comma_separated_string_list(gen_mec.objects_to_strings(group_contents))}.") delete_group_obj = True if delete_group_obj: group_obj.delete() return msg def _ungroup_coins(self, group_obj, obj_loc): """ Takes a pile of coins and ungroups them into the 4 coin types. (Plat, Gold, Silver, Copper) Will NOT ungroup a coin pile if it is already a single type of coin. (100 gold into 100 objects) Single coin objects are only generated from this action if they are part of a coin pile that contains additional coin types. Arguments: group_obj (object): The pile of coins to ungroup. obj_loc (object): The location that the group_obj resides and the ungroup objects will be placed in. Returns: msg (string): The resulting message that will be sent back to the caller that executed the ungroup command. delete_group_obj (boolean): Determines if the group_obj (original pile of coins) will be deleted in the main ungroup_objects() method. This is set to false if the coins are only of a single type of coin. """ def create_coin(coin_type, coin_value, group_obj, obj_loc): """ A helper method to allow a single point of coin generation and removal of its value from the original group_obj, no matter the coin type being passed in. Arguments: coin_type (string): The coin type being evaluated within this group_obj. coin_value (integer): The value of the specific coin type. group_obj (object): The pile of coins to ungroup. obj_loc (object): The location that the group_obj resides and the ungroup objects will be placed in. Returns: coin_obj.key (string): The name of the resulting coin that has been separated from the group_obj """ # Abandon the ungrouping if the coin value is 0 for the coin type. if coin_value < 1: return None temp_coin_dict = {} temp_coin_dict[coin_type] = coin_value coin_dict = coin.create_coin_dict(**temp_coin_dict) coin_obj = coin.generate_coin_object(coin_dict=coin_dict) coin_obj.location = obj_loc if coin_obj is not None: # Set the original group object's coin_type to zero, as it's been transferred over. group_obj.db.coin[coin_type] = 0 # We only need to return the key here, because the new object is already generated # and its location has been set. return coin_obj.key #------------------------------------------------------------------------------------ delete_group_obj = False if not coin.is_homogenized(group_obj.db.coin): new_coin_names = [] # Iterate over the group object's coin dictionary and generate new coin piles. for coin_type, coin_value in group_obj.db.coin.items(): new_coin_name = create_coin(coin_type, coin_value, group_obj, obj_loc) if new_coin_name is not None: new_coin_names.append(new_coin_name) # Generate the resulting string. names = gen_mec.comma_separated_string_list(new_coin_names) msg = f"You ungroup {group_obj.name}, producing {names}." delete_group_obj = True else: msg = (f"{group_obj.key} consists of a single coin type and cannot be ungrouped. " "Use the split command instead.") return msg, delete_group_obj def split_group(self, split_type, pile, obj_loc, quantity=0, extract_obj=None): """ Arguments: obj_loc (object): The object that contains these groupable objects. Their location. """ msg = '' pile_name = pile.name if pile.tags.get('coin', category='groupable'): msg = self._split_coins(split_type, pile, obj_loc, quantity, extract_obj, pile_name) elif pile.tags.get('quantity', category='groupable'): # This is a pile of quantity objects, or other similar pile. msg = self._split_quantity_objects(self, split_type, pile, obj_loc, quantity, pile_name) elif pile.is_typeclass('items.objects.InventoryGroup'): msg = self._split_inventory_objects(split_type, pile, obj_loc, quantity, extract_obj, pile_name) return msg def _split_coins(self, split_type, pile, obj_loc, quantity, extract_obj, pile_name): original_copper = 0 new_copper = 0 # Convert the coin into copper to do maths. total_copper = coin.coin_dict_to_copper(pile.db.coin) if split_type == 'default': if total_copper > 1: original_copper = (total_copper // 2) + (total_copper % 2) new_copper = total_copper // 2 else: return "You cannot split 1 copper!" elif split_type == 'from': coin_type = 'plat' if extract_obj == 'platinum' else extract_obj temp_coin_dict = {} temp_coin_dict[coin_type] = quantity new_copper = coin.coin_dict_to_copper(temp_coin_dict) if new_copper > total_copper: return f"There isn't enough {extract_obj} to split from {pile_name}!" else: original_copper = total_copper - new_copper # Original pile no longer has a use and will be remade. Delete it. pile.delete() # Convert the coppers back to coin dictionaries. original_coin_dict = coin.balance_coin_dict(coin.copper_to_coin_dict(original_copper)) new_coin_dict = coin.balance_coin_dict(coin.copper_to_coin_dict(new_copper)) original_coin_obj = coin.generate_coin_object(coin_dict=original_coin_dict) original_coin_obj.location = obj_loc new_coin_obj = coin.generate_coin_object(coin_dict=new_coin_dict) new_coin_obj.location = obj_loc if split_type == 'default': msg = f"You split {pile_name} into {original_coin_obj.key} and {new_coin_obj.key}." elif split_type == 'from': msg = f"You split {new_coin_obj.key} from {pile_name}, leaving {original_coin_obj.key}." return msg def _split_quantity_objects(self, split_type, pile, obj_loc, quantity, extract_obj, pile_name): pile_qty = pile.attributes.get('quantity', default=0) if pile_qty <= 1: return f"{pile_name} has a quantity of {pile_qty} and cannot be split!" if split_type == 'default': original_pile_qty = (pile_qty // 2) + (pile_qty % 2) new_pile_qty = pile_qty // 2 elif split_type == 'from': if quantity > pile_qty: return f"{pile_name} does not have {quantity} to split from itself!" original_pile_qty = pile_qty - quantity new_pile_qty = quantity pile.db.quantity = original_pile_qty new_pile = pile.copy() new_pile.db.quantity = new_pile_qty new_pile.location = obj_loc for pile in [pile, new_pile]: if pile.db.quantity > 1: pile.key = pile.db.plural_key else: pile.key = pile.db.singular_key if split_type == 'default': msg = f"You split {pile_name} into {pile.key} and {new_pile.key}." elif split_type == 'from': msg = f"You split {new_pile.key} from {pile_name}, leaving {pile.key}" return msg def _split_inventory_objects(self, split_type, pile, obj_loc, quantity, extract_obj, pile_name): """ """ msg = '' if split_type == 'default': pile_qty = len(pile) # Determine how many objects will be removed from the original pile. original_pile_qty = (pile_qty // 2) + (pile_qty % 2) new_pile_qty = pile_qty // 2 new_pile_items = [] # Grab references to all objects that are to be moved from the pile. # New pile objects are always taken from the backend of the pile's contents. # Due to list indexes starting at 0, the remaining quantity for the original pile # will actually be the starting index of the new pile's candidates. for index in range(original_pile_qty, pile_qty - 1): new_pile_items.append(pile.contents[index]) new_pile_qty = len(new_pile_items) if new_pile_qty > 1: # There are more than one object being split from the original pile. if gen_mec.all_same(new_pile_items): new_pile = create_object(typeclass="items.objects.InventoryGroup", key=f"a pile of {new_pile_items[0].db.plural_key}", location=obj_loc) else: new_pile = create_object(typeclass="items.objects.InventoryGroup", key=f"a pile of various items", location=obj_loc) # Move the objects from the original pile to the new pile. for item in new_pile_items: item.move_to(new_pile, quiet=True, move_hooks=False) # Set each pile's quantity attribute. pile.db.quantity = len(pile.contents) new_pile.db.quantity = len(new_pile.contents) msg = f"You split {pile.key} in two, creating {new_pile.key}" else: # The number of split objects is only 1 and is not a pile. # Move the object into the room. new_pile_items[0].move_to(obj_loc, quiet=True, move_hooks=False) msg = f"You split {new_pile_items[0]} from {pile.key}." # If only 1 object has been split from the pile, the original pile only has 1 or 2 # objects remaining. if len(pile.contents) == 1: for obj in pile.contents: obj.move_to(obj_loc, quiet=True, move_hooks=False) msg = f"{msg}\n{obj.key} is removed from {pile.key}. {pile.key} is no more." if len(pile.contents) == 0: pile.delete() if split_type == 'from': extract_obj_names = [] extract_objects = pile.search(extract_obj, location=pile, quiet=True) # Check that there are enough objects in the pile to meet requirements. if len(extract_objects) >= quantity: num = 1 while num <= quantity: obj = extract_objects.pop() extract_obj_names.append(obj.name) obj.move_to(obj_loc, quiet=True, move_hooks=False) num += 1 msg = f"You split" if gen_mec.all_same(extract_obj_names): msg = f"{msg} {quantity} {extract_obj_names[0]}" else: msg = f"{msg} {gen_mec.comma_separated_string_list(extract_obj_names)}" msg= f"{msg} from {pile_name}." else: msg = f"There aren't {quantity} of {extract_obj} in {pile.name}!" return msg # Check if the pile has 1 or less objects remaining. if len(pile.contents) == 1: obj = pile.contents[0] obj.move_to(obj_loc, quiet=True, move_hooks=False) if len(pile.contents) == 0: pile.delete() return msg def spawn(self, item_type, item_name=None): """ Spawn an item from the items.items module. Returns: item (object): An item object of the Object typeclass. """ owner = self.owner item_type_dict = self.items_dict.get(item_type, None) if not item_type_dict: owner.msg(f"|rWARNING! Could not find {item_type} from the items.items items dictionary " "within the ItemHandler spawn() method.|n") return location = owner tags = None attributes = None item = create_object(typeclass="items.objects.Object", key=item_name, location=location, home=None, tags=tags, attributes=attributes) return item
[ "evennia.utils.create.create_object", "evennia.utils.utils.variable_from_module" ]
[((411, 464), 'evennia.utils.utils.variable_from_module', 'variable_from_module', (['"""items.items"""'], {'variable': '"""items"""'}), "('items.items', variable='items')\n", (431, 464), False, 'from evennia.utils.utils import variable_from_module\n'), ((5066, 5112), 'misc.coin.generate_coin_object', 'coin.generate_coin_object', ([], {'copper': 'total_copper'}), '(copper=total_copper)\n', (5091, 5112), False, 'from misc import coin\n'), ((16196, 16234), 'misc.coin.coin_dict_to_copper', 'coin.coin_dict_to_copper', (['pile.db.coin'], {}), '(pile.db.coin)\n', (16220, 16234), False, 'from misc import coin\n'), ((17326, 17381), 'misc.coin.generate_coin_object', 'coin.generate_coin_object', ([], {'coin_dict': 'original_coin_dict'}), '(coin_dict=original_coin_dict)\n', (17351, 17381), False, 'from misc import coin\n'), ((17450, 17500), 'misc.coin.generate_coin_object', 'coin.generate_coin_object', ([], {'coin_dict': 'new_coin_dict'}), '(coin_dict=new_coin_dict)\n', (17475, 17500), False, 'from misc import coin\n'), ((23734, 23865), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""items.objects.Object"""', 'key': 'item_name', 'location': 'location', 'home': 'None', 'tags': 'tags', 'attributes': 'attributes'}), "(typeclass='items.objects.Object', key=item_name, location=\n location, home=None, tags=tags, attributes=attributes)\n", (23747, 23865), False, 'from evennia.utils.create import create_object\n'), ((3310, 3356), 'misc.general_mechanics.comma_separated_string_list', 'gen_mec.comma_separated_string_list', (['qty_names'], {}), '(qty_names)\n', (3345, 3356), True, 'from misc import general_mechanics as gen_mec\n'), ((4803, 4846), 'misc.general_mechanics.objects_to_strings', 'gen_mec.objects_to_strings', (['coin_groupables'], {}), '(coin_groupables)\n', (4829, 4846), True, 'from misc import general_mechanics as gen_mec\n'), ((4938, 4975), 'misc.coin.coin_dict_to_copper', 'coin.coin_dict_to_copper', (['obj.db.coin'], {}), '(obj.db.coin)\n', (4962, 4975), False, 'from misc import coin\n'), ((8988, 9030), 'misc.general_mechanics.objects_to_strings', 'gen_mec.objects_to_strings', (['inv_groupables'], {}), '(inv_groupables)\n', (9014, 9030), True, 'from misc import general_mechanics as gen_mec\n'), ((9154, 9284), 'evennia.utils.create.create_object', 'create_object', ([], {'key': 'f"""a pile of {inv_groupables[0].db.plural_key}"""', 'typeclass': '"""items.objects.InventoryGroup"""', 'location': 'obj_loc'}), "(key=f'a pile of {inv_groupables[0].db.plural_key}', typeclass\n ='items.objects.InventoryGroup', location=obj_loc)\n", (9167, 9284), False, 'from evennia.utils.create import create_object\n'), ((9628, 9738), 'evennia.utils.create.create_object', 'create_object', ([], {'key': 'f"""a pile of various items"""', 'typeclass': '"""items.objects.InventoryGroup"""', 'location': 'obj_loc'}), "(key=f'a pile of various items', typeclass=\n 'items.objects.InventoryGroup', location=obj_loc)\n", (9641, 9738), False, 'from evennia.utils.create import create_object\n'), ((13605, 13644), 'misc.coin.create_coin_dict', 'coin.create_coin_dict', ([], {}), '(**temp_coin_dict)\n', (13626, 13644), False, 'from misc import coin\n'), ((13668, 13714), 'misc.coin.generate_coin_object', 'coin.generate_coin_object', ([], {'coin_dict': 'coin_dict'}), '(coin_dict=coin_dict)\n', (13693, 13714), False, 'from misc import coin\n'), ((14268, 14306), 'misc.coin.is_homogenized', 'coin.is_homogenized', (['group_obj.db.coin'], {}), '(group_obj.db.coin)\n', (14287, 14306), False, 'from misc import coin\n'), ((14754, 14805), 'misc.general_mechanics.comma_separated_string_list', 'gen_mec.comma_separated_string_list', (['new_coin_names'], {}), '(new_coin_names)\n', (14789, 14805), True, 'from misc import general_mechanics as gen_mec\n'), ((17169, 17210), 'misc.coin.copper_to_coin_dict', 'coin.copper_to_coin_dict', (['original_copper'], {}), '(original_copper)\n', (17193, 17210), False, 'from misc import coin\n'), ((17259, 17295), 'misc.coin.copper_to_coin_dict', 'coin.copper_to_coin_dict', (['new_copper'], {}), '(new_copper)\n', (17283, 17295), False, 'from misc import coin\n'), ((8616, 8660), 'misc.general_mechanics.objects_to_strings', 'gen_mec.objects_to_strings', (['group_groupables'], {}), '(group_groupables)\n', (8642, 8660), True, 'from misc import general_mechanics as gen_mec\n'), ((9556, 9598), 'misc.general_mechanics.objects_to_strings', 'gen_mec.objects_to_strings', (['inv_groupables'], {}), '(inv_groupables)\n', (9582, 9598), True, 'from misc import general_mechanics as gen_mec\n'), ((16714, 16754), 'misc.coin.coin_dict_to_copper', 'coin.coin_dict_to_copper', (['temp_coin_dict'], {}), '(temp_coin_dict)\n', (16738, 16754), False, 'from misc import coin\n'), ((20186, 20218), 'misc.general_mechanics.all_same', 'gen_mec.all_same', (['new_pile_items'], {}), '(new_pile_items)\n', (20202, 20218), True, 'from misc import general_mechanics as gen_mec\n'), ((22441, 22476), 'misc.general_mechanics.all_same', 'gen_mec.all_same', (['extract_obj_names'], {}), '(extract_obj_names)\n', (22457, 22476), True, 'from misc import general_mechanics as gen_mec\n'), ((20251, 20381), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""items.objects.InventoryGroup"""', 'key': 'f"""a pile of {new_pile_items[0].db.plural_key}"""', 'location': 'obj_loc'}), "(typeclass='items.objects.InventoryGroup', key=\n f'a pile of {new_pile_items[0].db.plural_key}', location=obj_loc)\n", (20264, 20381), False, 'from evennia.utils.create import create_object\n'), ((20454, 20564), 'evennia.utils.create.create_object', 'create_object', ([], {'typeclass': '"""items.objects.InventoryGroup"""', 'key': 'f"""a pile of various items"""', 'location': 'obj_loc'}), "(typeclass='items.objects.InventoryGroup', key=\n f'a pile of various items', location=obj_loc)\n", (20467, 20564), False, 'from evennia.utils.create import create_object\n'), ((22604, 22658), 'misc.general_mechanics.comma_separated_string_list', 'gen_mec.comma_separated_string_list', (['extract_obj_names'], {}), '(extract_obj_names)\n', (22639, 22658), True, 'from misc import general_mechanics as gen_mec\n'), ((11330, 11372), 'misc.general_mechanics.objects_to_strings', 'gen_mec.objects_to_strings', (['group_contents'], {}), '(group_contents)\n', (11356, 11372), True, 'from misc import general_mechanics as gen_mec\n')]
""" I'm slowly replacing Attributes as the primary form of data storage of the game with real tables. Occasionally I'm finding places where the attributes aren't being used at all but were still having rows populated, so I wanted to wipe them without creating a one-off migration that would then need to be deleted right after being applied to avoid slowing down tests. """ from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Fix permissions for proxy models." def handle(self, *args, **options): wipe_attributes() def wipe_attributes(): from evennia.typeclasses.attributes import Attribute # different attributes that we're dumping due to not being used attr_names = ["stealth", "sense_difficulty", "is_wieldable"] print( f"Deleting stale attributes: {Attribute.objects.filter(db_key__in=attr_names).delete()}" )
[ "evennia.typeclasses.attributes.Attribute.objects.filter" ]
[((836, 883), 'evennia.typeclasses.attributes.Attribute.objects.filter', 'Attribute.objects.filter', ([], {'db_key__in': 'attr_names'}), '(db_key__in=attr_names)\n', (860, 883), False, 'from evennia.typeclasses.attributes import Attribute\n')]
""" At_initial_setup module template Custom at_initial_setup method. This allows you to hook special modifications to the initial server startup process. Note that this will only be run once - when the server starts up for the very first time! It is called last in the startup process and can thus be used to overload things that happened before it. The module must contain a global function at_initial_setup(). This will be called without arguments. Note that tracebacks in this module will be QUIETLY ignored, so make sure to check it well to make sure it does what you expect it to. """ from evennia.utils import create, search from AU_Modules.AU_RPGSystem import AU_RPGLanguages from AU_Modules.AU_Langs import AU_Languages def at_initial_setup(): # Definition of the english language AU_RPGLanguages.add_language(key=AU_Languages.english_key, phonemes=AU_Languages.english_phonemes, grammar=AU_Languages.english_grammar, word_length_variance=AU_Languages.english_word_length_variance, noun_translate=AU_Languages.english_noun_translate, noun_prefix=AU_Languages.english_noun_prefix, noun_postfix=AU_Languages.english_noun_postfix, vowels=AU_Languages.english_vowels, manual_translations=AU_Languages.english_manual_translations, auto_translations=AU_Languages.english_auto_translations, force=AU_Languages.english_force) # Definition of all languages used in the mud. # TODO: add the languages # Creation of the initial CharGen Room and its objects # Room creation # TODO: create chargen room # objects Creation # TODO: Create object in room # Create the main character generation room chargen_room = create.create_object(typeclass='CoC.CoC_Rooms.CoCCharGenRoom', key='Investigator Room') chargen_room.db.desc = 'Here you con create your investigator.' chargen_room.tags.add('default_chargen', category='rooms') chargen_room.save() limboroom=search.object_search('Limbo')[0] silla = create.create_object(typeclass='CoC.CoC_Objects.CoCObject', key='silla', location=limboroom) silla.save() pass """ # Create the main character generation room #chargen_room = create.create_object(typeclass='CoC.CoC_Rooms.CoCCharGenRoom', key='Investigator Room') #chargen_room.db.desc = dedent('Here you con create your investigator.') #chargen_room.tags.add('default_chargen', category='rooms') """
[ "evennia.utils.search.object_search", "evennia.utils.create.create_object" ]
[((805, 1377), 'AU_Modules.AU_RPGSystem.AU_RPGLanguages.add_language', 'AU_RPGLanguages.add_language', ([], {'key': 'AU_Languages.english_key', 'phonemes': 'AU_Languages.english_phonemes', 'grammar': 'AU_Languages.english_grammar', 'word_length_variance': 'AU_Languages.english_word_length_variance', 'noun_translate': 'AU_Languages.english_noun_translate', 'noun_prefix': 'AU_Languages.english_noun_prefix', 'noun_postfix': 'AU_Languages.english_noun_postfix', 'vowels': 'AU_Languages.english_vowels', 'manual_translations': 'AU_Languages.english_manual_translations', 'auto_translations': 'AU_Languages.english_auto_translations', 'force': 'AU_Languages.english_force'}), '(key=AU_Languages.english_key, phonemes=\n AU_Languages.english_phonemes, grammar=AU_Languages.english_grammar,\n word_length_variance=AU_Languages.english_word_length_variance,\n noun_translate=AU_Languages.english_noun_translate, noun_prefix=\n AU_Languages.english_noun_prefix, noun_postfix=AU_Languages.\n english_noun_postfix, vowels=AU_Languages.english_vowels,\n manual_translations=AU_Languages.english_manual_translations,\n auto_translations=AU_Languages.english_auto_translations, force=\n AU_Languages.english_force)\n', (833, 1377), False, 'from AU_Modules.AU_RPGSystem import AU_RPGLanguages\n'), ((1993, 2085), 'evennia.utils.create.create_object', 'create.create_object', ([], {'typeclass': '"""CoC.CoC_Rooms.CoCCharGenRoom"""', 'key': '"""Investigator Room"""'}), "(typeclass='CoC.CoC_Rooms.CoCCharGenRoom', key=\n 'Investigator Room')\n", (2013, 2085), False, 'from evennia.utils import create, search\n'), ((2295, 2391), 'evennia.utils.create.create_object', 'create.create_object', ([], {'typeclass': '"""CoC.CoC_Objects.CoCObject"""', 'key': '"""silla"""', 'location': 'limboroom'}), "(typeclass='CoC.CoC_Objects.CoCObject', key='silla',\n location=limboroom)\n", (2315, 2391), False, 'from evennia.utils import create, search\n'), ((2250, 2279), 'evennia.utils.search.object_search', 'search.object_search', (['"""Limbo"""'], {}), "('Limbo')\n", (2270, 2279), False, 'from evennia.utils import create, search\n')]
""" Various helper resources for writing unittests. Classes for testing Evennia core: - `BaseEvenniaTestCase` - no default objects, only enforced default settings - `BaseEvenniaTest` - all default objects, enforced default settings - `BaseEvenniaCommandTest` - for testing Commands, enforced default settings Classes for testing game folder content: - `EvenniaTestCase` - no default objects, using gamedir settings (identical to standard Python TestCase) - `EvenniaTest` - all default objects, using gamedir settings - `EvenniaCommandTest` - for testing game folder commands, using gamedir settings Other: - `EvenniaTestMixin` - A class mixin for creating the test environment objects, for making custom tests. - `EvenniaCommandMixin` - A class mixin that adds support for command testing with the .call() helper. Used by the command-test classes, but can be used for making a customt test class. """ import sys import re import types from twisted.internet.defer import Deferred from django.conf import settings from django.test import TestCase, override_settings from mock import Mock, patch, MagicMock from evennia.objects.objects import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit from evennia.accounts.accounts import DefaultAccount from evennia.scripts.scripts import DefaultScript from evennia.server.serversession import ServerSession from evennia.server.sessionhandler import SESSIONS from evennia.utils import create from evennia.utils.idmapper.models import flush_cache from evennia.utils.utils import all_from_module, to_str from evennia.utils import ansi from evennia import settings_default from evennia.commands.default.muxcommand import MuxCommand from evennia.commands.command import InterruptCommand _RE_STRIP_EVMENU = re.compile(r"^\+|-+\+|\+-+|--+|\|(?:\s|$)", re.MULTILINE) # set up a 'pristine' setting, unaffected by any changes in mygame DEFAULT_SETTING_RESETS = dict( CONNECTION_SCREEN_MODULE="evennia.game_template.server.conf.connection_screens", AT_SERVER_STARTSTOP_MODULE="evennia.game_template.server.conf.at_server_startstop", AT_SERVICES_PLUGINS_MODULES=["evennia.game_template.server.conf.server_services_plugins"], PORTAL_SERVICES_PLUGIN_MODULES=["evennia.game_template.server.conf.portal_services_plugins"], MSSP_META_MODULE="evennia.game_template.server.conf.mssp", WEB_PLUGINS_MODULE="server.conf.web_plugins", LOCK_FUNC_MODULES=("evennia.locks.lockfuncs", "evennia.game_template.server.conf.lockfuncs"), INPUT_FUNC_MODULES=["evennia.server.inputfuncs", "evennia.game_template.server.conf.inputfuncs"], PROTOTYPE_MODULES=["evennia.game_template.world.prototypes"], CMDSET_UNLOGGEDIN="evennia.game_template.commands.default_cmdsets.UnloggedinCmdSet", CMDSET_SESSION="evennia.game_template.commands.default_cmdsets.SessionCmdSet", CMDSET_CHARACTER="evennia.game_template.commands.default_cmdsets.CharacterCmdSet", CMDSET_ACCOUNT="evennia.game_template.commands.default_cmdsets.AccountCmdSet", CMDSET_PATHS=["evennia.game_template.commands", "evennia", "evennia.contrib"], TYPECLASS_PATHS=[ "evennia", "evennia.contrib", "evennia.contrib.game_systems", "evennia.contrib.base_systems", "evennia.contrib.full_systems", "evennia.contrib.tutorials", "evennia.contrib.utils"], BASE_ACCOUNT_TYPECLASS="evennia.accounts.accounts.DefaultAccount", BASE_OBJECT_TYPECLASS="evennia.objects.objects.DefaultObject", BASE_CHARACTER_TYPECLASS="evennia.objects.objects.DefaultCharacter", BASE_ROOM_TYPECLASS="evennia.objects.objects.DefaultRoom", BASE_EXIT_TYPECLASS="evennia.objects.objects.DefaultExit", BASE_CHANNEL_TYPECLASS="evennia.comms.comms.DefaultChannel", BASE_SCRIPT_TYPECLASS="evennia.scripts.scripts.DefaultScript", BASE_BATCHPROCESS_PATHS=["evennia.game_template.world", "evennia.contrib", "evennia.contrib.tutorials"], FILE_HELP_ENTRY_MODULES=["evennia.game_template.world.help_entries"], FUNCPARSER_OUTGOING_MESSAGES_MODULES=["evennia.utils.funcparser", "evennia.game_template.server.conf.inlinefuncs"], FUNCPARSER_PROTOTYPE_PARSING_MODULES=["evennia.prototypes.protfuncs", "evennia.game_template.server.conf.prototypefuncs"], BASE_GUEST_TYPECLASS="evennia.accounts.accounts.DefaultGuest", # a special flag; test with settings._TEST_ENVIRONMENT to see if code runs in a test _TEST_ENVIRONMENT=True, ) DEFAULT_SETTINGS = { **all_from_module(settings_default), **DEFAULT_SETTING_RESETS } DEFAULT_SETTINGS.pop("DATABASES") # we want different dbs tested in CI # mocking of evennia.utils.utils.delay def mockdelay(timedelay, callback, *args, **kwargs): callback(*args, **kwargs) return Deferred() # mocking of twisted's deferLater def mockdeferLater(reactor, timedelay, callback, *args, **kwargs): callback(*args, **kwargs) return Deferred() def unload_module(module): """ Reset import so one can mock global constants. Args: module (module, object or str): The module will be removed so it will have to be imported again. If given an object, the module in which that object sits will be unloaded. A string should directly give the module pathname to unload. Example: ```python # (in a test method) unload_module(foo) with mock.patch("foo.GLOBALTHING", "mockval"): import foo ... # test code using foo.GLOBALTHING, now set to 'mockval' ``` This allows for mocking constants global to the module, since otherwise those would not be mocked (since a module is only loaded once). """ if isinstance(module, str): modulename = module elif hasattr(module, "__module__"): modulename = module.__module__ else: modulename = module.__name__ if modulename in sys.modules: del sys.modules[modulename] def _mock_deferlater(reactor, timedelay, callback, *args, **kwargs): callback(*args, **kwargs) return Deferred() class EvenniaTestMixin: """ Evennia test environment mixin """ account_typeclass = DefaultAccount object_typeclass = DefaultObject character_typeclass = DefaultCharacter exit_typeclass = DefaultExit room_typeclass = DefaultRoom script_typeclass = DefaultScript def create_accounts(self): self.account = create.create_account( "TestAccount", email="<EMAIL>", password="<PASSWORD>", typeclass=self.account_typeclass, ) self.account2 = create.create_account( "TestAccount2", email="<EMAIL>", password="<PASSWORD>", typeclass=self.account_typeclass, ) self.account.permissions.add("Developer") def teardown_accounts(self): if hasattr(self, "account"): self.account.delete() if hasattr(self, "account2"): self.account2.delete() # Set up fake prototype module for allowing tests to use named prototypes. @override_settings(PROTOTYPE_MODULES=["evennia.utils.tests.data.prototypes_example"], DEFAULT_HOME="#1") def create_rooms(self): self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object( self.exit_typeclass, key="out", location=self.room1, destination=self.room2 ) def create_objs(self): self.obj1 = create.create_object( self.object_typeclass, key="Obj", location=self.room1, home=self.room1 ) self.obj2 = create.create_object( self.object_typeclass, key="Obj2", location=self.room1, home=self.room1 ) def create_chars(self): self.char1 = create.create_object( self.character_typeclass, key="Char", location=self.room1, home=self.room1 ) self.char1.permissions.add("Developer") self.char2 = create.create_object( self.character_typeclass, key="Char2", location=self.room1, home=self.room1 ) self.char1.account = self.account self.account.db._last_puppet = self.char1 self.char2.account = self.account2 self.account2.db._last_puppet = self.char2 def create_script(self): self.script = create.create_script(self.script_typeclass, key="Script") def setup_session(self): dummysession = ServerSession() dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS) dummysession.sessid = 1 SESSIONS.portal_connect( dummysession.get_sync_data() ) # note that this creates a new Session! session = SESSIONS.session_from_sessid(1) # the real session SESSIONS.login(session, self.account, testmode=True) self.session = session def teardown_session(self): if hasattr(self, "sessions"): del SESSIONS[self.session.sessid] @patch("evennia.scripts.taskhandler.deferLater", _mock_deferlater) def setUp(self): """ Sets up testing environment """ self.backups = ( SESSIONS.data_out, SESSIONS.disconnect, settings.DEFAULT_HOME, settings.PROTOTYPE_MODULES, ) SESSIONS.data_out = Mock() SESSIONS.disconnect = Mock() self.create_accounts() self.create_rooms() self.create_objs() self.create_chars() self.create_script() self.setup_session() def tearDown(self): flush_cache() try: SESSIONS.data_out = self.backups[0] SESSIONS.disconnect = self.backups[1] settings.DEFAULT_HOME = self.backups[2] settings.PROTOTYPE_MODULES = self.backups[3] except AttributeError as err: raise AttributeError(f"{err}: Teardown error. If you overrode the `setUp()` method " "in your test, make sure you also added `super().setUp()`!") del SESSIONS[self.session.sessid] self.teardown_accounts() super().tearDown() @patch("evennia.server.portal.portal.LoopingCall", new=MagicMock()) class EvenniaCommandTestMixin: """ Mixin to add to a test in order to provide the `.call` helper for testing the execution and returns of a command. Tests a Command by running it and comparing what messages it sends with expected values. This tests without actually spinning up the cmdhandler for every test, which is more controlled. Example: :: from commands.echo import CmdEcho class MyCommandTest(EvenniaTest, CommandTestMixin): def test_echo(self): ''' Test that the echo command really returns what you pass into it. ''' self.call(MyCommand(), "hello world!", "You hear your echo: 'Hello world!'") """ # formatting for .call's error message _ERROR_FORMAT = """ =========================== Wanted message =================================== {expected_msg} =========================== Returned message ================================= {returned_msg} ============================================================================== """.rstrip() def call( self, cmdobj, input_args, msg=None, cmdset=None, noansi=True, caller=None, receiver=None, cmdstring=None, obj=None, inputs=None, raw_string=None, ): """ Test a command by assigning all the needed properties to a cmdobj and running the sequence. The resulting `.msg` calls will be mocked and the text= calls to them compared to a expected output. Args: cmdobj (Command): The command object to use. input_args (str): This should be the full input the Command should see, such as 'look here'. This will become `.args` for the Command instance to parse. msg (str or dict, optional): This is the expected return value(s) returned through `caller.msg(text=...)` calls in the command. If a string, the receiver is controlled with the `receiver` kwarg (defaults to `caller`). If this is a `dict`, it is a mapping `{receiver1: "expected1", receiver2: "expected2",...}` and `receiver` is ignored. The message(s) are compared with the actual messages returned to the receiver(s) as the Command runs. Each check uses `.startswith`, so you can choose to only include the first part of the returned message if that's enough to verify a correct result. EvMenu decorations (like borders) are stripped and should not be included. This should also not include color tags unless `noansi=False`. If the command returns texts in multiple separate `.msg`- calls to a receiver, separate these with `|` if `noansi=True` (default) and `||` if `noansi=False`. If no `msg` is given (`None`), then no automatic comparison will be done. cmdset (str, optional): If given, make `.cmdset` available on the Command instance as it runs. While `.cmdset` is normally available on the Command instance by default, this is usually only used by commands that explicitly operates/displays cmdsets, like `examine`. noansi (str, optional): By default the color tags of the `msg` is ignored, this makes them significant. If unset, `msg` must contain the same color tags as the actual return message. caller (Object or Account, optional): By default `self.char1` is used as the command-caller (the `.caller` property on the Command). This allows to execute with another caller, most commonly an Account. receiver (Object or Account, optional): This is the object to receive the return messages we want to test. By default this is the same as `caller` (which in turn defaults to is `self.char1`). Note that if `msg` is a `dict`, this is ignored since the receiver is already specified there. cmdstring (str, optional): Normally this is the Command's `key`. This allows for tweaking the `.cmdname` property of the Command`. This isb used for commands with multiple aliases, where the command explicitly checs which alias was used to determine its functionality. obj (str, optional): This sets the `.obj` property of the Command - the object on which the Command 'sits'. By default this is the same as `caller`. This can be used for testing on-object Command interactions. inputs (list, optional): A list of strings to pass to functions that pause to take input from the user (normally using `@interactive` and `ret = yield(question)` or `evmenu.get_input`). Each element of the list will be passed into the command as if the user wrote that at the prompt. raw_string (str, optional): Normally the `.raw_string` property is set as a combination of your `key/cmdname` and `input_args`. This allows direct control of what this is, for example for testing edge cases or malformed inputs. Returns: str or dict: The message sent to `receiver`, or a dict of `{receiver: "msg", ...}` if multiple are given. This is usually only used with `msg=None` to do the validation externally. Raises: AssertionError: If the returns of `.msg` calls (tested with `.startswith`) does not match `expected_input`. Notes: As part of the tests, all methods of the Command will be called in the proper order: - cmdobj.at_pre_cmd() - cmdobj.parse() - cmdobj.func() - cmdobj.at_post_cmd() """ # The `self.char1` is created in the `EvenniaTest` base along with # other helper objects like self.room and self.obj caller = caller if caller else self.char1 cmdobj.caller = caller cmdobj.cmdname = cmdstring if cmdstring else cmdobj.key cmdobj.raw_cmdname = cmdobj.cmdname cmdobj.cmdstring = cmdobj.cmdname # deprecated cmdobj.args = input_args cmdobj.cmdset = cmdset cmdobj.session = SESSIONS.session_from_sessid(1) cmdobj.account = self.account cmdobj.raw_string = raw_string if raw_string is not None else cmdobj.key + " " + input_args cmdobj.obj = obj or (caller if caller else self.char1) inputs = inputs or [] # set up receivers receiver_mapping = {} if isinstance(msg, dict): # a mapping {receiver: msg, ...} receiver_mapping = {recv: str(msg).strip() if msg else None for recv, msg in msg.items()} else: # a single expected string and thus a single receiver (defaults to caller) receiver = receiver if receiver else caller receiver_mapping[receiver] = str(msg).strip() if msg is not None else None unmocked_msg_methods = {} for receiver in receiver_mapping: # save the old .msg method so we can get it back # cleanly after the test unmocked_msg_methods[receiver] = receiver.msg # replace normal `.msg` with a mock receiver.msg = Mock() # Run the methods of the Command. This mimics what happens in the # cmdhandler. This will have the mocked .msg be called as part of the # execution. Mocks remembers what was sent to them so we will be able # to retrieve what was sent later. try: if cmdobj.at_pre_cmd(): return cmdobj.parse() ret = cmdobj.func() # handle func's with yield in them (making them generators) if isinstance(ret, types.GeneratorType): while True: try: inp = inputs.pop() if inputs else None if inp: try: # this mimics a user's reply to a prompt ret.send(inp) except TypeError: next(ret) ret = ret.send(inp) else: # non-input yield, like yield(10). We don't pause # but fire it immediately. next(ret) except StopIteration: break cmdobj.at_post_cmd() except StopIteration: pass except InterruptCommand: pass for inp in inputs: # if there are any inputs left, we may have a non-generator # input to handle (get_input/ask_yes_no that uses a separate # cmdset rather than a yield caller.execute_cmd(inp) # At this point the mocked .msg methods on each receiver will have # stored all calls made to them (that's a basic function of the Mock # class). We will not extract them and compare to what we expected to # go to each receiver. returned_msgs = {} for receiver, expected_msg in receiver_mapping.items(): # get the stored messages from the Mock with Mock.mock_calls. stored_msg = [ args[0] if args and args[0] else kwargs.get("text", to_str(kwargs)) for name, args, kwargs in receiver.msg.mock_calls ] # we can return this now, we are done using the mock receiver.msg = unmocked_msg_methods[receiver] # Get the first element of a tuple if msg received a tuple instead of a string stored_msg = [str(smsg[0]) if isinstance(smsg, tuple) else str(smsg) for smsg in stored_msg] if expected_msg is None: # no expected_msg; just build the returned_msgs dict returned_msg = "\n".join(str(msg) for msg in stored_msg) returned_msgs[receiver] = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip() else: # compare messages to expected # set our separator for returned messages based on parsing ansi or not msg_sep = "|" if noansi else "||" # We remove Evmenu decorations since that just makes it harder # to write the comparison string. We also strip ansi before this # comparison since otherwise it would mess with the regex. returned_msg = msg_sep.join( _RE_STRIP_EVMENU.sub( "", ansi.parse_ansi(mess, strip_ansi=noansi)) for mess in stored_msg).strip() # this is the actual test if expected_msg == "" and returned_msg or not returned_msg.startswith(expected_msg): # failed the test raise AssertionError( self._ERROR_FORMAT.format( expected_msg=expected_msg, returned_msg=returned_msg) ) # passed! returned_msgs[receiver] = returned_msg if len(returned_msgs) == 1: return list(returned_msgs.values())[0] return returned_msgs # Base testing classes @override_settings(**DEFAULT_SETTINGS) class BaseEvenniaTestCase(TestCase): """ Base test (with no default objects) but with enforced default settings. """ class EvenniaTestCase(TestCase): """ For use with gamedir settings; Just like the normal test case, only for naming consistency. """ pass @override_settings(**DEFAULT_SETTINGS) class BaseEvenniaTest(EvenniaTestMixin, TestCase): """ This class parent has all default objects and uses only default settings. """ class EvenniaTest(EvenniaTestMixin, TestCase): """ This test class is intended for inheriting in mygame tests. It helps ensure your tests are run with your own objects and settings from your game folder. """ account_typeclass = settings.BASE_ACCOUNT_TYPECLASS object_typeclass = settings.BASE_OBJECT_TYPECLASS character_typeclass = settings.BASE_CHARACTER_TYPECLASS exit_typeclass = settings.BASE_EXIT_TYPECLASS room_typeclass = settings.BASE_ROOM_TYPECLASS script_typeclass = settings.BASE_SCRIPT_TYPECLASS @patch("evennia.commands.account.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.admin.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.batchprocess.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.building.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.comms.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.general.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.help.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.syscommands.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.system.COMMAND_DEFAULT_CLASS", MuxCommand) @patch("evennia.commands.unloggedin.COMMAND_DEFAULT_CLASS", MuxCommand) class BaseEvenniaCommandTest(BaseEvenniaTest, EvenniaCommandTestMixin): """ Commands only using the default settings. """ class EvenniaCommandTest(EvenniaTest, EvenniaCommandTestMixin): """ Parent class to inherit from - makes tests use your own classes and settings in mygame. """
[ "evennia.server.sessionhandler.SESSIONS.session_from_sessid", "evennia.utils.utils.to_str", "evennia.utils.ansi.parse_ansi", "evennia.utils.idmapper.models.flush_cache", "evennia.utils.utils.all_from_module", "evennia.server.sessionhandler.SESSIONS.login", "evennia.utils.create.create_script", "evenni...
[((1766, 1827), 're.compile', 're.compile', (['"""^\\\\+|-+\\\\+|\\\\+-+|--+|\\\\|(?:\\\\s|$)"""', 're.MULTILINE'], {}), "('^\\\\+|-+\\\\+|\\\\+-+|--+|\\\\|(?:\\\\s|$)', re.MULTILINE)\n", (1776, 1827), False, 'import re\n'), ((22349, 22386), 'django.test.override_settings', 'override_settings', ([], {}), '(**DEFAULT_SETTINGS)\n', (22366, 22386), False, 'from django.test import TestCase, override_settings\n'), ((22676, 22713), 'django.test.override_settings', 'override_settings', ([], {}), '(**DEFAULT_SETTINGS)\n', (22693, 22713), False, 'from django.test import TestCase, override_settings\n'), ((23418, 23485), 'mock.patch', 'patch', (['"""evennia.commands.account.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.account.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23423, 23485), False, 'from mock import Mock, patch, MagicMock\n'), ((23487, 23552), 'mock.patch', 'patch', (['"""evennia.commands.admin.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.admin.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23492, 23552), False, 'from mock import Mock, patch, MagicMock\n'), ((23554, 23626), 'mock.patch', 'patch', (['"""evennia.commands.batchprocess.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.batchprocess.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23559, 23626), False, 'from mock import Mock, patch, MagicMock\n'), ((23628, 23696), 'mock.patch', 'patch', (['"""evennia.commands.building.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.building.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23633, 23696), False, 'from mock import Mock, patch, MagicMock\n'), ((23698, 23763), 'mock.patch', 'patch', (['"""evennia.commands.comms.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.comms.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23703, 23763), False, 'from mock import Mock, patch, MagicMock\n'), ((23765, 23832), 'mock.patch', 'patch', (['"""evennia.commands.general.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.general.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23770, 23832), False, 'from mock import Mock, patch, MagicMock\n'), ((23834, 23898), 'mock.patch', 'patch', (['"""evennia.commands.help.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.help.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23839, 23898), False, 'from mock import Mock, patch, MagicMock\n'), ((23900, 23971), 'mock.patch', 'patch', (['"""evennia.commands.syscommands.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.syscommands.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23905, 23971), False, 'from mock import Mock, patch, MagicMock\n'), ((23973, 24039), 'mock.patch', 'patch', (['"""evennia.commands.system.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.system.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (23978, 24039), False, 'from mock import Mock, patch, MagicMock\n'), ((24041, 24111), 'mock.patch', 'patch', (['"""evennia.commands.unloggedin.COMMAND_DEFAULT_CLASS"""', 'MuxCommand'], {}), "('evennia.commands.unloggedin.COMMAND_DEFAULT_CLASS', MuxCommand)\n", (24046, 24111), False, 'from mock import Mock, patch, MagicMock\n'), ((4603, 4636), 'evennia.utils.utils.all_from_module', 'all_from_module', (['settings_default'], {}), '(settings_default)\n', (4618, 4636), False, 'from evennia.utils.utils import all_from_module, to_str\n'), ((4876, 4886), 'twisted.internet.defer.Deferred', 'Deferred', ([], {}), '()\n', (4884, 4886), False, 'from twisted.internet.defer import Deferred\n'), ((5031, 5041), 'twisted.internet.defer.Deferred', 'Deferred', ([], {}), '()\n', (5039, 5041), False, 'from twisted.internet.defer import Deferred\n'), ((6196, 6206), 'twisted.internet.defer.Deferred', 'Deferred', ([], {}), '()\n', (6204, 6206), False, 'from twisted.internet.defer import Deferred\n'), ((7239, 7347), 'django.test.override_settings', 'override_settings', ([], {'PROTOTYPE_MODULES': "['evennia.utils.tests.data.prototypes_example']", 'DEFAULT_HOME': '"""#1"""'}), "(PROTOTYPE_MODULES=[\n 'evennia.utils.tests.data.prototypes_example'], DEFAULT_HOME='#1')\n", (7256, 7347), False, 'from django.test import TestCase, override_settings\n'), ((9285, 9350), 'mock.patch', 'patch', (['"""evennia.scripts.taskhandler.deferLater"""', '_mock_deferlater'], {}), "('evennia.scripts.taskhandler.deferLater', _mock_deferlater)\n", (9290, 9350), False, 'from mock import Mock, patch, MagicMock\n'), ((6561, 6675), 'evennia.utils.create.create_account', 'create.create_account', (['"""TestAccount"""'], {'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""', 'typeclass': 'self.account_typeclass'}), "('TestAccount', email='<EMAIL>', password='<PASSWORD>',\n typeclass=self.account_typeclass)\n", (6582, 6675), False, 'from evennia.utils import create\n'), ((6755, 6871), 'evennia.utils.create.create_account', 'create.create_account', (['"""TestAccount2"""'], {'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""', 'typeclass': 'self.account_typeclass'}), "('TestAccount2', email='<EMAIL>', password=\n '<PASSWORD>', typeclass=self.account_typeclass)\n", (6776, 6871), False, 'from evennia.utils import create\n'), ((7415, 7481), 'evennia.utils.create.create_object', 'create.create_object', (['self.room_typeclass'], {'key': '"""Room"""', 'nohome': '(True)'}), "(self.room_typeclass, key='Room', nohome=True)\n", (7435, 7481), False, 'from evennia.utils import create\n'), ((7545, 7599), 'evennia.utils.create.create_object', 'create.create_object', (['self.room_typeclass'], {'key': '"""Room2"""'}), "(self.room_typeclass, key='Room2')\n", (7565, 7599), False, 'from evennia.utils import create\n'), ((7620, 7721), 'evennia.utils.create.create_object', 'create.create_object', (['self.exit_typeclass'], {'key': '"""out"""', 'location': 'self.room1', 'destination': 'self.room2'}), "(self.exit_typeclass, key='out', location=self.room1,\n destination=self.room2)\n", (7640, 7721), False, 'from evennia.utils import create\n'), ((7788, 7884), 'evennia.utils.create.create_object', 'create.create_object', (['self.object_typeclass'], {'key': '"""Obj"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.object_typeclass, key='Obj', location=self.room1,\n home=self.room1)\n", (7808, 7884), False, 'from evennia.utils import create\n'), ((7923, 8020), 'evennia.utils.create.create_object', 'create.create_object', (['self.object_typeclass'], {'key': '"""Obj2"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.object_typeclass, key='Obj2', location=self.room1,\n home=self.room1)\n", (7943, 8020), False, 'from evennia.utils import create\n'), ((8089, 8190), 'evennia.utils.create.create_object', 'create.create_object', (['self.character_typeclass'], {'key': '"""Char"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.character_typeclass, key='Char', location=self.\n room1, home=self.room1)\n", (8109, 8190), False, 'from evennia.utils import create\n'), ((8277, 8379), 'evennia.utils.create.create_object', 'create.create_object', (['self.character_typeclass'], {'key': '"""Char2"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.character_typeclass, key='Char2', location=self.\n room1, home=self.room1)\n", (8297, 8379), False, 'from evennia.utils import create\n'), ((8635, 8692), 'evennia.utils.create.create_script', 'create.create_script', (['self.script_typeclass'], {'key': '"""Script"""'}), "(self.script_typeclass, key='Script')\n", (8655, 8692), False, 'from evennia.utils import create\n'), ((8746, 8761), 'evennia.server.serversession.ServerSession', 'ServerSession', ([], {}), '()\n', (8759, 8761), False, 'from evennia.server.serversession import ServerSession\n'), ((9018, 9049), 'evennia.server.sessionhandler.SESSIONS.session_from_sessid', 'SESSIONS.session_from_sessid', (['(1)'], {}), '(1)\n', (9046, 9049), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((9078, 9130), 'evennia.server.sessionhandler.SESSIONS.login', 'SESSIONS.login', (['session', 'self.account'], {'testmode': '(True)'}), '(session, self.account, testmode=True)\n', (9092, 9130), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((9634, 9640), 'mock.Mock', 'Mock', ([], {}), '()\n', (9638, 9640), False, 'from mock import Mock, patch, MagicMock\n'), ((9671, 9677), 'mock.Mock', 'Mock', ([], {}), '()\n', (9675, 9677), False, 'from mock import Mock, patch, MagicMock\n'), ((9884, 9897), 'evennia.utils.idmapper.models.flush_cache', 'flush_cache', ([], {}), '()\n', (9895, 9897), False, 'from evennia.utils.idmapper.models import flush_cache\n'), ((17134, 17165), 'evennia.server.sessionhandler.SESSIONS.session_from_sessid', 'SESSIONS.session_from_sessid', (['(1)'], {}), '(1)\n', (17162, 17165), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((10507, 10518), 'mock.MagicMock', 'MagicMock', ([], {}), '()\n', (10516, 10518), False, 'from mock import Mock, patch, MagicMock\n'), ((18221, 18227), 'mock.Mock', 'Mock', ([], {}), '()\n', (18225, 18227), False, 'from mock import Mock, patch, MagicMock\n'), ((20376, 20390), 'evennia.utils.utils.to_str', 'to_str', (['kwargs'], {}), '(kwargs)\n', (20382, 20390), False, 'from evennia.utils.utils import all_from_module, to_str\n'), ((21040, 21088), 'evennia.utils.ansi.parse_ansi', 'ansi.parse_ansi', (['returned_msg'], {'strip_ansi': 'noansi'}), '(returned_msg, strip_ansi=noansi)\n', (21055, 21088), False, 'from evennia.utils import ansi\n'), ((21651, 21691), 'evennia.utils.ansi.parse_ansi', 'ansi.parse_ansi', (['mess'], {'strip_ansi': 'noansi'}), '(mess, strip_ansi=noansi)\n', (21666, 21691), False, 'from evennia.utils import ansi\n')]
""" The custom manager for Scripts. """ from django.db.models import Q from evennia.typeclasses.managers import TypedObjectManager, TypeclassManager from evennia.utils.utils import make_iter __all__ = ("ScriptManager", "ScriptDBManager") _GA = object.__getattribute__ VALIDATE_ITERATION = 0 class ScriptDBManager(TypedObjectManager): """ This Scriptmanager implements methods for searching and manipulating Scripts directly from the database. Evennia-specific search methods (will return Typeclasses or lists of Typeclasses, whereas Django-general methods will return Querysets or database objects). dbref (converter) get_id (or dbref_search) get_dbref_range object_totals typeclass_search get_all_scripts_on_obj get_all_scripts delete_script remove_non_persistent validate script_search (equivalent to evennia.search_script) copy_script """ def get_all_scripts_on_obj(self, obj, key=None): """ Find all Scripts related to a particular object. Args: obj (Object): Object whose Scripts we are looking for. key (str, optional): Script identifier - can be given as a dbref or name string. If given, only scripts matching the key on the object will be returned. Returns: matches (list): Matching scripts. """ if not obj: return [] account = _GA(_GA(obj, "__dbclass__"), "__name__") == "AccountDB" if key: dbref = self.dbref(key) if dbref or dbref == 0: if account: return self.filter(db_account=obj, id=dbref) else: return self.filter(db_obj=obj, id=dbref) elif account: return self.filter(db_account=obj, db_key=key) else: return self.filter(db_obj=obj, db_key=key) elif account: return self.filter(db_account=obj) else: return self.filter(db_obj=obj) def get_all_scripts(self, key=None): """ Get all scripts in the database. Args: key (str or int, optional): Restrict result to only those with matching key or dbref. Returns: scripts (list): All scripts found, or those matching `key`. """ if key: script = [] dbref = self.dbref(key) if dbref: return self.filter(id=dbref) return self.filter(db_key__iexact=key.strip()) return self.all() def delete_script(self, dbref): """ This stops and deletes a specific script directly from the script database. Args: dbref (int): Database unique id. Notes: This might be needed for global scripts not tied to a specific game object """ scripts = self.get_id(dbref) for script in make_iter(scripts): script.stop() script.delete() def update_scripts_after_server_start(self): """ Update/sync/restart/delete scripts after server shutdown/restart. """ for script in self.filter(db_is_active=True, db_persistent=False): script._stop_task() for script in self.filter(db_is_active=True): script._unpause_task(auto_unpause=True) script.at_server_start() for script in self.filter(db_is_active=False): script.at_server_start() def search_script(self, ostring, obj=None, only_timed=False, typeclass=None): """ Search for a particular script. Args: ostring (str): Search criterion - a script dbef or key. obj (Object, optional): Limit search to scripts defined on this object only_timed (bool): Limit search only to scripts that run on a timer. typeclass (class or str): Typeclass or path to typeclass. """ ostring = ostring.strip() dbref = self.dbref(ostring) if dbref: # this is a dbref, try to find the script directly dbref_match = self.dbref_search(dbref) if dbref_match and not ( (obj and obj != dbref_match.obj) or (only_timed and dbref_match.interval) ): return [dbref_match] if typeclass: if callable(typeclass): typeclass = "%s.%s" % (typeclass.__module__, typeclass.__name__) else: typeclass = "%s" % typeclass # not a dbref; normal search obj_restriction = obj and Q(db_obj=obj) or Q() timed_restriction = only_timed and Q(db_interval__gt=0) or Q() typeclass_restriction = typeclass and Q(db_typeclass_path=typeclass) or Q() scripts = self.filter( timed_restriction & obj_restriction & typeclass_restriction & Q(db_key__iexact=ostring) ) return scripts # back-compatibility alias script_search = search_script def copy_script(self, original_script, new_key=None, new_obj=None, new_locks=None): """ Make an identical copy of the original_script. Args: original_script (Script): The Script to copy. new_key (str, optional): Rename the copy. new_obj (Object, optional): Place copy on different Object. new_locks (str, optional): Give copy different locks from the original. Returns: script_copy (Script): A new Script instance, copied from the original. """ typeclass = original_script.typeclass_path new_key = new_key if new_key is not None else original_script.key new_obj = new_obj if new_obj is not None else original_script.obj new_locks = new_locks if new_locks is not None else original_script.db_lock_storage from evennia.utils import create new_script = create.create_script( typeclass, key=new_key, obj=new_obj, locks=new_locks, autostart=True ) return new_script class ScriptManager(ScriptDBManager, TypeclassManager): pass
[ "evennia.utils.create.create_script", "evennia.utils.utils.make_iter" ]
[((3020, 3038), 'evennia.utils.utils.make_iter', 'make_iter', (['scripts'], {}), '(scripts)\n', (3029, 3038), False, 'from evennia.utils.utils import make_iter\n'), ((6087, 6181), 'evennia.utils.create.create_script', 'create.create_script', (['typeclass'], {'key': 'new_key', 'obj': 'new_obj', 'locks': 'new_locks', 'autostart': '(True)'}), '(typeclass, key=new_key, obj=new_obj, locks=new_locks,\n autostart=True)\n', (6107, 6181), False, 'from evennia.utils import create\n'), ((4759, 4762), 'django.db.models.Q', 'Q', ([], {}), '()\n', (4760, 4762), False, 'from django.db.models import Q\n'), ((4830, 4833), 'django.db.models.Q', 'Q', ([], {}), '()\n', (4831, 4833), False, 'from django.db.models import Q\n'), ((4914, 4917), 'django.db.models.Q', 'Q', ([], {}), '()\n', (4915, 4917), False, 'from django.db.models import Q\n'), ((4742, 4755), 'django.db.models.Q', 'Q', ([], {'db_obj': 'obj'}), '(db_obj=obj)\n', (4743, 4755), False, 'from django.db.models import Q\n'), ((4806, 4826), 'django.db.models.Q', 'Q', ([], {'db_interval__gt': '(0)'}), '(db_interval__gt=0)\n', (4807, 4826), False, 'from django.db.models import Q\n'), ((4880, 4910), 'django.db.models.Q', 'Q', ([], {'db_typeclass_path': 'typeclass'}), '(db_typeclass_path=typeclass)\n', (4881, 4910), False, 'from django.db.models import Q\n'), ((5023, 5048), 'django.db.models.Q', 'Q', ([], {'db_key__iexact': 'ostring'}), '(db_key__iexact=ostring)\n', (5024, 5048), False, 'from django.db.models import Q\n')]
from django.conf import settings from evennia.utils.utils import class_from_module from athanor_entity.entities.base import AthanorGameEntity MIXINS = [] for mixin in settings.MIXINS["ENTITY_MOBILE"]: MIXINS.append(class_from_module(mixin)) MIXINS.sort(key=lambda x: getattr(x, "mixin_priority", 0)) class AthanorMobile(*MIXINS, AthanorGameEntity): pass
[ "evennia.utils.utils.class_from_module" ]
[((221, 245), 'evennia.utils.utils.class_from_module', 'class_from_module', (['mixin'], {}), '(mixin)\n', (238, 245), False, 'from evennia.utils.utils import class_from_module\n')]
""" Unit tests for the EvForm text form generator """ from django.test import TestCase from evennia.utils import evform class TestEvForm(TestCase): def test_form(self): self.maxDiff = None form1 = evform._test() form2 = evform._test() self.assertEqual(form1, form2) # self.assertEqual(form1, "") # '.------------------------------------------------.\n' # '| |\n' # '| Name: \x1b[0m\x1b[1m\x1b[32mTom\x1b[1m\x1b[32m \x1b' # '[1m\x1b[32mthe\x1b[1m\x1b[32m \x1b[0m \x1b[0m ' # 'Account: \x1b[0m\x1b[1m\x1b[33mGriatch ' # '\x1b[0m\x1b[0m\x1b[1m\x1b[32m\x1b[1m\x1b[32m\x1b[1m\x1b[32m\x1b[1m\x1b[32m\x1b[0m\x1b[0m ' # '|\n' # '| \x1b[0m\x1b[1m\x1b[32mBouncer\x1b[0m \x1b[0m |\n' # '| |\n' # ' >----------------------------------------------< \n' # '| |\n' # '| Desc: \x1b[0mA sturdy \x1b[0m \x1b[0m' # ' STR: \x1b[0m12 \x1b[0m\x1b[0m\x1b[0m\x1b[0m' # ' DEX: \x1b[0m10 \x1b[0m\x1b[0m\x1b[0m\x1b[0m |\n' # '| \x1b[0mfellow\x1b[0m \x1b[0m' # ' INT: \x1b[0m5 \x1b[0m\x1b[0m\x1b[0m\x1b[0m' # ' STA: \x1b[0m18 \x1b[0m\x1b[0m\x1b[0m\x1b[0m |\n' # '| \x1b[0m \x1b[0m' # ' LUC: \x1b[0m10 \x1b[0m\x1b[0m\x1b[0m' # ' MAG: \x1b[0m3 \x1b[0m\x1b[0m\x1b[0m |\n' # '| |\n' # ' >----------.-----------------------------------< \n' # '| | |\n' # '| \x1b[0mHP\x1b[0m|\x1b[0mMV \x1b[0m|\x1b[0mMP\x1b[0m ' # '| \x1b[0mSkill \x1b[0m|\x1b[0mValue \x1b[0m' # '|\x1b[0mExp \x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m |\n' # '| ~~+~~~+~~ | ~~~~~~~~~~~+~~~~~~~~~~+~~~~~~~~~~~ |\n' # '| \x1b[0m**\x1b[0m|\x1b[0m***\x1b[0m\x1b[0m|\x1b[0m**\x1b[0m\x1b[0m ' # '| \x1b[0mShooting \x1b[0m|\x1b[0m12 \x1b[0m' # '|\x1b[0m550/1200 \x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m |\n' # '| \x1b[0m \x1b[0m|\x1b[0m**\x1b[0m \x1b[0m|\x1b[0m*\x1b[0m \x1b[0m ' # '| \x1b[0mHerbalism \x1b[0m|\x1b[0m14 \x1b[0m' # '|\x1b[0m990/1400 \x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m |\n' # '| \x1b[0m \x1b[0m|\x1b[0m \x1b[0m|\x1b[0m \x1b[0m ' # '| \x1b[0mSmithing \x1b[0m|\x1b[0m9 \x1b[0m' # '|\x1b[0m205/900 \x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m\x1b[0m |\n' # '| | |\n' # ' -----------`-------------------------------------\n' # ' Footer: \x1b[0mrev 1 \x1b[0m \n' # ' info \n' # ' ') def test_ansi_escape(self): # note that in a msg() call, the result would be the correct |-----, # in a print, ansi only gets called once, so ||----- is the result self.assertEqual(str(evform.EvForm(form={"FORM": "\n||-----"})), "||-----")
[ "evennia.utils.evform._test", "evennia.utils.evform.EvForm" ]
[((220, 234), 'evennia.utils.evform._test', 'evform._test', ([], {}), '()\n', (232, 234), False, 'from evennia.utils import evform\n'), ((251, 265), 'evennia.utils.evform._test', 'evform._test', ([], {}), '()\n', (263, 265), False, 'from evennia.utils import evform\n'), ((3340, 3381), 'evennia.utils.evform.EvForm', 'evform.EvForm', ([], {'form': "{'FORM': '\\n||-----'}"}), "(form={'FORM': '\\n||-----'})\n", (3353, 3381), False, 'from evennia.utils import evform\n')]
# file mygame/typeclasses/latin_noun.py from evennia import DefaultObject # adding the following for colors in names for pluralization from evennia.utils import ansi # adding the following for redefinition of 'return_appearance' from collections import defaultdict # from evennia.utils.utils import list_to_string class LatinNoun(DefaultObject): def at_first_save(self): """ This is called by the typeclass system whenever an instance of this class is saved for the first time. It is a generic hook for calling the startup hooks for the various game entities. When overloading you generally don't overload this but overload the hooks called by this method. """ self.basetype_setup() # moving the below line to just before basetype_posthook # at the bottom of this defenitiion # self.at_object_creation() if hasattr(self, "_createdict"): # this will only be set if the utils.create function # was used to create the object. We want the create # call's kwargs to override the values set by hooks. cdict = self._createdict updates = [] if not cdict.get("key"): if not self.db_key: self.db_key = "#%i" % self.dbid updates.append("db_key") elif self.key != cdict.get("key"): updates.append("db_key") self.db_key = cdict["key"] if cdict.get("location") and self.location != cdict["location"]: self.db_location = cdict["location"] updates.append("db_location") if cdict.get("home") and self.home != cdict["home"]: self.home = cdict["home"] updates.append("db_home") if cdict.get("destination") and self.destination != cdict["destination"]: self.destination = cdict["destination"] updates.append("db_destination") if updates: self.save(update_fields=updates) if cdict.get("permissions"): self.permissions.batch_add(*cdict["permissions"]) if cdict.get("locks"): self.locks.add(cdict["locks"]) if cdict.get("aliases"): self.aliases.batch_add(*cdict["aliases"]) if cdict.get("location"): cdict["location"].at_object_receive(self, None) self.at_after_move(None) if cdict.get("tags"): # this should be a list of tags, tuples (key, category) or (key, category, data) self.tags.batch_add(*cdict["tags"]) if cdict.get("attributes"): # this should be tuples (key, val, ...) self.attributes.batch_add(*cdict["attributes"]) if cdict.get("nattributes"): # this should be a dict of nattrname:value for key, value in cdict["nattributes"]: self.nattributes.add(key, value) del self._createdict self.at_object_creation() self.basetype_posthook_setup() # adding the pluralization rules; so far they will only work for # nominative plurals for when you look in a new room; not sure # what to do with other plural functionality # redefine list_to_stringfor this function to use "et" def list_to_string(inlist, endsep="et", addquote=False): """ This pretty-formats a list as string output, adding an optional alternative separator to the second to last entry. If `addquote` is `True`, the outgoing strings will be surrounded by quotes. Args: inlist (list): The list to print. endsep (str, optional): If set, the last item separator will be replaced with this value. addquote (bool, optional): This will surround all outgoing values with double quotes. Returns: liststr (str): The list represented as a string. Examples: ```python # no endsep: [1,2,3] -> '1, 2, 3' # with endsep=='and': [1,2,3] -> '1, 2 and 3' # with addquote and endsep [1,2,3] -> '"1", "2" and "3"' ``` """ if not endsep: endsep = "," else: endsep = " " + endsep if not inlist: return "" if addquote: if len(inlist) == 1: return '"%s"' % inlist[0] return ", ".join('"%s"' % v for v in inlist[:-1]) + "%s %s" % (endsep, '"%s"' % inlist[-1]) else: if len(inlist) == 1: return str(inlist[0]) return ", ".join(str(v) for v in inlist[:-1]) + "%s %s" % (endsep, inlist[-1]) def get_numbered_name(self, count, looker, **kwargs): """ Return the numbered (Singular, plural) forms of this object's key. This is by default called by return_appearance and is used for grouping multiple same-named of this object. Note that this will be called on *every* member of a group even though the plural name will be only shown once. Also the singular display version, such as 'an apple', 'a tree' is determined from this method. Args: count (int): Number of objects of this type looker (Object): Onlooker. Not used by default Kwargs: key (str): Optional key to pluralize, if given, use this instead of the object's key Returns: singular (str): The singular form to display plural (str): The determined plural form of the key, including count. """ key = kwargs.get("key", self.key) key = ansi.ANSIString(key) # This is needed to allow inflection of colored names if self.db.nom_pl: plural = self.db.nom_pl[0] else: plural = self.key plural = "%s %s" % (count, plural) if self.db.nom_sg: singular = self.key else: singular = self.key if not self.aliases.get(plural, category="plural_key"): # We need to wipe any old plurals/an/a in case key changed in the interim self.aliases.clear(category="plural_key") self.aliases.add(plural, category="plural_key") # save the singular form as an alias here too so we can display "an egg" # and also look at "an egg". self.aliases.add(singular, category="plural_key") return singular, plural def return_appearance(self, looker, **kwargs): """ # Lightly editing to change "You see" to "Ecce" # and 'Exits' to 'Ad hos locos ire potes:' This formats a description. It is the hook a 'look' command should call. Args: looker (Object): Object doing the looking. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). """ if not looker: return "" # get and identify all objects visible = (con for con in self.contents if con != looker and con.access(looker, "view")) exits, users, things = [], [], defaultdict(list) # adjusted the exit name to take out the dbref so builders can # click on the exits to go there for con in visible: key = con.get_display_name(looker) if con.destination: exits.append(con.key) elif con.has_account: if con.db.is_glowing: users.append("|y(ardens)|n |c%s|n" % key) else: users.append("|c%s|n" % key) else: # things can be pluralized things[key].append(con) # get description, build string string = "|c%s|n\n" % self.get_display_name(looker) desc = self.db.desc # JI (12/7/9) Adding the following lines to accommodate clothing # Actually, added return_appearance to characters typeclass # and commenting this new section out # worn_string_list = [] # clothes_list = get_worn_clothes(self, exclude_covered=True) # # Append worn, uncovered clothing to the description # for garment in clothes_list: # # if 'worn' is True, just append the name # if garment.db.worn is True: # # JI (12/7/19) append the accusative name to the description, # # since these will be direct objects # worn_string_list.append(garment.db.acc_sg) # # Otherwise, append the name and the string value of 'worn' # elif garment.db.worn: # worn_string_list.append("%s %s" % (garment.name, garment.db.worn)) if desc: string += "%s" % desc # # Append worn clothes. # if worn_string_list: # string += "|/|/%s gerit: %s." % (self, list_to_string(worn_string_list)) # else: # string += "|/|/%s nud%s est!" % (self, 'a' if self.db.gender == 1 else 'us') # return string # Thinking that the above, added for clothing, might need to only be in the # character typeclass if exits: # Changing this string so that exits appear green # string += "\n|wAd hos locos potes ire:|n\n " + LatinNoun.list_to_string(exits) colorful_exits = [] for exit in exits: colorful_exits.append(f"|lc{exit}|lt|g{exit}|n|le") string += "\n|wAd hos locos potes ire:|n\n " + LatinNoun.list_to_string(colorful_exits) if users or things: # handle pluralization of things (never pluralize users) thing_strings = [] for key, itemlist in sorted(things.items()): nitem = len(itemlist) if nitem == 1: key, _ = itemlist[0].get_numbered_name(nitem, looker, key=key) if itemlist[0].db.is_glowing: key = "|y(ardens)|n " + key else: key = [item.get_numbered_name(nitem, looker, key=key)[1] for item in itemlist][ 0 ] thing_strings.append(key) string += "\n|wEcce:|n\n " + LatinNoun.list_to_string(users + thing_strings) return string
[ "evennia.utils.ansi.ANSIString" ]
[((5866, 5886), 'evennia.utils.ansi.ANSIString', 'ansi.ANSIString', (['key'], {}), '(key)\n', (5881, 5886), False, 'from evennia.utils import ansi\n'), ((7373, 7390), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (7384, 7390), False, 'from collections import defaultdict\n')]
from evennia.utils.test_resources import BaseEvenniaTest from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit from evennia.objects.models import ObjectDB from evennia.utils import create class DefaultObjectTest(BaseEvenniaTest): ip = "192.168.127.12" def test_object_create(self): description = "A home for a grouch." home = self.room1.dbref obj, errors = DefaultObject.create( "trashcan", self.account, description=description, ip=self.ip, home=home ) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) self.assertEqual(obj.db_home, self.room1) def test_character_create(self): description = "A furry green monster, reeking of garbage." home = self.room1.dbref obj, errors = DefaultCharacter.create( "oscar", self.account, description=description, ip=self.ip, home=home ) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) self.assertEqual(obj.db_home, self.room1) def test_character_create_noaccount(self): obj, errors = DefaultCharacter.create("oscar", None, home=self.room1.dbref) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(obj.db_home, self.room1) def test_character_create_weirdname(self): obj, errors = DefaultCharacter.create( "SigurðurÞórarinsson", self.account, home=self.room1.dbref ) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(obj.name, "SigurXurXorarinsson") def test_room_create(self): description = "A dimly-lit alley behind the local Chinese restaurant." obj, errors = DefaultRoom.create("alley", self.account, description=description, ip=self.ip) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) def test_exit_create(self): description = "The steaming depths of the dumpster, ripe with refuse in various states of decomposition." obj, errors = DefaultExit.create( "in", self.room1, self.room2, account=self.account, description=description, ip=self.ip ) self.assertTrue(obj, errors) self.assertFalse(errors, errors) self.assertEqual(description, obj.db.desc) self.assertEqual(obj.db.creator_ip, self.ip) def test_urls(self): "Make sure objects are returning URLs" self.assertTrue(self.char1.get_absolute_url()) self.assertTrue("admin" in self.char1.web_get_admin_url()) self.assertTrue(self.room1.get_absolute_url()) self.assertTrue("admin" in self.room1.web_get_admin_url()) def test_search_stacked(self): "Test searching stacks" coin1 = DefaultObject.create("coin", location=self.room1)[0] coin2 = DefaultObject.create("coin", location=self.room1)[0] colon = DefaultObject.create("colon", location=self.room1)[0] # stack self.assertEqual(self.char1.search("coin", stacked=2), [coin1, coin2]) self.assertEqual(self.char1.search("coin", stacked=5), [coin1, coin2]) # partial match to 'colon' - multimatch error since stack is not homogenous self.assertEqual(self.char1.search("co", stacked=2), None) class TestObjectManager(BaseEvenniaTest): "Test object manager methods" def test_get_object_with_account(self): query = ObjectDB.objects.get_object_with_account("TestAccount").first() self.assertEqual(query, self.char1) query = ObjectDB.objects.get_object_with_account(self.account.dbref) self.assertEqual(query, self.char1) query = ObjectDB.objects.get_object_with_account("#123456") self.assertFalse(query) query = ObjectDB.objects.get_object_with_account("TestAccou").first() self.assertFalse(query) query = ObjectDB.objects.get_object_with_account("TestAccou", exact=False) self.assertEqual(tuple(query), (self.char1, self.char2)) query = ObjectDB.objects.get_object_with_account( "TestAccou", candidates=[self.char1, self.obj1], exact=False ) self.assertEqual(list(query), [self.char1]) def test_get_objs_with_key_and_typeclass(self): query = ObjectDB.objects.get_objs_with_key_and_typeclass( "Char", "evennia.objects.objects.DefaultCharacter" ) self.assertEqual(list(query), [self.char1]) query = ObjectDB.objects.get_objs_with_key_and_typeclass( "Char", "evennia.objects.objects.DefaultObject" ) self.assertFalse(query) query = ObjectDB.objects.get_objs_with_key_and_typeclass( "NotFound", "evennia.objects.objects.DefaultCharacter" ) self.assertFalse(query) query = ObjectDB.objects.get_objs_with_key_and_typeclass( "Char", "evennia.objects.objects.DefaultCharacter", candidates=[self.char1, self.char2] ) self.assertEqual(list(query), [self.char1]) def test_get_objs_with_attr(self): self.obj1.db.testattr = "testval1" query = ObjectDB.objects.get_objs_with_attr("testattr") self.assertEqual(list(query), [self.obj1]) query = ObjectDB.objects.get_objs_with_attr("testattr", candidates=[self.char1, self.obj1]) self.assertEqual(list(query), [self.obj1]) query = ObjectDB.objects.get_objs_with_attr("NotFound", candidates=[self.char1, self.obj1]) self.assertFalse(query) def test_copy_object(self): "Test that all attributes and tags properly copy across objects" # Add some tags self.obj1.tags.add("plugh", category="adventure") self.obj1.tags.add("xyzzy") # Add some attributes self.obj1.attributes.add("phrase", "plugh", category="adventure") self.obj1.attributes.add("phrase", "xyzzy") # Create object copy obj2 = self.obj1.copy() # Make sure each of the tags were replicated self.assertTrue("plugh" in obj2.tags.all()) self.assertTrue("plugh" in obj2.tags.get(category="adventure")) self.assertTrue("xyzzy" in obj2.tags.all()) # Make sure each of the attributes were replicated self.assertEqual(obj2.attributes.get(key="phrase"), "xyzzy") self.assertEqual(self.obj1.attributes.get(key="phrase", category="adventure"), "plugh") self.assertEqual(obj2.attributes.get(key="phrase", category="adventure"), "plugh") class TestContentHandler(BaseEvenniaTest): "Test the ContentHandler (obj.contents)" def test_object_create_remove(self): """Create/destroy object""" self.assertTrue(self.obj1 in self.room1.contents) self.assertTrue(self.obj2 in self.room1.contents) obj3 = create.create_object(key="obj3", location=self.room1) self.assertTrue(obj3 in self.room1.contents) obj3.delete() self.assertFalse(obj3 in self.room1.contents) def test_object_move(self): """Move object from room to room in various ways""" self.assertTrue(self.obj1 in self.room1.contents) # use move_to hook self.obj1.move_to(self.room2) self.assertFalse(self.obj1 in self.room1.contents) self.assertTrue(self.obj1 in self.room2.contents) # move back via direct setting of .location self.obj1.location = self.room1 self.assertTrue(self.obj1 in self.room1.contents) self.assertFalse(self.obj1 in self.room2.contents) def test_content_type(self): self.assertEqual( set(self.room1.contents_get()), set([self.char1, self.char2, self.obj1, self.obj2, self.exit]), ) self.assertEqual( set(self.room1.contents_get(content_type="object")), set([self.obj1, self.obj2]) ) self.assertEqual( set(self.room1.contents_get(content_type="character")), set([self.char1, self.char2]) ) self.assertEqual(set(self.room1.contents_get(content_type="exit")), set([self.exit]))
[ "evennia.objects.models.ObjectDB.objects.get_object_with_account", "evennia.objects.models.ObjectDB.objects.get_objs_with_key_and_typeclass", "evennia.DefaultRoom.create", "evennia.DefaultExit.create", "evennia.DefaultCharacter.create", "evennia.utils.create.create_object", "evennia.objects.models.Objec...
[((418, 517), 'evennia.DefaultObject.create', 'DefaultObject.create', (['"""trashcan"""', 'self.account'], {'description': 'description', 'ip': 'self.ip', 'home': 'home'}), "('trashcan', self.account, description=description, ip=\n self.ip, home=home)\n", (438, 517), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((927, 1026), 'evennia.DefaultCharacter.create', 'DefaultCharacter.create', (['"""oscar"""', 'self.account'], {'description': 'description', 'ip': 'self.ip', 'home': 'home'}), "('oscar', self.account, description=description, ip=\n self.ip, home=home)\n", (950, 1026), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((1346, 1407), 'evennia.DefaultCharacter.create', 'DefaultCharacter.create', (['"""oscar"""', 'None'], {'home': 'self.room1.dbref'}), "('oscar', None, home=self.room1.dbref)\n", (1369, 1407), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((1606, 1694), 'evennia.DefaultCharacter.create', 'DefaultCharacter.create', (['"""SigurðurÞórarinsson"""', 'self.account'], {'home': 'self.room1.dbref'}), "('SigurðurÞórarinsson', self.account, home=self.\n room1.dbref)\n", (1629, 1694), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((1982, 2060), 'evennia.DefaultRoom.create', 'DefaultRoom.create', (['"""alley"""', 'self.account'], {'description': 'description', 'ip': 'self.ip'}), "('alley', self.account, description=description, ip=self.ip)\n", (2000, 2060), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((2412, 2523), 'evennia.DefaultExit.create', 'DefaultExit.create', (['"""in"""', 'self.room1', 'self.room2'], {'account': 'self.account', 'description': 'description', 'ip': 'self.ip'}), "('in', self.room1, self.room2, account=self.account,\n description=description, ip=self.ip)\n", (2430, 2523), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((3907, 3967), 'evennia.objects.models.ObjectDB.objects.get_object_with_account', 'ObjectDB.objects.get_object_with_account', (['self.account.dbref'], {}), '(self.account.dbref)\n', (3947, 3967), False, 'from evennia.objects.models import ObjectDB\n'), ((4028, 4079), 'evennia.objects.models.ObjectDB.objects.get_object_with_account', 'ObjectDB.objects.get_object_with_account', (['"""#123456"""'], {}), "('#123456')\n", (4068, 4079), False, 'from evennia.objects.models import ObjectDB\n'), ((4239, 4305), 'evennia.objects.models.ObjectDB.objects.get_object_with_account', 'ObjectDB.objects.get_object_with_account', (['"""TestAccou"""'], {'exact': '(False)'}), "('TestAccou', exact=False)\n", (4279, 4305), False, 'from evennia.objects.models import ObjectDB\n'), ((4388, 4495), 'evennia.objects.models.ObjectDB.objects.get_object_with_account', 'ObjectDB.objects.get_object_with_account', (['"""TestAccou"""'], {'candidates': '[self.char1, self.obj1]', 'exact': '(False)'}), "('TestAccou', candidates=[self.\n char1, self.obj1], exact=False)\n", (4428, 4495), False, 'from evennia.objects.models import ObjectDB\n'), ((4634, 4738), 'evennia.objects.models.ObjectDB.objects.get_objs_with_key_and_typeclass', 'ObjectDB.objects.get_objs_with_key_and_typeclass', (['"""Char"""', '"""evennia.objects.objects.DefaultCharacter"""'], {}), "('Char',\n 'evennia.objects.objects.DefaultCharacter')\n", (4682, 4738), False, 'from evennia.objects.models import ObjectDB\n'), ((4825, 4926), 'evennia.objects.models.ObjectDB.objects.get_objs_with_key_and_typeclass', 'ObjectDB.objects.get_objs_with_key_and_typeclass', (['"""Char"""', '"""evennia.objects.objects.DefaultObject"""'], {}), "('Char',\n 'evennia.objects.objects.DefaultObject')\n", (4873, 4926), False, 'from evennia.objects.models import ObjectDB\n'), ((4993, 5101), 'evennia.objects.models.ObjectDB.objects.get_objs_with_key_and_typeclass', 'ObjectDB.objects.get_objs_with_key_and_typeclass', (['"""NotFound"""', '"""evennia.objects.objects.DefaultCharacter"""'], {}), "('NotFound',\n 'evennia.objects.objects.DefaultCharacter')\n", (5041, 5101), False, 'from evennia.objects.models import ObjectDB\n'), ((5168, 5313), 'evennia.objects.models.ObjectDB.objects.get_objs_with_key_and_typeclass', 'ObjectDB.objects.get_objs_with_key_and_typeclass', (['"""Char"""', '"""evennia.objects.objects.DefaultCharacter"""'], {'candidates': '[self.char1, self.char2]'}), "('Char',\n 'evennia.objects.objects.DefaultCharacter', candidates=[self.char1,\n self.char2])\n", (5216, 5313), False, 'from evennia.objects.models import ObjectDB\n'), ((5479, 5526), 'evennia.objects.models.ObjectDB.objects.get_objs_with_attr', 'ObjectDB.objects.get_objs_with_attr', (['"""testattr"""'], {}), "('testattr')\n", (5514, 5526), False, 'from evennia.objects.models import ObjectDB\n'), ((5594, 5681), 'evennia.objects.models.ObjectDB.objects.get_objs_with_attr', 'ObjectDB.objects.get_objs_with_attr', (['"""testattr"""'], {'candidates': '[self.char1, self.obj1]'}), "('testattr', candidates=[self.char1,\n self.obj1])\n", (5629, 5681), False, 'from evennia.objects.models import ObjectDB\n'), ((5745, 5832), 'evennia.objects.models.ObjectDB.objects.get_objs_with_attr', 'ObjectDB.objects.get_objs_with_attr', (['"""NotFound"""'], {'candidates': '[self.char1, self.obj1]'}), "('NotFound', candidates=[self.char1,\n self.obj1])\n", (5780, 5832), False, 'from evennia.objects.models import ObjectDB\n'), ((7151, 7204), 'evennia.utils.create.create_object', 'create.create_object', ([], {'key': '"""obj3"""', 'location': 'self.room1'}), "(key='obj3', location=self.room1)\n", (7171, 7204), False, 'from evennia.utils import create\n'), ((3126, 3175), 'evennia.DefaultObject.create', 'DefaultObject.create', (['"""coin"""'], {'location': 'self.room1'}), "('coin', location=self.room1)\n", (3146, 3175), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((3195, 3244), 'evennia.DefaultObject.create', 'DefaultObject.create', (['"""coin"""'], {'location': 'self.room1'}), "('coin', location=self.room1)\n", (3215, 3244), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((3264, 3314), 'evennia.DefaultObject.create', 'DefaultObject.create', (['"""colon"""'], {'location': 'self.room1'}), "('colon', location=self.room1)\n", (3284, 3314), False, 'from evennia import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit\n'), ((3783, 3838), 'evennia.objects.models.ObjectDB.objects.get_object_with_account', 'ObjectDB.objects.get_object_with_account', (['"""TestAccount"""'], {}), "('TestAccount')\n", (3823, 3838), False, 'from evennia.objects.models import ObjectDB\n'), ((4128, 4181), 'evennia.objects.models.ObjectDB.objects.get_object_with_account', 'ObjectDB.objects.get_object_with_account', (['"""TestAccou"""'], {}), "('TestAccou')\n", (4168, 4181), False, 'from evennia.objects.models import ObjectDB\n')]
""" Skill handler handles a character's skills. """ import time import random from django.conf import settings from evennia import TICKER_HANDLER from evennia.utils import logger from muddery.utils.builder import build_object from muddery.utils.localized_strings_handler import _ from muddery.utils.game_settings import GAME_SETTINGS class SkillHandler(object): """ Skill handler handles a character's skills. """ def __init__(self, owner): """ Initialize handler. """ self.owner = owner self.skills = {} if owner: self.skills = owner.db.skills self.gcd = GAME_SETTINGS.get("global_cd") self.auto_cast_skill_cd = GAME_SETTINGS.get("auto_cast_skill_cd") self.can_auto_cast = False self.skill_target = None self.gcd_finish_time = 0 def __del__(self): """ Remove tickers. """ if self.can_auto_cast: TICKER_HANDLER.remove(callback=self.owner.auto_cast_skill) def get_all(self): """ Get all skills. """ return self.skills def learn_skill(self, skill_key, is_default=False): """ Learn a new skill. Args: skill_key: (string) skill's key is_default: (boolean) if it is a default skill Returns: (boolean) learned skill """ if not self.owner: return False if skill_key in self.skills: self.owner.msg({"msg": _("You have already learned this skill.")}) return False # Create skill object. skill_obj = build_object(skill_key) if not skill_obj: self.owner.msg({"msg": _("Can not learn this skill.")}) return False # set default if is_default: skill_obj.set_default(is_default) # Store new skill. skill_obj.set_owner(self.owner) self.skills[skill_key] = skill_obj # If it is a passive skill, player's status may change. if skill_obj.passive: self.owner.refresh_data() # Notify the player if self.owner.has_player: self.owner.show_status() # Notify the player if self.owner.has_player: self.owner.show_skills() self.owner.msg({"msg": _("You learned skill {c%s{n.") % skill_obj.get_name()}) return True def has_skill(self, skill): """ If the character has the skill or not. Args: skill: (string) skill's key Returns: None """ return skill in self.skills def cast_skill(self, skill_key, target): """ Cast a skill. Args: skill_key: (string) skill's key target: (object) skill's target Returns: (dict) result of the skill """ if not self.owner: return if time.time() < self.gcd_finish_time: # In GCD. self.owner.msg({"msg": _("This skill is not ready yet!")}) return if skill_key not in self.skills: self.owner.msg({"alert": _("You do not have this skill.")}) return skill = self.skills[skill_key] message = skill.check_available() if message: # Skill is not available. self.owner.msg({"msg": message}) return skill.cast_skill(target) if self.gcd > 0: # set GCD self.gcd_finish_time = time.time() + self.gcd # send CD to the player cd = {"skill": skill.get_data_key(), # skill's key "cd": skill.cd, # skill's cd "gcd": self.gcd} self.owner.msg({"skill_cd": cd}) return def auto_cast_skill(self): """ Cast a new skill automatically. """ if not self.can_auto_cast: return if not self.owner: return if not self.owner.is_alive(): return if not self.owner.ndb.combat_handler: # combat is finished, stop ticker TICKER_HANDLER.remove(self.auto_cast_skill_cd, self.owner.auto_cast_skill) return # Get target. choose_new_target = True if self.skill_target: if self.skill_target.is_alive(): choose_new_target = False if choose_new_target: self.skill_target = self.choose_skill_target() if not self.skill_target: # No target. return # Get available skills. available_skills = self.get_available_skills() if not available_skills: # No available skill. return # Random chooses a skill. skill = random.choice(available_skills) if skill: self.owner.ndb.combat_handler.prepare_skill(skill, self.owner, self.skill_target) def get_available_skills(self): """ Get available skills without cd. """ skills = [skill for skill in self.skills if self.skills[skill].is_available()] return skills def get_passive_skills(self): """ Get all passive skills. """ skills = [skill for skill in self.skills if self.skills[skill].passive] return skills def cast_passive_skills(self): """ Cast all passive skills. """ for skill in self.skills: if self.skills[skill].passive: self.skills[skill].cast_skill(None) def choose_skill_target(self): """ Choose a target automatically. """ if not self.owner: return if not self.owner.ndb.combat_handler: "Not in combat." return # Get all combat characters. characters = self.owner.ndb.combat_handler.get_all_characters() for character in characters: if character.is_alive() and character.dbref != self.owner.dbref: return character return def start_auto_combat_skill(self): """ Start auto cast skill. """ self.can_auto_cast = True # Cast a skill immediately self.auto_cast_skill() # Set timer of auto cast. TICKER_HANDLER.add(self.auto_cast_skill_cd, self.owner.auto_cast_skill) def stop_auto_combat_skill(self): """ Stop auto cast skill. """ self.can_auto_cast = False TICKER_HANDLER.remove(self.auto_cast_skill_cd, self.owner.auto_cast_skill)
[ "evennia.TICKER_HANDLER.add", "evennia.TICKER_HANDLER.remove" ]
[((647, 677), 'muddery.utils.game_settings.GAME_SETTINGS.get', 'GAME_SETTINGS.get', (['"""global_cd"""'], {}), "('global_cd')\n", (664, 677), False, 'from muddery.utils.game_settings import GAME_SETTINGS\n'), ((712, 751), 'muddery.utils.game_settings.GAME_SETTINGS.get', 'GAME_SETTINGS.get', (['"""auto_cast_skill_cd"""'], {}), "('auto_cast_skill_cd')\n", (729, 751), False, 'from muddery.utils.game_settings import GAME_SETTINGS\n'), ((1652, 1675), 'muddery.utils.builder.build_object', 'build_object', (['skill_key'], {}), '(skill_key)\n', (1664, 1675), False, 'from muddery.utils.builder import build_object\n'), ((4887, 4918), 'random.choice', 'random.choice', (['available_skills'], {}), '(available_skills)\n', (4900, 4918), False, 'import random\n'), ((6409, 6480), 'evennia.TICKER_HANDLER.add', 'TICKER_HANDLER.add', (['self.auto_cast_skill_cd', 'self.owner.auto_cast_skill'], {}), '(self.auto_cast_skill_cd, self.owner.auto_cast_skill)\n', (6427, 6480), False, 'from evennia import TICKER_HANDLER\n'), ((6617, 6691), 'evennia.TICKER_HANDLER.remove', 'TICKER_HANDLER.remove', (['self.auto_cast_skill_cd', 'self.owner.auto_cast_skill'], {}), '(self.auto_cast_skill_cd, self.owner.auto_cast_skill)\n', (6638, 6691), False, 'from evennia import TICKER_HANDLER\n'), ((968, 1026), 'evennia.TICKER_HANDLER.remove', 'TICKER_HANDLER.remove', ([], {'callback': 'self.owner.auto_cast_skill'}), '(callback=self.owner.auto_cast_skill)\n', (989, 1026), False, 'from evennia import TICKER_HANDLER\n'), ((2995, 3006), 'time.time', 'time.time', ([], {}), '()\n', (3004, 3006), False, 'import time\n'), ((4226, 4300), 'evennia.TICKER_HANDLER.remove', 'TICKER_HANDLER.remove', (['self.auto_cast_skill_cd', 'self.owner.auto_cast_skill'], {}), '(self.auto_cast_skill_cd, self.owner.auto_cast_skill)\n', (4247, 4300), False, 'from evennia import TICKER_HANDLER\n'), ((3598, 3609), 'time.time', 'time.time', ([], {}), '()\n', (3607, 3609), False, 'import time\n'), ((1531, 1572), 'muddery.utils.localized_strings_handler._', '_', (['"""You have already learned this skill."""'], {}), "('You have already learned this skill.')\n", (1532, 1572), False, 'from muddery.utils.localized_strings_handler import _\n'), ((1737, 1767), 'muddery.utils.localized_strings_handler._', '_', (['"""Can not learn this skill."""'], {}), "('Can not learn this skill.')\n", (1738, 1767), False, 'from muddery.utils.localized_strings_handler import _\n'), ((3088, 3121), 'muddery.utils.localized_strings_handler._', '_', (['"""This skill is not ready yet!"""'], {}), "('This skill is not ready yet!')\n", (3089, 3121), False, 'from muddery.utils.localized_strings_handler import _\n'), ((3222, 3254), 'muddery.utils.localized_strings_handler._', '_', (['"""You do not have this skill."""'], {}), "('You do not have this skill.')\n", (3223, 3254), False, 'from muddery.utils.localized_strings_handler import _\n'), ((2378, 2408), 'muddery.utils.localized_strings_handler._', '_', (['"""You learned skill {c%s{n."""'], {}), "('You learned skill {c%s{n.')\n", (2379, 2408), False, 'from muddery.utils.localized_strings_handler import _\n')]
""" Utility functions to help with our message handlers. """ _cached_lazy_imports = {} def lazy_import_from_str(clsname): """ Fetches a class from world.msgs.models by name and caches the reference. The idea here is mostly for preventing circular references with lazy imports. Args: clsname: The name of the proxy class in msgs.models to retrieve. Returns: The Msg proxy class we want to get from the name. """ from evennia.utils.utils import class_from_module if clsname in _cached_lazy_imports: return _cached_lazy_imports[clsname] cls = class_from_module("world.msgs.models." + clsname) _cached_lazy_imports[clsname] = cls return cls def get_initial_queryset(clsname, ordering="-db_date_created"): """ Gets an initial queryset for initializing our attributes. Args: clsname (str): Name of class from .models to import ordering (str): field to use for ordering """ cls = lazy_import_from_str(clsname) return cls.objects.all().order_by(ordering)
[ "evennia.utils.utils.class_from_module" ]
[((605, 654), 'evennia.utils.utils.class_from_module', 'class_from_module', (["('world.msgs.models.' + clsname)"], {}), "('world.msgs.models.' + clsname)\n", (622, 654), False, 'from evennia.utils.utils import class_from_module\n')]
""" Upgrade custom's game dir to the latest version. """ import traceback import os import django.core.management from evennia.server.evennia_launcher import init_game_directory from muddery.launcher.upgrader.base_upgrader import BaseUpgrader from muddery.launcher.upgrader.utils import file_append from muddery.launcher.utils import import_system_data from muddery.server.utils.exception import MudderyError, ERR class Upgrader(BaseUpgrader): """ Upgrade a game dir to a specified version. """ # Can upgrade the game of version between from_version and to_version. # from min version 0.6.2 (include this version) from_min_version = (0, 6, 2) # from max version 0.6.4 (not include this version) from_max_version = (0, 6, 4) target_version = None def upgrade_game(self, game_dir, game_template, muddery_lib): """ Upgrade a game. Args: game_dir: (string) the game dir to be upgraded. game_template: (string) the game template used to upgrade the game dir. muddery_lib: (string) muddery's dir """ os.chdir(game_dir) # add honour_settings table to the worlddata model file_path = os.path.join(game_dir, "worlddata", "models.py") file_append(file_path, [ "\n", "class honour_settings(BaseModels.honour_settings):\n", " pass\n", "\n" ]) # add honours table to the gamedata model file_path = os.path.join(game_dir, "gamedata", "models.py") file_append(file_path, [ "from muddery.server.database import gamedata_models as BaseModels", "\n", "class honours(BaseModels.honours):\n", " pass\n", "\n" ]) init_game_directory(game_dir, check_db=False) # make new migrations django_args = ["makemigrations", "worlddata"] django_kwargs = {} django.core.management.call_command(*django_args, **django_kwargs) django_args = ["migrate", "worlddata"] django_kwargs = {"database": "worlddata"} django.core.management.call_command(*django_args, **django_kwargs) django_args = ["makemigrations", "gamedata"] django_kwargs = {} django.core.management.call_command(*django_args, **django_kwargs) django_args = ["migrate", "gamedata"] django_kwargs = {"database": "gamedata"} django.core.management.call_command(*django_args, **django_kwargs) # load system data try: import_system_data() print("Import system data success.") except Exception as e: traceback.print_exc() raise def upgrade_data(self, data_path, game_template, muddery_lib): """ Upgrade game data. Args: data_path: (string) the data path to be upgraded. game_template: (string) the game template used to upgrade the game dir. muddery_lib: (string) muddery's dir """ pass
[ "evennia.server.evennia_launcher.init_game_directory" ]
[((1121, 1139), 'os.chdir', 'os.chdir', (['game_dir'], {}), '(game_dir)\n', (1129, 1139), False, 'import os\n'), ((1220, 1268), 'os.path.join', 'os.path.join', (['game_dir', '"""worlddata"""', '"""models.py"""'], {}), "(game_dir, 'worlddata', 'models.py')\n", (1232, 1268), False, 'import os\n'), ((1277, 1392), 'muddery.launcher.upgrader.utils.file_append', 'file_append', (['file_path', "['\\n', 'class honour_settings(BaseModels.honour_settings):\\n', ' pass\\n',\n '\\n']"], {}), "(file_path, ['\\n',\n 'class honour_settings(BaseModels.honour_settings):\\n', ' pass\\n', '\\n']\n )\n", (1288, 1392), False, 'from muddery.launcher.upgrader.utils import file_append\n'), ((1513, 1560), 'os.path.join', 'os.path.join', (['game_dir', '"""gamedata"""', '"""models.py"""'], {}), "(game_dir, 'gamedata', 'models.py')\n", (1525, 1560), False, 'import os\n'), ((1569, 1740), 'muddery.launcher.upgrader.utils.file_append', 'file_append', (['file_path', '[\'from muddery.server.database import gamedata_models as BaseModels\', \'\\n\',\n """class honours(BaseModels.honours):\n""", \' pass\\n\', \'\\n\']'], {}), '(file_path, [\n \'from muddery.server.database import gamedata_models as BaseModels\',\n \'\\n\', """class honours(BaseModels.honours):\n""", \' pass\\n\', \'\\n\'])\n', (1580, 1740), False, 'from muddery.launcher.upgrader.utils import file_append\n'), ((1808, 1853), 'evennia.server.evennia_launcher.init_game_directory', 'init_game_directory', (['game_dir'], {'check_db': '(False)'}), '(game_dir, check_db=False)\n', (1827, 1853), False, 'from evennia.server.evennia_launcher import init_game_directory\n'), ((2594, 2614), 'muddery.launcher.utils.import_system_data', 'import_system_data', ([], {}), '()\n', (2612, 2614), False, 'from muddery.launcher.utils import import_system_data\n'), ((2707, 2728), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (2726, 2728), False, 'import traceback\n')]
""" The script handler makes sure to check through all stored scripts to make sure they are still relevant. A scripthandler is automatically added to all game objects. You access it through the property `scripts` on the game object. """ from evennia.scripts.models import ScriptDB from evennia.utils import create from evennia.utils import logger from django.utils.translation import gettext as _ class ScriptHandler(object): """ Implements the handler. This sits on each game object. """ def __init__(self, obj): """ Set up internal state. Args: obj (Object): A reference to the object this handler is attached to. """ self.obj = obj def __str__(self): """ List the scripts tied to this object. """ scripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj) string = "" for script in scripts: interval = "inf" next_repeat = "inf" repeats = "inf" if script.interval > 0: interval = script.interval if script.repeats: repeats = script.repeats try: next_repeat = script.time_until_next_repeat() except Exception: next_repeat = "?" string += _("\n '{key}' ({next_repeat}/{interval}, {repeats} repeats): {desc}").format( key=script.key, next_repeat=next_repeat, interval=interval, repeats=repeats, desc=script.desc) return string.strip() def add(self, scriptclass, key=None, autostart=True): """ Add a script to this object. Args: scriptclass (Scriptclass, Script or str): Either a class object inheriting from DefaultScript, an instantiated script object or a python path to such a class object. key (str, optional): Identifier for the script (often set in script definition and listings) autostart (bool, optional): Start the script upon adding it. """ if self.obj.__dbclass__.__name__ == "AccountDB": # we add to an Account, not an Object script = create.create_script( scriptclass, key=key, account=self.obj, autostart=autostart ) else: # the normal - adding to an Object. We wait to autostart so we can differentiate # a failing creation from a script that immediately starts/stops. script = create.create_script(scriptclass, key=key, obj=self.obj, autostart=False) if not script: logger.log_err("Script %s failed to be created/started." % scriptclass) return False if autostart: script.start() if not script.id: # this can happen if the script has repeats=1 or calls stop() in at_repeat. logger.log_info( "Script %s started and then immediately stopped; " "it could probably be a normal function." % scriptclass ) return True def start(self, key): """ Find scripts and force-start them Args: key (str): The script's key or dbref. Returns: nr_started (int): The number of started scripts found. """ scripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=key) num = 0 for script in scripts: script.start() num += 1 return num def get(self, key): """ Search scripts on this object. Args: key (str): Search criterion, the script's key or dbref. Returns: scripts (list): The found scripts matching `key`. """ return list(ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=key)) def delete(self, key=None): """ Forcibly delete a script from this object. Args: key (str, optional): A script key or the path to a script (in the latter case all scripts with this path will be deleted!) If no key is given, delete *all* scripts on the object! """ delscripts = ScriptDB.objects.get_all_scripts_on_obj(self.obj, key=key) if not delscripts: delscripts = [ script for script in ScriptDB.objects.get_all_scripts_on_obj(self.obj) if script.path == key ] num = 0 for script in delscripts: script.delete() num += 1 return num # alias to delete stop = delete def all(self): """ Get all scripts stored in this handler. """ return ScriptDB.objects.get_all_scripts_on_obj(self.obj)
[ "evennia.utils.logger.log_err", "evennia.utils.logger.log_info", "evennia.utils.create.create_script", "evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj" ]
[((841, 890), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj', 'ScriptDB.objects.get_all_scripts_on_obj', (['self.obj'], {}), '(self.obj)\n', (880, 890), False, 'from evennia.scripts.models import ScriptDB\n'), ((3457, 3515), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj', 'ScriptDB.objects.get_all_scripts_on_obj', (['self.obj'], {'key': 'key'}), '(self.obj, key=key)\n', (3496, 3515), False, 'from evennia.scripts.models import ScriptDB\n'), ((4330, 4388), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj', 'ScriptDB.objects.get_all_scripts_on_obj', (['self.obj'], {'key': 'key'}), '(self.obj, key=key)\n', (4369, 4388), False, 'from evennia.scripts.models import ScriptDB\n'), ((4865, 4914), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj', 'ScriptDB.objects.get_all_scripts_on_obj', (['self.obj'], {}), '(self.obj)\n', (4904, 4914), False, 'from evennia.scripts.models import ScriptDB\n'), ((2306, 2392), 'evennia.utils.create.create_script', 'create.create_script', (['scriptclass'], {'key': 'key', 'account': 'self.obj', 'autostart': 'autostart'}), '(scriptclass, key=key, account=self.obj, autostart=\n autostart)\n', (2326, 2392), False, 'from evennia.utils import create\n'), ((2624, 2697), 'evennia.utils.create.create_script', 'create.create_script', (['scriptclass'], {'key': 'key', 'obj': 'self.obj', 'autostart': '(False)'}), '(scriptclass, key=key, obj=self.obj, autostart=False)\n', (2644, 2697), False, 'from evennia.utils import create\n'), ((2733, 2804), 'evennia.utils.logger.log_err', 'logger.log_err', (["('Script %s failed to be created/started.' % scriptclass)"], {}), "('Script %s failed to be created/started.' % scriptclass)\n", (2747, 2804), False, 'from evennia.utils import logger\n'), ((3005, 3135), 'evennia.utils.logger.log_info', 'logger.log_info', (["('Script %s started and then immediately stopped; it could probably be a normal function.'\n % scriptclass)"], {}), "(\n 'Script %s started and then immediately stopped; it could probably be a normal function.'\n % scriptclass)\n", (3020, 3135), False, 'from evennia.utils import logger\n'), ((3902, 3960), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj', 'ScriptDB.objects.get_all_scripts_on_obj', (['self.obj'], {'key': 'key'}), '(self.obj, key=key)\n', (3941, 3960), False, 'from evennia.scripts.models import ScriptDB\n'), ((1371, 1443), 'django.utils.translation.gettext', '_', (['"""\n \'{key}\' ({next_repeat}/{interval}, {repeats} repeats): {desc}"""'], {}), '("""\n \'{key}\' ({next_repeat}/{interval}, {repeats} repeats): {desc}""")\n', (1372, 1443), True, 'from django.utils.translation import gettext as _\n'), ((4496, 4545), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts_on_obj', 'ScriptDB.objects.get_all_scripts_on_obj', (['self.obj'], {}), '(self.obj)\n', (4535, 4545), False, 'from evennia.scripts.models import ScriptDB\n')]
""" These managers define helper methods for accessing the database from Comm system components. """ from django.conf import settings from django.db.models import Q from evennia.typeclasses.managers import TypedObjectManager, TypeclassManager from evennia.server import signals from evennia.utils import logger from evennia.utils.utils import dbref, make_iter, class_from_module _GA = object.__getattribute__ _AccountDB = None _ObjectDB = None _ChannelDB = None _ScriptDB = None _SESSIONS = None # error class class CommError(Exception): """ Raised by comm system, to allow feedback to player when caught. """ pass # # helper functions # def identify_object(inp): """ Helper function. Identifies if an object is an account or an object; return its database model Args: inp (any): Entity to be idtified. Returns: identified (tuple): This is a tuple with (`inp`, identifier) where `identifier` is one of "account", "object", "channel", "string", "dbref" or None. """ if hasattr(inp, "__dbclass__"): clsname = inp.__dbclass__.__name__ if clsname == "AccountDB": return inp, "account" elif clsname == "ObjectDB": return inp, "object" elif clsname == "ChannelDB": return inp, "channel" elif clsname == "ScriptDB": return inp, "script" if isinstance(inp, str): return inp, "string" elif dbref(inp): return dbref(inp), "dbref" else: return inp, None def to_object(inp, objtype="account"): """ Locates the object related to the given accountname or channel key. If input was already the correct object, return it. Args: inp (any): The input object/string objtype (str): Either 'account' or 'channel'. Returns: obj (object): The correct object related to `inp`. """ obj, typ = identify_object(inp) if typ == objtype: return obj if objtype == "account": if typ == "object": return obj.account if typ == "string": return _AccountDB.objects.get(user_username__iexact=obj) if typ == "dbref": return _AccountDB.objects.get(id=obj) logger.log_err("%s %s %s %s %s" % (objtype, inp, obj, typ, type(inp))) raise CommError() elif objtype == "object": if typ == "account": return obj.obj if typ == "string": return _ObjectDB.objects.get(db_key__iexact=obj) if typ == "dbref": return _ObjectDB.objects.get(id=obj) logger.log_err("%s %s %s %s %s" % (objtype, inp, obj, typ, type(inp))) raise CommError() elif objtype == "channel": if typ == "string": return _ChannelDB.objects.get(db_key__iexact=obj) if typ == "dbref": return _ChannelDB.objects.get(id=obj) logger.log_err("%s %s %s %s %s" % (objtype, inp, obj, typ, type(inp))) raise CommError() elif objtype == "script": if typ == "string": return _ScriptDB.objects.get(db_key__iexact=obj) if typ == "dbref": return _ScriptDB.objects.get(id=obj) logger.log_err("%s %s %s %s %s" % (objtype, inp, obj, typ, type(inp))) raise CommError() # an unknown return None # # Msg manager # class MsgManager(TypedObjectManager): """ This MsgManager implements methods for searching and manipulating Messages directly from the database. These methods will all return database objects (or QuerySets) directly. A Message represents one unit of communication, be it over a Channel or via some form of in-game mail system. Like an e-mail, it always has a sender and can have any number of receivers (some of which may be Channels). """ def identify_object(self, inp): """ Wrapper to identify_object if accessing via the manager directly. Args: inp (any): Entity to be idtified. Returns: identified (tuple): This is a tuple with (`inp`, identifier) where `identifier` is one of "account", "object", "channel", "string", "dbref" or None. """ return identify_object(inp) def get_message_by_id(self, idnum): """ Retrieve message by its id. Args: idnum (int or str): The dbref to retrieve. Returns: message (Msg): The message. """ try: return self.get(id=self.dbref(idnum, reqhash=False)) except Exception: return None def get_messages_by_sender(self, sender): """ Get all messages sent by one entity - this could be either a account or an object Args: sender (Account or Object): The sender of the message. Returns: QuerySet: Matching messages. Raises: CommError: For incorrect sender types. """ obj, typ = identify_object(sender) if typ == "account": return self.filter(db_sender_accounts=obj).exclude(db_hide_from_accounts=obj) elif typ == "object": return self.filter(db_sender_objects=obj).exclude(db_hide_from_objects=obj) elif typ == "script": return self.filter(db_sender_scripts=obj) else: raise CommError def get_messages_by_receiver(self, recipient): """ Get all messages sent to one given recipient. Args: recipient (Object, Account or Channel): The recipient of the messages to search for. Returns: Queryset: Matching messages. Raises: CommError: If the `recipient` is not of a valid type. """ obj, typ = identify_object(recipient) if typ == "account": return self.filter(db_receivers_accounts=obj).exclude(db_hide_from_accounts=obj) elif typ == "object": return self.filter(db_receivers_objects=obj).exclude(db_hide_from_objects=obj) elif typ == 'script': return self.filter(db_receivers_scripts=obj) else: raise CommError def search_message(self, sender=None, receiver=None, freetext=None, dbref=None): """ Search the message database for particular messages. At least one of the arguments must be given to do a search. Args: sender (Object, Account or Script, optional): Get messages sent by a particular sender. receiver (Object, Account or Channel, optional): Get messages received by a certain account,object or channel freetext (str): Search for a text string in a message. NOTE: This can potentially be slow, so make sure to supply one of the other arguments to limit the search. dbref (int): The exact database id of the message. This will override all other search criteria since it's unique and always gives only one match. Returns: Queryset: Iterable with 0, 1 or more matches. """ # unique msg id if dbref: return self.objects.filter(id=dbref) # We use Q objects to gradually build up the query - this way we only # need to do one database lookup at the end rather than gradually # refining with multiple filter:s. Django Note: Q objects can be # combined with & and | (=AND,OR). ~ negates the queryset # filter by sender (we need __pk to avoid an error with empty Q() objects) sender, styp = identify_object(sender) if sender: spk = sender.pk if styp == "account": sender_restrict = Q(db_sender_accounts__pk=spk) & ~Q(db_hide_from_accounts__pk=spk) elif styp == "object": sender_restrict = Q(db_sender_objects__pk=spk) & ~Q(db_hide_from_objects__pk=spk) elif styp == 'script': sender_restrict = Q(db_sender_scripts__pk=spk) else: sender_restrict = Q() # filter by receiver receiver, rtyp = identify_object(receiver) if receiver: rpk = receiver.pk if rtyp == "account": receiver_restrict = ( Q(db_receivers_accounts__pk=rpk) & ~Q(db_hide_from_accounts__pk=rpk)) elif rtyp == "object": receiver_restrict = Q(db_receivers_objects__pk=rpk) & ~Q(db_hide_from_objects__pk=rpk) elif rtyp == 'script': receiver_restrict = Q(db_receivers_scripts__pk=rpk) elif rtyp == "channel": raise DeprecationWarning( "Msg.objects.search don't accept channel recipients since " "Channels no longer accepts Msg objects.") else: receiver_restrict = Q() # filter by full text if freetext: fulltext_restrict = Q(db_header__icontains=freetext) | Q(db_message__icontains=freetext) else: fulltext_restrict = Q() # execute the query return self.filter(sender_restrict & receiver_restrict & fulltext_restrict) # back-compatibility alias message_search = search_message def create_message(self, senderobj, message, receivers=None, locks=None, tags=None, header=None, **kwargs): """ Create a new communication Msg. Msgs represent a unit of database-persistent communication between entites. Args: senderobj (Object, Account, Script, str or list): The entity (or entities) sending the Msg. If a `str`, this is the id-string for an external sender type. message (str): Text with the message. Eventual headers, titles etc should all be included in this text string. Formatting will be retained. receivers (Object, Account, Script, str or list): An Account/Object to send to, or a list of them. If a string, it's an identifier for an external receiver. locks (str): Lock definition string. tags (list): A list of tags or tuples `(tag, category)`. header (str): Mime-type or other optional information for the message Notes: The Comm system is created to be very open-ended, so it's fully possible to let a message both go several receivers at the same time, it's up to the command definitions to limit this as desired. """ if 'channels' in kwargs: raise DeprecationWarning( "create_message() does not accept 'channel' kwarg anymore " "- channels no longer accept Msg objects." ) if not message: # we don't allow empty messages. return None new_message = self.model(db_message=message) new_message.save() for sender in make_iter(senderobj): new_message.senders = sender new_message.header = header for receiver in make_iter(receivers): new_message.receivers = receiver if locks: new_message.locks.add(locks) if tags: new_message.tags.batch_add(*tags) new_message.save() return new_message # # Channel manager # class ChannelDBManager(TypedObjectManager): """ This ChannelManager implements methods for searching and manipulating Channels directly from the database. These methods will all return database objects (or QuerySets) directly. A Channel is an in-game venue for communication. It's essentially representation of a re-sender: Users sends Messages to the Channel, and the Channel re-sends those messages to all users subscribed to the Channel. """ def get_all_channels(self): """ Get all channels. Returns: channels (list): All channels in game. """ return self.all() def get_channel(self, channelkey): """ Return the channel object if given its key. Also searches its aliases. Args: channelkey (str): Channel key to search for. Returns: channel (Channel or None): A channel match. """ dbref = self.dbref(channelkey) if dbref: try: return self.get(id=dbref) except self.model.DoesNotExist: pass results = self.filter( Q(db_key__iexact=channelkey) | Q(db_tags__db_tagtype__iexact="alias", db_tags__db_key__iexact=channelkey) ).distinct() return results[0] if results else None def get_subscriptions(self, subscriber): """ Return all channels a given entity is subscribed to. Args: subscriber (Object or Account): The one subscribing. Returns: subscriptions (list): Channel subscribed to. """ clsname = subscriber.__dbclass__.__name__ if clsname == "AccountDB": return subscriber.account_subscription_set.all() if clsname == "ObjectDB": return subscriber.object_subscription_set.all() return [] def search_channel(self, ostring, exact=True): """ Search the channel database for a particular channel. Args: ostring (str): The key or database id of the channel. exact (bool, optional): Require an exact (but not case sensitive) match. Returns: Queryset: Iterable with 0, 1 or more matches. """ dbref = self.dbref(ostring) if dbref: dbref_match = self.search_dbref(dbref) if dbref_match: return dbref_match if exact: channels = self.filter( Q(db_key__iexact=ostring) | Q(db_tags__db_tagtype__iexact="alias", db_tags__db_key__iexact=ostring) ).distinct() else: channels = self.filter( Q(db_key__icontains=ostring) | Q(db_tags__db_tagtype__iexact="alias", db_tags__db_key__icontains=ostring) ).distinct() return channels def create_channel( self, key, aliases=None, desc=None, locks=None, keep_log=True, typeclass=None, tags=None ): """ Create A communication Channel. A Channel serves as a central hub for distributing Msgs to groups of people without specifying the receivers explicitly. Instead accounts may 'connect' to the channel and follow the flow of messages. By default the channel allows access to all old messages, but this can be turned off with the keep_log switch. Args: key (str): This must be unique. Keyword Args: aliases (list of str): List of alternative (likely shorter) keynames. desc (str): A description of the channel, for use in listings. locks (str): Lockstring. keep_log (bool): Log channel throughput. typeclass (str or class): The typeclass of the Channel (not often used). tags (list): A list of tags or tuples `(tag, category)`. Returns: channel (Channel): A newly created channel. """ typeclass = typeclass if typeclass else settings.BASE_CHANNEL_TYPECLASS if isinstance(typeclass, str): # a path is given. Load the actual typeclass typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS) # create new instance new_channel = typeclass(db_key=key) # store call signature for the signal new_channel._createdict = dict( key=key, aliases=aliases, desc=desc, locks=locks, keep_log=keep_log, tags=tags ) # this will trigger the save signal which in turn calls the # at_first_save hook on the typeclass, where the _createdict can be # used. new_channel.save() signals.SIGNAL_CHANNEL_POST_CREATE.send(sender=new_channel) return new_channel # back-compatibility alias channel_search = search_channel class ChannelManager(ChannelDBManager, TypeclassManager): """ Wrapper to group the typeclass manager to a consistent name. """ pass
[ "evennia.utils.utils.class_from_module", "evennia.utils.utils.dbref", "evennia.utils.utils.make_iter", "evennia.server.signals.SIGNAL_CHANNEL_POST_CREATE.send" ]
[((1484, 1494), 'evennia.utils.utils.dbref', 'dbref', (['inp'], {}), '(inp)\n', (1489, 1494), False, 'from evennia.utils.utils import dbref, make_iter, class_from_module\n'), ((11081, 11101), 'evennia.utils.utils.make_iter', 'make_iter', (['senderobj'], {}), '(senderobj)\n', (11090, 11101), False, 'from evennia.utils.utils import dbref, make_iter, class_from_module\n'), ((11204, 11224), 'evennia.utils.utils.make_iter', 'make_iter', (['receivers'], {}), '(receivers)\n', (11213, 11224), False, 'from evennia.utils.utils import dbref, make_iter, class_from_module\n'), ((16241, 16300), 'evennia.server.signals.SIGNAL_CHANNEL_POST_CREATE.send', 'signals.SIGNAL_CHANNEL_POST_CREATE.send', ([], {'sender': 'new_channel'}), '(sender=new_channel)\n', (16280, 16300), False, 'from evennia.server import signals\n'), ((9150, 9153), 'django.db.models.Q', 'Q', ([], {}), '()\n', (9151, 9153), False, 'from django.db.models import Q\n'), ((15726, 15780), 'evennia.utils.utils.class_from_module', 'class_from_module', (['typeclass', 'settings.TYPECLASS_PATHS'], {}), '(typeclass, settings.TYPECLASS_PATHS)\n', (15743, 15780), False, 'from evennia.utils.utils import dbref, make_iter, class_from_module\n'), ((1511, 1521), 'evennia.utils.utils.dbref', 'dbref', (['inp'], {}), '(inp)\n', (1516, 1521), False, 'from evennia.utils.utils import dbref, make_iter, class_from_module\n'), ((7862, 7891), 'django.db.models.Q', 'Q', ([], {'db_sender_accounts__pk': 'spk'}), '(db_sender_accounts__pk=spk)\n', (7863, 7891), False, 'from django.db.models import Q\n'), ((8402, 8434), 'django.db.models.Q', 'Q', ([], {'db_receivers_accounts__pk': 'rpk'}), '(db_receivers_accounts__pk=rpk)\n', (8403, 8434), False, 'from django.db.models import Q\n'), ((9035, 9067), 'django.db.models.Q', 'Q', ([], {'db_header__icontains': 'freetext'}), '(db_header__icontains=freetext)\n', (9036, 9067), False, 'from django.db.models import Q\n'), ((9070, 9103), 'django.db.models.Q', 'Q', ([], {'db_message__icontains': 'freetext'}), '(db_message__icontains=freetext)\n', (9071, 9103), False, 'from django.db.models import Q\n'), ((7895, 7927), 'django.db.models.Q', 'Q', ([], {'db_hide_from_accounts__pk': 'spk'}), '(db_hide_from_accounts__pk=spk)\n', (7896, 7927), False, 'from django.db.models import Q\n'), ((7989, 8017), 'django.db.models.Q', 'Q', ([], {'db_sender_objects__pk': 'spk'}), '(db_sender_objects__pk=spk)\n', (7990, 8017), False, 'from django.db.models import Q\n'), ((8114, 8142), 'django.db.models.Q', 'Q', ([], {'db_sender_scripts__pk': 'spk'}), '(db_sender_scripts__pk=spk)\n', (8115, 8142), False, 'from django.db.models import Q\n'), ((8187, 8190), 'django.db.models.Q', 'Q', ([], {}), '()\n', (8188, 8190), False, 'from django.db.models import Q\n'), ((8438, 8470), 'django.db.models.Q', 'Q', ([], {'db_hide_from_accounts__pk': 'rpk'}), '(db_hide_from_accounts__pk=rpk)\n', (8439, 8470), False, 'from django.db.models import Q\n'), ((8535, 8566), 'django.db.models.Q', 'Q', ([], {'db_receivers_objects__pk': 'rpk'}), '(db_receivers_objects__pk=rpk)\n', (8536, 8566), False, 'from django.db.models import Q\n'), ((8665, 8696), 'django.db.models.Q', 'Q', ([], {'db_receivers_scripts__pk': 'rpk'}), '(db_receivers_scripts__pk=rpk)\n', (8666, 8696), False, 'from django.db.models import Q\n'), ((8021, 8052), 'django.db.models.Q', 'Q', ([], {'db_hide_from_objects__pk': 'spk'}), '(db_hide_from_objects__pk=spk)\n', (8022, 8052), False, 'from django.db.models import Q\n'), ((8570, 8601), 'django.db.models.Q', 'Q', ([], {'db_hide_from_objects__pk': 'rpk'}), '(db_hide_from_objects__pk=rpk)\n', (8571, 8601), False, 'from django.db.models import Q\n'), ((8948, 8951), 'django.db.models.Q', 'Q', ([], {}), '()\n', (8949, 8951), False, 'from django.db.models import Q\n'), ((12662, 12690), 'django.db.models.Q', 'Q', ([], {'db_key__iexact': 'channelkey'}), '(db_key__iexact=channelkey)\n', (12663, 12690), False, 'from django.db.models import Q\n'), ((12705, 12779), 'django.db.models.Q', 'Q', ([], {'db_tags__db_tagtype__iexact': '"""alias"""', 'db_tags__db_key__iexact': 'channelkey'}), "(db_tags__db_tagtype__iexact='alias', db_tags__db_key__iexact=channelkey)\n", (12706, 12779), False, 'from django.db.models import Q\n'), ((14029, 14054), 'django.db.models.Q', 'Q', ([], {'db_key__iexact': 'ostring'}), '(db_key__iexact=ostring)\n', (14030, 14054), False, 'from django.db.models import Q\n'), ((14073, 14144), 'django.db.models.Q', 'Q', ([], {'db_tags__db_tagtype__iexact': '"""alias"""', 'db_tags__db_key__iexact': 'ostring'}), "(db_tags__db_tagtype__iexact='alias', db_tags__db_key__iexact=ostring)\n", (14074, 14144), False, 'from django.db.models import Q\n'), ((14236, 14264), 'django.db.models.Q', 'Q', ([], {'db_key__icontains': 'ostring'}), '(db_key__icontains=ostring)\n', (14237, 14264), False, 'from django.db.models import Q\n'), ((14283, 14357), 'django.db.models.Q', 'Q', ([], {'db_tags__db_tagtype__iexact': '"""alias"""', 'db_tags__db_key__icontains': 'ostring'}), "(db_tags__db_tagtype__iexact='alias', db_tags__db_key__icontains=ostring)\n", (14284, 14357), False, 'from django.db.models import Q\n')]
""" Unit tests for the utilities of the evennia.utils.utils module. TODO: Not nearly all utilities are covered yet. """ import os.path import random from parameterized import parameterized import mock from datetime import datetime, timedelta from django.test import TestCase from datetime import datetime from twisted.internet import task from evennia.utils.ansi import ANSIString from evennia.utils import utils from evennia.utils.test_resources import EvenniaTest class TestIsIter(TestCase): def test_is_iter(self): self.assertEqual(True, utils.is_iter([1, 2, 3, 4])) self.assertEqual(False, utils.is_iter("This is not an iterable")) class TestCrop(TestCase): def test_crop(self): # No text, return no text self.assertEqual("", utils.crop("", width=10, suffix="[...]")) # Input length equal to max width, no crop self.assertEqual("0123456789", utils.crop("0123456789", width=10, suffix="[...]")) # Input length greater than max width, crop (suffix included in width) self.assertEqual("0123[...]", utils.crop("0123456789", width=9, suffix="[...]")) # Input length less than desired width, no crop self.assertEqual("0123", utils.crop("0123", width=9, suffix="[...]")) # Width too small or equal to width of suffix self.assertEqual("012", utils.crop("0123", width=3, suffix="[...]")) self.assertEqual("01234", utils.crop("0123456", width=5, suffix="[...]")) class TestDedent(TestCase): def test_dedent(self): # Empty string, return empty string self.assertEqual("", utils.dedent("")) # No leading whitespace self.assertEqual("TestDedent", utils.dedent("TestDedent")) # Leading whitespace, single line self.assertEqual("TestDedent", utils.dedent(" TestDedent")) # Leading whitespace, multi line input_string = " hello\n world" expected_string = "hello\nworld" self.assertEqual(expected_string, utils.dedent(input_string)) class TestListToString(TestCase): """ Default function header from utils.py: list_to_string(inlist, endsep="and", addquote=False) Examples: no endsep: [1,2,3] -> '1, 2, 3' with endsep=='and': [1,2,3] -> '1, 2 and 3' with addquote and endsep [1,2,3] -> '"1", "2" and "3"' """ def test_list_to_string(self): self.assertEqual("1, 2, 3", utils.list_to_string([1, 2, 3], endsep="")) self.assertEqual('"1", "2", "3"', utils.list_to_string([1, 2, 3], endsep="", addquote=True)) self.assertEqual("1, 2, and 3", utils.list_to_string([1, 2, 3])) self.assertEqual( '"1", "2", and "3"', utils.list_to_string([1, 2, 3], endsep="and", addquote=True) ) self.assertEqual("1 and 2", utils.list_to_string([1, 2])) class TestMLen(TestCase): """ Verifies that m_len behaves like len in all situations except those where MXP may be involved. """ def test_non_mxp_string(self): self.assertEqual(utils.m_len("Test_string"), 11) def test_mxp_string(self): self.assertEqual(utils.m_len("|lclook|ltat|le"), 2) def test_mxp_ansi_string(self): self.assertEqual(utils.m_len(ANSIString("|lcl|gook|ltat|le|n")), 2) def test_non_mxp_ansi_string(self): self.assertEqual(utils.m_len(ANSIString("|gHello|n")), 5) def test_list(self): self.assertEqual(utils.m_len([None, None]), 2) def test_dict(self): self.assertEqual(utils.m_len({"hello": True, "Goodbye": False}), 2) class TestDisplayLen(TestCase): """ Verifies that display_len behaves like m_len in all situations except those where asian characters are involved. """ def test_non_mxp_string(self): self.assertEqual(utils.display_len("Test_string"), 11) def test_mxp_string(self): self.assertEqual(utils.display_len("|lclook|ltat|le"), 2) def test_mxp_ansi_string(self): self.assertEqual(utils.display_len(ANSIString("|lcl|gook|ltat|le|n")), 2) def test_non_mxp_ansi_string(self): self.assertEqual(utils.display_len(ANSIString("|gHello|n")), 5) def test_list(self): self.assertEqual(utils.display_len([None, None]), 2) def test_dict(self): self.assertEqual(utils.display_len({"hello": True, "Goodbye": False}), 2) def test_east_asian(self): self.assertEqual(utils.display_len("서서서"), 6) class TestANSIString(TestCase): """ Verifies that ANSIString's string-API works as intended. """ def setUp(self): self.example_raw = "|relectric |cboogaloo|n" self.example_ansi = ANSIString(self.example_raw) self.example_str = "electric boogaloo" self.example_output = "\x1b[1m\x1b[31melectric \x1b[1m\x1b[36mboogaloo\x1b[0m" def test_length(self): self.assertEqual(len(self.example_ansi), 17) def test_clean(self): self.assertEqual(self.example_ansi.clean(), self.example_str) def test_raw(self): self.assertEqual(self.example_ansi.raw(), self.example_output) def test_format(self): self.assertEqual(f"{self.example_ansi:0<20}", self.example_output + "000") class TestTimeformat(TestCase): """ Default function header from utils.py: time_format(seconds, style=0) """ def test_style_0(self): """Test the style 0 of time_format.""" self.assertEqual(utils.time_format(0, 0), "00:00") self.assertEqual(utils.time_format(28, 0), "00:00") self.assertEqual(utils.time_format(92, 0), "00:01") self.assertEqual(utils.time_format(300, 0), "00:05") self.assertEqual(utils.time_format(660, 0), "00:11") self.assertEqual(utils.time_format(3600, 0), "01:00") self.assertEqual(utils.time_format(3725, 0), "01:02") self.assertEqual(utils.time_format(86350, 0), "23:59") self.assertEqual(utils.time_format(86800, 0), "1d 00:06") self.assertEqual(utils.time_format(130800, 0), "1d 12:20") self.assertEqual(utils.time_format(530800, 0), "6d 03:26") def test_style_1(self): """Test the style 1 of time_format.""" self.assertEqual(utils.time_format(0, 1), "0s") self.assertEqual(utils.time_format(28, 1), "28s") self.assertEqual(utils.time_format(92, 1), "1m") self.assertEqual(utils.time_format(300, 1), "5m") self.assertEqual(utils.time_format(660, 1), "11m") self.assertEqual(utils.time_format(3600, 1), "1h") self.assertEqual(utils.time_format(3725, 1), "1h") self.assertEqual(utils.time_format(86350, 1), "23h") self.assertEqual(utils.time_format(86800, 1), "1d") self.assertEqual(utils.time_format(130800, 1), "1d") self.assertEqual(utils.time_format(530800, 1), "6d") def test_style_2(self): """Test the style 2 of time_format.""" self.assertEqual(utils.time_format(0, 2), "0 minutes") self.assertEqual(utils.time_format(28, 2), "0 minutes") self.assertEqual(utils.time_format(92, 2), "1 minute") self.assertEqual(utils.time_format(300, 2), "5 minutes") self.assertEqual(utils.time_format(660, 2), "11 minutes") self.assertEqual(utils.time_format(3600, 2), "1 hour, 0 minutes") self.assertEqual(utils.time_format(3725, 2), "1 hour, 2 minutes") self.assertEqual(utils.time_format(86350, 2), "23 hours, 59 minutes") self.assertEqual(utils.time_format(86800, 2), "1 day, 0 hours, 6 minutes") self.assertEqual(utils.time_format(130800, 2), "1 day, 12 hours, 20 minutes") self.assertEqual(utils.time_format(530800, 2), "6 days, 3 hours, 26 minutes") def test_style_3(self): """Test the style 3 of time_format.""" self.assertEqual(utils.time_format(0, 3), "") self.assertEqual(utils.time_format(28, 3), "28 seconds") self.assertEqual(utils.time_format(92, 3), "1 minute 32 seconds") self.assertEqual(utils.time_format(300, 3), "5 minutes 0 seconds") self.assertEqual(utils.time_format(660, 3), "11 minutes 0 seconds") self.assertEqual(utils.time_format(3600, 3), "1 hour, 0 minutes") self.assertEqual(utils.time_format(3725, 3), "1 hour, 2 minutes 5 seconds") self.assertEqual(utils.time_format(86350, 3), "23 hours, 59 minutes 10 seconds") self.assertEqual(utils.time_format(86800, 3), "1 day, 0 hours, 6 minutes 40 seconds") self.assertEqual(utils.time_format(130800, 3), "1 day, 12 hours, 20 minutes 0 seconds") self.assertEqual(utils.time_format(530800, 3), "6 days, 3 hours, 26 minutes 40 seconds") def test_style_4(self): """Test the style 4 of time_format.""" self.assertEqual(utils.time_format(0, 4), "0 seconds") self.assertEqual(utils.time_format(28, 4), "28 seconds") self.assertEqual(utils.time_format(92, 4), "a minute") self.assertEqual(utils.time_format(300, 4), "5 minutes") self.assertEqual(utils.time_format(660, 4), "11 minutes") self.assertEqual(utils.time_format(3600, 4), "an hour") self.assertEqual(utils.time_format(3725, 4), "an hour") self.assertEqual(utils.time_format(86350, 4), "23 hours") self.assertEqual(utils.time_format(86800, 4), "a day") self.assertEqual(utils.time_format(130800, 4), "a day") self.assertEqual(utils.time_format(530800, 4), "6 days") self.assertEqual(utils.time_format(3030800, 4), "a month") self.assertEqual(utils.time_format(7030800, 4), "2 months") self.assertEqual(utils.time_format(40030800, 4), "a year") self.assertEqual(utils.time_format(90030800, 4), "2 years") def test_unknown_format(self): """Test that unknown formats raise exceptions.""" self.assertRaises(ValueError, utils.time_format, 0, 5) self.assertRaises(ValueError, utils.time_format, 0, "u") @mock.patch( "evennia.utils.utils.timezone.now", new=mock.MagicMock(return_value=datetime(2019, 8, 28, 21, 56)), ) class TestDateTimeFormat(TestCase): def test_datetimes(self): dtobj = datetime(2017, 7, 26, 22, 54) self.assertEqual(utils.datetime_format(dtobj), "Jul 26, 2017") dtobj = datetime(2019, 7, 26, 22, 54) self.assertEqual(utils.datetime_format(dtobj), "Jul 26") dtobj = datetime(2019, 8, 28, 19, 54) self.assertEqual(utils.datetime_format(dtobj), "19:54") dtobj = datetime(2019, 8, 28, 21, 32) self.assertEqual(utils.datetime_format(dtobj), "21:32:00") class TestImportFunctions(TestCase): def _t_dir_file(self, filename): testdir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(testdir, filename) def test_mod_import(self): loaded_mod = utils.mod_import("evennia.utils.ansi") self.assertIsNotNone(loaded_mod) def test_mod_import_invalid(self): loaded_mod = utils.mod_import("evennia.utils.invalid_module") self.assertIsNone(loaded_mod) def test_mod_import_from_path(self): test_path = self._t_dir_file("test_eveditor.py") loaded_mod = utils.mod_import_from_path(test_path) self.assertIsNotNone(loaded_mod) def test_mod_import_from_path_invalid(self): test_path = self._t_dir_file("invalid_filename.py") loaded_mod = utils.mod_import_from_path(test_path) self.assertIsNone(loaded_mod) class LatinifyTest(TestCase): def setUp(self): super().setUp() self.example_str = "It naïvely says, “plugh.”" self.expected_output = 'It naively says, "plugh."' def test_plain_string(self): result = utils.latinify(self.example_str) self.assertEqual(result, self.expected_output) def test_byte_string(self): byte_str = utils.to_bytes(self.example_str) result = utils.latinify(byte_str) self.assertEqual(result, self.expected_output) class TestFormatGrid(TestCase): maxDiff = None def setUp(self): # make the random only semi-random with a fixed seed random.seed(1) def tearDown(self): # restore normal randomness random.seed(None) def _generate_elements(self, basewidth, variation, amount): return [ "X" * max(1, basewidth + int(random.randint(-variation, variation))) for _ in range(amount) ] def test_even_grid(self): """Grid with small variations""" elements = self._generate_elements(3, 1, 30) rows = utils.format_grid(elements, width=78) self.assertEqual(len(rows), 4) self.assertTrue(all(len(row) == 78 for row in rows)) def test_disparate_grid(self): """Grid with big variations""" elements = self._generate_elements(3, 15, 30) rows = utils.format_grid(elements, width=82, sep=" ") self.assertEqual(len(rows), 8) self.assertTrue(all(len(row) == 82 for row in rows)) def test_huge_grid(self): """Grid with very long strings""" elements = self._generate_elements(70, 20, 30) rows = utils.format_grid(elements, width=78) self.assertEqual(len(rows), 30) self.assertTrue(all(len(row) == 78 for row in rows)) def test_overlap(self): """Grid with elements overlapping into the next slot""" elements = ( "alias", "batchcode", "batchcommands", "cmdsets", "copy", "cpattr", "desc", "destroy", "dig", "examine", "find", "force", "lock", ) rows = utils.format_grid(elements, width=78) self.assertEqual(len(rows), 3) for element in elements: self.assertTrue(element in "\n".join(rows), f"element {element} is missing.") def test_breakline(self): """Grid with line-long elements in middle""" elements = self._generate_elements(6, 4, 30) elements[10] = elements[20] = "-" * 78 rows = utils.format_grid(elements, width=78) self.assertEqual(len(rows), 8) for element in elements: self.assertTrue(element in "\n".join(rows), f"element {element} is missing.") class TestPercent(TestCase): """ Test the utils.percentage function. """ def test_ok_input(self): result = utils.percent(3, 0, 10) self.assertEqual(result, "30.0%") result = utils.percent(2.5, 0, 5, formatting=None) self.assertEqual(result, 50.0) def test_bad_input(self): """Gracefully handle weird input.""" self.assertEqual(utils.percent(3, 10, 1), "0.0%") self.assertEqual(utils.percent(3, None, 1), "100.0%") self.assertEqual(utils.percent(1, 1, 1), "100.0%") self.assertEqual(utils.percent(3, 1, 1), "0.0%") self.assertEqual(utils.percent(3, 0, 1), "100.0%") self.assertEqual(utils.percent(-3, 0, 1), "0.0%") class TestSafeConvert(TestCase): """ Test evennia.utils.utils.safe_convert_to_types """ @parameterized.expand([ (('1', '2', 3, 4, '5'), {'a': 1, 'b': '2', 'c': 3}, ((int, float, str, int), {'a': int, 'b': float}), # " (1, 2.0, '3', 4, '5'), {'a': 1, 'b': 2.0, 'c': 3}), (('1 + 2', '[1, 2, 3]', [3, 4, 5]), {'a': '3 + 4', 'b': 5}, (('py', 'py', 'py'), {'a': 'py', 'b': 'py'}), (3, [1, 2, 3], [3, 4, 5]), {'a': 7, 'b': 5}), ]) def test_conversion(self, args, kwargs, converters, expected_args, expected_kwargs): """ Test the converter with different inputs """ result_args, result_kwargs = utils.safe_convert_to_types( converters, *args, raise_errors=True, **kwargs) self.assertEqual(expected_args, result_args) self.assertEqual(expected_kwargs, result_kwargs) def test_conversion__fail(self): """ Test failing conversion """ from evennia.utils.funcparser import ParsingError with self.assertRaises(ValueError): utils.safe_convert_to_types( (int, ), *('foo', ), raise_errors=True) with self.assertRaises(ParsingError) as err: utils.safe_convert_to_types( ('py', {}), *('foo', ), raise_errors=True) _TASK_HANDLER = None def dummy_func(obj): """ Used in TestDelay. A function that: can be serialized uses no memory references uses evennia objects """ # get a reference of object from evennia.objects.models import ObjectDB obj = ObjectDB.objects.object_search(obj) obj = obj[0] # make changes to object obj.ndb.dummy_var = 'dummy_func ran' return True class TestDelay(EvenniaTest): """ Test utils.delay. """ def setUp(self): super().setUp() # get a reference of TASK_HANDLER self.timedelay = 5 global _TASK_HANDLER if _TASK_HANDLER is None: from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER _TASK_HANDLER.clock = task.Clock() self.char1.ndb.dummy_var = False def tearDown(self): super().tearDown() _TASK_HANDLER.clear() def test_call_early(self): # call a task early with call for pers in (True, False): t = utils.delay(self.timedelay, dummy_func, self.char1.dbref, persistent=pers) result = t.call() self.assertTrue(result) self.assertEqual(self.char1.ndb.dummy_var, 'dummy_func ran') self.assertTrue(t.exists()) self.assertTrue(t.active()) self.char1.ndb.dummy_var = False def test_do_task(self): # call the task early with do_task for pers in (True, False): t = utils.delay(self.timedelay, dummy_func, self.char1.dbref, persistent=pers) # call the task early to test Task.call and TaskHandler.call_task result = t.do_task() self.assertTrue(result) self.assertEqual(self.char1.ndb.dummy_var, 'dummy_func ran') self.assertFalse(t.exists()) self.char1.ndb.dummy_var = False def test_deferred_call(self): # wait for deferred to call timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) self.assertTrue(t.active()) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertEqual(self.char1.ndb.dummy_var, 'dummy_func ran') self.assertFalse(t.exists()) self.char1.ndb.dummy_var = False def test_short_deferred_call(self): # wait for deferred to call with a very short time timedelay = .1 for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) self.assertTrue(t.active()) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertEqual(self.char1.ndb.dummy_var, 'dummy_func ran') self.assertFalse(t.exists()) self.char1.ndb.dummy_var = False def test_active(self): timedelay = self.timedelay t = utils.delay(timedelay, dummy_func, self.char1.dbref) self.assertTrue(_TASK_HANDLER.active(t.get_id())) self.assertTrue(t.active()) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertFalse(_TASK_HANDLER.active(t.get_id())) self.assertFalse(t.active()) def test_called(self): timedelay = self.timedelay t = utils.delay(timedelay, dummy_func, self.char1.dbref) self.assertFalse(t.called) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertTrue(t.called) def test_cancel(self): timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) self.assertTrue(t.active()) success = t.cancel() self.assertFalse(t.active()) self.assertTrue(success) self.assertTrue(t.exists()) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertEqual(self.char1.ndb.dummy_var, False) def test_remove(self): timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) self.assertTrue(t.active()) success = t.remove() self.assertTrue(success) self.assertFalse(t.active()) self.assertFalse(t.exists()) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertEqual(self.char1.ndb.dummy_var, False) def test_remove_canceled(self): # remove a canceled task timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) self.assertTrue(t.active()) success = t.cancel() self.assertTrue(success) self.assertTrue(t.exists()) self.assertFalse(t.active()) success = t.remove() self.assertTrue(success) self.assertFalse(t.exists()) _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertEqual(self.char1.ndb.dummy_var, False) def test_pause_unpause(self): # remove a canceled task timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) self.assertTrue(t.active()) t.pause() self.assertTrue(t.paused) t.unpause() self.assertFalse(t.paused) self.assertEqual(self.char1.ndb.dummy_var, False) t.pause() _TASK_HANDLER.clock.advance(timedelay) # make time pass self.assertEqual(self.char1.ndb.dummy_var, False) t.unpause() self.assertEqual(self.char1.ndb.dummy_var, 'dummy_func ran') self.char1.ndb.dummy_var = False def test_auto_stale_task_removal(self): # automated removal of stale tasks. timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) t.cancel() self.assertFalse(t.active()) _TASK_HANDLER.clock.advance(timedelay) # make time pass if pers: self.assertTrue(t.get_id() in _TASK_HANDLER.to_save) self.assertTrue(t.get_id() in _TASK_HANDLER.tasks) # Make task handler's now time, after the stale timeout _TASK_HANDLER._now = datetime.now() + timedelta(seconds=_TASK_HANDLER.stale_timeout + timedelay + 1) # add a task to test automatic removal t2 = utils.delay(timedelay, dummy_func, self.char1.dbref) if pers: self.assertFalse(t.get_id() in _TASK_HANDLER.to_save) self.assertFalse(t.get_id() in _TASK_HANDLER.tasks) self.assertEqual(self.char1.ndb.dummy_var, False) _TASK_HANDLER.clear() def test_manual_stale_task_removal(self): # manual removal of stale tasks. timedelay = self.timedelay for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) t.cancel() self.assertFalse(t.active()) _TASK_HANDLER.clock.advance(timedelay) # make time pass if pers: self.assertTrue(t.get_id() in _TASK_HANDLER.to_save) self.assertTrue(t.get_id() in _TASK_HANDLER.tasks) # Make task handler's now time, after the stale timeout _TASK_HANDLER._now = datetime.now() + timedelta(seconds=_TASK_HANDLER.stale_timeout + timedelay + 1) _TASK_HANDLER.clean_stale_tasks() # cleanup of stale tasks in in the save method if pers: self.assertFalse(t.get_id() in _TASK_HANDLER.to_save) self.assertFalse(t.get_id() in _TASK_HANDLER.tasks) self.assertEqual(self.char1.ndb.dummy_var, False) _TASK_HANDLER.clear() def test_disable_stale_removal(self): # manual removal of stale tasks. timedelay = self.timedelay _TASK_HANDLER.stale_timeout = 0 for pers in (False, True): t = utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=pers) t.cancel() self.assertFalse(t.active()) _TASK_HANDLER.clock.advance(timedelay) # make time pass if pers: self.assertTrue(t.get_id() in _TASK_HANDLER.to_save) self.assertTrue(t.get_id() in _TASK_HANDLER.tasks) # Make task handler's now time, after the stale timeout _TASK_HANDLER._now = datetime.now() + timedelta(seconds=_TASK_HANDLER.stale_timeout + timedelay + 1) t2 = utils.delay(timedelay, dummy_func, self.char1.dbref) if pers: self.assertTrue(t.get_id() in _TASK_HANDLER.to_save) self.assertTrue(t.get_id() in _TASK_HANDLER.tasks) self.assertEqual(self.char1.ndb.dummy_var, False) # manual removal should still work _TASK_HANDLER.clean_stale_tasks() # cleanup of stale tasks in in the save method if pers: self.assertFalse(t.get_id() in _TASK_HANDLER.to_save) self.assertFalse(t.get_id() in _TASK_HANDLER.tasks) _TASK_HANDLER.clear() def test_server_restart(self): # emulate a server restart timedelay = self.timedelay utils.delay(timedelay, dummy_func, self.char1.dbref, persistent=True) _TASK_HANDLER.clear(False) # remove all tasks from task handler, do not save this change. _TASK_HANDLER.clock.advance(timedelay) # advance twisted reactor time past callback time self.assertEqual(self.char1.ndb.dummy_var, False) # task has not run _TASK_HANDLER.load() # load persistent tasks from database. _TASK_HANDLER.create_delays() # create new deffered instances from persistent tasks _TASK_HANDLER.clock.advance(timedelay) # Clock must advance to trigger, even if past timedelay self.assertEqual(self.char1.ndb.dummy_var, 'dummy_func ran')
[ "evennia.utils.utils.time_format", "evennia.utils.utils.latinify", "evennia.utils.ansi.ANSIString", "evennia.objects.models.ObjectDB.objects.object_search", "evennia.utils.utils.list_to_string", "evennia.scripts.taskhandler.TASK_HANDLER.clock.advance", "evennia.utils.utils.format_grid", "evennia.utils...
[((15150, 15495), 'parameterized.parameterized.expand', 'parameterized.expand', (["[(('1', '2', 3, 4, '5'), {'a': 1, 'b': '2', 'c': 3}, ((int, float, str, int\n ), {'a': int, 'b': float}), (1, 2.0, '3', 4, '5'), {'a': 1, 'b': 2.0,\n 'c': 3}), (('1 + 2', '[1, 2, 3]', [3, 4, 5]), {'a': '3 + 4', 'b': 5}, (\n ('py', 'py', 'py'), {'a': 'py', 'b': 'py'}), (3, [1, 2, 3], [3, 4, 5]),\n {'a': 7, 'b': 5})]"], {}), "([(('1', '2', 3, 4, '5'), {'a': 1, 'b': '2', 'c': 3}, (\n (int, float, str, int), {'a': int, 'b': float}), (1, 2.0, '3', 4, '5'),\n {'a': 1, 'b': 2.0, 'c': 3}), (('1 + 2', '[1, 2, 3]', [3, 4, 5]), {'a':\n '3 + 4', 'b': 5}, (('py', 'py', 'py'), {'a': 'py', 'b': 'py'}), (3, [1,\n 2, 3], [3, 4, 5]), {'a': 7, 'b': 5})])\n", (15170, 15495), False, 'from parameterized import parameterized\n'), ((16678, 16713), 'evennia.objects.models.ObjectDB.objects.object_search', 'ObjectDB.objects.object_search', (['obj'], {}), '(obj)\n', (16708, 16713), False, 'from evennia.objects.models import ObjectDB\n'), ((4684, 4712), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['self.example_raw'], {}), '(self.example_raw)\n', (4694, 4712), False, 'from evennia.utils.ansi import ANSIString\n'), ((10164, 10193), 'datetime.datetime', 'datetime', (['(2017)', '(7)', '(26)', '(22)', '(54)'], {}), '(2017, 7, 26, 22, 54)\n', (10172, 10193), False, 'from datetime import datetime\n'), ((10281, 10310), 'datetime.datetime', 'datetime', (['(2019)', '(7)', '(26)', '(22)', '(54)'], {}), '(2019, 7, 26, 22, 54)\n', (10289, 10310), False, 'from datetime import datetime\n'), ((10392, 10421), 'datetime.datetime', 'datetime', (['(2019)', '(8)', '(28)', '(19)', '(54)'], {}), '(2019, 8, 28, 19, 54)\n', (10400, 10421), False, 'from datetime import datetime\n'), ((10502, 10531), 'datetime.datetime', 'datetime', (['(2019)', '(8)', '(28)', '(21)', '(32)'], {}), '(2019, 8, 28, 21, 32)\n', (10510, 10531), False, 'from datetime import datetime\n'), ((10836, 10874), 'evennia.utils.utils.mod_import', 'utils.mod_import', (['"""evennia.utils.ansi"""'], {}), "('evennia.utils.ansi')\n", (10852, 10874), False, 'from evennia.utils import utils\n'), ((10977, 11025), 'evennia.utils.utils.mod_import', 'utils.mod_import', (['"""evennia.utils.invalid_module"""'], {}), "('evennia.utils.invalid_module')\n", (10993, 11025), False, 'from evennia.utils import utils\n'), ((11184, 11221), 'evennia.utils.utils.mod_import_from_path', 'utils.mod_import_from_path', (['test_path'], {}), '(test_path)\n', (11210, 11221), False, 'from evennia.utils import utils\n'), ((11394, 11431), 'evennia.utils.utils.mod_import_from_path', 'utils.mod_import_from_path', (['test_path'], {}), '(test_path)\n', (11420, 11431), False, 'from evennia.utils import utils\n'), ((11713, 11745), 'evennia.utils.utils.latinify', 'utils.latinify', (['self.example_str'], {}), '(self.example_str)\n', (11727, 11745), False, 'from evennia.utils import utils\n'), ((11853, 11885), 'evennia.utils.utils.to_bytes', 'utils.to_bytes', (['self.example_str'], {}), '(self.example_str)\n', (11867, 11885), False, 'from evennia.utils import utils\n'), ((11903, 11927), 'evennia.utils.utils.latinify', 'utils.latinify', (['byte_str'], {}), '(byte_str)\n', (11917, 11927), False, 'from evennia.utils import utils\n'), ((12128, 12142), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (12139, 12142), False, 'import random\n'), ((12212, 12229), 'random.seed', 'random.seed', (['None'], {}), '(None)\n', (12223, 12229), False, 'import random\n'), ((12578, 12615), 'evennia.utils.utils.format_grid', 'utils.format_grid', (['elements'], {'width': '(78)'}), '(elements, width=78)\n', (12595, 12615), False, 'from evennia.utils import utils\n'), ((12860, 12907), 'evennia.utils.utils.format_grid', 'utils.format_grid', (['elements'], {'width': '(82)', 'sep': '""" """'}), "(elements, width=82, sep=' ')\n", (12877, 12907), False, 'from evennia.utils import utils\n'), ((13151, 13188), 'evennia.utils.utils.format_grid', 'utils.format_grid', (['elements'], {'width': '(78)'}), '(elements, width=78)\n', (13168, 13188), False, 'from evennia.utils import utils\n'), ((13715, 13752), 'evennia.utils.utils.format_grid', 'utils.format_grid', (['elements'], {'width': '(78)'}), '(elements, width=78)\n', (13732, 13752), False, 'from evennia.utils import utils\n'), ((14114, 14151), 'evennia.utils.utils.format_grid', 'utils.format_grid', (['elements'], {'width': '(78)'}), '(elements, width=78)\n', (14131, 14151), False, 'from evennia.utils import utils\n'), ((14448, 14471), 'evennia.utils.utils.percent', 'utils.percent', (['(3)', '(0)', '(10)'], {}), '(3, 0, 10)\n', (14461, 14471), False, 'from evennia.utils import utils\n'), ((14531, 14572), 'evennia.utils.utils.percent', 'utils.percent', (['(2.5)', '(0)', '(5)'], {'formatting': 'None'}), '(2.5, 0, 5, formatting=None)\n', (14544, 14572), False, 'from evennia.utils import utils\n'), ((15744, 15819), 'evennia.utils.utils.safe_convert_to_types', 'utils.safe_convert_to_types', (['converters', '*args'], {'raise_errors': '(True)'}), '(converters, *args, raise_errors=True, **kwargs)\n', (15771, 15819), False, 'from evennia.utils import utils\n'), ((17177, 17189), 'twisted.internet.task.Clock', 'task.Clock', ([], {}), '()\n', (17187, 17189), False, 'from twisted.internet import task\n'), ((17291, 17312), 'evennia.scripts.taskhandler.TASK_HANDLER.clear', '_TASK_HANDLER.clear', ([], {}), '()\n', (17310, 17312), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((19359, 19411), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {}), '(timedelay, dummy_func, self.char1.dbref)\n', (19370, 19411), False, 'from evennia.utils import utils\n'), ((19514, 19552), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (19541, 19552), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((19742, 19794), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {}), '(timedelay, dummy_func, self.char1.dbref)\n', (19753, 19794), False, 'from evennia.utils import utils\n'), ((19838, 19876), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (19865, 19876), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((25961, 26030), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': '(True)'}), '(timedelay, dummy_func, self.char1.dbref, persistent=True)\n', (25972, 26030), False, 'from evennia.utils import utils\n'), ((26039, 26065), 'evennia.scripts.taskhandler.TASK_HANDLER.clear', '_TASK_HANDLER.clear', (['(False)'], {}), '(False)\n', (26058, 26065), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((26138, 26176), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (26165, 26176), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((26314, 26334), 'evennia.scripts.taskhandler.TASK_HANDLER.load', '_TASK_HANDLER.load', ([], {}), '()\n', (26332, 26334), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((26383, 26412), 'evennia.scripts.taskhandler.TASK_HANDLER.create_delays', '_TASK_HANDLER.create_delays', ([], {}), '()\n', (26410, 26412), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((26476, 26514), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (26503, 26514), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((560, 587), 'evennia.utils.utils.is_iter', 'utils.is_iter', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (573, 587), False, 'from evennia.utils import utils\n'), ((621, 661), 'evennia.utils.utils.is_iter', 'utils.is_iter', (['"""This is not an iterable"""'], {}), "('This is not an iterable')\n", (634, 661), False, 'from evennia.utils import utils\n'), ((779, 819), 'evennia.utils.utils.crop', 'utils.crop', (['""""""'], {'width': '(10)', 'suffix': '"""[...]"""'}), "('', width=10, suffix='[...]')\n", (789, 819), False, 'from evennia.utils import utils\n'), ((911, 961), 'evennia.utils.utils.crop', 'utils.crop', (['"""0123456789"""'], {'width': '(10)', 'suffix': '"""[...]"""'}), "('0123456789', width=10, suffix='[...]')\n", (921, 961), False, 'from evennia.utils import utils\n'), ((1080, 1129), 'evennia.utils.utils.crop', 'utils.crop', (['"""0123456789"""'], {'width': '(9)', 'suffix': '"""[...]"""'}), "('0123456789', width=9, suffix='[...]')\n", (1090, 1129), False, 'from evennia.utils import utils\n'), ((1220, 1263), 'evennia.utils.utils.crop', 'utils.crop', (['"""0123"""'], {'width': '(9)', 'suffix': '"""[...]"""'}), "('0123', width=9, suffix='[...]')\n", (1230, 1263), False, 'from evennia.utils import utils\n'), ((1351, 1394), 'evennia.utils.utils.crop', 'utils.crop', (['"""0123"""'], {'width': '(3)', 'suffix': '"""[...]"""'}), "('0123', width=3, suffix='[...]')\n", (1361, 1394), False, 'from evennia.utils import utils\n'), ((1430, 1476), 'evennia.utils.utils.crop', 'utils.crop', (['"""0123456"""'], {'width': '(5)', 'suffix': '"""[...]"""'}), "('0123456', width=5, suffix='[...]')\n", (1440, 1476), False, 'from evennia.utils import utils\n'), ((1608, 1624), 'evennia.utils.utils.dedent', 'utils.dedent', (['""""""'], {}), "('')\n", (1620, 1624), False, 'from evennia.utils import utils\n'), ((1697, 1723), 'evennia.utils.utils.dedent', 'utils.dedent', (['"""TestDedent"""'], {}), "('TestDedent')\n", (1709, 1723), False, 'from evennia.utils import utils\n'), ((1806, 1835), 'evennia.utils.utils.dedent', 'utils.dedent', (['""" TestDedent"""'], {}), "(' TestDedent')\n", (1818, 1835), False, 'from evennia.utils import utils\n'), ((2003, 2029), 'evennia.utils.utils.dedent', 'utils.dedent', (['input_string'], {}), '(input_string)\n', (2015, 2029), False, 'from evennia.utils import utils\n'), ((2440, 2482), 'evennia.utils.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {'endsep': '""""""'}), "([1, 2, 3], endsep='')\n", (2460, 2482), False, 'from evennia.utils import utils\n'), ((2526, 2583), 'evennia.utils.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {'endsep': '""""""', 'addquote': '(True)'}), "([1, 2, 3], endsep='', addquote=True)\n", (2546, 2583), False, 'from evennia.utils import utils\n'), ((2625, 2656), 'evennia.utils.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (2645, 2656), False, 'from evennia.utils import utils\n'), ((2717, 2777), 'evennia.utils.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {'endsep': '"""and"""', 'addquote': '(True)'}), "([1, 2, 3], endsep='and', addquote=True)\n", (2737, 2777), False, 'from evennia.utils import utils\n'), ((2824, 2852), 'evennia.utils.utils.list_to_string', 'utils.list_to_string', (['[1, 2]'], {}), '([1, 2])\n', (2844, 2852), False, 'from evennia.utils import utils\n'), ((3062, 3088), 'evennia.utils.utils.m_len', 'utils.m_len', (['"""Test_string"""'], {}), "('Test_string')\n", (3073, 3088), False, 'from evennia.utils import utils\n'), ((3151, 3181), 'evennia.utils.utils.m_len', 'utils.m_len', (['"""|lclook|ltat|le"""'], {}), "('|lclook|ltat|le')\n", (3162, 3181), False, 'from evennia.utils import utils\n'), ((3457, 3482), 'evennia.utils.utils.m_len', 'utils.m_len', (['[None, None]'], {}), '([None, None])\n', (3468, 3482), False, 'from evennia.utils import utils\n'), ((3538, 3584), 'evennia.utils.utils.m_len', 'utils.m_len', (["{'hello': True, 'Goodbye': False}"], {}), "({'hello': True, 'Goodbye': False})\n", (3549, 3584), False, 'from evennia.utils import utils\n'), ((3821, 3853), 'evennia.utils.utils.display_len', 'utils.display_len', (['"""Test_string"""'], {}), "('Test_string')\n", (3838, 3853), False, 'from evennia.utils import utils\n'), ((3916, 3952), 'evennia.utils.utils.display_len', 'utils.display_len', (['"""|lclook|ltat|le"""'], {}), "('|lclook|ltat|le')\n", (3933, 3952), False, 'from evennia.utils import utils\n'), ((4240, 4271), 'evennia.utils.utils.display_len', 'utils.display_len', (['[None, None]'], {}), '([None, None])\n', (4257, 4271), False, 'from evennia.utils import utils\n'), ((4327, 4379), 'evennia.utils.utils.display_len', 'utils.display_len', (["{'hello': True, 'Goodbye': False}"], {}), "({'hello': True, 'Goodbye': False})\n", (4344, 4379), False, 'from evennia.utils import utils\n'), ((4441, 4465), 'evennia.utils.utils.display_len', 'utils.display_len', (['"""서서서"""'], {}), "('서서서')\n", (4458, 4465), False, 'from evennia.utils import utils\n'), ((5461, 5484), 'evennia.utils.utils.time_format', 'utils.time_format', (['(0)', '(0)'], {}), '(0, 0)\n', (5478, 5484), False, 'from evennia.utils import utils\n'), ((5520, 5544), 'evennia.utils.utils.time_format', 'utils.time_format', (['(28)', '(0)'], {}), '(28, 0)\n', (5537, 5544), False, 'from evennia.utils import utils\n'), ((5580, 5604), 'evennia.utils.utils.time_format', 'utils.time_format', (['(92)', '(0)'], {}), '(92, 0)\n', (5597, 5604), False, 'from evennia.utils import utils\n'), ((5640, 5665), 'evennia.utils.utils.time_format', 'utils.time_format', (['(300)', '(0)'], {}), '(300, 0)\n', (5657, 5665), False, 'from evennia.utils import utils\n'), ((5701, 5726), 'evennia.utils.utils.time_format', 'utils.time_format', (['(660)', '(0)'], {}), '(660, 0)\n', (5718, 5726), False, 'from evennia.utils import utils\n'), ((5762, 5788), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3600)', '(0)'], {}), '(3600, 0)\n', (5779, 5788), False, 'from evennia.utils import utils\n'), ((5824, 5850), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3725)', '(0)'], {}), '(3725, 0)\n', (5841, 5850), False, 'from evennia.utils import utils\n'), ((5886, 5913), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86350)', '(0)'], {}), '(86350, 0)\n', (5903, 5913), False, 'from evennia.utils import utils\n'), ((5949, 5976), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86800)', '(0)'], {}), '(86800, 0)\n', (5966, 5976), False, 'from evennia.utils import utils\n'), ((6015, 6043), 'evennia.utils.utils.time_format', 'utils.time_format', (['(130800)', '(0)'], {}), '(130800, 0)\n', (6032, 6043), False, 'from evennia.utils import utils\n'), ((6082, 6110), 'evennia.utils.utils.time_format', 'utils.time_format', (['(530800)', '(0)'], {}), '(530800, 0)\n', (6099, 6110), False, 'from evennia.utils import utils\n'), ((6225, 6248), 'evennia.utils.utils.time_format', 'utils.time_format', (['(0)', '(1)'], {}), '(0, 1)\n', (6242, 6248), False, 'from evennia.utils import utils\n'), ((6281, 6305), 'evennia.utils.utils.time_format', 'utils.time_format', (['(28)', '(1)'], {}), '(28, 1)\n', (6298, 6305), False, 'from evennia.utils import utils\n'), ((6339, 6363), 'evennia.utils.utils.time_format', 'utils.time_format', (['(92)', '(1)'], {}), '(92, 1)\n', (6356, 6363), False, 'from evennia.utils import utils\n'), ((6396, 6421), 'evennia.utils.utils.time_format', 'utils.time_format', (['(300)', '(1)'], {}), '(300, 1)\n', (6413, 6421), False, 'from evennia.utils import utils\n'), ((6454, 6479), 'evennia.utils.utils.time_format', 'utils.time_format', (['(660)', '(1)'], {}), '(660, 1)\n', (6471, 6479), False, 'from evennia.utils import utils\n'), ((6513, 6539), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3600)', '(1)'], {}), '(3600, 1)\n', (6530, 6539), False, 'from evennia.utils import utils\n'), ((6572, 6598), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3725)', '(1)'], {}), '(3725, 1)\n', (6589, 6598), False, 'from evennia.utils import utils\n'), ((6631, 6658), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86350)', '(1)'], {}), '(86350, 1)\n', (6648, 6658), False, 'from evennia.utils import utils\n'), ((6692, 6719), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86800)', '(1)'], {}), '(86800, 1)\n', (6709, 6719), False, 'from evennia.utils import utils\n'), ((6752, 6780), 'evennia.utils.utils.time_format', 'utils.time_format', (['(130800)', '(1)'], {}), '(130800, 1)\n', (6769, 6780), False, 'from evennia.utils import utils\n'), ((6813, 6841), 'evennia.utils.utils.time_format', 'utils.time_format', (['(530800)', '(1)'], {}), '(530800, 1)\n', (6830, 6841), False, 'from evennia.utils import utils\n'), ((6950, 6973), 'evennia.utils.utils.time_format', 'utils.time_format', (['(0)', '(2)'], {}), '(0, 2)\n', (6967, 6973), False, 'from evennia.utils import utils\n'), ((7013, 7037), 'evennia.utils.utils.time_format', 'utils.time_format', (['(28)', '(2)'], {}), '(28, 2)\n', (7030, 7037), False, 'from evennia.utils import utils\n'), ((7077, 7101), 'evennia.utils.utils.time_format', 'utils.time_format', (['(92)', '(2)'], {}), '(92, 2)\n', (7094, 7101), False, 'from evennia.utils import utils\n'), ((7140, 7165), 'evennia.utils.utils.time_format', 'utils.time_format', (['(300)', '(2)'], {}), '(300, 2)\n', (7157, 7165), False, 'from evennia.utils import utils\n'), ((7205, 7230), 'evennia.utils.utils.time_format', 'utils.time_format', (['(660)', '(2)'], {}), '(660, 2)\n', (7222, 7230), False, 'from evennia.utils import utils\n'), ((7271, 7297), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3600)', '(2)'], {}), '(3600, 2)\n', (7288, 7297), False, 'from evennia.utils import utils\n'), ((7345, 7371), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3725)', '(2)'], {}), '(3725, 2)\n', (7362, 7371), False, 'from evennia.utils import utils\n'), ((7419, 7446), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86350)', '(2)'], {}), '(86350, 2)\n', (7436, 7446), False, 'from evennia.utils import utils\n'), ((7497, 7524), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86800)', '(2)'], {}), '(86800, 2)\n', (7514, 7524), False, 'from evennia.utils import utils\n'), ((7580, 7608), 'evennia.utils.utils.time_format', 'utils.time_format', (['(130800)', '(2)'], {}), '(130800, 2)\n', (7597, 7608), False, 'from evennia.utils import utils\n'), ((7666, 7694), 'evennia.utils.utils.time_format', 'utils.time_format', (['(530800)', '(2)'], {}), '(530800, 2)\n', (7683, 7694), False, 'from evennia.utils import utils\n'), ((7828, 7851), 'evennia.utils.utils.time_format', 'utils.time_format', (['(0)', '(3)'], {}), '(0, 3)\n', (7845, 7851), False, 'from evennia.utils import utils\n'), ((7882, 7906), 'evennia.utils.utils.time_format', 'utils.time_format', (['(28)', '(3)'], {}), '(28, 3)\n', (7899, 7906), False, 'from evennia.utils import utils\n'), ((7947, 7971), 'evennia.utils.utils.time_format', 'utils.time_format', (['(92)', '(3)'], {}), '(92, 3)\n', (7964, 7971), False, 'from evennia.utils import utils\n'), ((8021, 8046), 'evennia.utils.utils.time_format', 'utils.time_format', (['(300)', '(3)'], {}), '(300, 3)\n', (8038, 8046), False, 'from evennia.utils import utils\n'), ((8096, 8121), 'evennia.utils.utils.time_format', 'utils.time_format', (['(660)', '(3)'], {}), '(660, 3)\n', (8113, 8121), False, 'from evennia.utils import utils\n'), ((8172, 8198), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3600)', '(3)'], {}), '(3600, 3)\n', (8189, 8198), False, 'from evennia.utils import utils\n'), ((8246, 8272), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3725)', '(3)'], {}), '(3725, 3)\n', (8263, 8272), False, 'from evennia.utils import utils\n'), ((8330, 8357), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86350)', '(3)'], {}), '(86350, 3)\n', (8347, 8357), False, 'from evennia.utils import utils\n'), ((8419, 8446), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86800)', '(3)'], {}), '(86800, 3)\n', (8436, 8446), False, 'from evennia.utils import utils\n'), ((8513, 8541), 'evennia.utils.utils.time_format', 'utils.time_format', (['(130800)', '(3)'], {}), '(130800, 3)\n', (8530, 8541), False, 'from evennia.utils import utils\n'), ((8609, 8637), 'evennia.utils.utils.time_format', 'utils.time_format', (['(530800)', '(3)'], {}), '(530800, 3)\n', (8626, 8637), False, 'from evennia.utils import utils\n'), ((8782, 8805), 'evennia.utils.utils.time_format', 'utils.time_format', (['(0)', '(4)'], {}), '(0, 4)\n', (8799, 8805), False, 'from evennia.utils import utils\n'), ((8845, 8869), 'evennia.utils.utils.time_format', 'utils.time_format', (['(28)', '(4)'], {}), '(28, 4)\n', (8862, 8869), False, 'from evennia.utils import utils\n'), ((8910, 8934), 'evennia.utils.utils.time_format', 'utils.time_format', (['(92)', '(4)'], {}), '(92, 4)\n', (8927, 8934), False, 'from evennia.utils import utils\n'), ((8973, 8998), 'evennia.utils.utils.time_format', 'utils.time_format', (['(300)', '(4)'], {}), '(300, 4)\n', (8990, 8998), False, 'from evennia.utils import utils\n'), ((9038, 9063), 'evennia.utils.utils.time_format', 'utils.time_format', (['(660)', '(4)'], {}), '(660, 4)\n', (9055, 9063), False, 'from evennia.utils import utils\n'), ((9104, 9130), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3600)', '(4)'], {}), '(3600, 4)\n', (9121, 9130), False, 'from evennia.utils import utils\n'), ((9168, 9194), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3725)', '(4)'], {}), '(3725, 4)\n', (9185, 9194), False, 'from evennia.utils import utils\n'), ((9232, 9259), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86350)', '(4)'], {}), '(86350, 4)\n', (9249, 9259), False, 'from evennia.utils import utils\n'), ((9298, 9325), 'evennia.utils.utils.time_format', 'utils.time_format', (['(86800)', '(4)'], {}), '(86800, 4)\n', (9315, 9325), False, 'from evennia.utils import utils\n'), ((9361, 9389), 'evennia.utils.utils.time_format', 'utils.time_format', (['(130800)', '(4)'], {}), '(130800, 4)\n', (9378, 9389), False, 'from evennia.utils import utils\n'), ((9425, 9453), 'evennia.utils.utils.time_format', 'utils.time_format', (['(530800)', '(4)'], {}), '(530800, 4)\n', (9442, 9453), False, 'from evennia.utils import utils\n'), ((9490, 9519), 'evennia.utils.utils.time_format', 'utils.time_format', (['(3030800)', '(4)'], {}), '(3030800, 4)\n', (9507, 9519), False, 'from evennia.utils import utils\n'), ((9557, 9586), 'evennia.utils.utils.time_format', 'utils.time_format', (['(7030800)', '(4)'], {}), '(7030800, 4)\n', (9574, 9586), False, 'from evennia.utils import utils\n'), ((9625, 9655), 'evennia.utils.utils.time_format', 'utils.time_format', (['(40030800)', '(4)'], {}), '(40030800, 4)\n', (9642, 9655), False, 'from evennia.utils import utils\n'), ((9692, 9722), 'evennia.utils.utils.time_format', 'utils.time_format', (['(90030800)', '(4)'], {}), '(90030800, 4)\n', (9709, 9722), False, 'from evennia.utils import utils\n'), ((10219, 10247), 'evennia.utils.utils.datetime_format', 'utils.datetime_format', (['dtobj'], {}), '(dtobj)\n', (10240, 10247), False, 'from evennia.utils import utils\n'), ((10336, 10364), 'evennia.utils.utils.datetime_format', 'utils.datetime_format', (['dtobj'], {}), '(dtobj)\n', (10357, 10364), False, 'from evennia.utils import utils\n'), ((10447, 10475), 'evennia.utils.utils.datetime_format', 'utils.datetime_format', (['dtobj'], {}), '(dtobj)\n', (10468, 10475), False, 'from evennia.utils import utils\n'), ((10557, 10585), 'evennia.utils.utils.datetime_format', 'utils.datetime_format', (['dtobj'], {}), '(dtobj)\n', (10578, 10585), False, 'from evennia.utils import utils\n'), ((14713, 14736), 'evennia.utils.utils.percent', 'utils.percent', (['(3)', '(10)', '(1)'], {}), '(3, 10, 1)\n', (14726, 14736), False, 'from evennia.utils import utils\n'), ((14771, 14796), 'evennia.utils.utils.percent', 'utils.percent', (['(3)', 'None', '(1)'], {}), '(3, None, 1)\n', (14784, 14796), False, 'from evennia.utils import utils\n'), ((14833, 14855), 'evennia.utils.utils.percent', 'utils.percent', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (14846, 14855), False, 'from evennia.utils import utils\n'), ((14892, 14914), 'evennia.utils.utils.percent', 'utils.percent', (['(3)', '(1)', '(1)'], {}), '(3, 1, 1)\n', (14905, 14914), False, 'from evennia.utils import utils\n'), ((14949, 14971), 'evennia.utils.utils.percent', 'utils.percent', (['(3)', '(0)', '(1)'], {}), '(3, 0, 1)\n', (14962, 14971), False, 'from evennia.utils import utils\n'), ((15008, 15031), 'evennia.utils.utils.percent', 'utils.percent', (['(-3)', '(0)', '(1)'], {}), '(-3, 0, 1)\n', (15021, 15031), False, 'from evennia.utils import utils\n'), ((16153, 16218), 'evennia.utils.utils.safe_convert_to_types', 'utils.safe_convert_to_types', (['(int,)', "*('foo',)"], {'raise_errors': '(True)'}), "((int,), *('foo',), raise_errors=True)\n", (16180, 16218), False, 'from evennia.utils import utils\n'), ((16304, 16373), 'evennia.utils.utils.safe_convert_to_types', 'utils.safe_convert_to_types', (["('py', {})", "*('foo',)"], {'raise_errors': '(True)'}), "(('py', {}), *('foo',), raise_errors=True)\n", (16331, 16373), False, 'from evennia.utils import utils\n'), ((17434, 17508), 'evennia.utils.utils.delay', 'utils.delay', (['self.timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(self.timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (17445, 17508), False, 'from evennia.utils import utils\n'), ((17896, 17970), 'evennia.utils.utils.delay', 'utils.delay', (['self.timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(self.timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (17907, 17970), False, 'from evennia.utils import utils\n'), ((18434, 18503), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (18445, 18503), False, 'from evennia.utils import utils\n'), ((18556, 18594), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (18583, 18594), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((18946, 19015), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (18957, 19015), False, 'from evennia.utils import utils\n'), ((19068, 19106), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (19095, 19106), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((20043, 20112), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (20054, 20112), False, 'from evennia.utils import utils\n'), ((20316, 20354), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (20343, 20354), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((20549, 20618), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (20560, 20618), False, 'from evennia.utils import utils\n'), ((20823, 20861), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (20850, 20861), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((21098, 21167), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (21109, 21167), False, 'from evennia.utils import utils\n'), ((21482, 21520), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (21509, 21520), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((21755, 21824), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (21766, 21824), False, 'from evennia.utils import utils\n'), ((22084, 22122), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (22111, 22122), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((22520, 22589), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (22531, 22589), False, 'from evennia.utils import utils\n'), ((22666, 22704), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (22693, 22704), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((23125, 23177), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {}), '(timedelay, dummy_func, self.char1.dbref)\n', (23136, 23177), False, 'from evennia.utils import utils\n'), ((23407, 23428), 'evennia.scripts.taskhandler.TASK_HANDLER.clear', '_TASK_HANDLER.clear', ([], {}), '()\n', (23426, 23428), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((23603, 23672), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (23614, 23672), False, 'from evennia.utils import utils\n'), ((23749, 23787), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (23776, 23787), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((24152, 24185), 'evennia.scripts.taskhandler.TASK_HANDLER.clean_stale_tasks', '_TASK_HANDLER.clean_stale_tasks', ([], {}), '()\n', (24183, 24185), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((24463, 24484), 'evennia.scripts.taskhandler.TASK_HANDLER.clear', '_TASK_HANDLER.clear', ([], {}), '()\n', (24482, 24484), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((24695, 24764), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {'persistent': 'pers'}), '(timedelay, dummy_func, self.char1.dbref, persistent=pers)\n', (24706, 24764), False, 'from evennia.utils import utils\n'), ((24841, 24879), 'evennia.scripts.taskhandler.TASK_HANDLER.clock.advance', '_TASK_HANDLER.clock.advance', (['timedelay'], {}), '(timedelay)\n', (24868, 24879), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((25249, 25301), 'evennia.utils.utils.delay', 'utils.delay', (['timedelay', 'dummy_func', 'self.char1.dbref'], {}), '(timedelay, dummy_func, self.char1.dbref)\n', (25260, 25301), False, 'from evennia.utils import utils\n'), ((25576, 25609), 'evennia.scripts.taskhandler.TASK_HANDLER.clean_stale_tasks', '_TASK_HANDLER.clean_stale_tasks', ([], {}), '()\n', (25607, 25609), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((25825, 25846), 'evennia.scripts.taskhandler.TASK_HANDLER.clear', '_TASK_HANDLER.clear', ([], {}), '()\n', (25844, 25846), True, 'from evennia.scripts.taskhandler import TASK_HANDLER as _TASK_HANDLER\n'), ((3260, 3293), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['"""|lcl|gook|ltat|le|n"""'], {}), "('|lcl|gook|ltat|le|n')\n", (3270, 3293), False, 'from evennia.utils.ansi import ANSIString\n'), ((3377, 3400), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['"""|gHello|n"""'], {}), "('|gHello|n')\n", (3387, 3400), False, 'from evennia.utils.ansi import ANSIString\n'), ((4037, 4070), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['"""|lcl|gook|ltat|le|n"""'], {}), "('|lcl|gook|ltat|le|n')\n", (4047, 4070), False, 'from evennia.utils.ansi import ANSIString\n'), ((4160, 4183), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['"""|gHello|n"""'], {}), "('|gHello|n')\n", (4170, 4183), False, 'from evennia.utils.ansi import ANSIString\n'), ((10048, 10077), 'datetime.datetime', 'datetime', (['(2019)', '(8)', '(28)', '(21)', '(56)'], {}), '(2019, 8, 28, 21, 56)\n', (10056, 10077), False, 'from datetime import datetime\n'), ((22977, 22991), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (22989, 22991), False, 'from datetime import datetime\n'), ((22994, 23056), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(_TASK_HANDLER.stale_timeout + timedelay + 1)'}), '(seconds=_TASK_HANDLER.stale_timeout + timedelay + 1)\n', (23003, 23056), False, 'from datetime import datetime, timedelta\n'), ((24060, 24074), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (24072, 24074), False, 'from datetime import datetime\n'), ((24077, 24139), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(_TASK_HANDLER.stale_timeout + timedelay + 1)'}), '(seconds=_TASK_HANDLER.stale_timeout + timedelay + 1)\n', (24086, 24139), False, 'from datetime import datetime, timedelta\n'), ((25152, 25166), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (25164, 25166), False, 'from datetime import datetime\n'), ((25169, 25231), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(_TASK_HANDLER.stale_timeout + timedelay + 1)'}), '(seconds=_TASK_HANDLER.stale_timeout + timedelay + 1)\n', (25178, 25231), False, 'from datetime import datetime, timedelta\n'), ((12353, 12390), 'random.randint', 'random.randint', (['(-variation)', 'variation'], {}), '(-variation, variation)\n', (12367, 12390), False, 'import random\n')]
""" General Character commands usually available to all characters """ import re from django.conf import settings from evennia.utils import utils, evtable from evennia.typeclasses.attributes import NickTemplateInvalid # adding the following for adaptions to commands based on the # addition of the clothing module from contrib from typeclasses.latin_noun import LatinNoun from commands.command import MuxCommand COMMAND_DEFAULT_CLASS = utils.class_from_module(settings.COMMAND_DEFAULT_CLASS) # Added for dealing with multiple objects # limit symbol import for API __all__ = ( "CmdHome", "CmdLook", "CmdNick", "CmdInventory", "CmdSetDesc", "CmdGet", "CmdDrop", "CmdGive", "CmdSay", "CmdWhisper", "CmdPose", "CmdAccess", ) def which_one(args,caller,stuff): if '-' in args: thing = args.split('-') args = thing[-1].strip().lower() # get the contents of the room # everything = stuff # identify what items are the same AND match the intended case same = [] for item in stuff: characteristics = item.aliases.all() [x.lower() for x in characteristics] if args in characteristics: same.append(item) # Return feedback if a number higher than the number of matches # was provided if len(same) == 0: caller.msg("Non invenisti!") return None, args if len(same) < int(thing[0]): caller.msg(f"Non sunt {thing[0]}, sed {len(same)}!") return None, args # match the number with the item target = same[int(thing[0])-1] return target, args else: same = [] args = args.strip().lower() for item in stuff: characteristics = [item.key] + item.aliases.all() # characteristics = item.aliases.all() # characteristics.append(item.key) [x.lower() for x in characteristics] if args in characteristics: same.append(item) if len(same) == 0: caller.msg("Non invenisti!") return None, args elif len(same) != 1: caller.msg(f"Sunt {len(same)}. Ecce:") for index,item in enumerate(same): caller.msg(f"{index + 1}-{item}") return None, args else: target = same[0] return target, args class CmdHome(COMMAND_DEFAULT_CLASS): """ move to your character's home location Usage: home Teleports you to your home location. """ key = "home" locks = "cmd:perm(home) or perm(Builder)" arg_regex = r"$" def func(self): """Implement the command""" caller = self.caller home = caller.home if not home: caller.msg("You have no home!") elif home == caller.location: caller.msg("You are already home!") else: caller.msg("There's no place like home ...") caller.move_to(home) class CmdLook(COMMAND_DEFAULT_CLASS): """ look at location or object Usage: aspice aspice <obj> aspice *<account> Observes your location or objects in your vicinity. """ key = "aspice" locks = "cmd:all()" arg_regex = r"\s|$" help_category = 'Latin' def func(self): """ Handle the looking. """ caller = self.caller if not self.args: target = caller.location if not target: caller.msg("Nihil est quod aspicere potes!") return else: stuff = caller.location.contents + caller.contents target, self.args = which_one(self.args,caller,stuff) if not target: return lower_case = [x.lower() for x in target.db.acc_sg] if self.args.strip().lower() not in lower_case and self.args: self.msg(f"(Did you mean '{target.db.acc_sg}'?)") return self.msg((caller.at_look(target), {"type": "look"}), options=None) class CmdInventory(COMMAND_DEFAULT_CLASS): """ view inventory Usage: habeo Shows your inventory. """ key = "habeo" locks = "cmd:all()" arg_regex = r"$" help_category = 'Latin' def func(self): """check inventory""" items = self.caller.contents if not items: string = "Nihil habes." else: table = self.styled_table(border="header") for item in items: table.add_row("|C%s|n" % item.name, item.db.desc or "") string = "|wEcce:\n%s" % table self.caller.msg(string) class CmdGet(COMMAND_DEFAULT_CLASS): """ pick up something Usage: cape <rem> Picks up an object from your location and puts it in your inventory. """ key = "cape" locks = "cmd:all()" arg_regex = r"\s|$" help_category = 'Latin' def func(self): """implements the command.""" # try to duplicate 'try_num_prefixes' from 'evennia/commands/cmdparser.py' caller = self.caller current_carry = caller.db.lift_carry['current'] carry_max = caller.db.lift_carry['max'] if not self.args: caller.msg("Quid capere velis?") return stuff = caller.location.contents obj, self.args = which_one(self.args,caller,stuff) if not obj: return lower_case = [x.lower() for x in obj.db.acc_sg] if self.args.strip().lower() not in lower_case: self.msg(f"(Did you mean '{obj.db.acc_sg}'?)") return if caller == obj: caller.msg("Tu te capere non potes.") return if not obj.access(caller, "get"): if obj.db.get_err_msg: caller.msg(obj.db.get_err_msg) else: caller.msg(f"Tu {obj.db.acc_sg[0]} capere non potes.") return # Check to see if hands are free possessions = caller.contents hands = ['left','right'] full_hands = 0 held_items = [] for possession in possessions: if possession.db.held: if possession.db.held in hands: full_hands += 1 held_items.append(possession) elif held == 'both': full_hands += 2 held_items.append(possession) if full_hands >= 2: caller.msg("Manus tuae sunt plenae!") return # calling at_before_get hook method if not obj.at_before_get(caller): return # See if character can carry any more if current_carry + obj.db.physical['mass'] > carry_max: caller.msg('Plus ponderis ferre non potes!') return obj.move_to(caller, quiet=True) caller.db.lift_carry['current'] += obj.db.physical['mass'] caller.msg("%s cepisti." % obj.db.acc_sg[0]) caller.location.msg_contents("%s %s cepit." % (caller.name, obj.db.acc_sg[0]), exclude=caller) # calling at_get hook method obj.at_get(caller) # Put the object in a hand; dominant if not already full if held_items: hands.remove(held_items[0].db.held) obj.db.held = hands[0] else: obj.db.held = caller.db.handedness class CmdDrop(COMMAND_DEFAULT_CLASS): """ Get rid of something Usage: relinque <rem> Lets you drop an object from your inventory into the location you are currently in. """ key = "relinque" locks = "cmd:all()" arg_regex = r"\s|$" help_category = 'Latin' def func(self): """Implement command""" caller = self.caller if not self.args: caller.msg("Quid relinquere velis?") # What would you like to give up? return # 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, # ) stuff = caller.contents obj, self.args = which_one(self.args,caller,stuff) if not obj: return lower_case = [x.lower() for x in obj.db.acc_sg] if self.args.strip().lower() not in lower_case: self.msg(f"(Did you mean '{obj.db.acc_sg}'?)") return # Call the object script's at_before_drop() method. if not obj.at_before_drop(caller): return # Adding the following to deal with clothing: if obj.db.held: obj.db.held = False if obj.db.worn: obj.remove(caller,quiet=True) obj.move_to(caller.location, quiet=True) caller.db.lift_carry['current'] -= obj.db.physical['mass'] caller.msg("%s reliquisti." % (obj.db.acc_sg[0],)) # You have given X up caller.location.msg_contents("%s %s reliquit." % (caller.name, obj.name), exclude=caller) # Call the object script's at_drop() method. obj.at_drop(caller) class CmdGive(COMMAND_DEFAULT_CLASS): """ give away something to someone Usage: da <rem> <alicui> Gives an item from your inventory to another character, placing it in their inventory. """ key = "da" locks = "cmd:all()" arg_regex = r"\s|$" def func(self): """Implement give""" caller = self.caller if not self.args: caller.msg("Usage: da <rem> <alicui>") return # get the various arguments objects = self.args.split(' ') for thing in objects: if not thing: objects.remove(thing) # require 2 arguments if len(objects) != 2: caller.msg("Usage: da <rem> <alicui>") return # create the pool of things to search external = caller.location.contents for noun in external: if not noun.db.nom_sg: external.remove(noun) possessions = caller.contents stuff = external + possessions # see if first argument is in either pool thing1, arg1 = which_one(objects[0],caller,stuff) arg1 = arg1.lower() if not thing1: return # see if second argument is in either pool thing2, arg2 = which_one(objects[1],caller,stuff) arg2 = arg2.lower() if not thing2: return # make a list of the object forms of the inventory: accusatives = [] for possession in possessions: if possession: accusatives.append(possession.db.acc_sg[0].lower()) # make a list of the dative forms of the things outside of the inventory datives = [] for extern in external: if extern and extern.db.dat_sg: datives.append(extern.db.dat_sg[0].lower()) # check grammar if thing1 in possessions and thing2 in external: if arg1 not in accusatives: caller.msg(f"(Did you mean '{thing1.db.acc_sg}'?)") return elif arg2 not in datives: caller.msg(f"(Did you mean '{thing2.db.dat_sg}'?)") return else: direct_object = thing1 indirect_object = thing2 elif thing1 in external and thing2 in possessions: if arg1 not in datives: caller.msg(f"(Did you mean '{thing1.db.dat_sg}'?)") return if arg2 not in accusatives: caller.msg(f"(Did you mean '{thing2.db.acc_sg}'?)") return else: direct_object = thing2 indirect_object = thing1 else: caller.msg("Usage: da <rem> <alicui>") return to_give = direct_object target = indirect_object if not (to_give and target): return if target == caller: caller.msg("Tu %s tibi dedisti." % to_give.db.acc_sg[0]) return if not to_give.location == caller: caller.msg("%s in manibus non habes." % to_give.db.acc_sg[0]) return # calling at_before_give hook method if not to_give.at_before_give(caller, target): return # Check if target's hands are full possessions = target.contents hands = ['left','right'] full_hands = 0 held_items = [] for possession in possessions: if possession.db.held: if possession.db.held in hands: full_hands += 1 held_items.append(possession) elif held == 'both': full_hands += 2 held_items.append(possession) if full_hands >= 2: caller.msg(f"Manus {target.db.gen_sg[0]} sunt plenae!") return # Weight calculations target_capacity = target.db.lift_carry['max'] target_current = target.db.lift_carry['current'] obj_mass = to_give.db.physical['mass'] if obj_mass + target_current > target_capacity: caller.msg(f"{target.db.nom_sg[0]} plus ponderis ferre non potest!") target.msg(f"{caller.db.nom_sg[0]} tibi {obj.db.acc_sg[0]} dare voluit, sed tu plus ponderis ferre non potes!") return # give object # 12/7/19 added to deal with clothing, removes worn clothes if to_give.db.worn: to_give.remove(caller) caller.msg("%s %s dedisti." % (to_give.db.acc_sg[0], target.db.dat_sg[0])) to_give.move_to(target, quiet=True) target.msg("%s %s tibi dedit." % (caller.key, to_give.db.acc_sg[0])) caller.location.msg_contents(f"{caller.db.nom_sg[0]} {to_give.db.acc_sg[0]} {target.db.dat_sg[0]} dedit.",exclude=(caller,target)) target.db.lift_carry['current'] += obj_mass caller.db.lift_carry['current'] -= obj_mass # Call the object script's at_give() method. to_give.at_give(caller, target) if held_items: hands.remove(held_items[0].db.held) to_give.db.held = hands[0] else: to_give.db.held = target.db.handedness class CmdSetDesc(COMMAND_DEFAULT_CLASS): """ describe yourself Usage: setdesc <description> Add a description to yourself. This will be visible to people when they look at you. """ key = "setdesc" locks = "cmd:all()" arg_regex = r"\s|$" def func(self): """add the description""" if not self.args: self.caller.msg("You must add a description.") return self.caller.db.desc = self.args.strip() self.caller.msg("You set your description.") class CmdSay(COMMAND_DEFAULT_CLASS): """ speak as your character Usage: dic <message> Talk to those in your current location. """ key = "dic" aliases = ['"', "'"] locks = "cmd:all()" help_category = "Latin" def func(self): """Run the say command""" caller = self.caller if not self.args: caller.msg("Say what?") return speech = self.args # Calling the at_before_say hook on the character speech = caller.at_before_say(speech) # If speech is empty, stop here if not speech: return # Call the at_after_say hook on the character caller.at_say(speech, msg_self=True) class CmdWhisper(COMMAND_DEFAULT_CLASS): """ Speak privately as your character to another Usage: whisper <character> = <message> whisper <char1>, <char2> = <message> Talk privately to one or more characters in your current location, without others in the room being informed. """ key = "whisper" locks = "cmd:all()" def func(self): """Run the whisper command""" caller = self.caller if not self.lhs or not self.rhs: caller.msg("Usage: whisper <character> = <message>") return receivers = [recv.strip() for recv in self.lhs.split(",")] receivers = [caller.search(receiver) for receiver in set(receivers)] receivers = [recv for recv in receivers if recv] speech = self.rhs # If the speech is empty, abort the command if not speech or not receivers: return # Call a hook to change the speech before whispering speech = caller.at_before_say(speech, whisper=True, receivers=receivers) # no need for self-message if we are whispering to ourselves (for some reason) msg_self = None if caller in receivers else True caller.at_say(speech, msg_self=msg_self, receivers=receivers, whisper=True) class CmdPose(COMMAND_DEFAULT_CLASS): """ strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name. """ key = "pose" aliases = [":", "emote"] locks = "cmd:all()" def parse(self): """ Custom parse the cases where the emote starts with some special letter, such as 's, at which we don't want to separate the caller's name and the emote with a space. """ args = self.args if args and not args[0] in ["'", ",", ":"]: args = " %s" % args.strip() self.args = args def func(self): """Hook function""" if not self.args: msg = "What do you want to do?" self.caller.msg(msg) else: msg = "%s%s" % (self.caller.name, self.args) self.caller.location.msg_contents(text=(msg, {"type": "pose"}), from_obj=self.caller) class CmdAccess(COMMAND_DEFAULT_CLASS): """ show your current game access Usage: access This command shows you the permission hierarchy and which permission groups you are a member of. """ key = "access" aliases = ["groups", "hierarchy"] locks = "cmd:all()" arg_regex = r"$" def func(self): """Load the permission groups""" caller = self.caller hierarchy_full = settings.PERMISSION_HIERARCHY string = "\n|wPermission Hierarchy|n (climbing):\n %s" % ", ".join(hierarchy_full) if self.caller.account.is_superuser: cperms = "<Superuser>" pperms = "<Superuser>" else: cperms = ", ".join(caller.permissions.all()) pperms = ", ".join(caller.account.permissions.all()) string += "\n|wYour access|n:" string += "\nCharacter |c%s|n: %s" % (caller.key, cperms) if hasattr(caller, "account"): string += "\nAccount |c%s|n: %s" % (caller.account.key, pperms) caller.msg(string) class CmdPut(COMMAND_DEFAULT_CLASS): """ Put one thing in possession in another thing in possession or room. Usage: pone <rem> in <rem> Store things in containers """ key = "pone" locks = "cmd:all()" help_category = "Latin" def func(self): """Run the say command""" caller = self.caller if not self.args: caller.msg("Usage: pone <rem> in <rem>") return arguments = self.args.split(' ') for index,argument in enumerate(arguments): arguments[index] = argument.strip() if 'in' not in arguments: caller.msg("Usage: pone <rem> in <rem>") return if len(arguments) != 3: caller.msg("Usage: pone <rem> in <rem>") return if arguments[2] == 'in': caller.msg("Usage: pone <rem> in <rem>") return if arguments[1] == 'in': destination = arguments[2] to_store = arguments[0] else: destination = arguments[1] to_store = arguments[2] # caller.msg(f"(to_store: {to_store}; destination = {destination})") stuff = caller.location.contents + caller.contents intended_container, destination = which_one(destination,caller,stuff) # self.msg(f"Intended_container: {intended_container}") if not intended_container: return if not intended_container.db.can_hold: caller.msg(f"{intended_container.db.nom_sg[0]} nihil tenere potest") return lower_case = [x.lower() for x in intended_container.db.acc_sg] if destination.lower() not in lower_case: caller.msg(f"(Did you mean 'in {intended_container.db.acc_sg}'?)") return stuff = caller.contents intended_to_store, to_store = which_one(to_store,caller,stuff) # self.msg(f"intended_to_store: {intended_to_store}") if not intended_to_store: return lower_case = [x.lower() for x in intended_to_store.db.acc_sg] if to_store not in lower_case: caller.msg(f"(Did you mean '{intended_to_store.db.acc_sg}'?)") return if intended_to_store.db.worn: caller.msg(f"Prius necesse est {intended_to_store.db.acc_sg[0]} exuere!") return if intended_to_store.dbref == intended_container.dbref: caller.msg(f"{intended_to_store.db.nom_sg[0]} in se poni non potest!") return # Manage volume and dimensions of container obj_volume = intended_to_store.db.physical['volume'] container_max_volume = intended_container.db.container['max_vol'] container_current_vol = intended_container.db.container['rem_vol'] if obj_volume > container_current_vol: caller.msg(f"In {intended_container.db.abl_sg[0]} non est spatium!") return if intended_to_store.db.physical['rigid']: obj_dimensions = [ intended_to_store.db.physical['x'], intended_to_store.db.physical['y'], intended_to_store.db.physical['z'] ] container_dimensions = [ intended_container.db.container['x'], intended_container.db.container['y'], intended_container.db.container['z'] ] obj_dimensions.sort() container_dimensions.sort() if (obj_dimensions[2] / 2) > container_dimensions[2]: caller.msg(f"Forma {intended_to_store.db.gen_sg[0]} in {intended_to_store.db.acc_sg[0]} poni non potest.") return elif obj_dimensions[1] > container_dimensions[1] or obj_dimensions[0] > container_dimensions[0]: caller.msg(f"Forma {intended_to_store.db.gen_sg[0]} in {intended_to_store.db.acc_sg[0]} poni non potest.") return caller.msg("%s in %s posuisti." % (intended_to_store.db.acc_sg[0], intended_container.db.acc_sg[0])) intended_container.db.container['rem_vol'] -= obj_volume intended_to_store.move_to(intended_container, quiet=True) caller.location.msg_contents("%s %s in %s posuit." % (caller.db.nom_sg[0], intended_to_store.db.acc_sg[0], intended_container.db.acc_sg[0]),exclude=caller) intended_to_store.db.held = False class CmdGetOut(COMMAND_DEFAULT_CLASS): """ Move an object from a location in the caller's vicinity into the caller's inventory. Usage: excipe <rem> ex <re> Take something out of something else """ key = "excipe" locks = "cmd:all()" help_category = "Latin" def func(self): """Run the say command""" caller = self.caller if not self.args: caller.msg("Usage: excipe <rem> ex <re>") return arguments = self.args.split(' ') for index,argument in enumerate(arguments): arguments[index] = argument.strip() if 'ex' not in arguments: caller.msg("Usage: excipe <rem> ex <re>") return if len(arguments) != 3: caller.msg("Usage: excipe <rem> ex <re>") return if arguments[2] == 'ex': caller.msg("Usage: excipe <rem> ex <re>") return if arguments[1] == 'ex': source_arg = arguments[2] get_arg = arguments[0] else: source_arg = arguments[1] get_arg = arguments[2] # caller.msg(f"(to_store: {to_store}; destination = {destination})") stuff = caller.location.contents + caller.contents intended_source, source_arg = which_one(source_arg,caller,stuff) # self.msg(f"Intended_source: {intended_source}") if not intended_source: return if not intended_source.db.can_hold: caller.msg(f"{indended_container.db.nom_sg[0]} nihil tenere potest") return lower_case = [x.lower() for x in intended_source.db.abl_sg] if source_arg.lower() not in lower_case: caller.msg(f"(Did you mean 'ex {inteded_source.db.abl_sg}'?)") return stuff = intended_source.contents intended_get, get_arg = which_one(get_arg,caller,stuff) # self.msg(f"intended_get: {intended_get}") if not intended_get: return lower_case = [x.lower() for x in intended_get.db.acc_sg] if get_arg.lower() not in lower_case: caller.msg(f"(Did you mean '{intended_get.db.acc_sg}'?)") return # Check if target's hands are full possessions = caller.contents hands = ['left','right'] full_hands = 0 held_items = [] for possession in possessions: if possession.db.held: if possession.db.held in hands: full_hands += 1 held_items.append(possession) elif held == 'both': full_hands += 2 held_items.append(possession) if full_hands >= 2: caller.msg(f"Manus tuae sunt plenae!") return # Deal with volume of container intended_source.db.container['rem_vol'] += intended_get.db.physical['volume'] caller.msg("%s ex %s excepisti." % (intended_get.db.acc_sg[0], intended_source.db.abl_sg[0])) intended_get.move_to(caller, quiet=True) caller.location.msg_contents("%s %s ex %s excepit." % (caller.db.nom_sg[0], intended_get.db.acc_sg[0], intended_source.db.abl_sg[0]),exclude=caller) # Put in hand if held_items: hands.remove(held_items[0].db.held) intended_get.db.held = hands[0] else: intended_get.db.held = caller.db.handedness class CmdLookIn(COMMAND_DEFAULT_CLASS): """ look inside a container Usage: inspice in <rem> Observes your location or objects in your vicinity. """ key = "inspice" locks = "cmd:all()" help_category = 'Latin' def func(self): """ Handle the looking. """ caller = self.caller if not self.args: caller.msg("Usage: inspice in <rem>") return self.args = self.args.split(' ') for index,arg in enumerate(self.args): self.args[index] = arg.strip() if len(self.args) != 2 or self.args[0] != 'in': caller.msg("Usage: inspice in <rem>") return else: self.args = self.args[1] stuff = caller.location.contents + caller.contents target, self.args = which_one(self.args,caller,stuff) if not target: return if not target.db.can_hold: caller.msg(f"{target.db.nom_sg[0]} nihil tenere potest!") lower_case = [x.lower() for x in target.db.acc_sg] if self.args.strip().lower() not in lower_case and self.args: self.msg(f"(Did you mean '{target.db.acc_sg}'?)") return items = target.contents if not items: string = "Nihil habet." else: table = self.styled_table(border="header") for item in items: table.add_row("|C%s|n" % item.name, item.db.desc or "") string = "|wEcce:\n%s" % table self.caller.msg(string) class CmdHold(COMMAND_DEFAULT_CLASS): """ Hold something in a particular hand Usage: tene <rem> <dextra>/<sinistra> Hold something in a particular hand. """ key = "tene" locks = "cmd:all()" arg_regex = r"\s|$" help_category = 'Latin' def func(self): """implements the command.""" # try to duplicate 'try_num_prefixes' from 'evennia/commands/cmdparser.py' caller = self.caller if not self.args: caller.msg("Quid capere velis?") return self.args = self.args.split(" ") for index,arg in enumerate(self.args): self.args[index] = arg.strip() if len(self.args) != 2: caller.msg("Usage: tene <rem> <dextra>/<sinistra>") return # Check to see if hands are free possessions = caller.contents hands = ['left','right'] full_hands = 0 held_items = [] for possession in possessions: if possession.db.held: if possession.db.held in hands: full_hands += 1 held_items.append(possession) elif held == 'both': full_hands += 2 held_items.append(possession) if full_hands >= 2: caller.msg("Manus tuae sunt plenae!") return # See which hand(s) is/are free if 'sinistra' not in self.args and 'dextra' not in self.args: caller.msg("Usage: tene <rem> <dextra>/<sinistra>") return if 'sinistra' in self.args: in_hand = 'left' self.args.remove('sinistra') else: in_hand = 'right' self.args.remove('dextra') self.args = self.args[0] stuff = caller.location.contents + caller.contents obj, self.args = which_one(self.args,caller,stuff) if not obj: return lower_case = [x.lower() for x in obj.db.acc_sg] if self.args.strip().lower() not in lower_case: self.msg(f"(Did you mean '{obj.db.acc_sg}'?)") return if caller == obj: caller.msg("Tu te tenere non potes.") return if not obj.access(caller, "get"): if obj.db.get_err_msg: caller.msg(obj.db.get_err_msg) else: caller.msg(f"Tu {obj.db.acc_sg[0]} tenere non potes.") return # See if specificed hand is free if held_items: hands.remove(held_items[0].db.held) obj.db.held = hands[0] if in_hand not in hands: caller.msg("Illa manus iam est plena!") return if obj in caller.contents: if obj.db.worn or obj.db.held: obj.db.worn = False obj.db.held = in_hand else: # calling at_before_get hook method if not obj.at_before_get(caller): return obj.move_to(caller, quiet=True) caller.msg("%s tenes." % obj.db.acc_sg[0]) caller.location.msg_contents("%s %s tenet." % (caller.name, obj.db.acc_sg[0]), exclude=caller) # calling at_get hook method obj.at_get(caller) # Desplay statistics about the character to that character class CmdStats(COMMAND_DEFAULT_CLASS): """ view vital statistics about yourself Usage: ego Shows you information about yourself. """ key = "ego" locks = "cmd:all()" arg_regex = r"$" help_category = 'Latin' def func(self): """display statistics / data""" caller = self.caller # Define the variables fullname = caller.db.praenomen if caller.db.nomen: fullname = fullname + ' ' + caller.db.nomen hp_max = caller.db.hp['max'] hp_cur = caller.db.hp['current'] vir = caller.db.stats['str'] cel = caller.db.stats['dex'] val = caller.db.stats['con'] sci = caller.db.stats['int'] sap = caller.db.stats['wis'] gra = caller.db.stats['cha'] car_cur = caller.db.lift_carry['current'] / .3289 car_cur = round(car_cur, 1) car_max = caller.db.lift_carry['max'] / .3289 car_max = round(car_max, 1) if caller.db.handedness == 'right': g_h = ' dextra' o_h = 'sinistra' else: g_h = 'sinistra' o_h = ' dextra' dfn = cel - 10 if dfn % 2 != 0: dfn -= 1 dfn /= 2 dfn += 10 dfn = round(dfn) # turn everything into strings in order to deal with padding: str_fig = {} two_figures = [vir,cel,val,sci,sap,gra,dfn] three_figures = [round(hp_max),round(hp_cur)] five_figures = [car_cur,car_max] for fig in two_figures: sfig = str(fig) if len(sfig) < 2: sfig = ' ' + sfig str_fig[fig] = sfig for fig in three_figures: sfig = str(fig) if len(sfig) == 1: sfig = ' ' + sfig elif len(sfig) == 2: sfig = ' ' + sfig str_fig[fig] = sfig diff = '' for fig in five_figures: sfig = str(fig) if len(sfig) < 5: for i in range(0,5-len(sfig)): diff += ' ' sfig = diff + sfig str_fig[fig] = sfig caller.msg( f"\n|c{fullname}|n\n" + f"---------------------------------\n" + f"|| |wVires|n: |c{str_fig[vir]}|n || |wScientia|n: |c{str_fig[sci]}|n ||\n" + f"|| |wCeleritas|n: |c{str_fig[cel]}|n || |wSapientia|n: |c{str_fig[sap]}|n ||\n" + f"|| |wValetudo|n: |c{str_fig[val]}|n || |wGratia|n: |c{str_fig[gra]}|n ||\n" + f"---------------------------------\n" + f"|| |wVita|n: |c{str_fig[hp_cur]}|n / |c{str_fig[hp_max]}|n ||\n" + f"---------------------------------\n" + f"|| |wFers|n: |c{str_fig[car_cur]}|n libras ex |c{str_fig[car_max]}|n ||\n" + f"---------------------------------\n" + f"|| |wManus Optima|n: |c{g_h}|n ||\n" + f"---------------------------------\n" + f"|| |wPraesidium|n: |c{str_fig[dfn]}|n ||\n" + f"---------------------------------\n\n" )
[ "evennia.utils.utils.class_from_module" ]
[((437, 492), 'evennia.utils.utils.class_from_module', 'utils.class_from_module', (['settings.COMMAND_DEFAULT_CLASS'], {}), '(settings.COMMAND_DEFAULT_CLASS)\n', (460, 492), False, 'from evennia.utils import utils, evtable\n')]
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-01-28 23:11 from base64 import b64encode from django.db import migrations import evennia.utils.picklefield from pickle import dumps, loads from evennia.utils.utils import to_bytes from copy import deepcopy def forwards(apps, schema_editor): ServerConfig = apps.get_model("server", "ServerConfig") for conf in ServerConfig.objects.all(): # picklefield requires base64 encoding value = loads(to_bytes(conf.db_value), encoding="bytes") # py2->py3 byte encoding conf.db_value = b64encode(dumps(deepcopy(value), protocol=4)).decode() conf.save(update_fields=["db_value"]) class Migration(migrations.Migration): dependencies = [("server", "0001_initial")] operations = [ migrations.RunPython(forwards, migrations.RunPython.noop), migrations.AlterField( model_name="serverconfig", name="db_value", field=evennia.utils.picklefield.PickledObjectField( help_text="The data returned when the config value is accessed. Must be written as a Python literal if editing through the admin interface. Attribute values which are not Python literals cannot be edited through the admin interface.", null=True, verbose_name="value", ), ), ]
[ "evennia.utils.utils.to_bytes" ]
[((791, 848), 'django.db.migrations.RunPython', 'migrations.RunPython', (['forwards', 'migrations.RunPython.noop'], {}), '(forwards, migrations.RunPython.noop)\n', (811, 848), False, 'from django.db import migrations\n'), ((479, 502), 'evennia.utils.utils.to_bytes', 'to_bytes', (['conf.db_value'], {}), '(conf.db_value)\n', (487, 502), False, 'from evennia.utils.utils import to_bytes\n'), ((588, 603), 'copy.deepcopy', 'deepcopy', (['value'], {}), '(value)\n', (596, 603), False, 'from copy import deepcopy\n')]
""" Attributes are arbitrary data stored on objects. Attributes supports both pure-string values and pickled arbitrary data. Attributes are also used to implement Nicks. This module also contains the Attribute- and NickHandlers as well as the `NAttributeHandler`, which is a non-db version of Attributes. """ import re import fnmatch import weakref from django.db import models from django.conf import settings from django.utils.encoding import smart_str from evennia.locks.lockhandler import LockHandler from evennia.utils.idmapper.models import SharedMemoryModel from evennia.utils.dbserialize import to_pickle, from_pickle from evennia.utils.picklefield import PickledObjectField from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter _TYPECLASS_AGGRESSIVE_CACHE = settings.TYPECLASS_AGGRESSIVE_CACHE # ------------------------------------------------------------- # # Attributes # # ------------------------------------------------------------- class Attribute(SharedMemoryModel): """ Attributes are things that are specific to different types of objects. For example, a drink container needs to store its fill level, whereas an exit needs to store its open/closed/locked/unlocked state. These are done via attributes, rather than making different classes for each object type and storing them directly. The added benefit is that we can add/remove attributes on the fly as we like. The Attribute class defines the following properties: - key (str): Primary identifier. - lock_storage (str): Perm strings. - model (str): A string defining the model this is connected to. This is a natural_key, like "objects.objectdb" - date_created (datetime): When the attribute was created. - value (any): The data stored in the attribute, in pickled form using wrappers to be able to store/retrieve models. - strvalue (str): String-only data. This data is not pickled and is thus faster to search for in the database. - category (str): Optional character string for grouping the Attribute. """ # # Attribute Database Model setup # # These database fields are all set using their corresponding properties, # named same as the field, but without the db_* prefix. db_key = models.CharField("key", max_length=255, db_index=True) db_value = PickledObjectField( "value", null=True, help_text="The data returned when the attribute is accessed. Must be " "written as a Python literal if editing through the admin " "interface. Attribute values which are not Python literals " "cannot be edited through the admin interface.", ) db_strvalue = models.TextField( "strvalue", null=True, blank=True, help_text="String-specific storage for quick look-up" ) db_category = models.CharField( "category", max_length=128, db_index=True, blank=True, null=True, help_text="Optional categorization of attribute.", ) # Lock storage db_lock_storage = models.TextField( "locks", blank=True, help_text="Lockstrings for this object are stored here." ) db_model = models.CharField( "model", max_length=32, db_index=True, blank=True, null=True, help_text="Which model of object this attribute is attached to (A " "natural key like 'objects.objectdb'). You should not change " "this value unless you know what you are doing.", ) # subclass of Attribute (None or nick) db_attrtype = models.CharField( "attrtype", max_length=16, db_index=True, blank=True, null=True, help_text="Subclass of Attribute (None or nick)", ) # time stamp db_date_created = models.DateTimeField("date_created", editable=False, auto_now_add=True) # Database manager # objects = managers.AttributeManager() @lazy_property def locks(self): return LockHandler(self) class Meta(object): "Define Django meta options" verbose_name = "Evennia Attribute" # read-only wrappers key = property(lambda self: self.db_key) strvalue = property(lambda self: self.db_strvalue) category = property(lambda self: self.db_category) model = property(lambda self: self.db_model) attrtype = property(lambda self: self.db_attrtype) date_created = property(lambda self: self.db_date_created) def __lock_storage_get(self): return self.db_lock_storage def __lock_storage_set(self, value): self.db_lock_storage = value self.save(update_fields=["db_lock_storage"]) def __lock_storage_del(self): self.db_lock_storage = "" self.save(update_fields=["db_lock_storage"]) lock_storage = property(__lock_storage_get, __lock_storage_set, __lock_storage_del) # Wrapper properties to easily set database fields. These are # @property decorators that allows to access these fields using # normal python operations (without having to remember to save() # etc). So e.g. a property 'attr' has a get/set/del decorator # defined that allows the user to do self.attr = value, # value = self.attr and del self.attr respectively (where self # is the object in question). # value property (wraps db_value) # @property def __value_get(self): """ Getter. Allows for `value = self.value`. We cannot cache here since it makes certain cases (such as storing a dbobj which is then deleted elsewhere) out-of-sync. The overhead of unpickling seems hard to avoid. """ return from_pickle(self.db_value, db_obj=self) # @value.setter def __value_set(self, new_value): """ Setter. Allows for self.value = value. We cannot cache here, see self.__value_get. """ self.db_value = to_pickle(new_value) # print("value_set, self.db_value:", repr(self.db_value)) # DEBUG self.save(update_fields=["db_value"]) # @value.deleter def __value_del(self): """Deleter. Allows for del attr.value. This removes the entire attribute.""" self.delete() value = property(__value_get, __value_set, __value_del) # # # Attribute methods # # def __str__(self): return smart_str("%s(%s)" % (self.db_key, self.id)) def __repr__(self): return "%s(%s)" % (self.db_key, self.id) def access(self, accessing_obj, access_type="attrread", default=False, **kwargs): """ Determines if another object has permission to access. Args: accessing_obj (object): Entity trying to access this one. access_type (str, optional): Type of access sought, see the lock documentation. default (bool, optional): What result to return if no lock of access_type was found. The default, `False`, means a lockdown policy, only allowing explicit access. kwargs (any, optional): Not used; here to make the API consistent with other access calls. Returns: result (bool): If the lock was passed or not. """ result = self.locks.check(accessing_obj, access_type=access_type, default=default) return result # # Handlers making use of the Attribute model # class AttributeHandler(object): """ Handler for adding Attributes to the object. """ _m2m_fieldname = "db_attributes" _attrcreate = "attrcreate" _attredit = "attredit" _attrread = "attrread" _attrtype = None def __init__(self, obj): """Initialize handler.""" self.obj = obj self._objid = obj.id self._model = to_str(obj.__dbclass__.__name__.lower()) self._cache = {} # store category names fully cached self._catcache = {} # full cache was run on all attributes self._cache_complete = False def _query_all(self): "Fetch all Attributes on this object" query = { "%s__id" % self._model: self._objid, "attribute__db_model__iexact": self._model, "attribute__db_attrtype": self._attrtype, } return [ conn.attribute for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query) ] def _fullcache(self): """Cache all attributes of this object""" if not _TYPECLASS_AGGRESSIVE_CACHE: return attrs = self._query_all() self._cache = dict( ( "%s-%s" % ( to_str(attr.db_key).lower(), attr.db_category.lower() if attr.db_category else None, ), attr, ) for attr in attrs ) self._cache_complete = True def _getcache(self, key=None, category=None): """ Retrieve from cache or database (always caches) Args: key (str, optional): Attribute key to query for category (str, optional): Attribiute category Returns: args (list): Returns a list of zero or more matches found from cache or database. Notes: When given a category only, a search for all objects of that cateogory is done and the category *name* is stored. This tells the system on subsequent calls that the list of cached attributes of this category is up-to-date and that the cache can be queried for category matches without missing any. The TYPECLASS_AGGRESSIVE_CACHE=False setting will turn off caching, causing each attribute access to trigger a database lookup. """ key = key.strip().lower() if key else None category = category.strip().lower() if category else None if key: cachekey = "%s-%s" % (key, category) cachefound = False try: attr = _TYPECLASS_AGGRESSIVE_CACHE and self._cache[cachekey] cachefound = True except KeyError: attr = None if attr and (not hasattr(attr, "pk") and attr.pk is None): # clear out Attributes deleted from elsewhere. We must search this anew. attr = None cachefound = False del self._cache[cachekey] if cachefound and _TYPECLASS_AGGRESSIVE_CACHE: if attr: return [attr] # return cached entity else: return [] # no such attribute: return an empty list else: query = { "%s__id" % self._model: self._objid, "attribute__db_model__iexact": self._model, "attribute__db_attrtype": self._attrtype, "attribute__db_key__iexact": key.lower(), "attribute__db_category__iexact": category.lower() if category else None, } if not self.obj.pk: return [] conn = getattr(self.obj, self._m2m_fieldname).through.objects.filter(**query) if conn: attr = conn[0].attribute if _TYPECLASS_AGGRESSIVE_CACHE: self._cache[cachekey] = attr return [attr] if attr.pk else [] else: # There is no such attribute. We will explicitly save that # in our cache to avoid firing another query if we try to # retrieve that (non-existent) attribute again. if _TYPECLASS_AGGRESSIVE_CACHE: self._cache[cachekey] = None return [] else: # only category given (even if it's None) - we can't # assume the cache to be complete unless we have queried # for this category before catkey = "-%s" % category if _TYPECLASS_AGGRESSIVE_CACHE and catkey in self._catcache: return [attr for key, attr in self._cache.items() if key.endswith(catkey) and attr] else: # we have to query to make this category up-date in the cache query = { "%s__id" % self._model: self._objid, "attribute__db_model__iexact": self._model, "attribute__db_attrtype": self._attrtype, "attribute__db_category__iexact": category.lower() if category else None, } attrs = [ conn.attribute for conn in getattr(self.obj, self._m2m_fieldname).through.objects.filter( **query ) ] if _TYPECLASS_AGGRESSIVE_CACHE: for attr in attrs: if attr.pk: cachekey = "%s-%s" % (attr.db_key, category) self._cache[cachekey] = attr # mark category cache as up-to-date self._catcache[catkey] = True return attrs def _setcache(self, key, category, attr_obj): """ Update cache. Args: key (str): A cleaned key string category (str or None): A cleaned category name attr_obj (Attribute): The newly saved attribute """ if not _TYPECLASS_AGGRESSIVE_CACHE: return if not key: # don't allow an empty key in cache return cachekey = "%s-%s" % (key, category) catkey = "-%s" % category self._cache[cachekey] = attr_obj # mark that the category cache is no longer up-to-date self._catcache.pop(catkey, None) self._cache_complete = False def _delcache(self, key, category): """ Remove attribute from cache Args: key (str): A cleaned key string category (str or None): A cleaned category name """ catkey = "-%s" % category if key: cachekey = "%s-%s" % (key, category) self._cache.pop(cachekey, None) else: self._cache = { key: attrobj for key, attrobj in list(self._cache.items()) if not key.endswith(catkey) } # mark that the category cache is no longer up-to-date self._catcache.pop(catkey, None) self._cache_complete = False def reset_cache(self): """ Reset cache from the outside. """ self._cache_complete = False self._cache = {} self._catcache = {} def has(self, key=None, category=None): """ Checks if the given Attribute (or list of Attributes) exists on the object. Args: key (str or iterable): The Attribute key or keys to check for. If `None`, search by category. category (str or None): Limit the check to Attributes with this category (note, that `None` is the default category). Returns: has_attribute (bool or list): If the Attribute exists on this object or not. If `key` was given as an iterable then the return is a list of booleans. """ ret = [] category = category.strip().lower() if category is not None else None for keystr in make_iter(key): keystr = key.strip().lower() ret.extend(bool(attr) for attr in self._getcache(keystr, category)) return ret[0] if len(ret) == 1 else ret def get( self, key=None, default=None, category=None, return_obj=False, strattr=False, raise_exception=False, accessing_obj=None, default_access=True, return_list=False, ): """ Get the Attribute. Args: key (str or list, optional): the attribute identifier or multiple attributes to get. if a list of keys, the method will return a list. category (str, optional): the category within which to retrieve attribute(s). default (any, optional): The value to return if an Attribute was not defined. If set, it will be returned in a one-item list. return_obj (bool, optional): If set, the return is not the value of the Attribute but the Attribute object itself. strattr (bool, optional): Return the `strvalue` field of the Attribute rather than the usual `value`, this is a string-only value for quick database searches. raise_exception (bool, optional): When an Attribute is not found, the return from this is usually `default`. If this is set, an exception is raised instead. accessing_obj (object, optional): If set, an `attrread` permission lock will be checked before returning each looked-after Attribute. default_access (bool, optional): If no `attrread` lock is set on object, this determines if the lock should then be passed or not. return_list (bool, optional): Returns: result (any or list): One or more matches for keys and/or categories. Each match will be the value of the found Attribute(s) unless `return_obj` is True, at which point it will be the attribute object itself or None. If `return_list` is True, this will always be a list, regardless of the number of elements. Raises: AttributeError: If `raise_exception` is set and no matching Attribute was found matching `key`. """ ret = [] for keystr in make_iter(key): # it's okay to send a None key attr_objs = self._getcache(keystr, category) if attr_objs: ret.extend(attr_objs) elif raise_exception: raise AttributeError elif return_obj: ret.append(None) if accessing_obj: # check 'attrread' locks ret = [ attr for attr in ret if attr.access(accessing_obj, self._attrread, default=default_access) ] if strattr: ret = ret if return_obj else [attr.strvalue for attr in ret if attr] else: ret = ret if return_obj else [attr.value for attr in ret if attr] if return_list: return ret if ret else [default] if default is not None else [] return ret[0] if ret and len(ret) == 1 else ret or default def add( self, key, value, category=None, lockstring="", strattr=False, accessing_obj=None, default_access=True, ): """ Add attribute to object, with optional `lockstring`. Args: key (str): An Attribute name to add. value (any or str): The value of the Attribute. If `strattr` keyword is set, this *must* be a string. category (str, optional): The category for the Attribute. The default `None` is the normal category used. lockstring (str, optional): A lock string limiting access to the attribute. strattr (bool, optional): Make this a string-only Attribute. This is only ever useful for optimization purposes. accessing_obj (object, optional): An entity to check for the `attrcreate` access-type. If not passing, this method will be exited. default_access (bool, optional): What access to grant if `accessing_obj` is given but no lock of the type `attrcreate` is defined on the Attribute in question. """ if accessing_obj and not self.obj.access( accessing_obj, self._attrcreate, default=default_access ): # check create access return if not key: return category = category.strip().lower() if category is not None else None keystr = key.strip().lower() attr_obj = self._getcache(key, category) if attr_obj: # update an existing attribute object attr_obj = attr_obj[0] if strattr: # store as a simple string (will not notify OOB handlers) attr_obj.db_strvalue = value attr_obj.save(update_fields=["db_strvalue"]) else: # store normally (this will also notify OOB handlers) attr_obj.value = value else: # create a new Attribute (no OOB handlers can be notified) kwargs = { "db_key": keystr, "db_category": category, "db_model": self._model, "db_attrtype": self._attrtype, "db_value": None if strattr else to_pickle(value), "db_strvalue": value if strattr else None, } new_attr = Attribute(**kwargs) new_attr.save() getattr(self.obj, self._m2m_fieldname).add(new_attr) # update cache self._setcache(keystr, category, new_attr) def batch_add(self, *args, **kwargs): """ Batch-version of `add()`. This is more efficient than repeat-calling add when having many Attributes to add. Args: *args (tuple): Each argument should be a tuples (can be of varying length) representing the Attribute to add to this object. Supported tuples are - `(key, value)` - `(key, value, category)` - `(key, value, category, lockstring)` - `(key, value, category, lockstring, default_access)` Kwargs: strattr (bool): If `True`, value must be a string. This will save the value without pickling which is less flexible but faster to search (not often used except internally). Raises: RuntimeError: If trying to pass a non-iterable as argument. Notes: The indata tuple order matters, so if you want a lockstring but no category, set the category to `None`. This method does not have the ability to check editing permissions like normal .add does, and is mainly used internally. It does not use the normal self.add but apply the Attributes directly to the database. """ new_attrobjs = [] strattr = kwargs.get("strattr", False) for tup in args: if not is_iter(tup) or len(tup) < 2: raise RuntimeError("batch_add requires iterables as arguments (got %r)." % tup) ntup = len(tup) keystr = str(tup[0]).strip().lower() new_value = tup[1] category = str(tup[2]).strip().lower() if ntup > 2 and tup[2] is not None else None lockstring = tup[3] if ntup > 3 else "" attr_objs = self._getcache(keystr, category) if attr_objs: attr_obj = attr_objs[0] # update an existing attribute object attr_obj.db_category = category attr_obj.db_lock_storage = lockstring or "" attr_obj.save(update_fields=["db_category", "db_lock_storage"]) if strattr: # store as a simple string (will not notify OOB handlers) attr_obj.db_strvalue = new_value attr_obj.save(update_fields=["db_strvalue"]) else: # store normally (this will also notify OOB handlers) attr_obj.value = new_value else: # create a new Attribute (no OOB handlers can be notified) kwargs = { "db_key": keystr, "db_category": category, "db_model": self._model, "db_attrtype": self._attrtype, "db_value": None if strattr else to_pickle(new_value), "db_strvalue": new_value if strattr else None, "db_lock_storage": lockstring or "", } new_attr = Attribute(**kwargs) new_attr.save() new_attrobjs.append(new_attr) self._setcache(keystr, category, new_attr) if new_attrobjs: # Add new objects to m2m field all at once getattr(self.obj, self._m2m_fieldname).add(*new_attrobjs) def remove( self, key=None, raise_exception=False, category=None, accessing_obj=None, default_access=True, ): """ Remove attribute or a list of attributes from object. Args: key (str or list, optional): An Attribute key to remove or a list of keys. If multiple keys, they must all be of the same `category`. If None and category is not given, remove all Attributes. raise_exception (bool, optional): If set, not finding the Attribute to delete will raise an exception instead of just quietly failing. category (str, optional): The category within which to remove the Attribute. accessing_obj (object, optional): An object to check against the `attredit` lock. If not given, the check will be skipped. default_access (bool, optional): The fallback access to grant if `accessing_obj` is given but there is no `attredit` lock set on the Attribute in question. Raises: AttributeError: If `raise_exception` is set and no matching Attribute was found matching `key`. Notes: If neither key nor category is given, this acts as clear(). """ if key is None: self.clear( category=category, accessing_obj=accessing_obj, default_access=default_access ) return category = category.strip().lower() if category is not None else None for keystr in make_iter(key): keystr = keystr.lower() attr_objs = self._getcache(keystr, category) for attr_obj in attr_objs: if not ( accessing_obj and not attr_obj.access(accessing_obj, self._attredit, default=default_access) ): try: attr_obj.delete() except AssertionError: print("Assertionerror for attr.delete()") # this happens if the attr was already deleted pass finally: self._delcache(keystr, category) if not attr_objs and raise_exception: raise AttributeError def clear(self, category=None, accessing_obj=None, default_access=True): """ Remove all Attributes on this object. Args: category (str, optional): If given, clear only Attributes of this category. accessing_obj (object, optional): If given, check the `attredit` lock on each Attribute before continuing. default_access (bool, optional): Use this permission as fallback if `access_obj` is given but there is no lock of type `attredit` on the Attribute in question. """ category = category.strip().lower() if category is not None else None if not self._cache_complete: self._fullcache() if category is not None: attrs = [attr for attr in self._cache.values() if attr.category == category] else: attrs = self._cache.values() if accessing_obj: [ attr.delete() for attr in attrs if attr and attr.access(accessing_obj, self._attredit, default=default_access) ] else: [attr.delete() for attr in attrs if attr and attr.pk] self._cache = {} self._catcache = {} self._cache_complete = False def all(self, accessing_obj=None, default_access=True): """ Return all Attribute objects on this object, regardless of category. Args: accessing_obj (object, optional): Check the `attrread` lock on each attribute before returning them. If not given, this check is skipped. default_access (bool, optional): Use this permission as a fallback if `accessing_obj` is given but one or more Attributes has no lock of type `attrread` defined on them. Returns: Attributes (list): All the Attribute objects (note: Not their values!) in the handler. """ if _TYPECLASS_AGGRESSIVE_CACHE: if not self._cache_complete: self._fullcache() attrs = sorted([attr for attr in self._cache.values() if attr], key=lambda o: o.id) else: attrs = sorted([attr for attr in self._query_all() if attr], key=lambda o: o.id) if accessing_obj: return [ attr for attr in attrs if attr.access(accessing_obj, self._attredit, default=default_access) ] else: return attrs # Nick templating # """ This supports the use of replacement templates in nicks: This happens in two steps: 1) The user supplies a template that is converted to a regex according to the unix-like templating language. 2) This regex is tested against nicks depending on which nick replacement strategy is considered (most commonly inputline). 3) If there is a template match and there are templating markers, these are replaced with the arguments actually given. @desc $1 $2 $3 This will be converted to the following regex: \@desc (?P<1>\w+) (?P<2>\w+) $(?P<3>\w+) Supported template markers (through fnmatch) * matches anything (non-greedy) -> .*? ? matches any single character -> [seq] matches any entry in sequence [!seq] matches entries not in sequence Custom arg markers $N argument position (1-99) """ _RE_NICK_ARG = re.compile(r"\\(\$)([1-9][0-9]?)") _RE_NICK_TEMPLATE_ARG = re.compile(r"(\$)([1-9][0-9]?)") _RE_NICK_SPACE = re.compile(r"\\ ") class NickTemplateInvalid(ValueError): pass def initialize_nick_templates(in_template, out_template): """ Initialize the nick templates for matching and remapping a string. Args: in_template (str): The template to be used for nick recognition. out_template (str): The template to be used to replace the string matched by the in_template. Returns: regex (regex): Regex to match against strings template (str): Template with markers {arg1}, {arg2}, etc for replacement using the standard .format method. Raises: NickTemplateInvalid: If the in/out template does not have a matching number of $args. """ # create the regex for in_template regex_string = fnmatch.translate(in_template) # we must account for a possible line break coming over the wire # NOTE-PYTHON3: fnmatch.translate format changed since Python2 regex_string = regex_string[:-2] + r"(?:[\n\r]*?)\Z" # validate the templates regex_args = [match.group(2) for match in _RE_NICK_ARG.finditer(regex_string)] temp_args = [match.group(2) for match in _RE_NICK_TEMPLATE_ARG.finditer(out_template)] if set(regex_args) != set(temp_args): # We don't have the same $-tags in input/output. raise NickTemplateInvalid regex_string = _RE_NICK_SPACE.sub(r"\\s+", regex_string) regex_string = _RE_NICK_ARG.sub(lambda m: "(?P<arg%s>.+?)" % m.group(2), regex_string) template_string = _RE_NICK_TEMPLATE_ARG.sub(lambda m: "{arg%s}" % m.group(2), out_template) return regex_string, template_string def parse_nick_template(string, template_regex, outtemplate): """ Parse a text using a template and map it to another template Args: string (str): The input string to processj template_regex (regex): A template regex created with initialize_nick_template. outtemplate (str): The template to which to map the matches produced by the template_regex. This should have $1, $2, etc to match the regex. """ match = template_regex.match(string) if match: return True, outtemplate.format(**match.groupdict()) return False, string class NickHandler(AttributeHandler): """ Handles the addition and removal of Nicks. Nicks are special versions of Attributes with an `_attrtype` hardcoded to `nick`. They also always use the `strvalue` fields for their data. """ _attrtype = "nick" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._regex_cache = {} def has(self, key, category="inputline"): """ Args: key (str or iterable): The Nick key or keys to check for. category (str): Limit the check to Nicks with this category (note, that `None` is the default category). Returns: has_nick (bool or list): If the Nick exists on this object or not. If `key` was given as an iterable then the return is a list of booleans. """ return super().has(key, category=category) def get(self, key=None, category="inputline", return_tuple=False, **kwargs): """ Get the replacement value matching the given key and category Args: key (str or list, optional): the attribute identifier or multiple attributes to get. if a list of keys, the method will return a list. category (str, optional): the category within which to retrieve the nick. The "inputline" means replacing data sent by the user. return_tuple (bool, optional): return the full nick tuple rather than just the replacement. For non-template nicks this is just a string. kwargs (any, optional): These are passed on to `AttributeHandler.get`. """ if return_tuple or "return_obj" in kwargs: return super().get(key=key, category=category, **kwargs) else: retval = super().get(key=key, category=category, **kwargs) if retval: return ( retval[3] if isinstance(retval, tuple) else [tup[3] for tup in make_iter(retval)] ) return None def add(self, key, replacement, category="inputline", **kwargs): """ Add a new nick. Args: key (str): A key (or template) for the nick to match for. replacement (str): The string (or template) to replace `key` with (the "nickname"). category (str, optional): the category within which to retrieve the nick. The "inputline" means replacing data sent by the user. kwargs (any, optional): These are passed on to `AttributeHandler.get`. """ if category == "channel": nick_regex, nick_template = initialize_nick_templates(key + " $1", replacement + " $1") else: nick_regex, nick_template = initialize_nick_templates(key, replacement) super().add(key, (nick_regex, nick_template, key, replacement), category=category, **kwargs) def remove(self, key, category="inputline", **kwargs): """ Remove Nick with matching category. Args: key (str): A key for the nick to match for. category (str, optional): the category within which to removethe nick. The "inputline" means replacing data sent by the user. kwargs (any, optional): These are passed on to `AttributeHandler.get`. """ super().remove(key, category=category, **kwargs) def nickreplace(self, raw_string, categories=("inputline", "channel"), include_account=True): """ Apply nick replacement of entries in raw_string with nick replacement. Args: raw_string (str): The string in which to perform nick replacement. categories (tuple, optional): Replacement categories in which to perform the replacement, such as "inputline", "channel" etc. include_account (bool, optional): Also include replacement with nicks stored on the Account level. kwargs (any, optional): Not used. Returns: string (str): A string with matching keys replaced with their nick equivalents. """ nicks = {} for category in make_iter(categories): nicks.update( { nick.key: nick for nick in make_iter(self.get(category=category, return_obj=True)) if nick and nick.key } ) if include_account and self.obj.has_account: for category in make_iter(categories): nicks.update( { nick.key: nick for nick in make_iter( self.obj.account.nicks.get(category=category, return_obj=True) ) if nick and nick.key } ) for key, nick in nicks.items(): nick_regex, template, _, _ = nick.value regex = self._regex_cache.get(nick_regex) if not regex: regex = re.compile(nick_regex, re.I + re.DOTALL + re.U) self._regex_cache[nick_regex] = regex is_match, raw_string = parse_nick_template(raw_string.strip(), regex, template) if is_match: break return raw_string class NAttributeHandler(object): """ This stand-alone handler manages non-database saving. It is similar to `AttributeHandler` and is used by the `.ndb` handler in the same way as `.db` does for the `AttributeHandler`. """ def __init__(self, obj): """ Initialized on the object """ self._store = {} self.obj = weakref.proxy(obj) def has(self, key): """ Check if object has this attribute or not. Args: key (str): The Nattribute key to check. Returns: has_nattribute (bool): If Nattribute is set or not. """ return key in self._store def get(self, key): """ Get the named key value. Args: key (str): The Nattribute key to get. Returns: the value of the Nattribute. """ return self._store.get(key, None) def add(self, key, value): """ Add new key and value. Args: key (str): The name of Nattribute to add. value (any): The value to store. """ self._store[key] = value def remove(self, key): """ Remove Nattribute from storage. Args: key (str): The name of the Nattribute to remove. """ if key in self._store: del self._store[key] def clear(self): """ Remove all NAttributes from handler. """ self._store = {} def all(self, return_tuples=False): """ List the contents of the handler. Args: return_tuples (bool, optional): Defines if the Nattributes are returns as a list of keys or as a list of `(key, value)`. Returns: nattributes (list): A list of keys `[key, key, ...]` or a list of tuples `[(key, value), ...]` depending on the setting of `return_tuples`. """ if return_tuples: return [(key, value) for (key, value) in self._store.items() if not key.startswith("_")] return [key for key in self._store if not key.startswith("_")]
[ "evennia.utils.dbserialize.from_pickle", "evennia.utils.utils.to_str", "evennia.utils.picklefield.PickledObjectField", "evennia.utils.dbserialize.to_pickle", "evennia.utils.utils.is_iter", "evennia.utils.utils.make_iter", "evennia.locks.lockhandler.LockHandler" ]
[((31192, 31228), 're.compile', 're.compile', (['"""\\\\\\\\(\\\\$)([1-9][0-9]?)"""'], {}), "('\\\\\\\\(\\\\$)([1-9][0-9]?)')\n", (31202, 31228), False, 'import re\n'), ((31251, 31283), 're.compile', 're.compile', (['"""(\\\\$)([1-9][0-9]?)"""'], {}), "('(\\\\$)([1-9][0-9]?)')\n", (31261, 31283), False, 'import re\n'), ((31301, 31320), 're.compile', 're.compile', (['"""\\\\\\\\ """'], {}), "('\\\\\\\\ ')\n", (31311, 31320), False, 'import re\n'), ((2320, 2374), 'django.db.models.CharField', 'models.CharField', (['"""key"""'], {'max_length': '(255)', 'db_index': '(True)'}), "('key', max_length=255, db_index=True)\n", (2336, 2374), False, 'from django.db import models\n'), ((2390, 2670), 'evennia.utils.picklefield.PickledObjectField', 'PickledObjectField', (['"""value"""'], {'null': '(True)', 'help_text': '"""The data returned when the attribute is accessed. Must be written as a Python literal if editing through the admin interface. Attribute values which are not Python literals cannot be edited through the admin interface."""'}), "('value', null=True, help_text=\n 'The data returned when the attribute is accessed. Must be written as a Python literal if editing through the admin interface. Attribute values which are not Python literals cannot be edited through the admin interface.'\n )\n", (2408, 2670), False, 'from evennia.utils.picklefield import PickledObjectField\n'), ((2743, 2854), 'django.db.models.TextField', 'models.TextField', (['"""strvalue"""'], {'null': '(True)', 'blank': '(True)', 'help_text': '"""String-specific storage for quick look-up"""'}), "('strvalue', null=True, blank=True, help_text=\n 'String-specific storage for quick look-up')\n", (2759, 2854), False, 'from django.db import models\n'), ((2882, 3019), 'django.db.models.CharField', 'models.CharField', (['"""category"""'], {'max_length': '(128)', 'db_index': '(True)', 'blank': '(True)', 'null': '(True)', 'help_text': '"""Optional categorization of attribute."""'}), "('category', max_length=128, db_index=True, blank=True,\n null=True, help_text='Optional categorization of attribute.')\n", (2898, 3019), False, 'from django.db import models\n'), ((3112, 3212), 'django.db.models.TextField', 'models.TextField', (['"""locks"""'], {'blank': '(True)', 'help_text': '"""Lockstrings for this object are stored here."""'}), "('locks', blank=True, help_text=\n 'Lockstrings for this object are stored here.')\n", (3128, 3212), False, 'from django.db import models\n'), ((3237, 3505), 'django.db.models.CharField', 'models.CharField', (['"""model"""'], {'max_length': '(32)', 'db_index': '(True)', 'blank': '(True)', 'null': '(True)', 'help_text': '"""Which model of object this attribute is attached to (A natural key like \'objects.objectdb\'). You should not change this value unless you know what you are doing."""'}), '(\'model\', max_length=32, db_index=True, blank=True, null=\n True, help_text=\n "Which model of object this attribute is attached to (A natural key like \'objects.objectdb\'). You should not change this value unless you know what you are doing."\n )\n', (3253, 3505), False, 'from django.db import models\n'), ((3629, 3765), 'django.db.models.CharField', 'models.CharField', (['"""attrtype"""'], {'max_length': '(16)', 'db_index': '(True)', 'blank': '(True)', 'null': '(True)', 'help_text': '"""Subclass of Attribute (None or nick)"""'}), "('attrtype', max_length=16, db_index=True, blank=True, null\n =True, help_text='Subclass of Attribute (None or nick)')\n", (3645, 3765), False, 'from django.db import models\n'), ((3855, 3926), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""date_created"""'], {'editable': '(False)', 'auto_now_add': '(True)'}), "('date_created', editable=False, auto_now_add=True)\n", (3875, 3926), False, 'from django.db import models\n'), ((32092, 32122), 'fnmatch.translate', 'fnmatch.translate', (['in_template'], {}), '(in_template)\n', (32109, 32122), False, 'import fnmatch\n'), ((4051, 4068), 'evennia.locks.lockhandler.LockHandler', 'LockHandler', (['self'], {}), '(self)\n', (4062, 4068), False, 'from evennia.locks.lockhandler import LockHandler\n'), ((5730, 5769), 'evennia.utils.dbserialize.from_pickle', 'from_pickle', (['self.db_value'], {'db_obj': 'self'}), '(self.db_value, db_obj=self)\n', (5741, 5769), False, 'from evennia.utils.dbserialize import to_pickle, from_pickle\n'), ((5976, 5996), 'evennia.utils.dbserialize.to_pickle', 'to_pickle', (['new_value'], {}), '(new_value)\n', (5985, 5996), False, 'from evennia.utils.dbserialize import to_pickle, from_pickle\n'), ((6423, 6467), 'django.utils.encoding.smart_str', 'smart_str', (["('%s(%s)' % (self.db_key, self.id))"], {}), "('%s(%s)' % (self.db_key, self.id))\n", (6432, 6467), False, 'from django.utils.encoding import smart_str\n'), ((15776, 15790), 'evennia.utils.utils.make_iter', 'make_iter', (['key'], {}), '(key)\n', (15785, 15790), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((18255, 18269), 'evennia.utils.utils.make_iter', 'make_iter', (['key'], {}), '(key)\n', (18264, 18269), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((26949, 26963), 'evennia.utils.utils.make_iter', 'make_iter', (['key'], {}), '(key)\n', (26958, 26963), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((37970, 37991), 'evennia.utils.utils.make_iter', 'make_iter', (['categories'], {}), '(categories)\n', (37979, 37991), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((39522, 39540), 'weakref.proxy', 'weakref.proxy', (['obj'], {}), '(obj)\n', (39535, 39540), False, 'import weakref\n'), ((38314, 38335), 'evennia.utils.utils.make_iter', 'make_iter', (['categories'], {}), '(categories)\n', (38323, 38335), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((38873, 38920), 're.compile', 're.compile', (['nick_regex', '(re.I + re.DOTALL + re.U)'], {}), '(nick_regex, re.I + re.DOTALL + re.U)\n', (38883, 38920), False, 'import re\n'), ((21538, 21554), 'evennia.utils.dbserialize.to_pickle', 'to_pickle', (['value'], {}), '(value)\n', (21547, 21554), False, 'from evennia.utils.dbserialize import to_pickle, from_pickle\n'), ((23320, 23332), 'evennia.utils.utils.is_iter', 'is_iter', (['tup'], {}), '(tup)\n', (23327, 23332), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((24788, 24808), 'evennia.utils.dbserialize.to_pickle', 'to_pickle', (['new_value'], {}), '(new_value)\n', (24797, 24808), False, 'from evennia.utils.dbserialize import to_pickle, from_pickle\n'), ((35685, 35702), 'evennia.utils.utils.make_iter', 'make_iter', (['retval'], {}), '(retval)\n', (35694, 35702), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n'), ((8768, 8787), 'evennia.utils.utils.to_str', 'to_str', (['attr.db_key'], {}), '(attr.db_key)\n', (8774, 8787), False, 'from evennia.utils.utils import lazy_property, to_str, make_iter, is_iter\n')]
""" MudderyNPC is NPC's base class. """ import json import traceback from evennia import TICKER_HANDLER from evennia.utils import logger from muddery.typeclasses.characters import MudderyCharacter from muddery.utils.localized_strings_handler import _ from muddery.utils.dialogue_handler import DIALOGUE_HANDLER from muddery.utils.builder import build_object, delete_object from muddery.utils.game_settings import GAME_SETTINGS from muddery.worlddata.data_sets import DATA_SETS class MudderyNPC(MudderyCharacter): """ Default NPC. NPCs are friendly to players, they can not be attacked. """ def at_object_creation(self): """ Called once, when this object is first created. This is the normal hook to overload for most object types. """ super(MudderyNPC, self).at_object_creation() # NPC's shop if not self.attributes.has("shops"): self.db.shops = {} def after_data_loaded(self): """ Init the character. """ super(MudderyNPC, self).after_data_loaded() # set home self.home = self.location # load dialogues. self.load_dialogues() # load shops self.load_shops() def load_dialogues(self): """ Load dialogues. """ npc_key = self.get_data_key() dialogues = DATA_SETS.npc_dialogues.objects.filter(npc=npc_key) self.default_dialogues = [dialogue.dialogue for dialogue in dialogues if dialogue.default] self.dialogues = [dialogue.dialogue for dialogue in dialogues if not dialogue.default] def load_shops(self): """ Load character's shop. """ # shops records shop_records = DATA_SETS.npc_shops.objects.filter(npc=self.get_data_key()) shop_keys = set([record.shop for record in shop_records]) # remove old shops for shop_key in self.db.shops: if shop_key not in shop_keys: # remove this shop self.db.shops[shop_key].delete() del self.db.shops[shop_key] # add new shop for shop_record in shop_records: shop_key = shop_record.shop if shop_key not in self.db.shops: # Create shop object. shop_obj = build_object(shop_key) if not shop_obj: logger.log_errmsg("Can't create shop: %s" % shop_key) continue self.db.shops[shop_key] = shop_obj def get_available_commands(self, caller): """ This returns a list of available commands. """ commands = [] if self.dialogues or self.default_dialogues: # If the character have something to talk, add talk command. commands.append({"name":_("Talk"), "cmd":"talk", "args":self.dbref}) # Add shops. for shop_obj in self.db.shops.values(): if not shop_obj.is_visible(caller): continue verb = shop_obj.verb if not verb: verb = shop_obj.get_name() commands.append({"name":verb, "cmd":"shopping", "args":shop_obj.dbref}) return commands def have_quest(self, caller): """ If the npc can complete or provide quests. Returns (can_provide_quest, can_complete_quest). """ return DIALOGUE_HANDLER.have_quest(caller, self)
[ "evennia.utils.logger.log_errmsg" ]
[((1401, 1452), 'muddery.worlddata.data_sets.DATA_SETS.npc_dialogues.objects.filter', 'DATA_SETS.npc_dialogues.objects.filter', ([], {'npc': 'npc_key'}), '(npc=npc_key)\n', (1439, 1452), False, 'from muddery.worlddata.data_sets import DATA_SETS\n'), ((3487, 3528), 'muddery.utils.dialogue_handler.DIALOGUE_HANDLER.have_quest', 'DIALOGUE_HANDLER.have_quest', (['caller', 'self'], {}), '(caller, self)\n', (3514, 3528), False, 'from muddery.utils.dialogue_handler import DIALOGUE_HANDLER\n'), ((2357, 2379), 'muddery.utils.builder.build_object', 'build_object', (['shop_key'], {}), '(shop_key)\n', (2369, 2379), False, 'from muddery.utils.builder import build_object, delete_object\n'), ((2433, 2486), 'evennia.utils.logger.log_errmsg', 'logger.log_errmsg', (['("Can\'t create shop: %s" % shop_key)'], {}), '("Can\'t create shop: %s" % shop_key)\n', (2450, 2486), False, 'from evennia.utils import logger\n'), ((2890, 2899), 'muddery.utils.localized_strings_handler._', '_', (['"""Talk"""'], {}), "('Talk')\n", (2891, 2899), False, 'from muddery.utils.localized_strings_handler import _\n')]
# file mygame/commands/make_npcs.py import time from evennia.utils import utils, create, logger, search from evennia.objects.models import ObjectDB from django.conf import settings from commands.make_crustumerians import Citizen self = Citizen() typeclass = settings.BASE_CHARACTER_TYPECLASS start_location = ObjectDB.objects.get_id(settings.START_LOCATION) default_home = ObjectDB.objects.get_id(settings.DEFAULT_HOME) permissions = settings.PERMISSION_ACCOUNT_DEFAULT new_character = create.create_object( typeclass, key=self.name, location='#249', home=default_home, permissions=permissions, attributes=[ ('gender',self.gender), ('age',self.age), ('gens',self.gens), ('hometown',self.hometown), ('pedigree',self.pedigree), ('praenomen',self.praenomen), ('nomen',self.nomen), ('nom_sg',[self.praenomen]), ('gen_sg',[self.genitive]), ('stats', self.stats) ] ) # only allow creator (and developers) to puppet this char #new_character.locks.add( # "puppet:id(%i) or pid(%i) or perm(Developer) or pperm(Developer);delete:id(%i) or perm(Admin)" # % (new_character.id, account.id, account.id) #) #if desc: # new_character.db.desc = desc #else: # new_character.db.desc = "This is a character." # #logger.log_sec( # "Character Created: %s (Caller: %s, IP: %s)." # % (new_character, account, self.session.address) #)
[ "evennia.objects.models.ObjectDB.objects.get_id", "evennia.utils.create.create_object" ]
[((238, 247), 'commands.make_crustumerians.Citizen', 'Citizen', ([], {}), '()\n', (245, 247), False, 'from commands.make_crustumerians import Citizen\n'), ((312, 360), 'evennia.objects.models.ObjectDB.objects.get_id', 'ObjectDB.objects.get_id', (['settings.START_LOCATION'], {}), '(settings.START_LOCATION)\n', (335, 360), False, 'from evennia.objects.models import ObjectDB\n'), ((376, 422), 'evennia.objects.models.ObjectDB.objects.get_id', 'ObjectDB.objects.get_id', (['settings.DEFAULT_HOME'], {}), '(settings.DEFAULT_HOME)\n', (399, 422), False, 'from evennia.objects.models import ObjectDB\n'), ((489, 892), 'evennia.utils.create.create_object', 'create.create_object', (['typeclass'], {'key': 'self.name', 'location': '"""#249"""', 'home': 'default_home', 'permissions': 'permissions', 'attributes': "[('gender', self.gender), ('age', self.age), ('gens', self.gens), (\n 'hometown', self.hometown), ('pedigree', self.pedigree), ('praenomen',\n self.praenomen), ('nomen', self.nomen), ('nom_sg', [self.praenomen]), (\n 'gen_sg', [self.genitive]), ('stats', self.stats)]"}), "(typeclass, key=self.name, location='#249', home=\n default_home, permissions=permissions, attributes=[('gender', self.\n gender), ('age', self.age), ('gens', self.gens), ('hometown', self.\n hometown), ('pedigree', self.pedigree), ('praenomen', self.praenomen),\n ('nomen', self.nomen), ('nom_sg', [self.praenomen]), ('gen_sg', [self.\n genitive]), ('stats', self.stats)])\n", (509, 892), False, 'from evennia.utils import utils, create, logger, search\n')]
""" Room Rooms are simple containers that are to gps metadata of their own. """ from evennia import DefaultRoom, utils from characters import Character from npc import Npc from mob import Mob from evennia import TICKER_HANDLER as tickerhandler class Room(DefaultRoom): """ Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all Objects. """ def at_object_creation(self): "Called at first creation of the object" super(Room, self).at_object_creation() self.db.roomtype_key = "Generic" # Room Type Key self.db.roomtype_value = "Generic" # Room Type Value self.db.location = "" # Room Location self.db.cweather = "" # Room Weather 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 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)
[ "evennia.TICKER_HANDLER.add", "evennia.TICKER_HANDLER.remove", "evennia.utils.inherits_from" ]
[((1055, 1084), 'evennia.utils.inherits_from', 'utils.inherits_from', (['obj', 'Npc'], {}), '(obj, Npc)\n', (1074, 1084), False, 'from evennia import DefaultRoom, utils\n'), ((2634, 2669), 'evennia.utils.inherits_from', 'utils.inherits_from', (['obj', 'Character'], {}), '(obj, Character)\n', (2653, 2669), False, 'from evennia import DefaultRoom, utils\n'), ((3592, 3621), 'evennia.utils.inherits_from', 'utils.inherits_from', (['obj', 'Npc'], {}), '(obj, Npc)\n', (3611, 3621), False, 'from evennia import DefaultRoom, utils\n'), ((1192, 1227), 'evennia.utils.inherits_from', 'utils.inherits_from', (['obj', 'Character'], {}), '(obj, Character)\n', (1211, 1227), False, 'from evennia import DefaultRoom, utils\n'), ((3671, 3700), 'evennia.utils.inherits_from', 'utils.inherits_from', (['obj', 'Mob'], {}), '(obj, Mob)\n', (3690, 3700), False, 'from evennia import DefaultRoom, utils\n'), ((3810, 3845), 'evennia.utils.inherits_from', 'utils.inherits_from', (['obj', 'Character'], {}), '(obj, Character)\n', (3829, 3845), False, 'from evennia import DefaultRoom, utils\n'), ((1435, 1465), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Npc'], {}), '(item, Npc)\n', (1454, 1465), False, 'from evennia import DefaultRoom, utils\n'), ((2872, 2908), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Character'], {}), '(item, Character)\n', (2891, 2908), False, 'from evennia import DefaultRoom, utils\n'), ((1606, 1632), 'evennia.TICKER_HANDLER.add', 'tickerhandler.add', (['item', '(1)'], {}), '(item, 1)\n', (1623, 1632), True, 'from evennia import TICKER_HANDLER as tickerhandler\n'), ((1831, 1867), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Character'], {}), '(item, Character)\n', (1850, 1867), False, 'from evennia import DefaultRoom, utils\n'), ((3141, 3171), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Mob'], {}), '(item, Mob)\n', (3160, 3171), False, 'from evennia import DefaultRoom, utils\n'), ((3954, 3984), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Npc'], {}), '(item, Npc)\n', (3973, 3984), False, 'from evennia import DefaultRoom, utils\n'), ((2110, 2140), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Mob'], {}), '(item, Mob)\n', (2129, 2140), False, 'from evennia import DefaultRoom, utils\n'), ((3327, 3357), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Npc'], {}), '(item, Npc)\n', (3346, 3357), False, 'from evennia import DefaultRoom, utils\n'), ((4072, 4101), 'evennia.TICKER_HANDLER.remove', 'tickerhandler.remove', (['item', '(1)'], {}), '(item, 1)\n', (4092, 4101), True, 'from evennia import TICKER_HANDLER as tickerhandler\n'), ((2305, 2335), 'evennia.utils.inherits_from', 'utils.inherits_from', (['item', 'Npc'], {}), '(item, Npc)\n', (2324, 2335), False, 'from evennia import DefaultRoom, utils\n')]
""" Different classes for running Arx-specific tests, mostly configuring evennia's built-in test framework to work for us. Some minor changes, like having their command tests print out raw strings so we don't need to guess what whitespace characters don't match. """ import re from mock import Mock from evennia.commands.default.tests import CommandTest from evennia.server.sessionhandler import SESSIONS from evennia.utils import ansi, utils from evennia.utils.test_resources import EvenniaTest from typeclasses.characters import Character from typeclasses.accounts import Account from typeclasses.objects import Object from typeclasses.rooms import ArxRoom from typeclasses.exits import Exit # set up signal here since we are not starting the server _RE = re.compile(r"^\+|-+\+|\+-+|--+|\|(?:\s|$)", re.MULTILINE) class ArxTestConfigMixin(object): """ Mixin for configuration of Evennia's test class. It adds a number of attributes we'll use during setUp. """ account_typeclass = Account object_typeclass = Object character_typeclass = Character exit_typeclass = Exit room_typeclass = ArxRoom num_additional_characters = 0 # additional characters for this test BASE_NUM_CHARACTERS = 2 # constant set by Evennia dompc = None dompc2 = None assetowner = None assetowner2 = None roster_entry = None roster_entry2 = None @property def total_num_characters(self): """The total number of characters we'll have for this test""" return self.BASE_NUM_CHARACTERS + self.num_additional_characters def setup_aliases(self): """Setup aliases because the inconsistency drove me crazy""" self.char = self.char1 self.account1 = self.account self.room = self.room1 self.obj = self.obj1 # noinspection PyAttributeOutsideInit def setUp(self): """Run for each testcase""" super(ArxTestConfigMixin, self).setUp() from web.character.models import Roster self.active_roster = Roster.objects.create(name="Active") self.setup_aliases() self.setup_arx_characters() def setup_arx_characters(self): """ Creates any additional characters/accounts and initializes them all. Sets up their roster entries, dominion objects, asset owners, etc. """ if self.num_additional_characters: first_additional = self.BASE_NUM_CHARACTERS + 1 for num in range(first_additional, self.total_num_characters + 1): self.add_character(num) for num in range(1, self.total_num_characters + 1): character = getattr(self, "char%s" % num) account = getattr(self, "account%s" % num) self.setup_character_and_account(character, account, num) def add_character(self, number): """Creates another character/account of the given number""" from evennia.utils import create setattr(self, "account%s" % number, create.create_account("TestAccount%s" % number, email="<EMAIL>", password="<PASSWORD>", typeclass=self.account_typeclass)) setattr(self, "char%s" % number, create.create_object(self.character_typeclass, key="Char%s" % number, location=self.room1, home=self.room1)) def setup_character_and_account(self, character, account, num=""): """Sets up a character/account combo with RosterEntry, dompc, etc.""" from world.dominion.setup_utils import setup_dom_for_player, setup_assets # the attributes that are for 1 don't have a number if num == 1: num = "" num = str(num) setattr(self, 'dompc%s' % num, setup_dom_for_player(account)) setattr(self, "assetowner%s" % num, setup_assets(getattr(self, "dompc%s" % num), 0)) setattr(self, "roster_entry%s" % num, self.active_roster.entries.create(player=getattr(self, "account%s" % num), character=getattr(self, "char%s" % num))) @property def fake_datetime(self): import datetime return datetime.datetime(1978, 8, 27, 12, 8, 0) class ArxTest(ArxTestConfigMixin, EvenniaTest): pass class ArxCommandTest(ArxTestConfigMixin, CommandTest): """ child of Evennia's CommandTest class specifically for Arx. We'll add some objects that our characters/players would be expected to have for any particular test. """ cmd_class = None caller = None def setup_cmd(self, cmd_cls, caller): self.cmd_class = cmd_cls self.caller = caller def call_cmd(self, args, msg, **kwargs): self.call(self.cmd_class(), args, msg, caller=self.caller, **kwargs) # noinspection PyBroadException def call(self, cmdobj, args, msg=None, cmdset=None, noansi=True, caller=None, receiver=None, cmdstring=None, obj=None): """ Test a command by assigning all the needed properties to cmdobj and running cmdobj.at_pre_cmd() cmdobj.parse() cmdobj.func() cmdobj.at_post_cmd() The msgreturn value is compared to eventual output sent to caller.msg in the game Returns: msg (str): The received message that was sent to the caller. """ caller = caller if caller else self.char1 receiver = receiver if receiver else caller cmdobj.caller = caller cmdobj.cmdstring = cmdstring if cmdstring else cmdobj.key cmdobj.args = args cmdobj.cmdset = cmdset cmdobj.session = SESSIONS.session_from_sessid(1) cmdobj.account = self.account cmdobj.raw_string = cmdobj.key + " " + args cmdobj.obj = obj or (caller if caller else self.char1) # test old_msg = receiver.msg try: receiver.msg = Mock() if cmdobj.at_pre_cmd(): return cmdobj.parse() cmdobj.func() cmdobj.at_post_cmd() except Exception: import traceback receiver.msg(traceback.format_exc()) finally: # clean out prettytable sugar. We only operate on text-type stored_msg = [args[0] if args and args[0] else kwargs.get("text", utils.to_str(kwargs, force_string=True)) for name, args, kwargs in receiver.msg.mock_calls] # Get the first element of a tuple if msg received a tuple instead of a string stored_msg = [smsg[0] if hasattr(smsg, '__iter__') else smsg for smsg in stored_msg] if msg is not None: returned_msg = self.format_returned_msg(stored_msg, noansi) if msg == "" and returned_msg or returned_msg != msg.strip(): sep1 = "\n" + "="*30 + "Wanted message" + "="*34 + "\n" sep2 = "\n" + "="*30 + "Returned message" + "="*32 + "\n" sep3 = "\n" + "="*78 # important - use raw strings for wanted/returned messages so we can see whitespace retval = "%s%r%s%r%s" % (sep1, msg.strip(), sep2, returned_msg, sep3) raise AssertionError(retval) else: returned_msg = "\n".join(str(msg) for msg in stored_msg) returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=noansi).strip() receiver.msg = old_msg return returned_msg @staticmethod def format_returned_msg(stored_msg, no_ansi): """ Formats the stored_msg list into a single string joined by separators Args: stored_msg: list of strings that have been sent to our receiver no_ansi: whether to strip ansi or not Returns: A string joined by | for each substring in stored_msg. Ansi will be stripped if no_ansi is specified. """ returned_msg = "||".join(_RE.sub("", str(mess)) for mess in stored_msg) returned_msg = ansi.parse_ansi(returned_msg, strip_ansi=no_ansi).strip() return returned_msg class TestEquipmentMixins(object): """ Creation of Wearable and Wieldable items used for testing commands. """ def setUp(self): super(TestEquipmentMixins, self).setUp() from evennia.utils import create from typeclasses.wearable.wearable import Wearable, WearableContainer from typeclasses.disguises.disguises import Mask from typeclasses.wearable.wieldable import Wieldable from typeclasses.wearable.decorative_weapon import DecorativeWieldable from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType wearable_typeclass = Wearable purse_typeclass = WearableContainer weapon_typeclass = Wieldable hairpin_typeclass = DecorativeWieldable mask_typeclass = Mask self.org = Organization.objects.create(name="Orgtest") AssetOwner.objects.create(organization_owner=self.org) self.org.members.create(player=self.dompc) self.mat1 = CraftingMaterialType.objects.create(name="Mat1", value=100) self.recipe1 = CraftingRecipe.objects.create(name="Top 1 Slot", primary_amount=5, level=5, result="slot:chest;slot_limit:1;baseval:1;penalty:2") self.recipe2 = CraftingRecipe.objects.create(name="Top 2 Slot", primary_amount=6, level=6, result="slot:chest;slot_limit:2") self.recipe3 = CraftingRecipe.objects.create(name="Bag", primary_amount=5, level=5, result="slot:bag;slot_limit:2;baseval:40") self.recipe4 = CraftingRecipe.objects.create(name="Small Weapon", primary_amount=4, level=4, result="baseval:1;weapon_skill:small wpn") self.recipe5 = CraftingRecipe.objects.create(name="Hairpins", primary_amount=4, level=4, result="slot:hair;slot_limit:2;baseval:4;") self.recipe6 = CraftingRecipe.objects.create(name="Mask", primary_amount=4, level=4, result="slot:face;slot_limit:1;fashion_mult:6") self.recipe7 = CraftingRecipe.objects.create(name="Medium Weapon", primary_amount=4, level=4, result="baseval:5") recipes = (self.recipe1, self.recipe2, self.recipe3, self.recipe4, self.recipe5, self.recipe6, self.recipe7) for recipe in recipes: recipe.primary_materials.add(self.mat1) # Top1 is a wearable object with no recipe or crafter designated self.top1 = create.create_object(wearable_typeclass, key="Top1", location=self.room1, home=self.room1) self.top1.db.quality_level = 6 # Top2 is a 1-slot_limit chest Wearable made by non-staff char2 self.top2 = create.create_object(wearable_typeclass, key="Top2", location=self.char2, home=self.room1) self.top2.db.quality_level = 6 self.top2.db.recipe = 1 self.top2.db.crafted_by = self.char2 # Slinkity1 is chest 2-slot_limit, so can stack once with chest-wearables. Also has adorns self.catsuit1 = create.create_object(wearable_typeclass, key="Slinkity1", location=self.char2, home=self.room1) self.catsuit1.db.quality_level = 11 self.catsuit1.db.recipe = 2 self.catsuit1.db.crafted_by = self.char2 self.catsuit1.db.adorns = {1: 200} # Purse1 is a wearable container; baseval is their capacity self.purse1 = create.create_object(purse_typeclass, key="Purse1", location=self.char2, home=self.room1) self.purse1.db.quality_level = 4 self.purse1.db.recipe = 3 self.purse1.db.crafted_by = self.char2 # Imps leer when they lick a knife self.knife1 = create.create_object(weapon_typeclass, key="Lickyknife1", location=self.char2, home=self.room1) self.knife1.db.quality_level = 11 self.knife1.db.recipe = 4 self.knife1.db.crafted_by = self.char2 self.knife1.db.attack_skill = self.knife1.recipe.resultsdict.get("weapon_skill", "medium wpn") # A larger weapon self.sword1 = create.create_object(weapon_typeclass, key="Sword1", location=self.char2, home=self.room1) self.sword1.db.quality_level = 6 self.sword1.db.recipe = 7 self.sword1.db.crafted_by = self.char2 self.sword1.db.attack_skill = self.sword1.recipe.resultsdict.get("weapon_skill", "medium wpn") # Hairpins1 is a decorative weapon and should always show as 'worn' rather than 'sheathed' self.hairpins1 = create.create_object(hairpin_typeclass, key="Hairpins1", location=self.char2, home=self.room1) self.hairpins1.db.quality_level = 4 self.hairpins1.db.recipe = 5 self.hairpins1.db.crafted_by = self.char2 self.hairpins1.db.attack_skill = self.hairpins1.recipe.resultsdict.get("weapon_skill", "small wpn") # Masks change wearer identity and are restricted from being worn by 0 quality self.mask1 = create.create_object(mask_typeclass, key="A Fox Mask", location=self.char2, home=self.room1) self.mask1.db.quality_level = 0 self.mask1.db.recipe = 6 # mask also has fashion_mult:6 self.mask1.db.crafted_by = self.char2 self.mask1.db.maskdesc = "A very Slyyyy Fox..." self.mask1.db.adorns = {1: 20} def start_ze_fight(self): """Helper to start a fight and add the current caller.""" from commands.cmdsets import combat fight = combat.start_fight_at_room(self.room1) fight.add_combatant(self.caller) return fight def create_ze_outfit(self, name): """Helper to create an outfit from current caller's equipped stuff.""" from world.fashion.models import FashionOutfit as Outfit outfit = Outfit.objects.create(name=name, owner=self.caller.dompc) worn = list(self.caller.worn) weapons = list(self.caller.wielded) + list(self.caller.sheathed) for weapon in weapons: slot = "primary weapon" if weapon.is_wielded else "sheathed weapon" outfit.add_fashion_item(item=weapon, slot=slot) for item in worn: outfit.add_fashion_item(item=item) return outfit
[ "evennia.server.sessionhandler.SESSIONS.session_from_sessid", "evennia.utils.utils.to_str", "evennia.utils.ansi.parse_ansi", "evennia.utils.create.create_object", "evennia.utils.create.create_account" ]
[((763, 824), 're.compile', 're.compile', (['"""^\\\\+|-+\\\\+|\\\\+-+|--+|\\\\|(?:\\\\s|$)"""', 're.MULTILINE'], {}), "('^\\\\+|-+\\\\+|\\\\+-+|--+|\\\\|(?:\\\\s|$)', re.MULTILINE)\n", (773, 824), False, 'import re\n'), ((2037, 2073), 'web.character.models.Roster.objects.create', 'Roster.objects.create', ([], {'name': '"""Active"""'}), "(name='Active')\n", (2058, 2073), False, 'from web.character.models import Roster\n'), ((4216, 4256), 'datetime.datetime', 'datetime.datetime', (['(1978)', '(8)', '(27)', '(12)', '(8)', '(0)'], {}), '(1978, 8, 27, 12, 8, 0)\n', (4233, 4256), False, 'import datetime\n'), ((5710, 5741), 'evennia.server.sessionhandler.SESSIONS.session_from_sessid', 'SESSIONS.session_from_sessid', (['(1)'], {}), '(1)\n', (5738, 5741), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((9052, 9095), 'world.dominion.models.Organization.objects.create', 'Organization.objects.create', ([], {'name': '"""Orgtest"""'}), "(name='Orgtest')\n", (9079, 9095), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((9104, 9158), 'world.dominion.models.AssetOwner.objects.create', 'AssetOwner.objects.create', ([], {'organization_owner': 'self.org'}), '(organization_owner=self.org)\n', (9129, 9158), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((9230, 9289), 'world.dominion.models.CraftingMaterialType.objects.create', 'CraftingMaterialType.objects.create', ([], {'name': '"""Mat1"""', 'value': '(100)'}), "(name='Mat1', value=100)\n", (9265, 9289), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((9313, 9446), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Top 1 Slot"""', 'primary_amount': '(5)', 'level': '(5)', 'result': '"""slot:chest;slot_limit:1;baseval:1;penalty:2"""'}), "(name='Top 1 Slot', primary_amount=5, level=5,\n result='slot:chest;slot_limit:1;baseval:1;penalty:2')\n", (9342, 9446), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((9572, 9685), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Top 2 Slot"""', 'primary_amount': '(6)', 'level': '(6)', 'result': '"""slot:chest;slot_limit:2"""'}), "(name='Top 2 Slot', primary_amount=6, level=6,\n result='slot:chest;slot_limit:2')\n", (9601, 9685), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((9811, 9927), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Bag"""', 'primary_amount': '(5)', 'level': '(5)', 'result': '"""slot:bag;slot_limit:2;baseval:40"""'}), "(name='Bag', primary_amount=5, level=5, result\n ='slot:bag;slot_limit:2;baseval:40')\n", (9840, 9927), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((10052, 10177), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Small Weapon"""', 'primary_amount': '(4)', 'level': '(4)', 'result': '"""baseval:1;weapon_skill:small wpn"""'}), "(name='Small Weapon', primary_amount=4, level=\n 4, result='baseval:1;weapon_skill:small wpn')\n", (10081, 10177), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((10302, 10423), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Hairpins"""', 'primary_amount': '(4)', 'level': '(4)', 'result': '"""slot:hair;slot_limit:2;baseval:4;"""'}), "(name='Hairpins', primary_amount=4, level=4,\n result='slot:hair;slot_limit:2;baseval:4;')\n", (10331, 10423), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((10549, 10670), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Mask"""', 'primary_amount': '(4)', 'level': '(4)', 'result': '"""slot:face;slot_limit:1;fashion_mult:6"""'}), "(name='Mask', primary_amount=4, level=4,\n result='slot:face;slot_limit:1;fashion_mult:6')\n", (10578, 10670), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((10796, 10899), 'world.dominion.models.CraftingRecipe.objects.create', 'CraftingRecipe.objects.create', ([], {'name': '"""Medium Weapon"""', 'primary_amount': '(4)', 'level': '(4)', 'result': '"""baseval:5"""'}), "(name='Medium Weapon', primary_amount=4, level\n =4, result='baseval:5')\n", (10825, 10899), False, 'from world.dominion.models import Organization, AssetOwner, CraftingRecipe, CraftingMaterialType\n'), ((11313, 11407), 'evennia.utils.create.create_object', 'create.create_object', (['wearable_typeclass'], {'key': '"""Top1"""', 'location': 'self.room1', 'home': 'self.room1'}), "(wearable_typeclass, key='Top1', location=self.room1,\n home=self.room1)\n", (11333, 11407), False, 'from evennia.utils import create\n'), ((11535, 11629), 'evennia.utils.create.create_object', 'create.create_object', (['wearable_typeclass'], {'key': '"""Top2"""', 'location': 'self.char2', 'home': 'self.room1'}), "(wearable_typeclass, key='Top2', location=self.char2,\n home=self.room1)\n", (11555, 11629), False, 'from evennia.utils import create\n'), ((11906, 12006), 'evennia.utils.create.create_object', 'create.create_object', (['wearable_typeclass'], {'key': '"""Slinkity1"""', 'location': 'self.char2', 'home': 'self.room1'}), "(wearable_typeclass, key='Slinkity1', location=self.\n char2, home=self.room1)\n", (11926, 12006), False, 'from evennia.utils import create\n'), ((12305, 12398), 'evennia.utils.create.create_object', 'create.create_object', (['purse_typeclass'], {'key': '"""Purse1"""', 'location': 'self.char2', 'home': 'self.room1'}), "(purse_typeclass, key='Purse1', location=self.char2,\n home=self.room1)\n", (12325, 12398), False, 'from evennia.utils import create\n'), ((12625, 12725), 'evennia.utils.create.create_object', 'create.create_object', (['weapon_typeclass'], {'key': '"""Lickyknife1"""', 'location': 'self.char2', 'home': 'self.room1'}), "(weapon_typeclass, key='Lickyknife1', location=self.\n char2, home=self.room1)\n", (12645, 12725), False, 'from evennia.utils import create\n'), ((13038, 13132), 'evennia.utils.create.create_object', 'create.create_object', (['weapon_typeclass'], {'key': '"""Sword1"""', 'location': 'self.char2', 'home': 'self.room1'}), "(weapon_typeclass, key='Sword1', location=self.char2,\n home=self.room1)\n", (13058, 13132), False, 'from evennia.utils import create\n'), ((13521, 13620), 'evennia.utils.create.create_object', 'create.create_object', (['hairpin_typeclass'], {'key': '"""Hairpins1"""', 'location': 'self.char2', 'home': 'self.room1'}), "(hairpin_typeclass, key='Hairpins1', location=self.\n char2, home=self.room1)\n", (13541, 13620), False, 'from evennia.utils import create\n'), ((14009, 14105), 'evennia.utils.create.create_object', 'create.create_object', (['mask_typeclass'], {'key': '"""A Fox Mask"""', 'location': 'self.char2', 'home': 'self.room1'}), "(mask_typeclass, key='A Fox Mask', location=self.char2,\n home=self.room1)\n", (14029, 14105), False, 'from evennia.utils import create\n'), ((14547, 14585), 'commands.cmdsets.combat.start_fight_at_room', 'combat.start_fight_at_room', (['self.room1'], {}), '(self.room1)\n', (14573, 14585), False, 'from commands.cmdsets import combat\n'), ((14848, 14905), 'world.fashion.models.FashionOutfit.objects.create', 'Outfit.objects.create', ([], {'name': 'name', 'owner': 'self.caller.dompc'}), '(name=name, owner=self.caller.dompc)\n', (14869, 14905), True, 'from world.fashion.models import FashionOutfit as Outfit\n'), ((3020, 3146), 'evennia.utils.create.create_account', 'create.create_account', (["('TestAccount%s' % number)"], {'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""', 'typeclass': 'self.account_typeclass'}), "('TestAccount%s' % number, email='<EMAIL>', password=\n '<PASSWORD>', typeclass=self.account_typeclass)\n", (3041, 3146), False, 'from evennia.utils import create\n'), ((3238, 3349), 'evennia.utils.create.create_object', 'create.create_object', (['self.character_typeclass'], {'key': "('Char%s' % number)", 'location': 'self.room1', 'home': 'self.room1'}), "(self.character_typeclass, key='Char%s' % number,\n location=self.room1, home=self.room1)\n", (3258, 3349), False, 'from evennia.utils import create\n'), ((3780, 3809), 'world.dominion.setup_utils.setup_dom_for_player', 'setup_dom_for_player', (['account'], {}), '(account)\n', (3800, 3809), False, 'from world.dominion.setup_utils import setup_dom_for_player, setup_assets\n'), ((5981, 5987), 'mock.Mock', 'Mock', ([], {}), '()\n', (5985, 5987), False, 'from mock import Mock\n'), ((8134, 8183), 'evennia.utils.ansi.parse_ansi', 'ansi.parse_ansi', (['returned_msg'], {'strip_ansi': 'no_ansi'}), '(returned_msg, strip_ansi=no_ansi)\n', (8149, 8183), False, 'from evennia.utils import ansi, utils\n'), ((6213, 6235), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (6233, 6235), False, 'import traceback\n'), ((6404, 6443), 'evennia.utils.utils.to_str', 'utils.to_str', (['kwargs'], {'force_string': '(True)'}), '(kwargs, force_string=True)\n', (6416, 6443), False, 'from evennia.utils import ansi, utils\n'), ((7456, 7504), 'evennia.utils.ansi.parse_ansi', 'ansi.parse_ansi', (['returned_msg'], {'strip_ansi': 'noansi'}), '(returned_msg, strip_ansi=noansi)\n', (7471, 7504), False, 'from evennia.utils import ansi, utils\n')]
# this is an optimized version only available in later Django versions from unittest import TestCase from evennia.scripts.models import ScriptDB, ObjectDoesNotExist from evennia.utils.create import create_script from evennia.scripts.scripts import DoNothing class TestScriptDB(TestCase): "Check the singleton/static ScriptDB object works correctly" def setUp(self): self.scr = create_script(DoNothing) def tearDown(self): try: self.scr.delete() except ObjectDoesNotExist: pass del self.scr def test_delete(self): "Check the script is removed from the database" self.scr.delete() self.assertFalse(self.scr in ScriptDB.objects.get_all_scripts()) def test_double_delete(self): "What should happen? Isn't it already deleted?" with self.assertRaises(ObjectDoesNotExist): self.scr.delete() self.scr.delete() def test_deleted_script_fails_start(self): "Would it ever be necessary to start a deleted script?" self.scr.delete() with self.assertRaises(ObjectDoesNotExist): # See issue #509 self.scr.start() # Check the script is not recreated as a side-effect self.assertFalse(self.scr in ScriptDB.objects.get_all_scripts()) def test_deleted_script_is_invalid(self): "Can deleted scripts be said to be valid?" self.scr.delete() self.assertFalse(self.scr.is_valid()) # assertRaises? See issue #509
[ "evennia.utils.create.create_script", "evennia.scripts.models.ScriptDB.objects.get_all_scripts" ]
[((395, 419), 'evennia.utils.create.create_script', 'create_script', (['DoNothing'], {}), '(DoNothing)\n', (408, 419), False, 'from evennia.utils.create import create_script\n'), ((708, 742), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts', 'ScriptDB.objects.get_all_scripts', ([], {}), '()\n', (740, 742), False, 'from evennia.scripts.models import ScriptDB, ObjectDoesNotExist\n'), ((1282, 1316), 'evennia.scripts.models.ScriptDB.objects.get_all_scripts', 'ScriptDB.objects.get_all_scripts', ([], {}), '()\n', (1314, 1316), False, 'from evennia.scripts.models import ScriptDB, ObjectDoesNotExist\n')]
""" Account (OOC) commands. These are stored on the Account object and self.caller is thus always an Account, not a Character. """ import datetime, re from django.conf import settings from evennia.commands.default.account import CmdOption as DefaultOption from evennia.server.sessionhandler import SESSIONS from evennia.utils import logger, utils from commands.command import Command from server.conf.settings import SERVERNAME from server.utils.colors import pick_color, show_colors from server.utils.utils import get_sw class CmdAccess(Command): """ Syntax: access Show your current game access. """ key = "access" locks = "cmd:all()" help_category = "Out of Character" arg_regex = r"$" def func(self): caller = self.caller hierarchy_full = settings.PERMISSION_HIERARCHY string = "\n|w Permission Hierarchy|n (climbing):\n %s" % ", ".join(hierarchy_full) if self.caller.account.is_superuser: cperms = "<Superuser>" pperms = "<Superuser>" else: cperms = ", ".join(caller.permissions.all()) pperms = ", ".join(caller.account.permissions.all()) string += "\n\n|w Your access|n:" string += "\n Character |c%s|n: %s" % (caller.key, cperms) if hasattr(caller, "account"): string += "\n Account |c%s|n: %s" % (caller.account.key, pperms) caller.msg(string) class CmdAlias(Command): """ Syntax: alias alias <alias> alias <alias> <replacement> Example: alias - List all aliases. alias <alias> - Check a specific alias. alias <alias> <replacement> - Define a new alias. Define personal aliases by assigning a string to match and replace another. Use unalias command to remove aliases. """ key = "alias" locks = "cmd:all()" help_category = "Out of Character" arg_regex = r"\s*|$" def parse(self): self.args = self.args.strip() self.alias = None self.replace = None match = re.match(r"^(\S+)(.*)$", self.args) if match is not None: self.alias = match.group(1) self.replace = match.group(2).strip() def func(self): caller = self.caller alias = self.alias replace = self.replace def _cy(string): "add color to the special markers" return re.sub(r"(\$[0-9]+|\*|\?|\[.+?\])", r"|Y\1|n", string) # Gather Aliases nicklist = ( utils.make_iter(caller.nicks.get(category="inputline", return_obj=True) or []) ) #check all aliases if not alias: if not nicklist: caller.msg("No aliases defined.") return table = self.styled_table("#", "Alias", "Replacement") for inum, nickobj in enumerate(nicklist): _, _, nickvalue, replacement = nickobj.value table.add_row( str(inum+1), _cy(nickvalue), _cy(replacement) ) string = "|wDefined Aliases:|n\n%s" % table caller.msg(string) #check one alias elif alias and not replace: strings = [] aliases = utils.make_iter(caller.nicks.get(return_obj=True)) for ali in aliases: _, _, nick, repl = ali.value if nick.startswith(alias): strings.append( "{}: {}".format(nick, repl) ) if strings: caller.msg("\n".join(strings)) else: caller.msg("No aliases matching '{}'.".format(alias)) #Alias != replacement elif alias == replace: caller.msg("No point in setting an alias as the string to replace...") #New alias else: string = "" #Check for pre-existing alias to update oldalias = caller.nicks.get(key=alias, return_obj=True) if oldalias: #Update old alias _, _, old_alias, old_replstring = oldalias.value if replace == old_replstring: string += "\nIdentical alias already set." else: string += "\nUpdated alias '%s' to '%s'." % ( alias, replace ) #Create new alias else: string += "\nAdded alias '%s' as '%s'." % ( alias, replace ) #Attempt Update/Creation try: caller.nicks.add(alias, replace) except Exception: caller.msg("Error: Alias failed.") return caller.msg(_cy(string)) class CmdColors(Command): """ Syntax: color colors color <color/code> colors <short/long> Examples: color red - display red and usage code. color 300 - display color associated with RGB value 300. colors short - display ASCII color table. colors long - display XTERM256 color table. (default) RGB values scale (000 - 555) where the first digit indicates red value, the second corresponds to green, and the final digit represents blue. These numbers cannot exceed five. As a rule of thumb, lower numbers will display a darker color whereas higher numbers will give brighter results. Making all the numbers equal (111, 222, 333, 444, 555) will result in black, a shade of gray, or white. When choosing a color, please be cognizant of readability. While all colors are available for use, the darker colors are often difficult to view and should be avoided when possible. """ key = "colors" aliases = ['color'] locks = "cmd:all()" help_category = "Out of Character" def func(self): caller = self.caller args = self.args.strip() #Standalone command if not args or args in ("long", "xterm"): caller.msg(show_colors("xterm")) return color = args.lower() #Displaying singular color if self.cmdstring == "color": #We don't like the invisible colors here. if args in ("000", "abyss"): color = "black" code, color = pick_color(caller, color) caller.msg(f"|{code}{color.capitalize()} ({code})|n") return #Displaying Colors if args in ("ascii", "short"): caller.msg(show_colors("ascii")) return class CmdOption(DefaultOption): """ Syntax: option <name=value> option/save Examples: option <name=value> - Change a value option/save - Save values for next login This command allows for the viewing and setting of client interface settings. Note that saved options may not be able to be used later when connecting with a different client. """ key = "option" locks = "cmd:all()" help_category = "Out of Character" def func(self): super().func() self.caller.msg(prompt='> ') class CmdPassword(Command): """ Syntax: password Change your password. Pick a safe one. """ key = "password" locks = "cmd:pperm(Player)" help_category = "Out of Character" account_caller = True def func(self): account = self.account oldpass = yield("Enter your old password: ").strip() newpass = yield("Enter your new password: ").strip() validated, error = account.validate_password(newpass) if not account.check_password(oldpass): self.msg("Old password incorrect.") elif not validated: errors = [e for suberror in error.messages for e in error.messages] string = "\n".join(errors) self.msg(string) else: account.set_password(newpass) account.save() self.msg("Password changed.") logger.log_sec( "Password Changed: %s (Caller: %s, IP: %s)." % (account, account, self.session.address) ) class CmdQuit(Command): """ Syntax: quit Quit the game and gracefully disconnect from the server. """ key = "quit" locks = "cmd:all()" help_category = "Out of Character" account_caller = True def func(self): account = self.account account.msg("|RQuitting|n. See you soon!", session=self.session) account.disconnect_session_from_account(self.session) class CmdUnalias(Command): """ Syntax: unalias <alias> Remove personal alias. Use alias command to create aliases. """ key = "unalias" locks = "cmd:all()" help_category = "Out of Character" def func(self): caller = self.caller args = self.args.strip() nicklist = ( utils.make_iter(caller.nicks.get(category="inputline", return_obj=True) or []) ) if not args: caller.msg("Syntax: unalias <alias>") return if not nicklist: caller.msg("No aliases defined.") return oldaliases = [] #See if number was given arg = args.lstrip("#") if arg.isdigit(): #We are given alias digit delindex = int(arg) if 0 < delindex <= len(nicklist): oldaliases.append(nicklist[delindex -1]) else: caller.msg("Not a valid alias index.") return else: oldaliases.append(caller.nicks.get(arg, return_obj=True)) if oldaliases: for oldalias in oldaliases: _, _, old_alias, old_repl = oldalias.value caller.nicks.remove(old_alias) caller.msg("Removed '%s' alias." % old_alias) else: caller.msg("No matching aliases to remove.") return class CmdWho(Command): """ Syntax: who Show who is currently online. """ key = "who" locks = "cmd:all()" help_category = "Out of Character" account_caller = True def func(self): account = self.account screen_width = get_sw(account) #poll sessions session_list = SESSIONS.get_sessions() session_list = sorted(session_list, key=lambda o: o.account.key) time = datetime.datetime.now() year = str(int(time.strftime("%Y"))) dmdy = (time.strftime("%A, %B %d, ") + year).center(screen_width-2, " ") hms = (time.strftime("%H:%M:%S")).center(screen_width-2, " ") a_len = len(f" [ {SERVERNAME} ] ") a_seps = "-" * int((screen_width - a_len) / 2 - 2) a_color = "|134" jake_len = len("Jake - Administrator") jake_seps = " " * int((screen_width - jake_len) / 2 - 3) staff_len = len(" [ Staff ] ") staff_seps = "-" * int((screen_width - staff_len) / 2 - 2) staff_color = "|232" players_len = len(" [ Players ] ") players_seps = "-" * int((screen_width - players_len) / 2 - 2) players_color = "|323" string = f" {a_seps} [{a_color} {SERVERNAME}|n ] {a_seps}|n\n\n" \ f"{dmdy}\n" \ f"{hms}\n\n" \ f" {staff_seps} [{staff_color} Staff|n ] {staff_seps}|n\n\n" \ f" {jake_seps} Jake - |rAdministrator|n {jake_seps}|n\n\n" \ f" {players_seps} [{players_color} Players|n ] {players_seps}|n\n" account.msg(string) char_list = [] for session in session_list: if not session.logged_in: continue account = session.get_account() if account.is_superuser \ or account.permissions.get("Developer") \ or account.permissions.get("Admin") \ or account.permissions.get("Builder"): continue char_list.append(account.name) for char in sorted(char_list): self.msg(" " * int((screen_width) / 8 - 2) + f"{char}") #self.msg(f"|n {char}") char_count = len(char_list) if char_count < 1: string = f"There are {char_count} people in {SERVERNAME}." elif char_count == 1: string = f"There is {char_count} person in {SERVERNAME}." else: string = f"There are no people in {SERVERNAME}." string = string.rjust(screen_width-4, " ") self.msg(string)
[ "evennia.utils.logger.log_sec", "evennia.server.sessionhandler.SESSIONS.get_sessions" ]
[((2112, 2147), 're.match', 're.match', (['"""^(\\\\S+)(.*)$"""', 'self.args'], {}), "('^(\\\\S+)(.*)$', self.args)\n", (2120, 2147), False, 'import datetime, re\n'), ((10504, 10519), 'server.utils.utils.get_sw', 'get_sw', (['account'], {}), '(account)\n', (10510, 10519), False, 'from server.utils.utils import get_sw\n'), ((10567, 10590), 'evennia.server.sessionhandler.SESSIONS.get_sessions', 'SESSIONS.get_sessions', ([], {}), '()\n', (10588, 10590), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((10680, 10703), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10701, 10703), False, 'import datetime, re\n'), ((2468, 2526), 're.sub', 're.sub', (['"""(\\\\$[0-9]+|\\\\*|\\\\?|\\\\[.+?\\\\])"""', '"""|Y\\\\1|n"""', 'string'], {}), "('(\\\\$[0-9]+|\\\\*|\\\\?|\\\\[.+?\\\\])', '|Y\\\\1|n', string)\n", (2474, 2526), False, 'import datetime, re\n'), ((6567, 6592), 'server.utils.colors.pick_color', 'pick_color', (['caller', 'color'], {}), '(caller, color)\n', (6577, 6592), False, 'from server.utils.colors import pick_color, show_colors\n'), ((6269, 6289), 'server.utils.colors.show_colors', 'show_colors', (['"""xterm"""'], {}), "('xterm')\n", (6280, 6289), False, 'from server.utils.colors import pick_color, show_colors\n'), ((6776, 6796), 'server.utils.colors.show_colors', 'show_colors', (['"""ascii"""'], {}), "('ascii')\n", (6787, 6796), False, 'from server.utils.colors import pick_color, show_colors\n'), ((8267, 8374), 'evennia.utils.logger.log_sec', 'logger.log_sec', (["('Password Changed: %s (Caller: %s, IP: %s).' % (account, account, self.\n session.address))"], {}), "('Password Changed: %s (Caller: %s, IP: %s).' % (account,\n account, self.session.address))\n", (8281, 8374), False, 'from evennia.utils import logger, utils\n')]
from django import template from django.utils.safestring import mark_safe from evennia.utils.ansi import parse_ansi register = template.Library() @register.filter def mush_to_html(value): if not value: return value value = value.replace("&", "&amp") value = value.replace("<", "&lt") value = value.replace(">", "&gt") value = value.replace("%r", "<br>") value = value.replace("%R", "<br>") value = value.replace("\n", "<br>") value = value.replace("%b", " ") value = value.replace("%t", "&nbsp&nbsp&nbsp&nbsp") value = value.replace("|/", "<br>") value = value.replace("{/", "<br>") value = parse_ansi(value, strip_ansi=True) return mark_safe(value) @register.filter def doc_str(value): return value.__doc__ @register.filter def date_from_header(header): """ When given a Msg object's header, extract and return IC date Args: header: str Returns: str: IC date of the header """ hlist = header.split(";") keyvalpairs = [pair.split(":") for pair in hlist] keydict = { pair[0].strip(): pair[1].strip() for pair in keyvalpairs if len(pair) == 2 } date = keydict.get("date", None) return date
[ "evennia.utils.ansi.parse_ansi" ]
[((132, 150), 'django.template.Library', 'template.Library', ([], {}), '()\n', (148, 150), False, 'from django import template\n'), ((671, 705), 'evennia.utils.ansi.parse_ansi', 'parse_ansi', (['value'], {'strip_ansi': '(True)'}), '(value, strip_ansi=True)\n', (681, 705), False, 'from evennia.utils.ansi import parse_ansi\n'), ((718, 734), 'django.utils.safestring.mark_safe', 'mark_safe', (['value'], {}), '(value)\n', (727, 734), False, 'from django.utils.safestring import mark_safe\n')]
""" TutorialWorld - basic objects - Griatch 2011 This module holds all "dead" object definitions for the tutorial world. Object-commands and -cmdsets are also defined here, together with the object. Objects: TutorialObject Readable Climbable Obelisk LightSource CrumblingWall Weapon WeaponRack """ import random from evennia import DefaultObject, DefaultExit, Command, CmdSet from evennia import utils from evennia.utils import search from evennia.utils.spawner import spawn #------------------------------------------------------------ # # TutorialObject # # The TutorialObject is the base class for all items # in the tutorial. They have an attribute "tutorial_info" # on them that the global tutorial command can use to extract # interesting behind-the scenes information about the object. # # TutorialObjects may also be "reset". What the reset means # is up to the object. It can be the resetting of the world # itself, or the removal of an inventory item from a # character's inventory when leaving the tutorial, for example. # #------------------------------------------------------------ class TutorialObject(DefaultObject): """ This is the baseclass for all objects in the tutorial. """ def at_object_creation(self): "Called when the object is first created." super(TutorialObject, self).at_object_creation() self.db.tutorial_info = "No tutorial info is available for this object." def reset(self): "Resets the object, whatever that may mean." self.location = self.home #------------------------------------------------------------ # # Readable - an object that can be "read" # #------------------------------------------------------------ # # Read command # class CmdRead(Command): """ Usage: read [obj] Read some text of a readable object. """ key = "read" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): """ Implements the read command. This simply looks for an Attribute "readable_text" on the object and displays that. """ if self.args: obj = self.caller.search(self.args.strip()) else: obj = self.obj if not obj: return # we want an attribute read_text to be defined. readtext = obj.db.readable_text if readtext: string = "You read {C%s{n:\n %s" % (obj.key, readtext) else: string = "There is nothing to read on %s." % obj.key self.caller.msg(string) class CmdSetReadable(CmdSet): """ A CmdSet for readables. """ def at_cmdset_creation(self): """ Called when the cmdset is created. """ self.add(CmdRead()) class Readable(TutorialObject): """ This simple object defines some attributes and """ def at_object_creation(self): """ Called when object is created. We make sure to set the needed Attribute and add the readable cmdset. """ super(Readable, self).at_object_creation() self.db.tutorial_info = "This is an object with a 'read' command defined in a command set on itself." self.db.readable_text = "There is no text written on %s." % self.key # define a command on the object. self.cmdset.add_default(CmdSetReadable, permanent=True) #------------------------------------------------------------ # # Climbable object # # The climbable object works so that once climbed, it sets # a flag on the climber to show that it was climbed. A simple # command 'climb' handles the actual climbing. The memory # of what was last climbed is used in a simple puzzle in the # tutorial. # #------------------------------------------------------------ class CmdClimb(Command): """ Climb an object Usage: climb <object> This allows you to climb. """ key = "climb" locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implements function" if not self.args: self.caller.msg("What do you want to climb?") return obj = self.caller.search(self.args.strip()) if not obj: return if obj != self.obj: self.caller.msg("Try as you might, you cannot climb that.") return ostring = self.obj.db.climb_text if not ostring: ostring = "You climb %s. Having looked around, you climb down again." % self.obj.name self.caller.msg(ostring) # set a tag on the caller to remember that we climbed. self.caller.tags.add("tutorial_climbed_tree", category="tutorial_world") class CmdSetClimbable(CmdSet): "Climbing cmdset" def at_cmdset_creation(self): "populate set" self.add(CmdClimb()) class Climbable(TutorialObject): """ A climbable object. All that is special about it is that it has the "climb" command available on it. """ def at_object_creation(self): "Called at initial creation only" self.cmdset.add_default(CmdSetClimbable, permanent=True) #------------------------------------------------------------ # # Obelisk - a unique item # # The Obelisk is an object with a modified return_appearance method # that causes it to look slightly different every time one looks at it. # Since what you actually see is a part of a game puzzle, the act of # looking also stores a key attribute on the looking object (different # depending on which text you saw) for later reference. # #------------------------------------------------------------ class Obelisk(TutorialObject): """ This object changes its description randomly, and which is shown determines which order "clue id" is stored on the Character for future puzzles. Important Attribute: puzzle_descs (list): list of descriptions. One of these is picked randomly when this object is looked at and its index in the list is used as a key for to solve the puzzle. """ def at_object_creation(self): "Called when object is created." super(Obelisk, self).at_object_creation() self.db.tutorial_info = "This object changes its desc randomly, and makes sure to remember which one you saw." self.db.puzzle_descs = ["You see a normal stone slab"] # make sure this can never be picked up self.locks.add("get:false()") def return_appearance(self, caller): """ This hook is called by the look command to get the description of the object. We overload it with our own version. """ # randomly get the index for one of the descriptions descs = self.db.puzzle_descs clueindex = random.randint(0, len(descs) - 1) # set this description, with the random extra string = "The surface of the obelisk seem to waver, shift and writhe under your gaze, with " \ "different scenes and structures appearing whenever you look at it. " self.db.desc = string + descs[clueindex] # remember that this was the clue we got. The Puzzle room will # look for this later to determine if you should be teleported # or not. caller.db.puzzle_clue = clueindex # call the parent function as normal (this will use # the new desc Attribute we just set) return super(Obelisk, self).return_appearance(caller) #------------------------------------------------------------ # # LightSource # # This object emits light. Once it has been turned on it # cannot be turned off. When it burns out it will delete # itself. # # This could be implemented using a single-repeat Script or by # registering with the TickerHandler. We do it simpler by # using the delay() utility function. This is very simple # to use but does not survive a server @reload. Because of # where the light matters (in the Dark Room where you can # find new light sources easily), this is okay here. # #------------------------------------------------------------ class CmdLight(Command): """ Creates light where there was none. Something to burn. """ key = "on" aliases = ["light", "burn"] # only allow this command if command.obj is carried by caller. locks = "cmd:holds()" help_category = "TutorialWorld" def func(self): """ Implements the light command. Since this command is designed to sit on a "lightable" object, we operate only on self.obj. """ if self.obj.light(): self.caller.msg("You light %s." % self.obj.key) self.caller.location.msg_contents("%s lights %s!" % (self.caller, self.obj.key), exclude=[self.caller]) else: self.caller.msg("%s is already burning." % self.obj.key) class CmdSetLight(CmdSet): "CmdSet for the lightsource commands" key = "lightsource_cmdset" # this is higher than the dark cmdset - important! priority = 3 def at_cmdset_creation(self): "called at cmdset creation" self.add(CmdLight()) class LightSource(TutorialObject): """ This implements a light source object. When burned out, the object will be deleted. """ def at_init(self): """ If this is called with the Attribute is_giving_light already set, we know that the timer got killed by a server reload/reboot before it had time to finish. So we kill it here instead. This is the price we pay for the simplicity of the non-persistent delay() method. """ if self.db.is_giving_light: self.delete() def at_object_creation(self): "Called when object is first created." super(LightSource, self).at_object_creation() self.db.tutorial_info = "This object can be lit to create light. It has a timeout for how long it burns." self.db.is_giving_light = False self.db.burntime = 60 * 3 # 3 minutes # this is the default desc, it can of course be customized # when created. self.db.desc = "A splinter of wood with remnants of resin on it, enough for burning." # add the Light command self.cmdset.add_default(CmdSetLight, permanent=True) def _burnout(self): """ This is called when this light source burns out. We make no use of the return value. """ # delete ourselves from the database self.db.is_giving_light = False try: self.location.location.msg_contents("%s's %s flickers and dies." % (self.location, self.key), exclude=self.location) self.location.msg("Your %s flickers and dies." % self.key) self.location.location.check_light_state() except AttributeError: try: self.location.msg_contents("A %s on the floor flickers and dies." % self.key) self.location.location.check_light_state() except AttributeError: pass self.delete() def light(self): """ Light this object - this is called by Light command. """ if self.db.is_giving_light: return False # burn for 3 minutes before calling _burnout self.db.is_giving_light = True # if we are in a dark room, trigger its light check try: self.location.location.check_light_state() except AttributeError: try: # maybe we are directly in the room self.location.check_light_state() except AttributeError: pass finally: # start the burn timer. When it runs out, self._burnout # will be called. utils.delay(60 * 3, self._burnout) return True #------------------------------------------------------------ # # Crumbling wall - unique exit # # This implements a simple puzzle exit that needs to be # accessed with commands before one can get to traverse it. # # The puzzle-part is simply to move roots (that have # presumably covered the wall) aside until a button for a # secret door is revealed. The original position of the # roots blocks the button, so they have to be moved to a certain # position - when they have, the "press button" command # is made available and the Exit is made traversable. # #------------------------------------------------------------ # There are four roots - two horizontal and two vertically # running roots. Each can have three positions: top/middle/bottom # and left/middle/right respectively. There can be any number of # roots hanging through the middle position, but only one each # along the sides. The goal is to make the center position clear. # (yes, it's really as simple as it sounds, just move the roots # to each side to "win". This is just a tutorial, remember?) # # The ShiftRoot command depends on the root object having an # Attribute root_pos (a dictionary) to describe the current # position of the roots. class CmdShiftRoot(Command): """ Shifts roots around. Usage: shift blue root left/right shift red root left/right shift yellow root up/down shift green root up/down """ key = "shift" aliases = ["shiftroot", "push", "pull", "move"] # we only allow to use this command while the # room is properly lit, so we lock it to the # setting of Attribute "is_lit" on our location. locks = "cmd:locattr(is_lit)" help_category = "TutorialWorld" def parse(self): """ Custom parser; split input by spaces for simplicity. """ self.arglist = self.args.strip().split() def func(self): """ Implement the command. blue/red - vertical roots yellow/green - horizontal roots """ if not self.arglist: self.caller.msg("What do you want to move, and in what direction?") return if "root" in self.arglist: # we clean out the use of the word "root" self.arglist.remove("root") # we accept arguments on the form <color> <direction> if not len(self.arglist) > 1: self.caller.msg("You must define which colour of root you want to move, and in which direction.") return color = self.arglist[0].lower() direction = self.arglist[1].lower() # get current root positions dict root_pos = self.obj.db.root_pos if not color in root_pos: self.caller.msg("No such root to move.") return # first, vertical roots (red/blue) - can be moved left/right if color == "red": if direction == "left": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the reddish root to the left.") if root_pos[color] != 0 and root_pos[color] == root_pos["blue"]: root_pos["blue"] += 1 self.caller.msg("The root with blue flowers gets in the way and is pushed to the right.") elif direction == "right": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the reddish root to the right.") if root_pos[color] != 0 and root_pos[color] == root_pos["blue"]: root_pos["blue"] -= 1 self.caller.msg("The root with blue flowers gets in the way and is pushed to the left.") else: self.caller.msg("You cannot move the root in that direction.") elif color == "blue": if direction == "left": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the root with small blue flowers to the left.") if root_pos[color] != 0 and root_pos[color] == root_pos["red"]: root_pos["red"] += 1 self.caller.msg("The reddish root is to big to fit as well, so that one falls away to the left.") elif direction == "right": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the root adorned with small blue flowers to the right.") if root_pos[color] != 0 and root_pos[color] == root_pos["red"]: root_pos["red"] -= 1 self.caller.msg("The thick reddish root gets in the way and is pushed back to the left.") else: self.caller.msg("You cannot move the root in that direction.") # now the horizontal roots (yellow/green). They can be moved up/down elif color == "yellow": if direction == "up": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the root with small yellow flowers upwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["green"]: root_pos["green"] += 1 self.caller.msg("The green weedy root falls down.") elif direction == "down": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the root adorned with small yellow flowers downwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["green"]: root_pos["green"] -= 1 self.caller.msg("The weedy green root is shifted upwards to make room.") else: self.caller.msg("You cannot move the root in that direction.") elif color == "green": if direction == "up": root_pos[color] = max(-1, root_pos[color] - 1) self.caller.msg("You shift the weedy green root upwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["yellow"]: root_pos["yellow"] += 1 self.caller.msg("The root with yellow flowers falls down.") elif direction == "down": root_pos[color] = min(1, root_pos[color] + 1) self.caller.msg("You shove the weedy green root downwards.") if root_pos[color] != 0 and root_pos[color] == root_pos["yellow"]: root_pos["yellow"] -= 1 self.caller.msg("The root with yellow flowers gets in the way and is pushed upwards.") else: self.caller.msg("You cannot move the root in that direction.") # we have moved the root. Store new position self.obj.db.root_pos = root_pos # Check victory condition if root_pos.values().count(0) == 0: # no roots in middle position # This will affect the cmd: lock of CmdPressButton self.obj.db.button_exposed = True self.caller.msg("Holding aside the root you think you notice something behind it ...") class CmdPressButton(Command): """ Presses a button. """ key = "press" aliases = ["press button", "button", "push", "push button"] # only accessible if the button was found and there is light. This checks # the Attribute button_exposed on the Wall object so that # you can only push the button when the puzzle is solved. It also # checks the is_lit Attribute on the location. locks = "cmd:objattr(button_exposed) and objlocattr(is_lit)" help_category = "TutorialWorld" def func(self): "Implements the command" if self.caller.db.crumbling_wall_found_exit: # we already pushed the button self.caller.msg("The button folded away when the secret passage opened. You cannot push it again.") return # pushing the button string = "You move your fingers over the suspicious depression, then gives it a " \ "decisive push. First nothing happens, then there is a rumble and a hidden " \ "{wpassage{n opens, dust and pebbles rumbling as part of the wall moves aside." self.caller.msg(string) string = "%s moves their fingers over the suspicious depression, then gives it a " \ "decisive push. First nothing happens, then there is a rumble and a hidden " \ "{wpassage{n opens, dust and pebbles rumbling as part of the wall moves aside." self.caller.location.msg_contents(string % self.caller.key, exclude=self.caller) self.obj.open_wall() class CmdSetCrumblingWall(CmdSet): "Group the commands for crumblingWall" key = "crumblingwall_cmdset" priority = 2 def at_cmdset_creation(self): "called when object is first created." self.add(CmdShiftRoot()) self.add(CmdPressButton()) class CrumblingWall(TutorialObject, DefaultExit): """ This is a custom Exit. The CrumblingWall can be examined in various ways, but only if a lit light source is in the room. The traversal itself is blocked by a traverse: lock on the exit that only allows passage if a certain attribute is set on the trying player. Important attribute destination - this property must be set to make this a valid exit whenever the button is pushed (this hides it as an exit until it actually is) """ def at_init(self): """ Called when object is recalled from cache. """ self.reset() def at_object_creation(self): "called when the object is first created." super(CrumblingWall, self).at_object_creation() self.aliases.add(["secret passage", "passage", "crack", "opening", "secret door"]) # starting root positions. H1/H2 are the horizontally hanging roots, # V1/V2 the vertically hanging ones. Each can have three positions: # (-1, 0, 1) where 0 means the middle position. yellow/green are # horizontal roots and red/blue vertical, all may have value 0, but n # ever any other identical value. self.db.root_pos = {"yellow": 0, "green": 0, "red": 0, "blue": 0} # flags controlling the puzzle victory conditions self.db.button_exposed = False self.db.exit_open = False # this is not even an Exit until it has a proper destination, and we won't assign # that until it is actually open. Until then we store the destination here. This # should be given a reasonable value at creation! self.db.destination = 2 # we lock this Exit so that one can only execute commands on it # if its location is lit and only traverse it once the Attribute # exit_open is set to True. self.locks.add("cmd:locattr(is_lit);traverse:objattr(exit_open)") # set cmdset self.cmdset.add(CmdSetCrumblingWall, permanent=True) def open_wall(self): """ This method is called by the push button command once the puzzle is solved. It opens the wall and sets a timer for it to reset itself. """ # this will make it into a proper exit (this returns a list) eloc = search.search_object(self.db.destination) if not eloc: self.caller.msg("The exit leads nowhere, there's just more stone behind it ...") else: self.destination = eloc[0] self.exit_open = True # start a 45 second timer before closing again utils.delay(45, self.reset) def _translate_position(self, root, ipos): "Translates the position into words" rootnames = {"red": "The {rreddish{n vertical-hanging root ", "blue": "The thick vertical root with {bblue{n flowers ", "yellow": "The thin horizontal-hanging root with {yyellow{n flowers ", "green": "The weedy {ggreen{n horizontal root "} vpos = {-1: "hangs far to the {wleft{n on the wall.", 0: "hangs straight down the {wmiddle{n of the wall.", 1: "hangs far to the {wright{n of the wall."} hpos = {-1: "covers the {wupper{n part of the wall.", 0: "passes right over the {wmiddle{n of the wall.", 1: "nearly touches the floor, near the {wbottom{n of the wall."} if root in ("yellow", "green"): string = rootnames[root] + hpos[ipos] else: string = rootnames[root] + vpos[ipos] return string def return_appearance(self, caller): """ This is called when someone looks at the wall. We need to echo the current root positions. """ if self.db.button_exposed: # we found the button by moving the roots string = "Having moved all the roots aside, you find that the center of the wall, " \ "previously hidden by the vegetation, hid a curious square depression. It was maybe once " \ "concealed and made to look a part of the wall, but with the crumbling of stone around it," \ "it's now easily identifiable as some sort of button." elif self.db.exit_open: # we pressed the button; the exit is open string = "With the button pressed, a crack has opened in the root-covered wall, just wide enough " \ "to squeeze through. A cold draft is coming from the hole and you get the feeling the " \ "opening may close again soon." else: # puzzle not solved yet. string = "The wall is old and covered with roots that here and there have permeated the stone. " \ "The roots (or whatever they are - some of them are covered in small non-descript flowers) " \ "crisscross the wall, making it hard to clearly see its stony surface. Maybe you could " \ "try to {wshift{n or {wmove{n them.\n" # display the root positions to help with the puzzle for key, pos in self.db.root_pos.items(): string += "\n" + self._translate_position(key, pos) self.db.desc = string # call the parent to continue execution (will use the desc we just set) return super(CrumblingWall, self).return_appearance(caller) def at_after_traverse(self, traverser, source_location): """ This is called after we traversed this exit. Cleans up and resets the puzzle. """ del traverser.db.crumbling_wall_found_buttothe del traverser.db.crumbling_wall_found_exit self.reset() def at_failed_traverse(self, traverser): "This is called if the player fails to pass the Exit." traverser.msg("No matter how you try, you cannot force yourself through %s." % self.key) def reset(self): """ Called by tutorial world runner, or whenever someone successfully traversed the Exit. """ self.location.msg_contents("The secret door closes abruptly, roots falling back into place.") # reset the flags and remove the exit destination self.db.button_exposed = False self.db.exit_open = False self.destination = None # Reset the roots with some random starting positions for the roots: start_pos = [{"yellow":1, "green":0, "red":0, "blue":0}, {"yellow":0, "green":0, "red":0, "blue":0}, {"yellow":0, "green":1, "red":-1, "blue":0}, {"yellow":1, "green":0, "red":0, "blue":0}, {"yellow":0, "green":0, "red":0, "blue":1}] self.db.root_pos = random.choice(start_pos) #------------------------------------------------------------ # # Weapon - object type # # A weapon is necessary in order to fight in the tutorial # world. A weapon (which here is assumed to be a bladed # melee weapon for close combat) has three commands, # stab, slash and defend. Weapons also have a property "magic" # to determine if they are usable against certain enemies. # # Since Characters don't have special skills in the tutorial, # we let the weapon itself determine how easy/hard it is # to hit with it, and how much damage it can do. # #------------------------------------------------------------ class CmdAttack(Command): """ Attack the enemy. Commands: stab <enemy> slash <enemy> parry stab - (thrust) makes a lot of damage but is harder to hit with. slash - is easier to land, but does not make as much damage. parry - forgoes your attack but will make you harder to hit on next enemy attack. """ # this is an example of implementing many commands as a single # command class, using the given command alias to separate between them. key = "attack" aliases = ["hit","kill", "fight", "thrust", "pierce", "stab", "slash", "chop", "parry", "defend"] locks = "cmd:all()" help_category = "TutorialWorld" def func(self): "Implements the stab" cmdstring = self.cmdstring if cmdstring in ("attack", "fight"): string = "How do you want to fight? Choose one of 'stab', 'slash' or 'defend'." self.caller.msg(string) return # parry mode if cmdstring in ("parry", "defend"): string = "You raise your weapon in a defensive pose, ready to block the next enemy attack." self.caller.msg(string) self.caller.db.combat_parry_mode = True self.caller.location.msg_contents("%s takes a defensive stance" % self.caller, exclude=[self.caller]) return if not self.args: self.caller.msg("Who do you attack?") return target = self.caller.search(self.args.strip()) if not target: return string = "" tstring = "" ostring = "" if cmdstring in ("thrust", "pierce", "stab"): hit = float(self.obj.db.hit) * 0.7 # modified due to stab damage = self.obj.db.damage * 2 # modified due to stab string = "You stab with %s. " % self.obj.key tstring = "%s stabs at you with %s. " % (self.caller.key, self.obj.key) ostring = "%s stabs at %s with %s. " % (self.caller.key, target.key, self.obj.key) self.caller.db.combat_parry_mode = False elif cmdstring in ("slash", "chop"): hit = float(self.obj.db.hit) # un modified due to slash damage = self.obj.db.damage # un modified due to slash string = "You slash with %s. " % self.obj.key tstring = "%s slash at you with %s. " % (self.caller.key, self.obj.key) ostring = "%s slash at %s with %s. " % (self.caller.key, target.key, self.obj.key) self.caller.db.combat_parry_mode = False else: self.caller.msg("You fumble with your weapon, unsure of whether to stab, slash or parry ...") self.caller.location.msg_contents("%s fumbles with their weapon." % self.caller, exclude=self.caller) self.caller.db.combat_parry_mode = False return if target.db.combat_parry_mode: # target is defensive; even harder to hit! target.msg("{GYou defend, trying to avoid the attack.{n") hit *= 0.5 if random.random() <= hit: self.caller.msg(string + "{gIt's a hit!{n") target.msg(tstring + "{rIt's a hit!{n") self.caller.location.msg_contents(ostring + "It's a hit!", exclude=[target,self.caller]) # call enemy hook if hasattr(target, "at_hit"): # should return True if target is defeated, False otherwise. return target.at_hit(self.obj, self.caller, damage) elif target.db.health: target.db.health -= damage else: # sorry, impossible to fight this enemy ... self.caller.msg("The enemy seems unaffacted.") return False else: self.caller.msg(string + "{rYou miss.{n") target.msg(tstring + "{gThey miss you.{n") self.caller.location.msg_contents(ostring + "They miss.", exclude=[target, self.caller]) class CmdSetWeapon(CmdSet): "Holds the attack command." def at_cmdset_creation(self): "called at first object creation." self.add(CmdAttack()) class Weapon(TutorialObject): """ This defines a bladed weapon. Important attributes (set at creation): hit - chance to hit (0-1) parry - chance to parry (0-1) damage - base damage given (modified by hit success and type of attack) (0-10) """ def at_object_creation(self): "Called at first creation of the object" super(Weapon, self).at_object_creation() self.db.hit = 0.4 # hit chance self.db.parry = 0.8 # parry chance self.db.damage = 1.0 self.db.magic = False self.cmdset.add_default(CmdSetWeapon, permanent=True) def reset(self): """ When reset, the weapon is simply deleted, unless it has a place to return to. """ if self.location.has_player and self.home == self.location: self.location.msg_contents("%s suddenly and magically fades into nothingness, as if it was never there ..." % self.key) self.delete() else: self.location = self.home #------------------------------------------------------------ # # Weapon rack - spawns weapons # # This is a spawner mechanism that creates custom weapons from a # spawner prototype dictionary. Note that we only create a single typeclass # (Weapon) yet customize all these different weapons using the spawner. # The spawner dictionaries could easily sit in separate modules and be # used to create unique and interesting variations of typeclassed # objects. # #------------------------------------------------------------ WEAPON_PROTOTYPES = { "weapon": { "typeclass": "evennia.contrib.tutorial_world.objects.Weapon", "key": "Weapon", "hit": 0.2, "parry": 0.2, "damage": 1.0, "magic": False, "desc": "A generic blade."}, "knife": { "prototype": "weapon", "aliases": "sword", "key": "Kitchen knife", "desc":"A rusty kitchen knife. Better than nothing.", "damage": 3}, "dagger": { "prototype": "knife", "key": "Rusty dagger", "aliases": ["knife", "dagger"], "desc": "A double-edged dagger with a nicked edge and a wooden handle.", "hit": 0.25}, "sword": { "prototype": "weapon", "key": "Rusty sword", "aliases": ["sword"], "desc": "A rusty shortsword. It has a leather-wrapped handle covered i food grease.", "hit": 0.3, "damage": 5, "parry": 0.5}, "club": { "prototype": "weapon", "key":"Club", "desc": "A heavy wooden club, little more than a heavy branch.", "hit": 0.4, "damage": 6, "parry": 0.2}, "axe": { "prototype": "weapon", "key":"Axe", "desc": "A woodcutter's axe with a keen edge.", "hit": 0.4, "damage": 6, "parry": 0.2}, "ornate longsword": { "prototype":"sword", "key": "Ornate longsword", "desc": "A fine longsword with some swirling patterns on the handle.", "hit": 0.5, "magic": True, "damage": 5}, "warhammer": { "prototype": "club", "key": "Silver Warhammer", "aliases": ["hammer", "warhammer", "war"], "desc": "A heavy war hammer with silver ornaments. This huge weapon causes massive damage - if you can hit.", "hit": 0.4, "magic": True, "damage": 8}, "rune axe": { "prototype": "axe", "key": "Runeaxe", "aliases": ["axe"], "hit": 0.4, "magic": True, "damage": 6}, "thruning": { "prototype": "ornate longsword", "key": "Broadsword named Thruning", "desc": "This heavy bladed weapon is marked with the name 'Thruning'. It is very powerful in skilled hands.", "hit": 0.6, "parry": 0.6, "damage": 7}, "slayer waraxe": { "prototype": "rune axe", "key": "Slayer waraxe", "aliases": ["waraxe", "war", "slayer"], "desc": "A huge double-bladed axe marked with the runes for 'Slayer'. It has more runic inscriptions on its head, which you cannot decipher.", "hit": 0.7, "damage": 8}, "ghostblade": { "prototype": "ornate longsword", "key": "The Ghostblade", "aliases": ["blade", "ghost"], "desc": "This massive sword is large as you are tall, yet seems to weigh almost nothing. It's almost like it's not really there.", "hit": 0.9, "parry": 0.8, "damage": 10}, "hawkblade": { "prototype": "ghostblade", "key": "The Hawblade", "aliases": ["hawk", "blade"], "desc": "The weapon of a long-dead heroine and a more civilized age, the hawk-shaped hilt of this blade almost has a life of its own.", "hit": 0.85, "parry": 0.7, "damage": 11} } class CmdGetWeapon(Command): """ Usage: get weapon This will try to obtain a weapon from the container. """ key = "get weapon" aliases = "get weapon" locks = "cmd:all()" help_cateogory = "TutorialWorld" def func(self): """ Get a weapon from the container. It will itself handle all messages. """ self.obj.produce_weapon(self.caller) class CmdSetWeaponRack(CmdSet): """ The cmdset for the rack. """ key = "weaponrack_cmdset" def at_cmdset_creation(self): "Called at first creation of cmdset" self.add(CmdGetWeapon()) class WeaponRack(TutorialObject): """ This object represents a weapon store. When people use the "get weapon" command on this rack, it will produce one random weapon from among those registered to exist on it. This will also set a property on the character to make sure they can't get more than one at a time. Attributes to set on this object: available_weapons: list of prototype-keys from WEAPON_PROTOTYPES, the weapons available in this rack. no_more_weapons_msg - error message to return to players who already got one weapon from the rack and tries to grab another one. """ def at_object_creation(self): """ called at creation """ self.cmdset.add_default(CmdSetWeaponRack, permanent=True) self.db.rack_id = "weaponrack_1" # these are prototype names from the prototype # dictionary above. self.db.get_weapon_msg = "You find {c%s{n." self.db.no_more_weapons_msg = "you find nothing else of use." self.db.available_weapons = ["knife", "dagger", "sword", "club"] def produce_weapon(self, caller): """ This will produce a new weapon from the rack, assuming the caller hasn't already gotten one. When doing so, the caller will get Tagged with the id of this rack, to make sure they cannot keep pulling weapons from it indefinitely. """ rack_id = self.db.rack_id if caller.tags.get(rack_id, category="tutorial_world"): caller.msg(self.db.no_more_weapons_msg) else: prototype = random.choice(self.db.available_weapons) # use the spawner to create a new Weapon from the # spawner dictionary, tag the caller wpn = spawn(WEAPON_PROTOTYPES[prototype], prototype_parents=WEAPON_PROTOTYPES)[0] caller.tags.add(rack_id, category="tutorial_world") wpn.location = caller caller.msg(self.db.get_weapon_msg % wpn.key + "[REWARD_weapon = 5]")
[ "evennia.utils.spawner.spawn", "evennia.utils.search.search_object", "evennia.utils.delay" ]
[((23234, 23275), 'evennia.utils.search.search_object', 'search.search_object', (['self.db.destination'], {}), '(self.db.destination)\n', (23254, 23275), False, 'from evennia.utils import search\n'), ((23536, 23563), 'evennia.utils.delay', 'utils.delay', (['(45)', 'self.reset'], {}), '(45, self.reset)\n', (23547, 23563), False, 'from evennia import utils\n'), ((27760, 27784), 'random.choice', 'random.choice', (['start_pos'], {}), '(start_pos)\n', (27773, 27784), False, 'import random\n'), ((11826, 11860), 'evennia.utils.delay', 'utils.delay', (['(60 * 3)', 'self._burnout'], {}), '(60 * 3, self._burnout)\n', (11837, 11860), False, 'from evennia import utils\n'), ((31492, 31507), 'random.random', 'random.random', ([], {}), '()\n', (31505, 31507), False, 'import random\n'), ((39823, 39863), 'random.choice', 'random.choice', (['self.db.available_weapons'], {}), '(self.db.available_weapons)\n', (39836, 39863), False, 'import random\n'), ((39993, 40065), 'evennia.utils.spawner.spawn', 'spawn', (['WEAPON_PROTOTYPES[prototype]'], {'prototype_parents': 'WEAPON_PROTOTYPES'}), '(WEAPON_PROTOTYPES[prototype], prototype_parents=WEAPON_PROTOTYPES)\n', (39998, 40065), False, 'from evennia.utils.spawner import spawn\n')]
"""Tests for validatorfuncs """ from django.test import TestCase from evennia.utils import validatorfuncs import mock import datetime import pytz class TestValidatorFuncs(TestCase): def test_text_ok(self): for val in [None, -123, "abc", 1.234, {1: True, 2: False}, ["a", 1]]: self.assertEqual(str(val), validatorfuncs.text(val)) @mock.patch("builtins.str") def test_text_raises_ValueError(self, mocked_str): mocked_str.side_effect = Exception with self.assertRaises(ValueError): validatorfuncs.text(None) def test_color_ok(self): for color in ["r", "g", "b", "H", "R", "M", "^"]: self.assertEqual(color, validatorfuncs.color(color)) def test_color_falsy_raises_ValueError(self): for color in [None, (), [], False, True, {}]: with self.assertRaises(ValueError): validatorfuncs.color(color) def test_datetime_ok(self): for dt in ["Oct 12 1:00 1492", "Jan 2 12:00 2020", "Dec 31 00:00 2018"]: self.assertTrue( isinstance(validatorfuncs.datetime(dt, from_tz=pytz.UTC), datetime.datetime) ) def test_datetime_raises_ValueError(self): for dt in ["", "January 1, 2019", "1/1/2019", "Jan 1 2019"]: with self.assertRaises(ValueError): validatorfuncs.datetime(dt) def test_duration_ok(self): for d in ["1d", "2w", "3h", "4s", "5m", "6y"]: self.assertTrue(isinstance(validatorfuncs.duration(d), datetime.timedelta)) self.assertEqual( datetime.timedelta(1 + 6 * 365, 2, 0, 0, 3, 4, 5), validatorfuncs.duration("1d 2s 3m 4h 5w 6y"), ) # values may be duplicated self.assertEqual( datetime.timedelta((1 + 7) + (6 + 12) * 365, 2 + 8, 0, 0, 3 + 9, 4 + 10, 5 + 11), validatorfuncs.duration("1d 2s 3m 4h 5w 6y 7d 8s 9m 10h 11w 12y"), ) def test_duration_raises_ValueError(self): for d in ["", "1", "5days", "1Week"]: with self.assertRaises(ValueError): validatorfuncs.duration(d) def test_future_ok(self): year = int(datetime.datetime.utcnow().strftime("%Y")) for f in [f"Jan 2 12:00 {year+1}", f"Dec 31 00:00 {year+1}"]: self.assertTrue( isinstance(validatorfuncs.future(f, from_tz=pytz.UTC), datetime.datetime) ) def test_future_raises_ValueError(self): year = int(datetime.datetime.utcnow().strftime("%Y")) for f in [f"Jan 2 12:00 {year-1}", f"Dec 31 00:00 {year-1}"]: with self.assertRaises(ValueError): validatorfuncs.future(f, from_tz=pytz.UTC) def test_signed_integer_ok(self): for si in ["123", "4567890", "001", "-123", "-45", "0"]: self.assertEqual(int(si), validatorfuncs.signed_integer(si)) @mock.patch("builtins.int") def test_signed_integer_raises_ValueError(self, mocked_int): for si in ["", "000", "abc"]: mocked_int.side_effect = ValueError with self.assertRaises(ValueError): validatorfuncs.signed_integer(si) def test_positive_integer_ok(self): for pi in ["123", "4567890", "001"]: self.assertEqual(int(pi), validatorfuncs.positive_integer(pi)) @mock.patch("builtins.int") def test_positive_integer_raises_ValueError(self, mocked_int): mocked_int.return_value = -1 with self.assertRaises(ValueError): validatorfuncs.positive_integer(str(-1)) for pi in ["", "000", "abc", "-1"]: mocked_int.side_effect = ValueError with self.assertRaises(ValueError): validatorfuncs.positive_integer(pi) def test_unsigned_integer_ok(self): for ui in ["123", "4567890", "001", "0"]: self.assertEqual(int(ui), validatorfuncs.unsigned_integer(ui)) @mock.patch("builtins.int") def test_unsigned_integer_raises_ValueError(self, mocked_int): mocked_int.return_value = -1 with self.assertRaises(ValueError): validatorfuncs.unsigned_integer(str(-1)) for ui in ["", "000", "abc", "-1", "0"]: mocked_int.side_effect = ValueError with self.assertRaises(ValueError): validatorfuncs.unsigned_integer(ui) def test_boolean(self): for b in ["true", "1", "on", "ENABLED"]: self.assertTrue(validatorfuncs.boolean(b)) for b in ["FalSe", "0", "oFF", "disabled"]: self.assertFalse(validatorfuncs.boolean(b)) def test_boolean_raises_ValueError(self): for b in ["", None, 1, 0, True, False, [None], {True: True}]: with self.assertRaises(ValueError): validatorfuncs.boolean(b) def test_timezone_ok(self): for tz in ["America/Chicago", "GMT", "UTC"]: self.assertEqual(tz, validatorfuncs.timezone(tz).zone) def test_timezone_raises_ValueError(self): for tz in ["America", None, "", "Mars", "DT"]: with self.assertRaises(ValueError): validatorfuncs.timezone(tz) def test_email_ok(self): for e in ["<EMAIL>", "<EMAIL>"]: self.assertEqual(e, validatorfuncs.email(e)) def test_email_raises_ValueError(self): for e in ["", None, ["<EMAIL>"], 123]: with self.assertRaises(ValueError): validatorfuncs.email(e) def test_lock_ok(self): for l in ["do:true;look:no", "a:t"]: self.assertEqual(l, validatorfuncs.lock(l)) def test_lock_raises_ValueError(self): for l in [";;;", "", ":", ":::", ";:;:", "x:", ":y"]: with self.assertRaises(ValueError): validatorfuncs.lock(l) with self.assertRaises(ValueError): validatorfuncs.lock("view:", access_options=()) with self.assertRaises(ValueError): validatorfuncs.lock("view:", access_options=("look"))
[ "evennia.utils.validatorfuncs.signed_integer", "evennia.utils.validatorfuncs.text", "evennia.utils.validatorfuncs.future", "evennia.utils.validatorfuncs.positive_integer", "evennia.utils.validatorfuncs.boolean", "evennia.utils.validatorfuncs.timezone", "evennia.utils.validatorfuncs.duration", "evennia...
[((362, 388), 'mock.patch', 'mock.patch', (['"""builtins.str"""'], {}), "('builtins.str')\n", (372, 388), False, 'import mock\n'), ((2905, 2931), 'mock.patch', 'mock.patch', (['"""builtins.int"""'], {}), "('builtins.int')\n", (2915, 2931), False, 'import mock\n'), ((3348, 3374), 'mock.patch', 'mock.patch', (['"""builtins.int"""'], {}), "('builtins.int')\n", (3358, 3374), False, 'import mock\n'), ((3940, 3966), 'mock.patch', 'mock.patch', (['"""builtins.int"""'], {}), "('builtins.int')\n", (3950, 3966), False, 'import mock\n'), ((543, 568), 'evennia.utils.validatorfuncs.text', 'validatorfuncs.text', (['None'], {}), '(None)\n', (562, 568), False, 'from evennia.utils import validatorfuncs\n'), ((1593, 1642), 'datetime.timedelta', 'datetime.timedelta', (['(1 + 6 * 365)', '(2)', '(0)', '(0)', '(3)', '(4)', '(5)'], {}), '(1 + 6 * 365, 2, 0, 0, 3, 4, 5)\n', (1611, 1642), False, 'import datetime\n'), ((1656, 1700), 'evennia.utils.validatorfuncs.duration', 'validatorfuncs.duration', (['"""1d 2s 3m 4h 5w 6y"""'], {}), "('1d 2s 3m 4h 5w 6y')\n", (1679, 1700), False, 'from evennia.utils import validatorfuncs\n'), ((1785, 1863), 'datetime.timedelta', 'datetime.timedelta', (['(1 + 7 + (6 + 12) * 365)', '(2 + 8)', '(0)', '(0)', '(3 + 9)', '(4 + 10)', '(5 + 11)'], {}), '(1 + 7 + (6 + 12) * 365, 2 + 8, 0, 0, 3 + 9, 4 + 10, 5 + 11)\n', (1803, 1863), False, 'import datetime\n'), ((1879, 1944), 'evennia.utils.validatorfuncs.duration', 'validatorfuncs.duration', (['"""1d 2s 3m 4h 5w 6y 7d 8s 9m 10h 11w 12y"""'], {}), "('1d 2s 3m 4h 5w 6y 7d 8s 9m 10h 11w 12y')\n", (1902, 1944), False, 'from evennia.utils import validatorfuncs\n'), ((5848, 5895), 'evennia.utils.validatorfuncs.lock', 'validatorfuncs.lock', (['"""view:"""'], {'access_options': '()'}), "('view:', access_options=())\n", (5867, 5895), False, 'from evennia.utils import validatorfuncs\n'), ((5952, 6003), 'evennia.utils.validatorfuncs.lock', 'validatorfuncs.lock', (['"""view:"""'], {'access_options': '"""look"""'}), "('view:', access_options='look')\n", (5971, 6003), False, 'from evennia.utils import validatorfuncs\n'), ((330, 354), 'evennia.utils.validatorfuncs.text', 'validatorfuncs.text', (['val'], {}), '(val)\n', (349, 354), False, 'from evennia.utils import validatorfuncs\n'), ((693, 720), 'evennia.utils.validatorfuncs.color', 'validatorfuncs.color', (['color'], {}), '(color)\n', (713, 720), False, 'from evennia.utils import validatorfuncs\n'), ((891, 918), 'evennia.utils.validatorfuncs.color', 'validatorfuncs.color', (['color'], {}), '(color)\n', (911, 918), False, 'from evennia.utils import validatorfuncs\n'), ((1350, 1377), 'evennia.utils.validatorfuncs.datetime', 'validatorfuncs.datetime', (['dt'], {}), '(dt)\n', (1373, 1377), False, 'from evennia.utils import validatorfuncs\n'), ((2114, 2140), 'evennia.utils.validatorfuncs.duration', 'validatorfuncs.duration', (['d'], {}), '(d)\n', (2137, 2140), False, 'from evennia.utils import validatorfuncs\n'), ((2679, 2721), 'evennia.utils.validatorfuncs.future', 'validatorfuncs.future', (['f'], {'from_tz': 'pytz.UTC'}), '(f, from_tz=pytz.UTC)\n', (2700, 2721), False, 'from evennia.utils import validatorfuncs\n'), ((2864, 2897), 'evennia.utils.validatorfuncs.signed_integer', 'validatorfuncs.signed_integer', (['si'], {}), '(si)\n', (2893, 2897), False, 'from evennia.utils import validatorfuncs\n'), ((3147, 3180), 'evennia.utils.validatorfuncs.signed_integer', 'validatorfuncs.signed_integer', (['si'], {}), '(si)\n', (3176, 3180), False, 'from evennia.utils import validatorfuncs\n'), ((3305, 3340), 'evennia.utils.validatorfuncs.positive_integer', 'validatorfuncs.positive_integer', (['pi'], {}), '(pi)\n', (3336, 3340), False, 'from evennia.utils import validatorfuncs\n'), ((3732, 3767), 'evennia.utils.validatorfuncs.positive_integer', 'validatorfuncs.positive_integer', (['pi'], {}), '(pi)\n', (3763, 3767), False, 'from evennia.utils import validatorfuncs\n'), ((3897, 3932), 'evennia.utils.validatorfuncs.unsigned_integer', 'validatorfuncs.unsigned_integer', (['ui'], {}), '(ui)\n', (3928, 3932), False, 'from evennia.utils import validatorfuncs\n'), ((4329, 4364), 'evennia.utils.validatorfuncs.unsigned_integer', 'validatorfuncs.unsigned_integer', (['ui'], {}), '(ui)\n', (4360, 4364), False, 'from evennia.utils import validatorfuncs\n'), ((4471, 4496), 'evennia.utils.validatorfuncs.boolean', 'validatorfuncs.boolean', (['b'], {}), '(b)\n', (4493, 4496), False, 'from evennia.utils import validatorfuncs\n'), ((4579, 4604), 'evennia.utils.validatorfuncs.boolean', 'validatorfuncs.boolean', (['b'], {}), '(b)\n', (4601, 4604), False, 'from evennia.utils import validatorfuncs\n'), ((4787, 4812), 'evennia.utils.validatorfuncs.boolean', 'validatorfuncs.boolean', (['b'], {}), '(b)\n', (4809, 4812), False, 'from evennia.utils import validatorfuncs\n'), ((5133, 5160), 'evennia.utils.validatorfuncs.timezone', 'validatorfuncs.timezone', (['tz'], {}), '(tz)\n', (5156, 5160), False, 'from evennia.utils import validatorfuncs\n'), ((5264, 5287), 'evennia.utils.validatorfuncs.email', 'validatorfuncs.email', (['e'], {}), '(e)\n', (5284, 5287), False, 'from evennia.utils import validatorfuncs\n'), ((5445, 5468), 'evennia.utils.validatorfuncs.email', 'validatorfuncs.email', (['e'], {}), '(e)\n', (5465, 5468), False, 'from evennia.utils import validatorfuncs\n'), ((5575, 5597), 'evennia.utils.validatorfuncs.lock', 'validatorfuncs.lock', (['l'], {}), '(l)\n', (5594, 5597), False, 'from evennia.utils import validatorfuncs\n'), ((5769, 5791), 'evennia.utils.validatorfuncs.lock', 'validatorfuncs.lock', (['l'], {}), '(l)\n', (5788, 5791), False, 'from evennia.utils import validatorfuncs\n'), ((1089, 1134), 'evennia.utils.validatorfuncs.datetime', 'validatorfuncs.datetime', (['dt'], {'from_tz': 'pytz.UTC'}), '(dt, from_tz=pytz.UTC)\n', (1112, 1134), False, 'from evennia.utils import validatorfuncs\n'), ((1505, 1531), 'evennia.utils.validatorfuncs.duration', 'validatorfuncs.duration', (['d'], {}), '(d)\n', (1528, 1531), False, 'from evennia.utils import validatorfuncs\n'), ((2191, 2217), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (2215, 2217), False, 'import datetime\n'), ((2360, 2402), 'evennia.utils.validatorfuncs.future', 'validatorfuncs.future', (['f'], {'from_tz': 'pytz.UTC'}), '(f, from_tz=pytz.UTC)\n', (2381, 2402), False, 'from evennia.utils import validatorfuncs\n'), ((2502, 2528), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (2526, 2528), False, 'import datetime\n'), ((4932, 4959), 'evennia.utils.validatorfuncs.timezone', 'validatorfuncs.timezone', (['tz'], {}), '(tz)\n', (4955, 4959), False, 'from evennia.utils import validatorfuncs\n')]
import re try: from django.utils.unittest import TestCase except ImportError: from django.test import TestCase from .ansi import ANSIString from evennia import utils class ANSIStringTestCase(TestCase): def checker(self, ansi, raw, clean): """ Verifies the raw and clean strings of an ANSIString match expected output. """ self.assertEqual(unicode(ansi.clean()), clean) self.assertEqual(unicode(ansi.raw()), raw) def table_check(self, ansi, char, code): """ Verifies the indexes in an ANSIString match what they should. """ self.assertEqual(ansi._char_indexes, char) self.assertEqual(ansi._code_indexes, code) def test_instance(self): """ Make sure the ANSIString is always constructed correctly. """ clean = u'This isA{r testTest' encoded = u'\x1b[1m\x1b[32mThis is\x1b[1m\x1b[31mA{r test\x1b[0mTest\x1b[0m' target = ANSIString(r'{gThis is{rA{{r test{nTest{n') char_table = [9, 10, 11, 12, 13, 14, 15, 25, 26, 27, 28, 29, 30, 31, 32, 37, 38, 39, 40] code_table = [0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 17, 18, 19, 20, 21, 22, 23, 24, 33, 34, 35, 36, 41, 42, 43, 44] self.checker(target, encoded, clean) self.table_check(target, char_table, code_table) self.checker(ANSIString(target), encoded, clean) self.table_check(ANSIString(target), char_table, code_table) self.checker(ANSIString(encoded, decoded=True), encoded, clean) self.table_check(ANSIString(encoded, decoded=True), char_table, code_table) self.checker(ANSIString('Test'), u'Test', u'Test') self.table_check(ANSIString('Test'), [0, 1, 2, 3], []) self.checker(ANSIString(''), u'', u'') def test_slice(self): """ Verifies that slicing an ANSIString results in expected color code distribution. """ target = ANSIString(r'{gTest{rTest{n') result = target[:3] self.checker(result, u'\x1b[1m\x1b[32mTes', u'Tes') result = target[:4] self.checker(result, u'\x1b[1m\x1b[32mTest\x1b[1m\x1b[31m', u'Test') result = target[:] self.checker( result, u'\x1b[1m\x1b[32mTest\x1b[1m\x1b[31mTest\x1b[0m', u'TestTest') result = target[:-1] self.checker( result, u'\x1b[1m\x1b[32mTest\x1b[1m\x1b[31mTes', u'TestTes') result = target[0:0] self.checker( result, u'', u'') def test_split(self): """ Verifies that re.split and .split behave similarly and that color codes end up where they should. """ target = ANSIString("{gThis is {nA split string{g") first = (u'\x1b[1m\x1b[32mThis is \x1b[0m', u'This is ') second = (u'\x1b[1m\x1b[32m\x1b[0m split string\x1b[1m\x1b[32m', u' split string') re_split = re.split('A', target) normal_split = target.split('A') self.assertEqual(re_split, normal_split) self.assertEqual(len(normal_split), 2) self.checker(normal_split[0], *first) self.checker(normal_split[1], *second) def test_join(self): """ Verify that joining a set of ANSIStrings works. """ # This isn't the desired behavior, but the expected one. Python # concatinates the in-memory representation with the built-in string's # join. l = [ANSIString("{gTest{r") for s in range(0, 3)] # Force the generator to be evaluated. result = "".join(l) self.assertEqual(unicode(result), u'TestTestTest') result = ANSIString("").join(l) self.checker(result, u'\x1b[1m\x1b[32mTest\x1b[1m\x1b[31m\x1b[1m\x1b' u'[32mTest\x1b[1m\x1b[31m\x1b[1m\x1b[32mTest' u'\x1b[1m\x1b[31m', u'TestTestTest') def test_len(self): """ Make sure that length reporting on ANSIStrings does not include ANSI codes. """ self.assertEqual(len(ANSIString('{gTest{n')), 4) def test_capitalize(self): """ Make sure that capitalization works. This is the simplest of the _transform functions. """ target = ANSIString('{gtest{n') result = u'\x1b[1m\x1b[32mTest\x1b[0m' self.checker(target.capitalize(), result, u'Test') def test_mxp_agnostic(self): """ Make sure MXP tags are not treated like ANSI codes, but normal text. """ mxp1 = "{lclook{ltat{le" mxp2 = "Start to {lclook here{ltclick somewhere here{le first" self.assertEqual(15, len(ANSIString(mxp1))) self.assertEqual(53, len(ANSIString(mxp2))) # These would indicate an issue with the tables. self.assertEqual(len(ANSIString(mxp1)), len(ANSIString(mxp1).split("\n")[0])) self.assertEqual(len(ANSIString(mxp2)), len(ANSIString(mxp2).split("\n")[0])) self.assertEqual(mxp1, ANSIString(mxp1)) self.assertEqual(mxp2, unicode(ANSIString(mxp2))) def test_add(self): """ Verify concatination works correctly. """ a = ANSIString("{gTest") b = ANSIString("{cString{n") c = a + b result = u'\x1b[1m\x1b[32mTest\x1b[1m\x1b[36mString\x1b[0m' self.checker(c, result, u'TestString') char_table = [9, 10, 11, 12, 22, 23, 24, 25, 26, 27] code_table = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 28, 29, 30, 31 ] self.table_check(c, char_table, code_table) class TestIsIter(TestCase): def test_is_iter(self): self.assertEqual(True, utils.is_iter([1,2,3,4])) self.assertEqual(False, utils.is_iter("This is not an iterable")) class TestCrop(TestCase): def test_crop(self): # No text, return no text self.assertEqual("", utils.crop("", width=10, suffix="[...]")) # Input length equal to max width, no crop self.assertEqual("0123456789", utils.crop("0123456789", width=10, suffix="[...]")) # Input length greater than max width, crop (suffix included in width) self.assertEqual("0123[...]", utils.crop("0123456789", width=9, suffix="[...]")) # Input length less than desired width, no crop self.assertEqual("0123", utils.crop("0123", width=9, suffix="[...]")) # Width too small or equal to width of suffix self.assertEqual("012", utils.crop("0123", width=3, suffix="[...]")) self.assertEqual("01234", utils.crop("0123456", width=5, suffix="[...]")) class TestDedent(TestCase): def test_dedent(self): #print "Did TestDedent run?" # Empty string, return empty string self.assertEqual("", utils.dedent("")) # No leading whitespace self.assertEqual("TestDedent", utils.dedent("TestDedent")) # Leading whitespace, single line self.assertEqual("TestDedent", utils.dedent(" TestDedent")) # Leading whitespace, multi line input_string = " hello\n world" expected_string = "hello\nworld" self.assertEqual(expected_string, utils.dedent(input_string)) class TestListToString(TestCase): """ Default function header from utils.py: list_to_string(inlist, endsep="and", addquote=False) Examples: no endsep: [1,2,3] -> '1, 2, 3' with endsep=='and': [1,2,3] -> '1, 2 and 3' with addquote and endsep [1,2,3] -> '"1", "2" and "3"' """ def test_list_to_string(self): self.assertEqual('1, 2, 3', utils.list_to_string([1,2,3], endsep="")) self.assertEqual('"1", "2", "3"', utils.list_to_string([1,2,3], endsep="", addquote=True)) self.assertEqual('1, 2 and 3', utils.list_to_string([1,2,3])) self.assertEqual('"1", "2" and "3"', utils.list_to_string([1,2,3], endsep="and", addquote=True)) class TestMLen(TestCase): """ Verifies that m_len behaves like len in all situations except those where MXP may be involved. """ def test_non_mxp_string(self): self.assertEqual(utils.m_len('Test_string'), 11) def test_mxp_string(self): self.assertEqual(utils.m_len('{lclook{ltat{le'), 2) def test_mxp_ansi_string(self): self.assertEqual(utils.m_len(ANSIString('{lcl{gook{ltat{le{n')), 2) def test_non_mxp_ansi_string(self): self.assertEqual(utils.m_len(ANSIString('{gHello{n')), 5) def test_list(self): self.assertEqual(utils.m_len([None, None]), 2) def test_dict(self): self.assertEqual(utils.m_len({'hello': True, 'Goodbye': False}), 2)
[ "evennia.utils.m_len", "evennia.utils.crop", "evennia.utils.dedent", "evennia.utils.list_to_string", "evennia.utils.is_iter" ]
[((3075, 3096), 're.split', 're.split', (['"""A"""', 'target'], {}), "('A', target)\n", (3083, 3096), False, 'import re\n'), ((5856, 5883), 'evennia.utils.is_iter', 'utils.is_iter', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (5869, 5883), False, 'from evennia import utils\n'), ((5914, 5954), 'evennia.utils.is_iter', 'utils.is_iter', (['"""This is not an iterable"""'], {}), "('This is not an iterable')\n", (5927, 5954), False, 'from evennia import utils\n'), ((6072, 6112), 'evennia.utils.crop', 'utils.crop', (['""""""'], {'width': '(10)', 'suffix': '"""[...]"""'}), "('', width=10, suffix='[...]')\n", (6082, 6112), False, 'from evennia import utils\n'), ((6204, 6254), 'evennia.utils.crop', 'utils.crop', (['"""0123456789"""'], {'width': '(10)', 'suffix': '"""[...]"""'}), "('0123456789', width=10, suffix='[...]')\n", (6214, 6254), False, 'from evennia import utils\n'), ((6373, 6422), 'evennia.utils.crop', 'utils.crop', (['"""0123456789"""'], {'width': '(9)', 'suffix': '"""[...]"""'}), "('0123456789', width=9, suffix='[...]')\n", (6383, 6422), False, 'from evennia import utils\n'), ((6513, 6556), 'evennia.utils.crop', 'utils.crop', (['"""0123"""'], {'width': '(9)', 'suffix': '"""[...]"""'}), "('0123', width=9, suffix='[...]')\n", (6523, 6556), False, 'from evennia import utils\n'), ((6644, 6687), 'evennia.utils.crop', 'utils.crop', (['"""0123"""'], {'width': '(3)', 'suffix': '"""[...]"""'}), "('0123', width=3, suffix='[...]')\n", (6654, 6687), False, 'from evennia import utils\n'), ((6723, 6769), 'evennia.utils.crop', 'utils.crop', (['"""0123456"""'], {'width': '(5)', 'suffix': '"""[...]"""'}), "('0123456', width=5, suffix='[...]')\n", (6733, 6769), False, 'from evennia import utils\n'), ((6938, 6954), 'evennia.utils.dedent', 'utils.dedent', (['""""""'], {}), "('')\n", (6950, 6954), False, 'from evennia import utils\n'), ((7027, 7053), 'evennia.utils.dedent', 'utils.dedent', (['"""TestDedent"""'], {}), "('TestDedent')\n", (7039, 7053), False, 'from evennia import utils\n'), ((7136, 7165), 'evennia.utils.dedent', 'utils.dedent', (['""" TestDedent"""'], {}), "(' TestDedent')\n", (7148, 7165), False, 'from evennia import utils\n'), ((7333, 7359), 'evennia.utils.dedent', 'utils.dedent', (['input_string'], {}), '(input_string)\n', (7345, 7359), False, 'from evennia import utils\n'), ((7769, 7811), 'evennia.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {'endsep': '""""""'}), "([1, 2, 3], endsep='')\n", (7789, 7811), False, 'from evennia import utils\n'), ((7853, 7910), 'evennia.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {'endsep': '""""""', 'addquote': '(True)'}), "([1, 2, 3], endsep='', addquote=True)\n", (7873, 7910), False, 'from evennia import utils\n'), ((7949, 7980), 'evennia.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (7969, 7980), False, 'from evennia import utils\n'), ((8025, 8085), 'evennia.utils.list_to_string', 'utils.list_to_string', (['[1, 2, 3]'], {'endsep': '"""and"""', 'addquote': '(True)'}), "([1, 2, 3], endsep='and', addquote=True)\n", (8045, 8085), False, 'from evennia import utils\n'), ((8292, 8318), 'evennia.utils.m_len', 'utils.m_len', (['"""Test_string"""'], {}), "('Test_string')\n", (8303, 8318), False, 'from evennia import utils\n'), ((8381, 8411), 'evennia.utils.m_len', 'utils.m_len', (['"""{lclook{ltat{le"""'], {}), "('{lclook{ltat{le')\n", (8392, 8411), False, 'from evennia import utils\n'), ((8687, 8712), 'evennia.utils.m_len', 'utils.m_len', (['[None, None]'], {}), '([None, None])\n', (8698, 8712), False, 'from evennia import utils\n'), ((8768, 8814), 'evennia.utils.m_len', 'utils.m_len', (["{'hello': True, 'Goodbye': False}"], {}), "({'hello': True, 'Goodbye': False})\n", (8779, 8814), False, 'from evennia import utils\n')]
from django.conf import settings from evennia.utils.ansi import strip_ansi screen_width = settings.CLIENT_DEFAULT_WIDTH def pick_color(caller, color): code = None string = "" try: if color.isnumeric(): #Grab RGB values from string. r, g, b = color[0], color[1], color[2] #Convert RGB values into their hexidemical counterparts r = hex_chart[r] g = hex_chart[g] b = hex_chart[b] #Define color based off hexidemical. code = color color = r + g + b color = [k for k in xterm_chart if xterm_chart[k] == color][0] elif color in xterm_chart: #Grab the hex value of a specific color hex = xterm_chart[color] #Convert hex value into XTERM. r = int(int(hex[0] + hex[1], 16) / 256 * 6) g = int(int(hex[2] + hex[3], 16) / 256 * 6) b = int(int(hex[4] + hex[5], 16) / 256 * 6) code = (str(r) + str(g) + str(b)) if not code or not xterm_chart[color]: return "n", "This color does not exist." return code, color.capitalize() except Exception: return "n", "This color does not exist." def show_colors(type="xterm"): string = "" strings = [] if type == "ascii": strings.append("ASCII Colors:\n".center(34, " ")) strings.append("||r - |rBrightred|n ||R - |RBrightred|n") strings.append("||g - |gBrightgreen|n ||G - |GGreen|n") strings.append("||y - |yYellow|n ||Y - |YOlive|n") strings.append("||b - |bBrightblue|n ||B - |BBlue|n") strings.append("||m - |mMagenta|n ||M - |MPurple|n") strings.append("||c - |cCyan|n ||C - |CTeal|n") strings.append("||x - |xBlack|n ||w - |wSilver|n") strings.append("||n - |nNone|n ||W - |WWhite|n") else: max_len = max(map(len, xterm_chart)) text_len = None for key in xterm_chart: hex = xterm_chart[key] a = int(int(hex[0] + hex[1], 16) / 256 * 6) b = int(int(hex[2] + hex[3], 16) / 256 * 6) c = int(int(hex[4] + hex[5], 16) / 256 * 6) code = (str(a) + str(b) + str(c)) text = f"|{code}{key.capitalize()}" text_len = len(strip_ansi(text)) spaces = " " * int(max_len - text_len + 2) text += spaces + f"({code}) " string += text if len(string) >= screen_width - (max_len + 6): strings.append(string) string = "" strings.append(string) message = "\n".join(strings) return message hex_chart = { "0" : "00", "1" : "33", "2" : "66", "3" : "99", "4" : "cc", "5" : "ff" } xterm_chart = { "abyss" : "000000", "darkred" : "330000", "maroon" : "660000", "red" : "990000", "cherry" : "cc0000", "brightred" : "ff0000", "darkgreen" : "003300", "racegreen" : "333300", "bronze" : "663300", "garnet" : "993300", "tawny" : "cc3300", "scarlet" : "ff3300", "jungle" : "006600", "verdun" : "336600", "brown" : "666600", "sienna" : "996600", "saddle" : "cc6600", "darkorange" : "ff6600", "green" : "009900", "limeade" : "339900", "olivedrab" : "669900", "olive" : "999900", "darkgold" : "cc9900", "orange" : "ff9900", "lime" : "00cc00", "harlequin" : "33cc00", "lawngreen" : "66cc00", "citrus" : "99cc00", "goldenrod" : "cccc00", "gold" : "ffcc00", "brightgreen" : "00ff00", "electric" : "33ff00", "chartreuse" : "66ff00", "atlantic" : "99ff00", "springbud" : "ccff00", "yellow" : "ffff00", "stratos" : "000033", "tyrian" : "330033", "darkpurple" : "660033", "carmine" : "990033", "ruby" : "cc0033", "crimson" : "ff0033", "deepteal" : "003333", "black" : "333333", "brick" : "663333", "milano" : "993333", "amaranth" : "cc3333", "redorange" : "ff3333", "watercourse" : "006633", "parsley" : "336633", "saratoga" : "666633", "indochine" : "996633", "chocolate" : "cc6633", "tomato" : "ff6633", "pigment" : "009933", "forest" : "339933", "sushi" : "669933", "reefgold" : "999933", "darkyellow" : "cc9933", "carrot" : "ff9933", "pastel" : "00cc33", "apple" : "33cc33", "feijoa" : "66cc33", "yellowgreen" : "99cc33", "wattle" : "cccc33", "sunglow" : "ffcc33", "speech" : "00ff33", "lightgreen" : "33ff33", "conifer" : "66ff33", "greenyellow" : "99ff33", "inchworm" : "ccff33", "gorse" : "ffff33", "navy" : "000066", "bluediamond" : "330066", "flirt" : "660066", "eggplant" : "990066", "razzmatazz" : "cc0066", "razz" : "ff0066", "prussian" : "003366", "koamaru" : "333366", "palatinate" : "663366", "lipstick" : "993366", "oldrose" : "cc3366", "radicalred" : "ff3366", "lagoon" : "006666", "blumine" : "336666", "dimgray" : "666666", "copper" : "996666", "indian" : "cc6666", "coral" : "ff6666", "shamrock" : "009966", "eucalyptus" : "339966", "oxley" : "669966", "stardust" : "999966", "eunry" : "cc9966", "salmon" : "ff9966", "jade" : "00cc66", "emerald" : "33cc66", "peridot" : "66cc66", "mantis" : "99cc66", "willow" : "cccc66", "grandis" : "ffcc66", "spring" : "00ff66", "parakeet" : "33ff66", "sulu" : "66ff66", "aquaforest" : "99ff66", "laserlemon" : "ccff66", "lemon" : "ffff66", "blue" : "000099", "bluegem" : "330099", "indigo" : "660099", "purple" : "990099", "cerise" : "cc0099", "redcerise" : "ff0099", "smalt" : "003399", "violetgem" : "333399", "royal" : "663399", "violet" : "993399", "sangria" : "cc3399", "strawberry" : "ff3399", "cerulean" : "006699", "lochmara" : "336699", "scampi" : "666699", "violetblue" : "996699", "hopbush" : "cc6699", "rose" : "ff6699", "teal" : "009999", "steel" : "339999", "cadet" : "669999", "gray" : "999999", "careys" : "cc9999", "mona" : "ff9999", "caribbean" : "00cc99", "shamgreen" : "33cc99", "seagreen" : "66cc99", "chinook" : "99cc99", "whiteyellow" : "cccc99", "tan" : "ffcc99", "lizard" : "00ff99", "seafoam" : "33ff99", "tea" : "66ff99", "mint" : "99ff99", "canary" : "ccff99", "khaki" : "ffff99", "ultramarine" : "0000cc", "midnight" : "3300cc", "affair" : "6600cc", "eleviolet" : "9900cc", "deepmageta" : "cc00cc", "hotmagenta" : "ff00cc", "klein" : "0033cc", "governor" : "3333cc", "purpleheart" : "6633cc", "orchid" : "9933cc", "fuchsia" : "cc33cc", "razzle" : "ff33cc", "sapphire" : "0066cc", "mariner" : "3366cc", "slate" : "6666cc", "amethyst" : "9966cc", "heliotrope" : "cc66cc", "neonpink" : "ff66cc", "pacific" : "0099cc", "pelorous" : "3399cc", "picton" : "6699cc", "bluebell" : "9999cc", "periwinkle" : "cc99cc", "carnation" : "ff99cc", "robin" : "00cccc", "waterfall" : "33cccc", "downy" : "66cccc", "morning" : "99cccc", "white" : "cccccc", "pink" : "ffcccc", "turquoise" : "00ffcc", "brightaqua" : "33ffcc", "blizzard" : "66ffcc", "aquamarine" : "99ffcc", "honeydew" : "ccffcc", "cream" : "ffffcc", "brightblue" : "0000ff", "cobalt" : "3300ff", "grape" : "6600ff", "darkviolet" : "9900ff", "charm" : "cc00ff", "magenta" : "ff00ff", "blueribbon" : "0033ff", "neonblue" : "3333ff", "christalle" : "6633ff", "blueviolet" : "9933ff", "cosmic" : "cc33ff", "dazzle" : "ff33ff", "dodger" : "0066ff", "royalblue" : "3366ff", "lightslate" : "6666ff", "iris" : "9966ff", "lilac" : "cc66ff", "flamingo" : "ff66ff", "azure" : "0099ff", "astral" : "3399ff", "cornflower" : "6699ff", "melrose" : "9999ff", "mauve" : "cc99ff", "hotpink" : "ff99ff", "deepsky" : "00ccff", "skyblue" : "33ccff", "powderblue" : "66ccff", "lightblue" : "99ccff", "lavender" : "ccccff", "plum" : "ffccff", "cyan" : "00ffff", "aqua" : "33ffff", "babyblue" : "66ffff", "lightcyan" : "99ffff", "alice" : "ccffff", "silver" : "ffffff", }
[ "evennia.utils.ansi.strip_ansi" ]
[((2356, 2372), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['text'], {}), '(text)\n', (2366, 2372), False, 'from evennia.utils.ansi import strip_ansi\n')]
from evennia.utils.utils import class_from_module from evennia.utils.logger import log_trace import athanor.messages.themes as tmsg from athanor.gamedb.scripts import AthanorGlobalScript from athanor.utils.text import partial_match from athanor.gamedb.models import ThemeBridge from athanor.gamedb.themes import AthanorTheme class AthanorThemeController(AthanorGlobalScript): system_name = 'THEME' option_dict = { 'system_locks': ('Locks governing Theme System.', 'Lock', "create:perm(Admin);delete:perm(Admin)"), 'theme_locks': ('Default/Fallback locks for all Themes.', 'Lock', "see:all();control:perm(Admin)") } def at_start(self): from django.conf import settings try: theme_typeclass = getattr(settings, "BASE_THEME_TYPECLASS", "athanor_mush.gamedb.themes.AthanorTheme") self.ndb.theme_typeclass = class_from_module(theme_typeclass, defaultpaths=settings.TYPECLASS_PATHS) except Exception: log_trace() self.ndb.theme_typeclass = AthanorTheme def themes(self): return AthanorTheme.objects.filter_family().order_by('db_key') def create_theme(self, session, theme_name, description): enactor = session.get_puppet_or_account() new_theme = self.ndb.theme_typeclass.create_theme(theme_name, description) tmsg.ThemeCreateMessage(enactor, theme=new_theme).send() return new_theme def find_theme(self, enactor, theme_name): if isinstance(theme_name, AthanorTheme): return theme_name if isinstance(theme_name, ThemeBridge): return theme_name.db_script if isinstance(theme_name, int): theme = AthanorTheme.objects.filter_family(id=theme_name).first() if not theme: raise ValueError(f"Theme ID {theme_name}' not found!") return theme theme = partial_match(theme_name, self.themes()) if not theme: raise ValueError(f"Theme '{theme_name}' not found!") return theme.db_script def set_description(self, session, theme_name, new_description): enactor = session.get_puppet_or_account() theme = self.find_theme(session, theme_name) if not theme.access(enactor, 'control', default="perm(Admin)"): raise ValueError("Permission denied.") if not new_description: raise ValueError("Nothing entered to change description to!") old_description = theme.description theme.description = new_description tmsg.ThemeDescribeMessage(enactor, theme=theme).send() def rename_theme(self, session, theme_name, new_name): enactor = session.get_puppet_or_account() theme = self.find_theme(session, theme_name) clean_name = AthanorTheme.validate_unique_key(new_name, rename_target=theme) old_name = theme.key theme.key = clean_name tmsg.ThemeRenameMessage(enactor, theme=theme, old_name=old_name).send() def delete_theme(self, session, theme_name, name_verify): enactor = session.get_puppet_or_account() theme = self.find_theme(enactor, theme_name) if not name_verify or not theme.key.lower() == name_verify.lower(): raise ValueError("Theme name validation mismatch. Can only delete if names match for safety.") tmsg.ThemeDeleteMessage(enactor, theme=theme).send() theme.delete() def theme_add_character(self, session, theme_name, character, list_type): enactor = session.get_puppet_or_account() theme = self.find_theme(enactor, theme_name) participating = character.themes.filter() not_this = participating.exclude(db_theme=theme) primary = True if not_this: primary = False if participating.filter(db_theme=theme).count(): raise ValueError(f"{character} is already a member of {theme}!") new_part = theme.add_character(character, list_type) tmsg.ThemeAssignedMessage(enactor, target=character, theme=theme, list_type=list_type).send() if primary: character.db._primary_theme = new_part tmsg.ThemeSetPrimaryMessage(enactor, target=character, theme_name=theme.key, list_type=list_type).send() def theme_remove_character(self, session, theme_name, character): enactor = session.get_puppet_or_account() theme = self.find_theme(enactor, theme_name) participating = character.themes.filter(db_theme=theme).first() if not participating: raise ValueError(f"{character} is not a member of {theme}!") list_type = participating.list_type theme.remove_character(character) tmsg.ThemeRemovedMessage(enactor, target=character, theme=theme, list_type=list_type).send() def character_change_status(self, session, character, new_status): enactor = session.get_puppet_or_account() old_status = character.db._theme_status character.db._theme_status = new_status tmsg.ThemeStatusMessage(enactor, target=character, status=new_status, theme=character.db._primary_theme.theme).send() def participant_change_type(self, session, theme_name, character, new_type): enactor = session.get_puppet_or_account() theme = self.find_theme(enactor, theme_name) participant = theme.participants.filter(db_character=character).first() if not participant: raise ValueError(f"{character} is not a member of {theme}!") old_type = participant.list_type participant.change_type(new_type) tmsg.ThemeListTypeMessage(enactor, target=character, theme=theme, old_list_type=old_type, list_type=new_type).send() def character_change_primary(self, session, character, theme_name): enactor = session.get_puppet_or_account() participating = character.themes.all() if not participating: raise ValueError("Character has no themes!") old_primary = character.db._primary_theme if old_primary: old_list_type = old_primary.list_type else: old_list_type = None theme_part = partial_match(theme_name, participating) if not theme_part: raise ValueError(f"Character has no Theme named {theme_name}!") character.db._primary_theme = theme_part if old_primary: tmsg.ThemeChangePrimaryMessage(enactor, target=character, old_theme_name=old_primary.theme.key, old_list_type=old_list_type, theme=theme_part.theme, list_type=theme_part.list_type).send() else: tmsg.ThemeSetPrimaryMessage(enactor, target=character, theme_name=theme_part.theme.key, list_type=theme_part.list_type)
[ "evennia.utils.utils.class_from_module", "evennia.utils.logger.log_trace" ]
[((2852, 2915), 'athanor.gamedb.themes.AthanorTheme.validate_unique_key', 'AthanorTheme.validate_unique_key', (['new_name'], {'rename_target': 'theme'}), '(new_name, rename_target=theme)\n', (2884, 2915), False, 'from athanor.gamedb.themes import AthanorTheme\n'), ((6313, 6353), 'athanor.utils.text.partial_match', 'partial_match', (['theme_name', 'participating'], {}), '(theme_name, participating)\n', (6326, 6353), False, 'from athanor.utils.text import partial_match\n'), ((928, 1001), 'evennia.utils.utils.class_from_module', 'class_from_module', (['theme_typeclass'], {'defaultpaths': 'settings.TYPECLASS_PATHS'}), '(theme_typeclass, defaultpaths=settings.TYPECLASS_PATHS)\n', (945, 1001), False, 'from evennia.utils.utils import class_from_module\n'), ((6803, 6927), 'athanor.messages.themes.ThemeSetPrimaryMessage', 'tmsg.ThemeSetPrimaryMessage', (['enactor'], {'target': 'character', 'theme_name': 'theme_part.theme.key', 'list_type': 'theme_part.list_type'}), '(enactor, target=character, theme_name=\n theme_part.theme.key, list_type=theme_part.list_type)\n', (6830, 6927), True, 'import athanor.messages.themes as tmsg\n'), ((1041, 1052), 'evennia.utils.logger.log_trace', 'log_trace', ([], {}), '()\n', (1050, 1052), False, 'from evennia.utils.logger import log_trace\n'), ((1143, 1179), 'athanor.gamedb.themes.AthanorTheme.objects.filter_family', 'AthanorTheme.objects.filter_family', ([], {}), '()\n', (1177, 1179), False, 'from athanor.gamedb.themes import AthanorTheme\n'), ((1403, 1452), 'athanor.messages.themes.ThemeCreateMessage', 'tmsg.ThemeCreateMessage', (['enactor'], {'theme': 'new_theme'}), '(enactor, theme=new_theme)\n', (1426, 1452), True, 'import athanor.messages.themes as tmsg\n'), ((2613, 2660), 'athanor.messages.themes.ThemeDescribeMessage', 'tmsg.ThemeDescribeMessage', (['enactor'], {'theme': 'theme'}), '(enactor, theme=theme)\n', (2638, 2660), True, 'import athanor.messages.themes as tmsg\n'), ((2984, 3048), 'athanor.messages.themes.ThemeRenameMessage', 'tmsg.ThemeRenameMessage', (['enactor'], {'theme': 'theme', 'old_name': 'old_name'}), '(enactor, theme=theme, old_name=old_name)\n', (3007, 3048), True, 'import athanor.messages.themes as tmsg\n'), ((3413, 3458), 'athanor.messages.themes.ThemeDeleteMessage', 'tmsg.ThemeDeleteMessage', (['enactor'], {'theme': 'theme'}), '(enactor, theme=theme)\n', (3436, 3458), True, 'import athanor.messages.themes as tmsg\n'), ((4053, 4144), 'athanor.messages.themes.ThemeAssignedMessage', 'tmsg.ThemeAssignedMessage', (['enactor'], {'target': 'character', 'theme': 'theme', 'list_type': 'list_type'}), '(enactor, target=character, theme=theme, list_type\n =list_type)\n', (4078, 4144), True, 'import athanor.messages.themes as tmsg\n'), ((4778, 4868), 'athanor.messages.themes.ThemeRemovedMessage', 'tmsg.ThemeRemovedMessage', (['enactor'], {'target': 'character', 'theme': 'theme', 'list_type': 'list_type'}), '(enactor, target=character, theme=theme, list_type=\n list_type)\n', (4802, 4868), True, 'import athanor.messages.themes as tmsg\n'), ((5097, 5212), 'athanor.messages.themes.ThemeStatusMessage', 'tmsg.ThemeStatusMessage', (['enactor'], {'target': 'character', 'status': 'new_status', 'theme': 'character.db._primary_theme.theme'}), '(enactor, target=character, status=new_status, theme\n =character.db._primary_theme.theme)\n', (5120, 5212), True, 'import athanor.messages.themes as tmsg\n'), ((5709, 5822), 'athanor.messages.themes.ThemeListTypeMessage', 'tmsg.ThemeListTypeMessage', (['enactor'], {'target': 'character', 'theme': 'theme', 'old_list_type': 'old_type', 'list_type': 'new_type'}), '(enactor, target=character, theme=theme,\n old_list_type=old_type, list_type=new_type)\n', (5734, 5822), True, 'import athanor.messages.themes as tmsg\n'), ((1760, 1809), 'athanor.gamedb.themes.AthanorTheme.objects.filter_family', 'AthanorTheme.objects.filter_family', ([], {'id': 'theme_name'}), '(id=theme_name)\n', (1794, 1809), False, 'from athanor.gamedb.themes import AthanorTheme\n'), ((4230, 4331), 'athanor.messages.themes.ThemeSetPrimaryMessage', 'tmsg.ThemeSetPrimaryMessage', (['enactor'], {'target': 'character', 'theme_name': 'theme.key', 'list_type': 'list_type'}), '(enactor, target=character, theme_name=theme.key,\n list_type=list_type)\n', (4257, 4331), True, 'import athanor.messages.themes as tmsg\n'), ((6542, 6732), 'athanor.messages.themes.ThemeChangePrimaryMessage', 'tmsg.ThemeChangePrimaryMessage', (['enactor'], {'target': 'character', 'old_theme_name': 'old_primary.theme.key', 'old_list_type': 'old_list_type', 'theme': 'theme_part.theme', 'list_type': 'theme_part.list_type'}), '(enactor, target=character, old_theme_name=\n old_primary.theme.key, old_list_type=old_list_type, theme=theme_part.\n theme, list_type=theme_part.list_type)\n', (6572, 6732), True, 'import athanor.messages.themes as tmsg\n')]
# -*- coding: utf-8 -*- """ EvMore - pager mechanism This is a pager for displaying long texts and allows stepping up and down in the text (the name comes from the traditional 'more' unix command). To use, simply pass the text through the EvMore object: from evennia.utils.evmore import EvMore text = some_long_text_output() EvMore(caller, text, always_page=False, session=None, justify_kwargs=None, **kwargs) One can also use the convenience function msg from this module: from evennia.utils import evmore text = some_long_text_output() evmore.msg(caller, text, always_page=False, session=None, justify_kwargs=None, **kwargs) Where always_page decides if the pager is used also if the text is not long enough to need to scroll, session is used to determine which session to relay to and justify_kwargs are kwargs to pass to utils.utils.justify in order to change the formatting of the text. The remaining **kwargs will be passed on to the caller.msg() construct every time the page is updated. """ from django.conf import settings from evennia import Command, CmdSet from evennia.commands import cmdhandler from evennia.utils.utils import justify, make_iter _CMD_NOMATCH = cmdhandler.CMD_NOMATCH _CMD_NOINPUT = cmdhandler.CMD_NOINPUT # we need to use NAWS for this _SCREEN_WIDTH = settings.CLIENT_DEFAULT_WIDTH _SCREEN_HEIGHT = settings.CLIENT_DEFAULT_HEIGHT _EVTABLE = None # text _DISPLAY = """{text} (|wmore|n [{pageno}/{pagemax}] retur|wn|n|||wb|nack|||wt|nop|||we|nnd|||wq|nuit)""" class CmdMore(Command): """ Manipulate the text paging """ key = _CMD_NOINPUT aliases = ["quit", "q", "abort", "a", "next", "n", "back", "b", "top", "t", "end", "e"] auto_help = False def func(self): """ Implement the command """ more = self.caller.ndb._more if not more and hasattr(self.caller, "account"): more = self.caller.account.ndb._more if not more: self.caller.msg("Error in loading the pager. Contact an admin.") return cmd = self.cmdstring if cmd in ("abort", "a", "q"): more.page_quit() elif cmd in ("back", "b"): more.page_back() elif cmd in ("top", "t", "look", "l"): more.page_top() elif cmd in ("end", "e"): more.page_end() else: # return or n, next more.page_next() class CmdMoreLook(Command): """ Override look to display window and prevent OOCLook from firing """ key = "look" aliases = ["l"] auto_help = False def func(self): """ Implement the command """ more = self.caller.ndb._more if not more and hasattr(self.caller, "account"): more = self.caller.account.ndb._more if not more: self.caller.msg("Error in loading the pager. Contact an admin.") return more.display() class CmdSetMore(CmdSet): """ Stores the more command """ key = "more_commands" priority = 110 def at_cmdset_creation(self): self.add(CmdMore()) self.add(CmdMoreLook()) class EvMore(object): """ The main pager object """ def __init__( self, caller, text, always_page=False, session=None, justify=False, justify_kwargs=None, exit_on_lastpage=False, exit_cmd=None, **kwargs, ): """ Initialization of the text handler. Args: caller (Object or Account): Entity reading the text. text (str, EvTable or iterator): The text or data to put under paging. - If a string, paginage normally. If this text contains one or more `\f` format symbol, automatic pagination and justification are force-disabled and page-breaks will only happen after each `\f`. - If `EvTable`, the EvTable will be paginated with the same setting on each page if it is too long. The table decorations will be considered in the size of the page. - Otherwise `text` is converted to an iterator, where each step is expected to be a line in the final display. Each line will be run through repr() (so one could pass a list of objects). always_page (bool, optional): If `False`, the pager will only kick in if `text` is too big to fit the screen. session (Session, optional): If given, this session will be used to determine the screen width and will receive all output. justify (bool, optional): If set, auto-justify long lines. This must be turned off for fixed-width or formatted output, like tables. It's force-disabled if `text` is an EvTable. justify_kwargs (dict, optional): Keywords for the justifiy function. Used only if `justify` is True. If this is not set, default arguments will be used. exit_on_lastpage (bool, optional): If reaching the last page without the page being completely filled, exit pager immediately. If unset, another move forward is required to exit. If set, the pager exit message will not be shown. exit_cmd (str, optional): If given, this command-string will be executed on the caller when the more page exits. Note that this will be using whatever cmdset the user had *before* the evmore pager was activated (so none of the evmore commands will be available when this is run). kwargs (any, optional): These will be passed on to the `caller.msg` method. Examples: super_long_text = " ... " EvMore(caller, super_long_text) from django.core.paginator import Paginator query = ObjectDB.objects.all() pages = Paginator(query, 10) # 10 objs per page EvMore(caller, pages) # will repr() each object per line, 10 to a page multi_page_table = [ [[..],[..]], ...] EvMore(caller, multi_page_table, use_evtable=True, evtable_args=("Header1", "Header2"), evtable_kwargs={"align": "r", "border": "tablecols"}) """ self._caller = caller self._kwargs = kwargs self._pages = [] self._npages = 1 self._npos = 0 self.exit_on_lastpage = exit_on_lastpage self.exit_cmd = exit_cmd self._exit_msg = "Exited |wmore|n pager." if not session: # if not supplied, use the first session to # determine screen size sessions = caller.sessions.get() if not sessions: return session = sessions[0] self._session = session # set up individual pages for different sessions height = max(4, session.protocol_flags.get("SCREENHEIGHT", {0: _SCREEN_HEIGHT})[0] - 4) width = session.protocol_flags.get("SCREENWIDTH", {0: _SCREEN_WIDTH})[0] if hasattr(text, "table") and hasattr(text, "get"): # This is an EvTable. table = text if table.height: # enforced height of each paged table, plus space for evmore extras height = table.height - 4 # convert table to string text = str(text) justify_kwargs = None # enforce if not isinstance(text, str): # not a string - pre-set pages of some form text = "\n".join(str(repr(element)) for element in make_iter(text)) if "\f" in text: # we use \f to indicate the user wants to enforce their line breaks # on their own. If so, we do no automatic line-breaking/justification # at all. self._pages = text.split("\f") self._npages = len(self._pages) else: if justify: # we must break very long lines into multiple ones. Note that this # will also remove spurious whitespace. justify_kwargs = justify_kwargs or {} width = justify_kwargs.get("width", width) justify_kwargs["width"] = width justify_kwargs["align"] = justify_kwargs.get("align", "l") justify_kwargs["indent"] = justify_kwargs.get("indent", 0) lines = [] for line in text.split("\n"): if len(line) > width: lines.extend(justify(line, **justify_kwargs).split("\n")) else: lines.append(line) else: # no justification. Simple division by line lines = text.split("\n") # always limit number of chars to 10 000 per page height = min(10000 // max(1, width), height) # figure out the pagination self._pages = ["\n".join(lines[i : i + height]) for i in range(0, len(lines), height)] self._npages = len(self._pages) if self._npages <= 1 and not always_page: # no need for paging; just pass-through. caller.msg(text=self._get_page(0), session=self._session, **kwargs) else: # go into paging mode # first pass on the msg kwargs caller.ndb._more = self caller.cmdset.add(CmdSetMore) # goto top of the text self.page_top() def _get_page(self, pos): return self._pages[pos] def display(self, show_footer=True): """ Pretty-print the page. """ pos = self._npos text = self._get_page(pos) if show_footer: page = _DISPLAY.format(text=text, pageno=pos + 1, pagemax=self._npages) else: page = text # check to make sure our session is still valid sessions = self._caller.sessions.get() if not sessions: self.page_quit() return # this must be an 'is', not == check if not any(ses for ses in sessions if self._session is ses): self._session = sessions[0] self._caller.msg(text=page, session=self._session, **self._kwargs) def page_top(self): """ Display the top page """ self._npos = 0 self.display() def page_end(self): """ Display the bottom page. """ self._npos = self._npages - 1 self.display() def page_next(self): """ Scroll the text to the next page. Quit if already at the end of the page. """ if self._npos >= self._npages - 1: # exit if we are already at the end self.page_quit() else: self._npos += 1 if self.exit_on_lastpage and self._npos >= (self._npages - 1): self.display(show_footer=False) self.page_quit(quiet=True) else: self.display() def page_back(self): """ Scroll the text back up, at the most to the top. """ self._npos = max(0, self._npos - 1) self.display() def page_quit(self, quiet=False): """ Quit the pager """ del self._caller.ndb._more if not quiet: self._caller.msg(text=self._exit_msg, **self._kwargs) self._caller.cmdset.remove(CmdSetMore) if self.exit_cmd: self._caller.execute_cmd(self.exit_cmd, session=self._session) # helper function def msg( caller, text="", always_page=False, session=None, justify=False, justify_kwargs=None, exit_on_lastpage=True, **kwargs, ): """ EvMore-supported version of msg, mimicking the normal msg method. Args: caller (Object or Account): Entity reading the text. text (str, EvTable or iterator): The text or data to put under paging. - If a string, paginage normally. If this text contains one or more `\f` format symbol, automatic pagination is disabled and page-breaks will only happen after each `\f`. - If `EvTable`, the EvTable will be paginated with the same setting on each page if it is too long. The table decorations will be considered in the size of the page. - Otherwise `text` is converted to an iterator, where each step is is expected to be a line in the final display, and each line will be run through repr(). always_page (bool, optional): If `False`, the pager will only kick in if `text` is too big to fit the screen. session (Session, optional): If given, this session will be used to determine the screen width and will receive all output. justify (bool, optional): If set, justify long lines in output. Disable for fixed-format output, like tables. justify_kwargs (dict, bool or None, optional): If given, this should be valid keyword arguments to the utils.justify() function. If False, no justification will be done. exit_on_lastpage (bool, optional): Immediately exit pager when reaching the last page. use_evtable (bool, optional): If True, each page will be rendered as an EvTable. For this to work, `text` must be an iterable, where each element is the table (list of list) to render on that page. evtable_args (tuple, optional): The args to use for EvTable on each page. evtable_kwargs (dict, optional): The kwargs to use for EvTable on each page (except `table`, which is supplied by EvMore per-page). kwargs (any, optional): These will be passed on to the `caller.msg` method. """ EvMore( caller, text, always_page=always_page, session=session, justify=justify, justify_kwargs=justify_kwargs, exit_on_lastpage=exit_on_lastpage, **kwargs, )
[ "evennia.utils.utils.justify", "evennia.utils.utils.make_iter" ]
[((7791, 7806), 'evennia.utils.utils.make_iter', 'make_iter', (['text'], {}), '(text)\n', (7800, 7806), False, 'from evennia.utils.utils import justify, make_iter\n'), ((8746, 8777), 'evennia.utils.utils.justify', 'justify', (['line'], {}), '(line, **justify_kwargs)\n', (8753, 8777), False, 'from evennia.utils.utils import justify, make_iter\n')]
""" Tutorial - talking NPC tests. """ from evennia.commands.default.tests import BaseEvenniaCommandTest from evennia.utils.create import create_object from . import talking_npc class TestTalkingNPC(BaseEvenniaCommandTest): def test_talkingnpc(self): npc = create_object(talking_npc.TalkingNPC, key="npctalker", location=self.room1) self.call(talking_npc.CmdTalk(), "", "(You walk up and talk to Char.)") npc.delete()
[ "evennia.utils.create.create_object" ]
[((271, 346), 'evennia.utils.create.create_object', 'create_object', (['talking_npc.TalkingNPC'], {'key': '"""npctalker"""', 'location': 'self.room1'}), "(talking_npc.TalkingNPC, key='npctalker', location=self.room1)\n", (284, 346), False, 'from evennia.utils.create import create_object\n')]
""" MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from evennia import Command from evennia.utils.ansi import raw as raw_ansi from evennia.utils import utils from world.definitions.itemdefs import WearLocation from typeclasses.characters import calculate_ability_modifier class CmdInventory(Command): """ view inventory Usage: inventory inv Shows your inventory. """ key = "inventory" aliases = ["inv", "i"] locks = "cmd:all()" arg_regex = r"$" def func(self): """check inventory""" items = self.caller.contents if not items: string = "You are not carrying anything." else: from evennia.utils.ansi import raw as raw_ansi table = self.styled_table(border="header") for item in items: if item.attributes.has("current_worn_location"): if item.is_currently_worn(): # do not display messages as being in inventory if they # are being worn continue if item in self.caller.db.auras: # ignore auras continue table.add_row( f"|C{item.name}|n", "{}|n".format( utils.crop(raw_ansi(item.db.desc), width=50) or "" ), ) string = f"|wYou are carrying:\n{table}" self.caller.msg(string) class CmdSheet(Command): key = "sheet" def func(self): caller = self.caller stat_sheet = """ +-------------------------------------------------------- | Name: {name} | Age: {age}, Race: {race}, Gender: {gender} | Birth Augur: {augur} | Occupation: {occupation} | Alignment: {align} | Wealth: {gold}gp, {silver}sp, {copper}cp | Level: {level}, XP: {xp} +-------------------------------------------------------- | Str : {strength} | HP : {cur_hp} (max: {max_hp}) | Agi : {agility} | AC : {ac} | Stam : {stamina} | Speed : {speed} | Pers : {personality} | | Int : {intelligence} | | Luck : {luck} | +-------------------------------------------------------- | Known Languages: {languages} +-------------------------------------------------------- """ languages = "" current_line = "" first_line = True for lang in caller.db.known_languages: lang_str = lang.display_name lang_len = len(lang_str) line_length = 52 if first_line: line_length = 40 if (len(current_line) + lang_len) > line_length: if first_line: first_line = False languages += current_line.rstrip().rstrip(",") current_line = "\n| " current_line = f'{current_line}{lang_str}, ' languages += current_line.rstrip().rstrip(",") augur_str = caller.db.birth_augur.display_name[1] modified_strength = caller.get_modified_strength() modified_agility = caller.get_modified_agility() modified_stamina = caller.get_modified_stamina() modified_personality = caller.get_modified_personality() modified_intelligence = caller.get_modified_intelligence() modified_luck = caller.get_modified_luck() modified_speed = caller.get_modified_speed() modified_hp = caller.get_modified_hp() modified_ac = caller.get_modified_ac() caller.msg(stat_sheet.format( name=caller.name, age=caller.db.age, race=caller.db.race.display_name, level=caller.db.level, xp=caller.db.xp, gender=caller.db.gender, occupation=caller.db.occupation.display_name, align=caller.db.alignment.display_name, augur=augur_str, strength=f'{modified_strength}'.rjust(2, " "), agility=f'{modified_agility}'.rjust(2, " "), stamina=f'{modified_stamina}'.rjust(2, " "), personality=f'{modified_personality}'.rjust(2, " "), intelligence=f'{modified_intelligence}'.rjust(2, " "), luck=f'{modified_luck}'.rjust(2, " "), max_hp=f'{modified_hp}'.rjust(2, " "), cur_hp=f'{caller.db.current_hp}'.rjust(2, " "), languages=languages, ac=f'{modified_ac}'.rjust(2, " "), gold=f'{caller.db.gold}'.rjust(3, " "), silver=f'{caller.db.silver}'.rjust(3, " "), copper=f'{caller.db.copper}'.rjust(3, " "), speed=f'{modified_speed}'.rjust(2, " ") )) class CmdModifiers(Command): key = "modifiers" def func(self): caller = self.caller modifiers_sheet = """ +-------------------------------------------------------- | Str : {strength} {str_effect} | Agi : {agility} {agi_effect} | Stam : {stamina} {stam_effect} | Pers : {personality} {pers_effect} | Int : {intelligence} | Luck : {luck} {calamaties} {known_effects} """ augur_effect = "No effect." calamaties = \ "+--------------------------------------------------------" has_calamaties = False if caller.db.strength <= 5: calamaties += \ "\n| You can only hold a weapon or a shield, not both." has_calamaties = True if caller.db.stamina <= 5: calamaties += \ "\n| You take double damage from poisons and diseases." has_calamaties = True if caller.db.intelligence <= 7: calamaties += "\n| You can only speak Common." has_calamaties = True if caller.db.intelligence <= 5: calamaties += "\n| You cannot read or write." has_calamaties = True if has_calamaties: calamaties += \ "\n+--------------------------------------------------------" effects = "| Effects:" has_effects = False if len(caller.db.auras) > 0: for a in caller.db.auras: if not a.db.hidden and a.db.known_effects: effects += f'\n| {a.key}: {a.db.modifier_description}' has_effects = True if has_effects: effects += \ "\n+--------------------------------------------------------" else: effects += "\n| None" effects += \ "\n+--------------------------------------------------------" str_modifier = calculate_ability_modifier(caller.db.strength) str_effect = "to melee atk/dmg rolls" agi_modifier = calculate_ability_modifier(caller.db.agility) agi_effect = "to AC, ranged atk, initiative, reflex save" stam_modifier = calculate_ability_modifier(caller.db.stamina) stam_effect = "to max HP, fortitude save" pers_modifier = calculate_ability_modifier(caller.db.personality) pers_effect = "to willpower save" int_modifier = calculate_ability_modifier(caller.db.intelligence) luck_modifier = calculate_ability_modifier(caller.db.luck) caller.msg(modifiers_sheet.format( strength=f'{str_modifier}'.rjust(2, " "), agility=f'{agi_modifier}'.rjust(2, " "), stamina=f'{stam_modifier}'.rjust(2, " "), personality=f'{pers_modifier}'.rjust(2, " "), intelligence=f'{int_modifier}'.rjust(2, " "), luck=f'{luck_modifier}'.rjust(2, " "), str_effect=str_effect, agi_effect=agi_effect, stam_effect=stam_effect, pers_effect=pers_effect, augur_effect=augur_effect, calamaties=calamaties, known_effects=effects )) class CmdEquipment(Command): """ view equipment Usage: equipment equip Shows your equipment. """ key = "equipment" aliases = ["equip"] locks = "cmd:all()" def func(self): caller = self.caller items = caller.contents if not items: string = "You are not wearing anything." else: table = self.styled_table(border="header") worn_items = {} for item in items: if item.attributes.has("current_worn_location"): if item.is_currently_worn(): if item.db.current_worn_location not in worn_items: worn_items[item.db.current_worn_location] = [] worn_items[item.db.current_worn_location].append( item ) wearlocs = list(WearLocation) for loc in wearlocs: if loc in worn_items: for item in worn_items[loc]: table.add_row( "[{}]".format(loc.display_name), "{}|n".format( utils.crop(raw_ansi(item.name), width=50) ), ) string = f"|wYou are wearing:\n{table}" caller.msg(string)
[ "evennia.utils.ansi.raw" ]
[((7600, 7646), 'typeclasses.characters.calculate_ability_modifier', 'calculate_ability_modifier', (['caller.db.strength'], {}), '(caller.db.strength)\n', (7626, 7646), False, 'from typeclasses.characters import calculate_ability_modifier\n'), ((7717, 7762), 'typeclasses.characters.calculate_ability_modifier', 'calculate_ability_modifier', (['caller.db.agility'], {}), '(caller.db.agility)\n', (7743, 7762), False, 'from typeclasses.characters import calculate_ability_modifier\n'), ((7854, 7899), 'typeclasses.characters.calculate_ability_modifier', 'calculate_ability_modifier', (['caller.db.stamina'], {}), '(caller.db.stamina)\n', (7880, 7899), False, 'from typeclasses.characters import calculate_ability_modifier\n'), ((7975, 8024), 'typeclasses.characters.calculate_ability_modifier', 'calculate_ability_modifier', (['caller.db.personality'], {}), '(caller.db.personality)\n', (8001, 8024), False, 'from typeclasses.characters import calculate_ability_modifier\n'), ((8091, 8141), 'typeclasses.characters.calculate_ability_modifier', 'calculate_ability_modifier', (['caller.db.intelligence'], {}), '(caller.db.intelligence)\n', (8117, 8141), False, 'from typeclasses.characters import calculate_ability_modifier\n'), ((8166, 8208), 'typeclasses.characters.calculate_ability_modifier', 'calculate_ability_modifier', (['caller.db.luck'], {}), '(caller.db.luck)\n', (8192, 8208), False, 'from typeclasses.characters import calculate_ability_modifier\n'), ((2367, 2389), 'evennia.utils.ansi.raw', 'raw_ansi', (['item.db.desc'], {}), '(item.db.desc)\n', (2375, 2389), True, 'from evennia.utils.ansi import raw as raw_ansi\n'), ((10081, 10100), 'evennia.utils.ansi.raw', 'raw_ansi', (['item.name'], {}), '(item.name)\n', (10089, 10100), True, 'from evennia.utils.ansi import raw as raw_ansi\n')]
# # This sets up how models are displayed # in the web admin interface. # from django.conf import settings from django import forms from django.urls import reverse from django.http import HttpResponseRedirect from django.conf import settings from django.conf.urls import url from django.contrib import admin, messages from django.contrib.admin.utils import flatten_fieldsets from django.contrib.admin.widgets import ForeignKeyRawIdWidget from django.utils.html import format_html from django.utils.translation import gettext as _ from evennia.objects.models import ObjectDB from evennia.accounts.models import AccountDB from .attributes import AttributeInline from .tags import TagInline from . import utils as adminutils class ObjectAttributeInline(AttributeInline): """ Defines inline descriptions of Attributes (experimental) """ model = ObjectDB.db_attributes.through related_field = "objectdb" class ObjectTagInline(TagInline): """ Defines inline descriptions of Tags (experimental) """ model = ObjectDB.db_tags.through related_field = "objectdb" class ObjectCreateForm(forms.ModelForm): """ This form details the look of the fields. """ class Meta(object): model = ObjectDB fields = "__all__" db_key = forms.CharField( label="Name/Key", widget=forms.TextInput(attrs={"size": "78"}), help_text="Main identifier, like 'apple', 'strong guy', 'Elizabeth' etc. " "If creating a Character, check so the name is unique among characters!", ) db_typeclass_path = forms.ChoiceField( label="Typeclass", initial={settings.BASE_OBJECT_TYPECLASS: settings.BASE_OBJECT_TYPECLASS}, help_text="This is the Python-path to the class implementing the actual functionality. " f"<BR>If you are creating a Character you usually need <B>{settings.BASE_CHARACTER_TYPECLASS}</B> " "or a subclass of that. <BR>If your custom class is not found in the list, it may not be imported " "into Evennia yet.", choices=lambda: adminutils.get_and_load_typeclasses(parent=ObjectDB)) db_lock_storage = forms.CharField( label="Locks", required=False, widget=forms.Textarea(attrs={"cols": "100", "rows": "2"}), help_text="In-game lock definition string. If not given, defaults will be used. " "This string should be on the form " "<i>type:lockfunction(args);type2:lockfunction2(args);...", ) db_cmdset_storage = forms.CharField( label="CmdSet", initial="", required=False, widget=forms.TextInput(attrs={"size": "78"}), ) # This is not working well because it will not properly allow an empty choice, and will # also not work well for comma-separated storage without more work. Notably, it's also # a bit hard to visualize. # db_cmdset_storage = forms.MultipleChoiceField( # label="CmdSet", # required=False, # choices=adminutils.get_and_load_typeclasses(parent=ObjectDB)) db_location = forms.ModelChoiceField( ObjectDB.objects.all(), label="Location", required=False, widget=ForeignKeyRawIdWidget( ObjectDB._meta.get_field('db_location').remote_field, admin.site), help_text="The (current) in-game location.<BR>" "Usually a Room but can be<BR>" "empty for un-puppeted Characters." ) db_home = forms.ModelChoiceField( ObjectDB.objects.all(), label="Home", required=False, widget=ForeignKeyRawIdWidget( ObjectDB._meta.get_field('db_location').remote_field, admin.site), help_text="Fallback in-game location.<BR>" "All objects should usually have<BR>" "a home location." ) db_destination = forms.ModelChoiceField( ObjectDB.objects.all(), label="Destination", required=False, widget=ForeignKeyRawIdWidget( ObjectDB._meta.get_field('db_destination').remote_field, admin.site), help_text="Only used by Exits." ) def __init__(self, *args, **kwargs): """ Tweak some fields dynamically. """ super().__init__(*args, **kwargs) # set default home home_id = str(settings.DEFAULT_HOME) home_id = home_id[1:] if home_id.startswith("#") else home_id default_home = ObjectDB.objects.filter(id=home_id) if default_home: default_home = default_home[0] self.fields["db_home"].initial = default_home self.fields["db_location"].initial = default_home # better help text for cmdset_storage char_cmdset = settings.CMDSET_CHARACTER account_cmdset = settings.CMDSET_ACCOUNT self.fields["db_cmdset_storage"].help_text = ( "Path to Command-set path. Most non-character objects don't need a cmdset" " and can leave this field blank. Default cmdset-path<BR> for Characters " f"is <strong>{char_cmdset}</strong> ." ) class ObjectEditForm(ObjectCreateForm): """ Form used for editing. Extends the create one with more fields """ class Meta: model = ObjectDB fields = "__all__" db_account = forms.ModelChoiceField( AccountDB.objects.all(), label="Puppeting Account", required=False, widget=ForeignKeyRawIdWidget( ObjectDB._meta.get_field('db_account').remote_field, admin.site), help_text="An Account puppeting this Object (if any).<BR>Note that when a user logs " "off/unpuppets, this<BR>field will be empty again. This is normal." ) @admin.register(ObjectDB) class ObjectAdmin(admin.ModelAdmin): """ Describes the admin page for Objects. """ inlines = [ObjectTagInline, ObjectAttributeInline] list_display = ("id", "db_key", "db_typeclass_path", "db_location", "db_destination", "db_account", "db_date_created") list_display_links = ("id", "db_key") ordering = ["-db_date_created", "-id"] search_fields = ["=id", "^db_key", "db_typeclass_path", "^db_account__db_key", "^db_location__db_key"] raw_id_fields = ("db_destination", "db_location", "db_home", "db_account") readonly_fields = ("serialized_string", "link_button") save_as = True save_on_top = True list_select_related = True view_on_site = False list_filter = ("db_typeclass_path",) # editing fields setup form = ObjectEditForm fieldsets = ( ( None, { "fields": ( ("db_key", "db_typeclass_path"), ("db_location", "db_home", "db_destination"), ("db_account", "link_button"), "db_cmdset_storage", "db_lock_storage", "serialized_string" ) }, ), ) add_form = ObjectCreateForm add_fieldsets = ( ( None, { "fields": ( ("db_key", "db_typeclass_path"), ("db_location", "db_home", "db_destination"), "db_cmdset_storage", ) }, ), ) def serialized_string(self, obj): """ Get the serialized version of the object. """ from evennia.utils import dbserialize return str(dbserialize.pack_dbobj(obj)) serialized_string.help_text = ( "Copy & paste this string into an Attribute's `value` field to store it there." ) def get_fieldsets(self, request, obj=None): """ Return fieldsets. Args: request (Request): Incoming request. obj (Object, optional): Database object. """ if not obj: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during creation. Args: request (Request): Incoming request. obj (Object, optional): Database object. """ help_texts = kwargs.get("help_texts", {}) help_texts["serialized_string"] = self.serialized_string.help_text kwargs["help_texts"] = help_texts defaults = {} if obj is None: defaults.update( {"form": self.add_form, "fields": flatten_fieldsets(self.add_fieldsets)} ) defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): urls = super().get_urls() custom_urls = [ url( r"^account-object-link/(?P<object_id>.+)/$", self.admin_site.admin_view(self.link_object_to_account), name="object-account-link" ) ] return custom_urls + urls def link_button(self, obj): return format_html( '<a class="button" href="{}">Link to Account</a>&nbsp;', reverse("admin:object-account-link", args=[obj.pk]) ) link_button.short_description = "Create attrs/locks for puppeting" link_button.allow_tags = True def link_object_to_account(self, request, object_id): """ Link object and account when pressing the button. This will: - Set account.db._last_puppet to this object - Add object to account.db._playable_characters - Change object locks to allow puppeting by account """ obj = self.get_object(request, object_id) account = obj.db_account if account: account.db._last_puppet = obj if not account.db._playable_characters: account.db._playable_characters = [] if obj not in account.db._playable_characters: account.db._playable_characters.append(obj) if not obj.access(account, "puppet"): lock = obj.locks.get("puppet") lock += f" or pid({account.id})" obj.locks.add(lock) self.message_user(request, "Did the following (where possible): " f"Set Account.db._last_puppet = {obj}, " f"Added {obj} to Account.db._playable_characters list, " f"Added 'puppet:pid({account.id})' lock to {obj}.") else: self.message_user(request, "Account must be connected for this action " "(set Puppeting Account and save this page first).", level=messages.ERROR) # stay on the same page return HttpResponseRedirect(reverse("admin:objects_objectdb_change", args=[obj.pk])) def save_model(self, request, obj, form, change): """ Model-save hook. Args: request (Request): Incoming request. obj (Object): Database object. form (Form): Form instance. change (bool): If this is a change or a new object. """ if not change: # adding a new object # have to call init with typeclass passed to it obj.set_class_from_typeclass(typeclass_path=obj.db_typeclass_path) obj.save() obj.basetype_setup() obj.basetype_posthook_setup() obj.at_object_creation() else: obj.save() obj.at_init() def response_add(self, request, obj, post_url_continue=None): from django.http import HttpResponseRedirect from django.urls import reverse return HttpResponseRedirect(reverse("admin:objects_objectdb_change", args=[obj.id]))
[ "evennia.accounts.models.AccountDB.objects.all", "evennia.objects.models.ObjectDB.objects.filter", "evennia.objects.models.ObjectDB.objects.all", "evennia.utils.dbserialize.pack_dbobj", "evennia.objects.models.ObjectDB._meta.get_field" ]
[((5747, 5771), 'django.contrib.admin.register', 'admin.register', (['ObjectDB'], {}), '(ObjectDB)\n', (5761, 5771), False, 'from django.contrib import admin, messages\n'), ((3105, 3127), 'evennia.objects.models.ObjectDB.objects.all', 'ObjectDB.objects.all', ([], {}), '()\n', (3125, 3127), False, 'from evennia.objects.models import ObjectDB\n'), ((3508, 3530), 'evennia.objects.models.ObjectDB.objects.all', 'ObjectDB.objects.all', ([], {}), '()\n', (3528, 3530), False, 'from evennia.objects.models import ObjectDB\n'), ((3902, 3924), 'evennia.objects.models.ObjectDB.objects.all', 'ObjectDB.objects.all', ([], {}), '()\n', (3922, 3924), False, 'from evennia.objects.models import ObjectDB\n'), ((4463, 4498), 'evennia.objects.models.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'id': 'home_id'}), '(id=home_id)\n', (4486, 4498), False, 'from evennia.objects.models import ObjectDB\n'), ((5358, 5381), 'evennia.accounts.models.AccountDB.objects.all', 'AccountDB.objects.all', ([], {}), '()\n', (5379, 5381), False, 'from evennia.accounts.models import AccountDB\n'), ((1356, 1393), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'size': '78'}"}), "(attrs={'size': '78'})\n", (1371, 1393), False, 'from django import forms\n'), ((2232, 2282), 'django.forms.Textarea', 'forms.Textarea', ([], {'attrs': "{'cols': '100', 'rows': '2'}"}), "(attrs={'cols': '100', 'rows': '2'})\n", (2246, 2282), False, 'from django import forms\n'), ((2617, 2654), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'size': '78'}"}), "(attrs={'size': '78'})\n", (2632, 2654), False, 'from django import forms\n'), ((7514, 7541), 'evennia.utils.dbserialize.pack_dbobj', 'dbserialize.pack_dbobj', (['obj'], {}), '(obj)\n', (7536, 7541), False, 'from evennia.utils import dbserialize\n'), ((9150, 9201), 'django.urls.reverse', 'reverse', (['"""admin:object-account-link"""'], {'args': '[obj.pk]'}), "('admin:object-account-link', args=[obj.pk])\n", (9157, 9201), False, 'from django.urls import reverse\n'), ((10851, 10906), 'django.urls.reverse', 'reverse', (['"""admin:objects_objectdb_change"""'], {'args': '[obj.pk]'}), "('admin:objects_objectdb_change', args=[obj.pk])\n", (10858, 10906), False, 'from django.urls import reverse\n'), ((11817, 11872), 'django.urls.reverse', 'reverse', (['"""admin:objects_objectdb_change"""'], {'args': '[obj.id]'}), "('admin:objects_objectdb_change', args=[obj.id])\n", (11824, 11872), False, 'from django.urls import reverse\n'), ((3229, 3268), 'evennia.objects.models.ObjectDB._meta.get_field', 'ObjectDB._meta.get_field', (['"""db_location"""'], {}), "('db_location')\n", (3253, 3268), False, 'from evennia.objects.models import ObjectDB\n'), ((3628, 3667), 'evennia.objects.models.ObjectDB._meta.get_field', 'ObjectDB._meta.get_field', (['"""db_location"""'], {}), "('db_location')\n", (3652, 3667), False, 'from evennia.objects.models import ObjectDB\n'), ((4029, 4071), 'evennia.objects.models.ObjectDB._meta.get_field', 'ObjectDB._meta.get_field', (['"""db_destination"""'], {}), "('db_destination')\n", (4053, 4071), False, 'from evennia.objects.models import ObjectDB\n'), ((5492, 5530), 'evennia.objects.models.ObjectDB._meta.get_field', 'ObjectDB._meta.get_field', (['"""db_account"""'], {}), "('db_account')\n", (5516, 5530), False, 'from evennia.objects.models import ObjectDB\n'), ((8530, 8567), 'django.contrib.admin.utils.flatten_fieldsets', 'flatten_fieldsets', (['self.add_fieldsets'], {}), '(self.add_fieldsets)\n', (8547, 8567), False, 'from django.contrib.admin.utils import flatten_fieldsets\n')]
# Views for our help topics app from django.core.exceptions import PermissionDenied from django.http import Http404 from django.shortcuts import render, get_object_or_404 from evennia.help.models import HelpEntry from world.dominion.models import ( CraftingRecipe, CraftingMaterialType, Organization, Member, ) from web.helpdesk.models import KBCategory def topic(request, object_key): object_key = object_key.lower() topic_ob = get_object_or_404(HelpEntry, db_key__iexact=object_key) can_see = False try: can_see = topic_ob.access(request.user, "view", default=True) except AttributeError: pass if not can_see: raise PermissionDenied return render( request, "help_topics/topic.html", {"topic": topic_ob, "page_title": object_key} ) def command_help(request, cmd_key): from commands.default_cmdsets import AccountCmdSet, CharacterCmdSet from commands.cmdsets.situational import SituationalCmdSet user = request.user cmd_key = cmd_key.lower() matches = [ ob for ob in AccountCmdSet() if ob.key.lower() == cmd_key and ob.access(user, "cmd") ] matches += [ ob for ob in CharacterCmdSet() if ob.key.lower() == cmd_key and ob.access(user, "cmd") ] matches += [ ob for ob in SituationalCmdSet() if ob.key.lower() == cmd_key and ob.access(user, "cmd") ] return render( request, "help_topics/command_help.html", {"matches": matches, "page_title": cmd_key}, ) def list_topics(request): user = request.user try: all_topics = [] for topic_ob in HelpEntry.objects.all(): try: if topic_ob.access(user, "view", default=True): all_topics.append(topic_ob) except AttributeError: continue all_topics = sorted(all_topics, key=lambda entry: entry.key.lower()) all_categories = list( set( [ topic_ob.help_category.capitalize() for topic_ob in all_topics if topic_ob.access(user, "view") ] ) ) all_categories = sorted(all_categories) except IndexError: raise Http404("Error in compiling topic list.") # organizations also from django.db.models import Q all_orgs = ( Organization.objects.filter( Q(secret=False) & Q(members__deguilded=False) & Q(members__player__player__isnull=False) ) .distinct() .order_by("name") ) secret_orgs = [] # noinspection PyBroadException try: if user.is_staff or user.check_permstring("can_see_secret_orgs"): secret_orgs = Organization.objects.filter(secret=True) else: secret_orgs = Organization.objects.filter( Q(members__deguilded=False) & Q(secret=True) & Q(members__player__player=user) ) except Exception: pass lore_categories = KBCategory.objects.filter(parent__isnull=True) return render( request, "help_topics/list.html", { "all_topics": all_topics, "all_categories": all_categories, "lore_categories": lore_categories, "all_orgs": all_orgs, "secret_orgs": secret_orgs, "page_title": "topics", }, ) def list_recipes(request): user = request.user all_recipes = CraftingRecipe.objects.all().order_by("ability", "difficulty") if not user.is_staff: all_recipes = all_recipes.exclude(known_by__organization_owner__isnull=False) recipe_name = request.GET.get("recipe_name") if recipe_name: all_recipes = all_recipes.filter(name__icontains=recipe_name) ability = request.GET.get("ability") if ability: all_recipes = all_recipes.filter(ability__iexact=ability) difficulty = request.GET.get("difficulty") if difficulty: try: all_recipes = all_recipes.filter(difficulty__gte=difficulty) except (ValueError, TypeError): pass known_recipes = [] materials = CraftingMaterialType.objects.all().order_by("value") try: known_recipes = user.Dominion.assets.recipes.all() except AttributeError: pass return render( request, "help_topics/recipes.html", { "all_recipes": all_recipes, "materials": materials, "known_recipes": known_recipes, "page_title": "recipes", }, ) def display_org(request, object_id): user = request.user rank_display = 0 show_secret = 0 org = get_object_or_404(Organization, id=object_id) if not user.is_staff: if org.secret: try: if not org.members.filter( deguilded=False, player__player__id=user.id ).exists(): raise PermissionDenied try: rank_display = user.Dominion.memberships.get( organization=org, deguilded=False ).rank except (Member.DoesNotExist, AttributeError): rank_display = 11 show_secret = rank_display except (AttributeError, PermissionDenied): raise PermissionDenied else: try: show_secret = user.Dominion.memberships.get( organization=org, deguilded=False ).rank except (Member.DoesNotExist, AttributeError): show_secret = 11 try: show_money = org.assets.can_be_viewed_by(user) except AttributeError: show_money = False try: holdings = org.assets.estate.holdings.all() except AttributeError: holdings = [] active_tab = request.GET.get("active_tab") if not active_tab or active_tab == "all": members = org.all_members.exclude(player__player__roster__roster__name="Gone") active_tab = "all" elif active_tab == "active": members = org.active_members elif active_tab == "available": members = org.all_members.filter( player__player__roster__roster__name="Available" ) else: members = org.all_members.filter(player__player__roster__roster__name="Gone") return render( request, "help_topics/org.html", { "org": org, "members": members, "active_tab": active_tab, "holdings": holdings, "rank_display": rank_display, "show_secret": show_secret, "page_title": org, "show_money": show_money, }, ) def list_commands(request): from commands.default_cmdsets import AccountCmdSet, CharacterCmdSet from commands.cmdsets.situational import SituationalCmdSet user = request.user def sort_name(cmd): cmdname = cmd.key.lower() cmdname = cmdname.lstrip("+").lstrip("@") return cmdname def check_cmd_access(cmdset): cmd_list = [] for cmd in cmdset: try: if cmd.access(user, "cmd"): cmd_list.append(cmd) except (AttributeError, ValueError, TypeError): continue return sorted(cmd_list, key=sort_name) player_cmds = check_cmd_access(AccountCmdSet()) char_cmds = check_cmd_access(CharacterCmdSet()) situational_cmds = check_cmd_access(SituationalCmdSet()) return render( request, "help_topics/list_commands.html", { "player_cmds": player_cmds, "character_cmds": char_cmds, "situational_cmds": situational_cmds, "page_title": "commands", }, ) def lore_categories(request, object_id): kb_cat = get_object_or_404(KBCategory, id=object_id) return render( request, "help_topics/lore_category.html", { "kb_cat": kb_cat, "kb_items": kb_cat.kb_items.all(), "kb_subs": kb_cat.subcategories.all(), "kb_parent": kb_cat.parent, "page_title": kb_cat, }, )
[ "evennia.help.models.HelpEntry.objects.all" ]
[((456, 511), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['HelpEntry'], {'db_key__iexact': 'object_key'}), '(HelpEntry, db_key__iexact=object_key)\n', (473, 511), False, 'from django.shortcuts import render, get_object_or_404\n'), ((713, 805), 'django.shortcuts.render', 'render', (['request', '"""help_topics/topic.html"""', "{'topic': topic_ob, 'page_title': object_key}"], {}), "(request, 'help_topics/topic.html', {'topic': topic_ob, 'page_title':\n object_key})\n", (719, 805), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1456, 1553), 'django.shortcuts.render', 'render', (['request', '"""help_topics/command_help.html"""', "{'matches': matches, 'page_title': cmd_key}"], {}), "(request, 'help_topics/command_help.html', {'matches': matches,\n 'page_title': cmd_key})\n", (1462, 1553), False, 'from django.shortcuts import render, get_object_or_404\n'), ((3148, 3194), 'web.helpdesk.models.KBCategory.objects.filter', 'KBCategory.objects.filter', ([], {'parent__isnull': '(True)'}), '(parent__isnull=True)\n', (3173, 3194), False, 'from web.helpdesk.models import KBCategory\n'), ((3206, 3426), 'django.shortcuts.render', 'render', (['request', '"""help_topics/list.html"""', "{'all_topics': all_topics, 'all_categories': all_categories,\n 'lore_categories': lore_categories, 'all_orgs': all_orgs, 'secret_orgs':\n secret_orgs, 'page_title': 'topics'}"], {}), "(request, 'help_topics/list.html', {'all_topics': all_topics,\n 'all_categories': all_categories, 'lore_categories': lore_categories,\n 'all_orgs': all_orgs, 'secret_orgs': secret_orgs, 'page_title': 'topics'})\n", (3212, 3426), False, 'from django.shortcuts import render, get_object_or_404\n'), ((4461, 4623), 'django.shortcuts.render', 'render', (['request', '"""help_topics/recipes.html"""', "{'all_recipes': all_recipes, 'materials': materials, 'known_recipes':\n known_recipes, 'page_title': 'recipes'}"], {}), "(request, 'help_topics/recipes.html', {'all_recipes': all_recipes,\n 'materials': materials, 'known_recipes': known_recipes, 'page_title':\n 'recipes'})\n", (4467, 4623), False, 'from django.shortcuts import render, get_object_or_404\n'), ((4820, 4865), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Organization'], {'id': 'object_id'}), '(Organization, id=object_id)\n', (4837, 4865), False, 'from django.shortcuts import render, get_object_or_404\n'), ((6541, 6777), 'django.shortcuts.render', 'render', (['request', '"""help_topics/org.html"""', "{'org': org, 'members': members, 'active_tab': active_tab, 'holdings':\n holdings, 'rank_display': rank_display, 'show_secret': show_secret,\n 'page_title': org, 'show_money': show_money}"], {}), "(request, 'help_topics/org.html', {'org': org, 'members': members,\n 'active_tab': active_tab, 'holdings': holdings, 'rank_display':\n rank_display, 'show_secret': show_secret, 'page_title': org,\n 'show_money': show_money})\n", (6547, 6777), False, 'from django.shortcuts import render, get_object_or_404\n'), ((7721, 7901), 'django.shortcuts.render', 'render', (['request', '"""help_topics/list_commands.html"""', "{'player_cmds': player_cmds, 'character_cmds': char_cmds,\n 'situational_cmds': situational_cmds, 'page_title': 'commands'}"], {}), "(request, 'help_topics/list_commands.html', {'player_cmds':\n player_cmds, 'character_cmds': char_cmds, 'situational_cmds':\n situational_cmds, 'page_title': 'commands'})\n", (7727, 7901), False, 'from django.shortcuts import render, get_object_or_404\n'), ((8040, 8083), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['KBCategory'], {'id': 'object_id'}), '(KBCategory, id=object_id)\n', (8057, 8083), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1690, 1713), 'evennia.help.models.HelpEntry.objects.all', 'HelpEntry.objects.all', ([], {}), '()\n', (1711, 1713), False, 'from evennia.help.models import HelpEntry\n'), ((7580, 7595), 'commands.default_cmdsets.AccountCmdSet', 'AccountCmdSet', ([], {}), '()\n', (7593, 7595), False, 'from commands.default_cmdsets import AccountCmdSet, CharacterCmdSet\n'), ((7630, 7647), 'commands.default_cmdsets.CharacterCmdSet', 'CharacterCmdSet', ([], {}), '()\n', (7645, 7647), False, 'from commands.default_cmdsets import AccountCmdSet, CharacterCmdSet\n'), ((7689, 7708), 'commands.cmdsets.situational.SituationalCmdSet', 'SituationalCmdSet', ([], {}), '()\n', (7706, 7708), False, 'from commands.cmdsets.situational import SituationalCmdSet\n'), ((1089, 1104), 'commands.default_cmdsets.AccountCmdSet', 'AccountCmdSet', ([], {}), '()\n', (1102, 1104), False, 'from commands.default_cmdsets import AccountCmdSet, CharacterCmdSet\n'), ((1221, 1238), 'commands.default_cmdsets.CharacterCmdSet', 'CharacterCmdSet', ([], {}), '()\n', (1236, 1238), False, 'from commands.default_cmdsets import AccountCmdSet, CharacterCmdSet\n'), ((1355, 1374), 'commands.cmdsets.situational.SituationalCmdSet', 'SituationalCmdSet', ([], {}), '()\n', (1372, 1374), False, 'from commands.cmdsets.situational import SituationalCmdSet\n'), ((2330, 2371), 'django.http.Http404', 'Http404', (['"""Error in compiling topic list."""'], {}), "('Error in compiling topic list.')\n", (2337, 2371), False, 'from django.http import Http404\n'), ((2840, 2880), 'world.dominion.models.Organization.objects.filter', 'Organization.objects.filter', ([], {'secret': '(True)'}), '(secret=True)\n', (2867, 2880), False, 'from world.dominion.models import CraftingRecipe, CraftingMaterialType, Organization, Member\n'), ((3604, 3632), 'world.dominion.models.CraftingRecipe.objects.all', 'CraftingRecipe.objects.all', ([], {}), '()\n', (3630, 3632), False, 'from world.dominion.models import CraftingRecipe, CraftingMaterialType, Organization, Member\n'), ((4289, 4323), 'world.dominion.models.CraftingMaterialType.objects.all', 'CraftingMaterialType.objects.all', ([], {}), '()\n', (4321, 4323), False, 'from world.dominion.models import CraftingRecipe, CraftingMaterialType, Organization, Member\n'), ((3045, 3076), 'django.db.models.Q', 'Q', ([], {'members__player__player': 'user'}), '(members__player__player=user)\n', (3046, 3076), False, 'from django.db.models import Q\n'), ((2966, 2993), 'django.db.models.Q', 'Q', ([], {'members__deguilded': '(False)'}), '(members__deguilded=False)\n', (2967, 2993), False, 'from django.db.models import Q\n'), ((3012, 3026), 'django.db.models.Q', 'Q', ([], {'secret': '(True)'}), '(secret=True)\n', (3013, 3026), False, 'from django.db.models import Q\n'), ((2571, 2611), 'django.db.models.Q', 'Q', ([], {'members__player__player__isnull': '(False)'}), '(members__player__player__isnull=False)\n', (2572, 2611), False, 'from django.db.models import Q\n'), ((2499, 2514), 'django.db.models.Q', 'Q', ([], {'secret': '(False)'}), '(secret=False)\n', (2500, 2514), False, 'from django.db.models import Q\n'), ((2529, 2556), 'django.db.models.Q', 'Q', ([], {'members__deguilded': '(False)'}), '(members__deguilded=False)\n', (2530, 2556), False, 'from django.db.models import Q\n')]
""" Various helper resources for writing unittests. """ import sys from twisted.internet.defer import Deferred from django.conf import settings from django.test import TestCase from mock import Mock, patch from evennia.objects.objects import DefaultObject, DefaultCharacter, DefaultRoom, DefaultExit from evennia.accounts.accounts import DefaultAccount from evennia.scripts.scripts import DefaultScript from evennia.server.serversession import ServerSession from evennia.server.sessionhandler import SESSIONS from evennia.utils import create from evennia.utils.idmapper.models import flush_cache # mocking of evennia.utils.utils.delay def mockdelay(timedelay, callback, *args, **kwargs): callback(*args, **kwargs) return Deferred() # mocking of twisted's deferLater def mockdeferLater(reactor, timedelay, callback, *args, **kwargs): callback(*args, **kwargs) return Deferred() def unload_module(module): """ Reset import so one can mock global constants. Args: module (module, object or str): The module will be removed so it will have to be imported again. If given an object, the module in which that object sits will be unloaded. A string should directly give the module pathname to unload. Example: # (in a test method) unload_module(foo) with mock.patch("foo.GLOBALTHING", "mockval"): import foo ... # test code using foo.GLOBALTHING, now set to 'mockval' This allows for mocking constants global to the module, since otherwise those would not be mocked (since a module is only loaded once). """ if isinstance(module, str): modulename = module elif hasattr(module, "__module__"): modulename = module.__module__ else: modulename = module.__name__ if modulename in sys.modules: del sys.modules[modulename] def _mock_deferlater(reactor, timedelay, callback, *args, **kwargs): callback(*args, **kwargs) return Deferred() class EvenniaTest(TestCase): """ Base test for Evennia, sets up a basic environment. """ account_typeclass = DefaultAccount object_typeclass = DefaultObject character_typeclass = DefaultCharacter exit_typeclass = DefaultExit room_typeclass = DefaultRoom script_typeclass = DefaultScript @patch("evennia.scripts.taskhandler.deferLater", _mock_deferlater) def setUp(self): """ Sets up testing environment """ self.backups = ( SESSIONS.data_out, SESSIONS.disconnect, settings.DEFAULT_HOME, settings.PROTOTYPE_MODULES, ) SESSIONS.data_out = Mock() SESSIONS.disconnect = Mock() self.account = create.create_account( "TestAccount", email="<EMAIL>", password="<PASSWORD>", typeclass=self.account_typeclass, ) self.account2 = create.create_account( "TestAccount2", email="<EMAIL>", password="<PASSWORD>", typeclass=self.account_typeclass, ) self.room1 = create.create_object(self.room_typeclass, key="Room", nohome=True) self.room1.db.desc = "room_desc" settings.DEFAULT_HOME = "#%i" % self.room1.id # we must have a default home # Set up fake prototype module for allowing tests to use named prototypes. settings.PROTOTYPE_MODULES = "evennia.utils.tests.data.prototypes_example" self.room2 = create.create_object(self.room_typeclass, key="Room2") self.exit = create.create_object( self.exit_typeclass, key="out", location=self.room1, destination=self.room2 ) self.obj1 = create.create_object( self.object_typeclass, key="Obj", location=self.room1, home=self.room1 ) self.obj2 = create.create_object( self.object_typeclass, key="Obj2", location=self.room1, home=self.room1 ) self.char1 = create.create_object( self.character_typeclass, key="Char", location=self.room1, home=self.room1 ) self.char1.permissions.add("Developer") self.char2 = create.create_object( self.character_typeclass, key="Char2", location=self.room1, home=self.room1 ) self.char1.account = self.account self.account.db._last_puppet = self.char1 self.char2.account = self.account2 self.account2.db._last_puppet = self.char2 self.script = create.create_script(self.script_typeclass, key="Script") self.account.permissions.add("Developer") # set up a fake session dummysession = ServerSession() dummysession.init_session("telnet", ("localhost", "testmode"), SESSIONS) dummysession.sessid = 1 SESSIONS.portal_connect( dummysession.get_sync_data() ) # note that this creates a new Session! session = SESSIONS.session_from_sessid(1) # the real session SESSIONS.login(session, self.account, testmode=True) self.session = session def tearDown(self): flush_cache() SESSIONS.data_out = self.backups[0] SESSIONS.disconnect = self.backups[1] settings.DEFAULT_HOME = self.backups[2] settings.PROTOTYPE_MODULES = self.backups[3] del SESSIONS[self.session.sessid] self.account.delete() self.account2.delete() super().tearDown() class LocalEvenniaTest(EvenniaTest): """ This test class is intended for inheriting in mygame tests. It helps ensure your tests are run with your own objects. """ account_typeclass = settings.BASE_ACCOUNT_TYPECLASS object_typeclass = settings.BASE_OBJECT_TYPECLASS character_typeclass = settings.BASE_CHARACTER_TYPECLASS exit_typeclass = settings.BASE_EXIT_TYPECLASS room_typeclass = settings.BASE_ROOM_TYPECLASS script_typeclass = settings.BASE_SCRIPT_TYPECLASS
[ "evennia.server.sessionhandler.SESSIONS.session_from_sessid", "evennia.utils.idmapper.models.flush_cache", "evennia.server.sessionhandler.SESSIONS.login", "evennia.utils.create.create_script", "evennia.utils.create.create_object", "evennia.server.serversession.ServerSession", "evennia.utils.create.creat...
[((732, 742), 'twisted.internet.defer.Deferred', 'Deferred', ([], {}), '()\n', (740, 742), False, 'from twisted.internet.defer import Deferred\n'), ((887, 897), 'twisted.internet.defer.Deferred', 'Deferred', ([], {}), '()\n', (895, 897), False, 'from twisted.internet.defer import Deferred\n'), ((2023, 2033), 'twisted.internet.defer.Deferred', 'Deferred', ([], {}), '()\n', (2031, 2033), False, 'from twisted.internet.defer import Deferred\n'), ((2366, 2431), 'mock.patch', 'patch', (['"""evennia.scripts.taskhandler.deferLater"""', '_mock_deferlater'], {}), "('evennia.scripts.taskhandler.deferLater', _mock_deferlater)\n", (2371, 2431), False, 'from mock import Mock, patch\n'), ((2715, 2721), 'mock.Mock', 'Mock', ([], {}), '()\n', (2719, 2721), False, 'from mock import Mock, patch\n'), ((2752, 2758), 'mock.Mock', 'Mock', ([], {}), '()\n', (2756, 2758), False, 'from mock import Mock, patch\n'), ((2783, 2897), 'evennia.utils.create.create_account', 'create.create_account', (['"""TestAccount"""'], {'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""', 'typeclass': 'self.account_typeclass'}), "('TestAccount', email='<EMAIL>', password='<PASSWORD>',\n typeclass=self.account_typeclass)\n", (2804, 2897), False, 'from evennia.utils import create\n'), ((2977, 3093), 'evennia.utils.create.create_account', 'create.create_account', (['"""TestAccount2"""'], {'email': '"""<EMAIL>"""', 'password': '"""<PASSWORD>"""', 'typeclass': 'self.account_typeclass'}), "('TestAccount2', email='<EMAIL>', password=\n '<PASSWORD>', typeclass=self.account_typeclass)\n", (2998, 3093), False, 'from evennia.utils import create\n'), ((3169, 3235), 'evennia.utils.create.create_object', 'create.create_object', (['self.room_typeclass'], {'key': '"""Room"""', 'nohome': '(True)'}), "(self.room_typeclass, key='Room', nohome=True)\n", (3189, 3235), False, 'from evennia.utils import create\n'), ((3549, 3603), 'evennia.utils.create.create_object', 'create.create_object', (['self.room_typeclass'], {'key': '"""Room2"""'}), "(self.room_typeclass, key='Room2')\n", (3569, 3603), False, 'from evennia.utils import create\n'), ((3624, 3725), 'evennia.utils.create.create_object', 'create.create_object', (['self.exit_typeclass'], {'key': '"""out"""', 'location': 'self.room1', 'destination': 'self.room2'}), "(self.exit_typeclass, key='out', location=self.room1,\n destination=self.room2)\n", (3644, 3725), False, 'from evennia.utils import create\n'), ((3764, 3860), 'evennia.utils.create.create_object', 'create.create_object', (['self.object_typeclass'], {'key': '"""Obj"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.object_typeclass, key='Obj', location=self.room1,\n home=self.room1)\n", (3784, 3860), False, 'from evennia.utils import create\n'), ((3899, 3996), 'evennia.utils.create.create_object', 'create.create_object', (['self.object_typeclass'], {'key': '"""Obj2"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.object_typeclass, key='Obj2', location=self.room1,\n home=self.room1)\n", (3919, 3996), False, 'from evennia.utils import create\n'), ((4036, 4137), 'evennia.utils.create.create_object', 'create.create_object', (['self.character_typeclass'], {'key': '"""Char"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.character_typeclass, key='Char', location=self.\n room1, home=self.room1)\n", (4056, 4137), False, 'from evennia.utils import create\n'), ((4224, 4326), 'evennia.utils.create.create_object', 'create.create_object', (['self.character_typeclass'], {'key': '"""Char2"""', 'location': 'self.room1', 'home': 'self.room1'}), "(self.character_typeclass, key='Char2', location=self.\n room1, home=self.room1)\n", (4244, 4326), False, 'from evennia.utils import create\n'), ((4552, 4609), 'evennia.utils.create.create_script', 'create.create_script', (['self.script_typeclass'], {'key': '"""Script"""'}), "(self.script_typeclass, key='Script')\n", (4572, 4609), False, 'from evennia.utils import create\n'), ((4717, 4732), 'evennia.server.serversession.ServerSession', 'ServerSession', ([], {}), '()\n', (4730, 4732), False, 'from evennia.server.serversession import ServerSession\n'), ((4989, 5020), 'evennia.server.sessionhandler.SESSIONS.session_from_sessid', 'SESSIONS.session_from_sessid', (['(1)'], {}), '(1)\n', (5017, 5020), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((5049, 5101), 'evennia.server.sessionhandler.SESSIONS.login', 'SESSIONS.login', (['session', 'self.account'], {'testmode': '(True)'}), '(session, self.account, testmode=True)\n', (5063, 5101), False, 'from evennia.server.sessionhandler import SESSIONS\n'), ((5166, 5179), 'evennia.utils.idmapper.models.flush_cache', 'flush_cache', ([], {}), '()\n', (5177, 5179), False, 'from evennia.utils.idmapper.models import flush_cache\n')]
""" Typeclasses for the in-game Python system. To use thm, one should inherit from these classes (EventObject, EventRoom, EventCharacter and EventExit). """ from evennia import DefaultCharacter, DefaultExit, DefaultObject, DefaultRoom from evennia import ScriptDB from evennia.utils.utils import delay, inherits_from, lazy_property from evennia.contrib.ingame_python.callbackhandler import CallbackHandler from evennia.contrib.ingame_python.utils import register_events, time_event, phrase_event # Character help CHARACTER_CAN_DELETE = """ Can the character be deleted? This event is called before the character is deleted. You can use 'deny()' in this event to prevent this character from being deleted. If this event doesn't prevent the character from being deleted, its 'delete' event is called right away. Variables you can use in this event: character: the character connected to this event. """ CHARACTER_CAN_MOVE = """ Can the character move? This event is called before the character moves into another location. You can prevent the character from moving using the 'deny()' eventfunc. Variables you can use in this event: character: the character connected to this event. origin: the current location of the character. destination: the future location of the character. """ CHARACTER_CAN_PART = """ Can the departing charaacter leave this room? This event is called before another character can move from the location where the current character also is. This event can be used to prevent someone to leave this room if, for instance, he/she hasn't paid, or he/she is going to a protected area, past a guard, and so on. Use 'deny()' to prevent the departing character from moving. Variables you can use in this event: departing: the character who wants to leave this room. character: the character connected to this event. """ CHARACTER_CAN_SAY = """ Before another character can say something in the same location. This event is called before another character says something in the character's location. The "something" in question can be modified, or the action can be prevented by using 'deny()'. To change the content of what the character says, simply change the variable 'message' to another string of characters. Variables you can use in this event: speaker: the character who is using the say command. character: the character connected to this event. message: the text spoken by the character. """ CHARACTER_DELETE = """ Before deleting the character. This event is called just before deleting this character. It shouldn't be prevented (using the `deny()` function at this stage doesn't have any effect). If you want to prevent deletion of this character, use the event `can_delete` instead. Variables you can use in this event: character: the character connected to this event. """ CHARACTER_GREET = """ A new character arrives in the location of this character. This event is called when another character arrives in the location where the current character is. For instance, a puppeted character arrives in the shop of a shopkeeper (assuming the shopkeeper is a character). As its name suggests, this event can be very useful to have NPC greeting one another, or players, who come to visit. Variables you can use in this event: character: the character connected to this event. newcomer: the character arriving in the same location. """ CHARACTER_MOVE = """ After the character has moved into its new room. This event is called when the character has moved into a new room. It is too late to prevent the move at this point. Variables you can use in this event: character: the character connected to this event. origin: the old location of the character. destination: the new location of the character. """ CHARACTER_PUPPETED = """ When the character has been puppeted by a player. This event is called when a player has just puppeted this character. This can commonly happen when a player connects onto this character, or when puppeting to a NPC or free character. Variables you can use in this event: character: the character connected to this event. """ CHARACTER_SAY = """ After another character has said something in the character's room. This event is called right after another character has said something in the same location.. The action cannot be prevented at this moment. Instead, this event is ideal to create keywords that would trigger a character (like a NPC) in doing something if a specific phrase is spoken in the same location. To use this event, you have to specify a list of keywords as parameters that should be present, as separate words, in the spoken phrase. For instance, you can set an event tthat would fire if the phrase spoken by the character contains "menu" or "dinner" or "lunch": @call/add ... = say menu, dinner, lunch Then if one of the words is present in what the character says, this event will fire. Variables you can use in this event: speaker: the character speaking in this room. character: the character connected to this event. message: the text having been spoken by the character. """ CHARACTER_TIME = """ A repeated event to be called regularly. This event is scheduled to repeat at different times, specified as parameters. You can set it to run every day at 8:00 AM (game time). You have to specify the time as an argument to @call/add, like: @call/add here = time 8:00 The parameter (8:00 here) must be a suite of digits separated by spaces, colons or dashes. Keep it as close from a recognizable date format, like this: @call/add here = time 06-15 12:20 This event will fire every year on June the 15th at 12 PM (still game time). Units have to be specified depending on your set calendar (ask a developer for more details). Variables you can use in this event: character: the character connected to this event. """ CHARACTER_UNPUPPETED = """ When the character is about to be un-puppeted. This event is called when a player is about to un-puppet the character, which can happen if the player is disconnecting or changing puppets. Variables you can use in this event: character: the character connected to this event. """ @register_events class EventCharacter(DefaultCharacter): """Typeclass to represent a character and call event types.""" _events = { "can_delete": (["character"], CHARACTER_CAN_DELETE), "can_move": (["character", "origin", "destination"], CHARACTER_CAN_MOVE), "can_part": (["character", "departing"], CHARACTER_CAN_PART), "can_say": (["speaker", "character", "message"], CHARACTER_CAN_SAY, phrase_event), "delete": (["character"], CHARACTER_DELETE), "greet": (["character", "newcomer"], CHARACTER_GREET), "move": (["character", "origin", "destination"], CHARACTER_MOVE), "puppeted": (["character"], CHARACTER_PUPPETED), "say": (["speaker", "character", "message"], CHARACTER_SAY, phrase_event), "time": (["character"], CHARACTER_TIME, None, time_event), "unpuppeted": (["character"], CHARACTER_UNPUPPETED), } def announce_move_from(self, destination, msg=None, mapping=None): """ Called if the move is to be announced. This is called while we are still standing in the old location. Args: destination (Object): The place we are going to. msg (str, optional): a replacement message. mapping (dict, optional): additional mapping objects. You can override this method and call its parent with a message to simply change the default message. In the string, you can use the following as mappings (between braces): object: the object which is moving. exit: the exit from which the object is moving (if found). origin: the location of the object before the move. destination: the location of the object after moving. """ if not self.location: return string = msg or "{object} is leaving {origin}, heading for {destination}." # Get the exit from location to destination location = self.location exits = [o for o in location.contents if o.location is location and o.destination is destination] mapping = mapping or {} mapping.update({ "character": self, }) if exits: exits[0].callbacks.call("msg_leave", self, exits[0], location, destination, string, mapping) string = exits[0].callbacks.get_variable("message") mapping = exits[0].callbacks.get_variable("mapping") # If there's no string, don't display anything # It can happen if the "message" variable in events is set to None if not string: return super(EventCharacter, self).announce_move_from(destination, msg=string, mapping=mapping) def announce_move_to(self, source_location, msg=None, mapping=None): """ Called after the move if the move was not quiet. At this point we are standing in the new location. Args: source_location (Object): The place we came from msg (str, optional): the replacement message if location. mapping (dict, optional): additional mapping objects. You can override this method and call its parent with a message to simply change the default message. In the string, you can use the following as mappings (between braces): object: the object which is moving. exit: the exit from which the object is moving (if found). origin: the location of the object before the move. destination: the location of the object after moving. """ if not source_location and self.location.has_player: # This was created from nowhere and added to a player's # inventory; it's probably the result of a create command. string = "You now have %s in your possession." % self.get_display_name(self.location) self.location.msg(string) return if source_location: string = msg or "{character} arrives to {destination} from {origin}." else: string = "{character} arrives to {destination}." origin = source_location destination = self.location exits = [] mapping = mapping or {} mapping.update({ "character": self, }) if origin: exits = [o for o in destination.contents if o.location is destination and o.destination is origin] if exits: exits[0].callbacks.call("msg_arrive", self, exits[0], origin, destination, string, mapping) string = exits[0].callbacks.get_variable("message") mapping = exits[0].callbacks.get_variable("mapping") # If there's no string, don't display anything # It can happen if the "message" variable in events is set to None if not string: return super(EventCharacter, self).announce_move_to(source_location, msg=string, mapping=mapping) def at_before_move(self, destination): """ Called just before starting to move this object to destination. Args: destination (Object): The object we are moving to Returns: shouldmove (bool): If we should move or not. Notes: If this method returns False/None, the move is cancelled before it is even started. """ origin = self.location Room = DefaultRoom if isinstance(origin, Room) and isinstance(destination, Room): can = self.callbacks.call("can_move", self, origin, destination) if can: can = origin.callbacks.call("can_move", self, origin) if can: # Call other character's 'can_part' event for present in [o for o in origin.contents if isinstance( o, DefaultCharacter) and o is not self]: can = present.callbacks.call("can_part", present, self) if not can: break if can is None: return True return can return True def at_after_move(self, source_location): """ Called after move has completed, regardless of quiet mode or not. Allows changes to the object due to the location it is now in. Args: source_location (Object): Wwhere we came from. This may be `None`. """ super(EventCharacter, self).at_after_move(source_location) origin = source_location destination = self.location Room = DefaultRoom if isinstance(origin, Room) and isinstance(destination, Room): self.callbacks.call("move", self, origin, destination) destination.callbacks.call("move", self, origin, destination) # Call the 'greet' event of characters in the location for present in [o for o in destination.contents if isinstance( o, DefaultCharacter) and o is not self]: present.callbacks.call("greet", present, self) def at_object_delete(self): """ Called just before the database object is permanently delete()d from the database. If this method returns False, deletion is aborted. """ if not self.callbacks.call("can_delete", self): return False self.callbacks.call("delete", self) return True def at_post_puppet(self): """ Called just after puppeting has been completed and all Player<->Object links have been established. Note: You can use `self.player` and `self.sessions.get()` to get player and sessions at this point; the last entry in the list from `self.sessions.get()` is the latest Session puppeting this Object. """ super(EventCharacter, self).at_post_puppet() self.callbacks.call("puppeted", self) # Call the room's puppeted_in event location = self.location if location and isinstance(location, DefaultRoom): location.callbacks.call("puppeted_in", self, location) def at_pre_unpuppet(self): """ Called just before beginning to un-connect a puppeting from this Player. Note: You can use `self.player` and `self.sessions.get()` to get player and sessions at this point; the last entry in the list from `self.sessions.get()` is the latest Session puppeting this Object. """ self.callbacks.call("unpuppeted", self) # Call the room's unpuppeted_in event location = self.location if location and isinstance(location, DefaultRoom): location.callbacks.call("unpuppeted_in", self, location) super(EventCharacter, self).at_pre_unpuppet() # Exit help EXIT_CAN_TRAVERSE = """ Can the character traverse through this exit? This event is called when a character is about to traverse this exit. You can use the deny() function to deny the character from exitting for this time. Variables you can use in this event: character: the character that wants to traverse this exit. exit: the exit to be traversed. room: the room in which stands the character before moving. """ EXIT_MSG_ARRIVE = """ Customize the message when a character arrives through this exit. This event is called when a character arrives through this exit. To customize the message that will be sent to the room where the character arrives, change the value of the variable "message" to give it your custom message. The character itself will not be notified. You can use mapping between braces, like this: message = "{character} climbs out of a hole." In your mapping, you can use {character} (the character who has arrived), {exit} (the exit), {origin} (the room in which the character was), and {destination} (the room in which the character now is). If you need to customize the message with other information, you can also set "message" to None and send something else instead. Variables you can use in this event: character: the character who is arriving through this exit. exit: the exit having been traversed. origin: the past location of the character. destination: the current location of the character. message: the message to be displayed in the destination. mapping: a dictionary containing the mapping of the message. """ EXIT_MSG_LEAVE = """ Customize the message when a character leaves through this exit. This event is called when a character leaves through this exit. To customize the message that will be sent to the room where the character came from, change the value of the variable "message" to give it your custom message. The character itself will not be notified. You can use mapping between braces, like this: message = "{character} falls into a hole!" In your mapping, you can use {character} (the character who is about to leave), {exit} (the exit), {origin} (the room in which the character is), and {destination} (the room in which the character is heading for). If you need to customize the message with other information, you can also set "message" to None and send something else instead. Variables you can use in this event: character: the character who is leaving through this exit. exit: the exit being traversed. origin: the location of the character. destination: the destination of the character. message: the message to be displayed in the location. mapping: a dictionary containing additional mapping. """ EXIT_TIME = """ A repeated event to be called regularly. This event is scheduled to repeat at different times, specified as parameters. You can set it to run every day at 8:00 AM (game time). You have to specify the time as an argument to @call/add, like: @call/add north = time 8:00 The parameter (8:00 here) must be a suite of digits separated by spaces, colons or dashes. Keep it as close from a recognizable date format, like this: @call/add south = time 06-15 12:20 This event will fire every year on June the 15th at 12 PM (still game time). Units have to be specified depending on your set calendar (ask a developer for more details). Variables you can use in this event: exit: the exit connected to this event. """ EXIT_TRAVERSE = """ After the characer has traversed through this exit. This event is called after a character has traversed through this exit. Traversing cannot be prevented using 'deny()' at this point. The character will be in a different room and she will have received the room's description when this event is called. Variables you can use in this event: character: the character who has traversed through this exit. exit: the exit that was just traversed through. origin: the exit's location (where the character was before moving). destination: the character's location after moving. """ @register_events class EventExit(DefaultExit): """Modified exit including management of events.""" _events = { "can_traverse": (["character", "exit", "room"], EXIT_CAN_TRAVERSE), "msg_arrive": (["character", "exit", "origin", "destination", "message", "mapping"], EXIT_MSG_ARRIVE), "msg_leave": (["character", "exit", "origin", "destination", "message", "mapping"], EXIT_MSG_LEAVE), "time": (["exit"], EXIT_TIME, None, time_event), "traverse": (["character", "exit", "origin", "destination"], EXIT_TRAVERSE), } def at_traverse(self, traversing_object, target_location): """ This hook is responsible for handling the actual traversal, normally by calling `traversing_object.move_to(target_location)`. It is normally only implemented by Exit objects. If it returns False (usually because `move_to` returned False), `at_after_traverse` below should not be called and instead `at_failed_traverse` should be called. Args: traversing_object (Object): Object traversing us. target_location (Object): Where target is going. """ is_character = inherits_from(traversing_object, DefaultCharacter) if is_character: allow = self.callbacks.call("can_traverse", traversing_object, self, self.location) if not allow: return super(EventExit, self).at_traverse(traversing_object, target_location) # After traversing if is_character: self.callbacks.call("traverse", traversing_object, self, self.location, self.destination) # Object help OBJECT_DROP = """ When a character drops this object. This event is called when a character drops this object. It is called after the command has ended and displayed its message, and the action cannot be prevented at this time. Variables you can use in this event: character: the character having dropped the object. obj: the object connected to this event. """ OBJECT_GET = """ When a character gets this object. This event is called when a character gets this object. It is called after the command has ended and displayed its message, and the action cannot be prevented at this time. Variables you can use in this event: character: the character having picked up the object. obj: the object connected to this event. """ OBJECT_TIME = """ A repeated event to be called regularly. This event is scheduled to repeat at different times, specified as parameters. You can set it to run every day at 8:00 AM (game time). You have to specify the time as an argument to @call/add, like: @call/add here = time 8:00 The parameter (8:00 here) must be a suite of digits separated by spaces, colons or dashes. Keep it as close from a recognizable date format, like this: @call/add here = time 06-15 12:20 This event will fire every year on June the 15th at 12 PM (still game time). Units have to be specified depending on your set calendar (ask a developer for more details). Variables you can use in this event: object: the object connected to this event. """ @register_events class EventObject(DefaultObject): """Default object with management of events.""" _events = { "drop": (["character", "obj"], OBJECT_DROP), "get": (["character", "obj"], OBJECT_GET), "time": (["object"], OBJECT_TIME, None, time_event), } @lazy_property def callbacks(self): """Return the CallbackHandler.""" return CallbackHandler(self) def at_get(self, getter): """ Called by the default `get` command when this object has been picked up. Args: getter (Object): The object getting this object. Notes: This hook cannot stop the pickup from happening. Use permissions for that. """ super(EventObject, self).at_get(getter) self.callbacks.call("get", getter, self) def at_drop(self, dropper): """ Called by the default `drop` command when this object has been dropped. Args: dropper (Object): The object which just dropped this object. Notes: This hook cannot stop the drop from happening. Use permissions from that. """ super(EventObject, self).at_drop(dropper) self.callbacks.call("drop", dropper, self) # Room help ROOM_CAN_DELETE = """ Can the room be deleted? This event is called before the room is deleted. You can use 'deny()' in this event to prevent this room from being deleted. If this event doesn't prevent the room from being deleted, its 'delete' event is called right away. Variables you can use in this event: room: the room connected to this event. """ ROOM_CAN_MOVE = """ Can the character move into this room? This event is called before the character can move into this specific room. You can prevent the move by using the 'deny()' function. Variables you can use in this event: character: the character who wants to move in this room. room: the room connected to this event. """ ROOM_CAN_SAY = """ Before a character can say something in this room. This event is called before a character says something in this room. The "something" in question can be modified, or the action can be prevented by using 'deny()'. To change the content of what the character says, simply change the variable 'message' to another string of characters. Variables you can use in this event: character: the character who is using the say command. room: the room connected to this event. message: the text spoken by the character. """ ROOM_DELETE = """ Before deleting the room. This event is called just before deleting this room. It shouldn't be prevented (using the `deny()` function at this stage doesn't have any effect). If you want to prevent deletion of this room, use the event `can_delete` instead. Variables you can use in this event: room: the room connected to this event. """ ROOM_MOVE = """ After the character has moved into this room. This event is called when the character has moved into this room. It is too late to prevent the move at this point. Variables you can use in this event: character: the character connected to this event. origin: the old location of the character. destination: the new location of the character. """ ROOM_PUPPETED_IN = """ After the character has been puppeted in this room. This event is called after a character has been puppeted in this room. This can happen when a player, having connected, begins to puppet a character. The character's location at this point, if it's a room, will see this event fire. Variables you can use in this event: character: the character who have just been puppeted in this room. room: the room connected to this event. """ ROOM_SAY = """ After the character has said something in the room. This event is called right after a character has said something in this room. The action cannot be prevented at this moment. Instead, this event is ideal to create actions that will respond to something being said aloud. To use this event, you have to specify a list of keywords as parameters that should be present, as separate words, in the spoken phrase. For instance, you can set an event tthat would fire if the phrase spoken by the character contains "menu" or "dinner" or "lunch": @call/add ... = say menu, dinner, lunch Then if one of the words is present in what the character says, this event will fire. Variables you can use in this event: character: the character having spoken in this room. room: the room connected to this event. message: the text having been spoken by the character. """ ROOM_TIME = """ A repeated event to be called regularly. This event is scheduled to repeat at different times, specified as parameters. You can set it to run every day at 8:00 AM (game time). You have to specify the time as an argument to @call/add, like: @call/add here = time 8:00 The parameter (8:00 here) must be a suite of digits separated by spaces, colons or dashes. Keep it as close from a recognizable date format, like this: @call/add here = time 06-15 12:20 This event will fire every year on June the 15th at 12 PM (still game time). Units have to be specified depending on your set calendar (ask a developer for more details). Variables you can use in this event: room: the room connected to this event. """ ROOM_UNPUPPETED_IN = """ Before the character is un-puppeted in this room. This event is called before a character is un-puppeted in this room. This can happen when a player, puppeting a character, is disconnecting. The character's location at this point, if it's a room, will see this event fire. Variables you can use in this event: character: the character who is about to be un-puppeted in this room. room: the room connected to this event. """ @register_events class EventRoom(DefaultRoom): """Default room with management of events.""" _events = { "can_delete": (["room"], ROOM_CAN_DELETE), "can_move": (["character", "room"], ROOM_CAN_MOVE), "can_say": (["character", "room", "message"], ROOM_CAN_SAY, phrase_event), "delete": (["room"], ROOM_DELETE), "move": (["character", "origin", "destination"], ROOM_MOVE), "puppeted_in": (["character", "room"], ROOM_PUPPETED_IN), "say": (["character", "room", "message"], ROOM_SAY, phrase_event), "time": (["room"], ROOM_TIME, None, time_event), "unpuppeted_in": (["character", "room"], ROOM_UNPUPPETED_IN), } def at_object_delete(self): """ Called just before the database object is permanently delete()d from the database. If this method returns False, deletion is aborted. """ if not self.callbacks.call("can_delete", self): return False self.callbacks.call("delete", self) return True def at_say(self, speaker, message): """ Called on this object if an object inside this object speaks. The string returned from this method is the final form of the speech. Args: speaker (Object): The object speaking. message (str): The words spoken. Returns: The message to be said (str) or None. Notes: You should not need to add things like 'you say: ' or similar here, that should be handled by the say command before this. """ allow = self.callbacks.call("can_say", speaker, self, message, parameters=message) if not allow: return message = self.callbacks.get_variable("message") # Call the event "can_say" of other characters in the location for present in [o for o in self.contents if isinstance( o, DefaultCharacter) and o is not speaker]: allow = present.callbacks.call("can_say", speaker, present, message, parameters=message) if not allow: return message = present.callbacks.get_variable("message") # We force the next event to be called after the message # This will have to change when the Evennia API adds new hooks delay(0, self.callbacks.call, "say", speaker, self, message, parameters=message) for present in [o for o in self.contents if isinstance( o, DefaultCharacter) and o is not speaker]: delay(0, present.callbacks.call, "say", speaker, present, message, parameters=message) return message
[ "evennia.contrib.ingame_python.callbackhandler.CallbackHandler", "evennia.utils.utils.delay", "evennia.utils.utils.inherits_from" ]
[((20605, 20655), 'evennia.utils.utils.inherits_from', 'inherits_from', (['traversing_object', 'DefaultCharacter'], {}), '(traversing_object, DefaultCharacter)\n', (20618, 20655), False, 'from evennia.utils.utils import delay, inherits_from, lazy_property\n'), ((23001, 23022), 'evennia.contrib.ingame_python.callbackhandler.CallbackHandler', 'CallbackHandler', (['self'], {}), '(self)\n', (23016, 23022), False, 'from evennia.contrib.ingame_python.callbackhandler import CallbackHandler\n'), ((30879, 30964), 'evennia.utils.utils.delay', 'delay', (['(0)', 'self.callbacks.call', '"""say"""', 'speaker', 'self', 'message'], {'parameters': 'message'}), "(0, self.callbacks.call, 'say', speaker, self, message, parameters=message\n )\n", (30884, 30964), False, 'from evennia.utils.utils import delay, inherits_from, lazy_property\n'), ((31112, 31202), 'evennia.utils.utils.delay', 'delay', (['(0)', 'present.callbacks.call', '"""say"""', 'speaker', 'present', 'message'], {'parameters': 'message'}), "(0, present.callbacks.call, 'say', speaker, present, message,\n parameters=message)\n", (31117, 31202), False, 'from evennia.utils.utils import delay, inherits_from, lazy_property\n')]
""" This file contains the generic, assorted views that don't fall under one of the other applications. Views are django's way of processing e.g. html templates on the fly. """ from django.contrib.admin.sites import site from django.conf import settings from django.contrib.auth import authenticate from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import render from evennia import SESSION_HANDLER from evennia.objects.models import ObjectDB from evennia.accounts.models import AccountDB from evennia.utils import logger from django.contrib.auth import login _BASE_CHAR_TYPECLASS = settings.BASE_CHARACTER_TYPECLASS def _shared_login(request): """ Handle the shared login between website and webclient. """ csession = request.session account = request.user website_uid = csession.get("website_authenticated_uid", None) webclient_uid = csession.get("webclient_authenticated_uid", None) if not csession.session_key: # this is necessary to build the sessid key csession.save() if account.is_authenticated(): # Logged into website if not website_uid: # fresh website login (just from login page) csession["website_authenticated_uid"] = account.id if webclient_uid is None: # auto-login web client csession["webclient_authenticated_uid"] = account.id elif webclient_uid: # Not logged into website, but logged into webclient if not website_uid: csession["website_authenticated_uid"] = account.id account = AccountDB.objects.get(id=webclient_uid) try: # calls our custom authenticate, in web/utils/backend.py authenticate(autologin=account) login(request, account) except AttributeError: logger.log_trace() def _gamestats(): # Some misc. configurable stuff. # TODO: Move this to either SQL or settings.py based configuration. fpage_account_limit = 4 # A QuerySet of the most recently connected accounts. recent_users = AccountDB.objects.get_recently_connected_accounts()[:fpage_account_limit] nplyrs_conn_recent = len(recent_users) or "none" nplyrs = AccountDB.objects.num_total_accounts() or "none" nplyrs_reg_recent = len(AccountDB.objects.get_recently_created_accounts()) or "none" nsess = SESSION_HANDLER.account_count() # nsess = len(AccountDB.objects.get_connected_accounts()) or "no one" nobjs = ObjectDB.objects.all().count() nrooms = ObjectDB.objects.filter(db_location__isnull=True).exclude(db_typeclass_path=_BASE_CHAR_TYPECLASS).count() nexits = ObjectDB.objects.filter(db_location__isnull=False, db_destination__isnull=False).count() nchars = ObjectDB.objects.filter(db_typeclass_path=_BASE_CHAR_TYPECLASS).count() nothers = nobjs - nrooms - nchars - nexits pagevars = { "page_title": "Front Page", "accounts_connected_recent": recent_users, "num_accounts_connected": nsess or "no one", "num_accounts_registered": nplyrs or "no", "num_accounts_connected_recent": nplyrs_conn_recent or "no", "num_accounts_registered_recent": nplyrs_reg_recent or "no one", "num_rooms": nrooms or "none", "num_exits": nexits or "no", "num_objects": nobjs or "none", "num_characters": nchars or "no", "num_others": nothers or "no" } return pagevars def page_index(request): """ Main root page. """ # handle webclient-website shared login _shared_login(request) # get game db stats pagevars = _gamestats() return render(request, 'index.html', pagevars) def to_be_implemented(request): """ A notice letting the user know that this particular feature hasn't been implemented yet. """ pagevars = { "page_title": "To Be Implemented...", } return render(request, 'tbi.html', pagevars) @staff_member_required def evennia_admin(request): """ Helpful Evennia-specific admin page. """ return render( request, 'evennia_admin.html', { 'accountdb': AccountDB}) def admin_wrapper(request): """ Wrapper that allows us to properly use the base Django admin site, if needed. """ return staff_member_required(site.index)(request)
[ "evennia.objects.models.ObjectDB.objects.filter", "evennia.utils.logger.log_trace", "evennia.SESSION_HANDLER.account_count", "evennia.accounts.models.AccountDB.objects.get", "evennia.accounts.models.AccountDB.objects.num_total_accounts", "evennia.accounts.models.AccountDB.objects.get_recently_connected_ac...
[((2449, 2480), 'evennia.SESSION_HANDLER.account_count', 'SESSION_HANDLER.account_count', ([], {}), '()\n', (2478, 2480), False, 'from evennia import SESSION_HANDLER\n'), ((3725, 3764), 'django.shortcuts.render', 'render', (['request', '"""index.html"""', 'pagevars'], {}), "(request, 'index.html', pagevars)\n", (3731, 3764), False, 'from django.shortcuts import render\n'), ((3994, 4031), 'django.shortcuts.render', 'render', (['request', '"""tbi.html"""', 'pagevars'], {}), "(request, 'tbi.html', pagevars)\n", (4000, 4031), False, 'from django.shortcuts import render\n'), ((4153, 4216), 'django.shortcuts.render', 'render', (['request', '"""evennia_admin.html"""', "{'accountdb': AccountDB}"], {}), "(request, 'evennia_admin.html', {'accountdb': AccountDB})\n", (4159, 4216), False, 'from django.shortcuts import render\n'), ((2159, 2210), 'evennia.accounts.models.AccountDB.objects.get_recently_connected_accounts', 'AccountDB.objects.get_recently_connected_accounts', ([], {}), '()\n', (2208, 2210), False, 'from evennia.accounts.models import AccountDB\n'), ((2299, 2337), 'evennia.accounts.models.AccountDB.objects.num_total_accounts', 'AccountDB.objects.num_total_accounts', ([], {}), '()\n', (2335, 2337), False, 'from evennia.accounts.models import AccountDB\n'), ((4378, 4411), 'django.contrib.admin.views.decorators.staff_member_required', 'staff_member_required', (['site.index'], {}), '(site.index)\n', (4399, 4411), False, 'from django.contrib.admin.views.decorators import staff_member_required\n'), ((2376, 2425), 'evennia.accounts.models.AccountDB.objects.get_recently_created_accounts', 'AccountDB.objects.get_recently_created_accounts', ([], {}), '()\n', (2423, 2425), False, 'from evennia.accounts.models import AccountDB\n'), ((2568, 2590), 'evennia.objects.models.ObjectDB.objects.all', 'ObjectDB.objects.all', ([], {}), '()\n', (2588, 2590), False, 'from evennia.objects.models import ObjectDB\n'), ((2731, 2816), 'evennia.objects.models.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'db_location__isnull': '(False)', 'db_destination__isnull': '(False)'}), '(db_location__isnull=False, db_destination__isnull=False\n )\n', (2754, 2816), False, 'from evennia.objects.models import ObjectDB\n'), ((2833, 2896), 'evennia.objects.models.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'db_typeclass_path': '_BASE_CHAR_TYPECLASS'}), '(db_typeclass_path=_BASE_CHAR_TYPECLASS)\n', (2856, 2896), False, 'from evennia.objects.models import ObjectDB\n'), ((1636, 1675), 'evennia.accounts.models.AccountDB.objects.get', 'AccountDB.objects.get', ([], {'id': 'webclient_uid'}), '(id=webclient_uid)\n', (1657, 1675), False, 'from evennia.accounts.models import AccountDB\n'), ((1782, 1813), 'django.contrib.auth.authenticate', 'authenticate', ([], {'autologin': 'account'}), '(autologin=account)\n', (1794, 1813), False, 'from django.contrib.auth import authenticate\n'), ((1830, 1853), 'django.contrib.auth.login', 'login', (['request', 'account'], {}), '(request, account)\n', (1835, 1853), False, 'from django.contrib.auth import login\n'), ((2612, 2661), 'evennia.objects.models.ObjectDB.objects.filter', 'ObjectDB.objects.filter', ([], {'db_location__isnull': '(True)'}), '(db_location__isnull=True)\n', (2635, 2661), False, 'from evennia.objects.models import ObjectDB\n'), ((1905, 1923), 'evennia.utils.logger.log_trace', 'logger.log_trace', ([], {}), '()\n', (1921, 1923), False, 'from evennia.utils import logger\n')]
# -*- coding: utf-8 -*- from datetime import datetime import re from django.db import models from django.conf import settings from django.utils.timezone import now from evennia.accounts.models import AccountDB from evennia.utils.utils import time_format from evennia_wiki.markdown_engine import ENGINE from evennia_wiki.managers import PageManager ## Constants _PERMISSION_HIERARCHY = ["anonymous"] + [pe.lower() for pe in settings.PERMISSION_HIERARCHY] RE_PATH = re.compile(r"^[A-Za-z0-9_/-]*$") class Page(models.Model): """A wiki page, with a history of revisions.""" objects = PageManager() address = models.CharField(max_length=2000, db_index=True, unique=True) title = models.CharField(max_length=200, default="") created_on = models.DateTimeField("created on", auto_now_add=True) author = models.ForeignKey(AccountDB, null=True, blank=True, on_delete=models.SET_NULL) html = models.TextField(default="") can_write = models.CharField(max_length=50, default="Developer") can_read = models.CharField(max_length=50, default="Developer") @property def last_revision(self): """Return the last revision, if any, or None.""" return self.revision_set.order_by("created_on").last() @property def last_modified_ago(self): """Return the X {unit}{s} ago.""" revision = self.last_revision if revision: seconds = (now() - revision.created_on).total_seconds() ago = time_format(seconds, 4) return "{} ago".format(ago) return "never" @property def content(self): """Return the text content of the last revision. Note: This returns the text content (unprocessed-markdown str) of the last revision, or an empty string. """ last = self.last_revision if last: return last.content else: return "" @property def parent_address(self): """Return the direct parent address deduced from the current address. If the address is "a/b/c", the parent's address will be "a/b". A page with an address like "a" will have the root (empty string) as a parent address. The root itself will have no parent (None). """ address = self.address if address.startswith("/"): address = address[1:] if address.endswith("/"): address = address[:-1] if "/" in address: # Return everything before the last / sign return address.rsplit("/", 1)[0] elif address: return "" else: return None @property def parent(self): """Return the parent page or None.""" address = self.parent_address try: parent = Page.objects.get(address=address) except Page.DoesNotExist: parent = None return parent @property def parent_addresses(self): """Return the succession of parent addresses. Return a list of str (each element of the list being a piece of URI split by the / sign). This list can be empty or contain only an empty string. If the list is not empty, the first element is always the root class (an empty string). """ address = self.address if not address.startswith("/"): address = "/" + address if address.endswith("/"): address = address[:-1] if address: return address.split("/")[:-1] return [] @property def parents(self): """Return all the parent pages, ordered by hierarchy. If this is not the root page (with an empty address), then the first list element will be the root. Next will be all pages in the hierarchy of this page. For instance, if the address of this page is: "story/fairy/001", then the list will be: `[<RootPage>, <Page story>, <Page fairy>]`. """ addresses = self.parent_addresses q = models.Q() for address in addresses: q |= models.Q(address=address) if addresses: pages = Page.objects.filter(q) # Order the pages in a hierarchy pages = sorted(list(pages), key=lambda page: addresses.index(page.address)) else: pages = [] return pages @property def children(self): """Return the direct children of this page.""" address = self.address if address: address += "/" # Escape the address for re matching addres = re.escape(address) regex = "^" + address + "[^/]+$" children = Page.objects.filter(address__regex=regex).order_by("address") return list(children) @property def part_address(self): """Return the last part of the address after the last /.""" address = self.address if address.startswith("/"): address = address[1:] if address.endswith("/"): address = address[:-1] if not address: return "root" elif "/" in address: return address.rsplit("/", 1)[1] else: return address def __str__(self): address = self.address if address: return self.address else: return "/" def check_address(self): """Check that the current address is compliant.""" if RE_PATH.search(self.address) is None: raise ValueError("{} isn't an acceptable path".format(repr(self.address))) def update_html(self, plain_text): """Update the HTML field with the plain text markdown.""" ENGINE.reset() self.html = ENGINE.convert(self.content) self.save() def access(self, user, can="read"): """Return True if the user can access the page. Args: user (AccountDB): the user accessing the page. can (str): what to access (can be read" or "write"). Returns: access (bool): can the user access this page to read or write? """ if can == "read": permission = self.can_read elif can == "write": permission = self.can_write else: raise ValueError("Invalid access: {}".format(can)) # However, the settings for `WIKI_ALLOW_*` takes precedence permission = getattr(settings, f"WIKI_CAN_{can.upper()}", permission) permission = permission.lower() if user is None or not user.is_authenticated: perms_object = ["anonymous"] else: perms_object = user.permissions.all() if permission in perms_object: # simplest case - we have direct match return True if permission in _PERMISSION_HIERARCHY: # check if we have a higher hierarchy position hpos_target = _PERMISSION_HIERARCHY.index(permission) return any(1 for hpos, hperm in enumerate(_PERMISSION_HIERARCHY) if hperm in perms_object and hpos_target < hpos) return False class Revision(models.Model): """A wiki revision, with an author and text.""" page = models.ForeignKey(Page, null=True, blank=True, on_delete=models.SET_NULL) owner = models.ForeignKey(AccountDB, null=True, blank=True, on_delete=models.SET_NULL) created_on = models.DateTimeField("created on", auto_now_add=True) content = models.TextField()
[ "evennia.utils.utils.time_format" ]
[((467, 498), 're.compile', 're.compile', (['"""^[A-Za-z0-9_/-]*$"""'], {}), "('^[A-Za-z0-9_/-]*$')\n", (477, 498), False, 'import re\n'), ((595, 608), 'evennia_wiki.managers.PageManager', 'PageManager', ([], {}), '()\n', (606, 608), False, 'from evennia_wiki.managers import PageManager\n'), ((623, 684), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2000)', 'db_index': '(True)', 'unique': '(True)'}), '(max_length=2000, db_index=True, unique=True)\n', (639, 684), False, 'from django.db import models\n'), ((697, 741), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'default': '""""""'}), "(max_length=200, default='')\n", (713, 741), False, 'from django.db import models\n'), ((759, 812), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""created on"""'], {'auto_now_add': '(True)'}), "('created on', auto_now_add=True)\n", (779, 812), False, 'from django.db import models\n'), ((826, 904), 'django.db.models.ForeignKey', 'models.ForeignKey', (['AccountDB'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.SET_NULL'}), '(AccountDB, null=True, blank=True, on_delete=models.SET_NULL)\n', (843, 904), False, 'from django.db import models\n'), ((916, 944), 'django.db.models.TextField', 'models.TextField', ([], {'default': '""""""'}), "(default='')\n", (932, 944), False, 'from django.db import models\n'), ((961, 1013), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'default': '"""Developer"""'}), "(max_length=50, default='Developer')\n", (977, 1013), False, 'from django.db import models\n'), ((1029, 1081), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'default': '"""Developer"""'}), "(max_length=50, default='Developer')\n", (1045, 1081), False, 'from django.db import models\n'), ((7314, 7387), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Page'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.SET_NULL'}), '(Page, null=True, blank=True, on_delete=models.SET_NULL)\n', (7331, 7387), False, 'from django.db import models\n'), ((7400, 7478), 'django.db.models.ForeignKey', 'models.ForeignKey', (['AccountDB'], {'null': '(True)', 'blank': '(True)', 'on_delete': 'models.SET_NULL'}), '(AccountDB, null=True, blank=True, on_delete=models.SET_NULL)\n', (7417, 7478), False, 'from django.db import models\n'), ((7496, 7549), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""created on"""'], {'auto_now_add': '(True)'}), "('created on', auto_now_add=True)\n", (7516, 7549), False, 'from django.db import models\n'), ((7564, 7582), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (7580, 7582), False, 'from django.db import models\n'), ((4088, 4098), 'django.db.models.Q', 'models.Q', ([], {}), '()\n', (4096, 4098), False, 'from django.db import models\n'), ((4671, 4689), 're.escape', 're.escape', (['address'], {}), '(address)\n', (4680, 4689), False, 'import re\n'), ((5772, 5786), 'evennia_wiki.markdown_engine.ENGINE.reset', 'ENGINE.reset', ([], {}), '()\n', (5784, 5786), False, 'from evennia_wiki.markdown_engine import ENGINE\n'), ((5807, 5835), 'evennia_wiki.markdown_engine.ENGINE.convert', 'ENGINE.convert', (['self.content'], {}), '(self.content)\n', (5821, 5835), False, 'from evennia_wiki.markdown_engine import ENGINE\n'), ((1481, 1504), 'evennia.utils.utils.time_format', 'time_format', (['seconds', '(4)'], {}), '(seconds, 4)\n', (1492, 1504), False, 'from evennia.utils.utils import time_format\n'), ((4150, 4175), 'django.db.models.Q', 'models.Q', ([], {'address': 'address'}), '(address=address)\n', (4158, 4175), False, 'from django.db import models\n'), ((1418, 1423), 'django.utils.timezone.now', 'now', ([], {}), '()\n', (1421, 1423), False, 'from django.utils.timezone import now\n')]
""" Test map builder. """ from evennia.commands.default.tests import BaseEvenniaCommandTest from . import mapbuilder # -*- coding: utf-8 -*- # Add the necessary imports for your instructions here. from evennia import create_object from typeclasses import rooms, exits from random import randint import random # A map with a temple (▲) amongst mountains (n,∩) in a forest (♣,♠) on an # island surrounded by water (≈). By giving no instructions for the water # characters we effectively skip it and create no rooms for those squares. EXAMPLE1_MAP = '''\ ≈≈≈≈≈ ≈♣n♣≈ ≈∩▲∩≈ ≈♠n♠≈ ≈≈≈≈≈ ''' def example1_build_forest(x, y, **kwargs): '''A basic example of build instructions. Make sure to include **kwargs in the arguments and return an instance of the room for exit generation.''' # Create a room and provide a basic description. room = create_object(rooms.Room, key="forest" + str(x) + str(y)) room.db.desc = "Basic forest room." # Send a message to the account kwargs["caller"].msg(room.key + " " + room.dbref) # This is generally mandatory. return room def example1_build_mountains(x, y, **kwargs): '''A room that is a little more advanced''' # Create the room. room = create_object(rooms.Room, key="mountains" + str(x) + str(y)) # Generate a description by randomly selecting an entry from a list. room_desc = [ "Mountains as far as the eye can see", "Your path is surrounded by sheer cliffs", "Haven't you seen that rock before?", ] room.db.desc = random.choice(room_desc) # Create a random number of objects to populate the room. for i in range(randint(0, 3)): rock = create_object(key="Rock", location=room) rock.db.desc = "An ordinary rock." # Send a message to the account kwargs["caller"].msg(room.key + " " + room.dbref) # This is generally mandatory. return room def example1_build_temple(x, y, **kwargs): '''A unique room that does not need to be as general''' # Create the room. room = create_object(rooms.Room, key="temple" + str(x) + str(y)) # Set the description. room.db.desc = ( "In what, from the outside, appeared to be a grand and " "ancient temple you've somehow found yourself in the the " "Evennia Inn! It consists of one large room filled with " "tables. The bardisk extends along the east wall, where " "multiple barrels and bottles line the shelves. The " "barkeep seems busy handing out ale and chatting with " "the patrons, which are a rowdy and cheerful lot, " "keeping the sound level only just below thunderous. " "This is a rare spot of mirth on this dread moor." ) # Send a message to the account kwargs["caller"].msg(room.key + " " + room.dbref) # This is generally mandatory. return room # Include your trigger characters and build functions in a legend dict. EXAMPLE1_LEGEND = { ("♣", "♠"): example1_build_forest, ("∩", "n"): example1_build_mountains, ("▲"): example1_build_temple, } # Example two # @mapbuilder/two evennia.contrib.grid.mapbuilder.EXAMPLE2_MAP EXAMPLE2_LEGEND # -*- coding: utf-8 -*- # Add the necessary imports for your instructions here. # from evennia import create_object # from typeclasses import rooms, exits # from evennia.utils import utils # from random import randint # import random # This is the same layout as Example 1 but included are characters for exits. # We can use these characters to determine which rooms should be connected. EXAMPLE2_MAP = '''\ ≈ ≈ ≈ ≈ ≈ ≈ ♣-♣-♣ ≈ | | ≈ ♣ ♣ ♣ ≈ | | | ≈ ♣-♣-♣ ≈ ≈ ≈ ≈ ≈ ≈ ''' def example2_build_forest(x, y, **kwargs): '''A basic room''' # If on anything other than the first iteration - Do nothing. if kwargs["iteration"] > 0: return None room = create_object(rooms.Room, key="forest" + str(x) + str(y)) room.db.desc = "Basic forest room." kwargs["caller"].msg(room.key + " " + room.dbref) return room def example2_build_verticle_exit(x, y, **kwargs): '''Creates two exits to and from the two rooms north and south.''' # If on the first iteration - Do nothing. if kwargs["iteration"] == 0: return north_room = kwargs["room_dict"][(x, y - 1)] south_room = kwargs["room_dict"][(x, y + 1)] # create exits in the rooms create_object( exits.Exit, key="south", aliases=["s"], location=north_room, destination=south_room ) create_object( exits.Exit, key="north", aliases=["n"], location=south_room, destination=north_room ) kwargs["caller"].msg("Connected: " + north_room.key + " & " + south_room.key) def example2_build_horizontal_exit(x, y, **kwargs): '''Creates two exits to and from the two rooms east and west.''' # If on the first iteration - Do nothing. if kwargs["iteration"] == 0: return west_room = kwargs["room_dict"][(x - 1, y)] east_room = kwargs["room_dict"][(x + 1, y)] create_object(exits.Exit, key="east", aliases=["e"], location=west_room, destination=east_room) create_object(exits.Exit, key="west", aliases=["w"], location=east_room, destination=west_room) kwargs["caller"].msg("Connected: " + west_room.key + " & " + east_room.key) # Include your trigger characters and build functions in a legend dict. EXAMPLE2_LEGEND = { ("♣", "♠"): example2_build_forest, ("|"): example2_build_verticle_exit, ("-"): example2_build_horizontal_exit, } class TestMapBuilder(BaseEvenniaCommandTest): def test_cmdmapbuilder(self): self.call( mapbuilder.CmdMapBuilder(), "evennia.contrib.grid.mapbuilder.tests.EXAMPLE1_MAP " "evennia.contrib.grid.mapbuilder.tests.EXAMPLE1_LEGEND", """Creating Map...|≈≈≈≈≈ ≈♣n♣≈ ≈∩▲∩≈ ≈♠n♠≈ ≈≈≈≈≈ |Creating Landmass...|""", ) self.call( mapbuilder.CmdMapBuilder(), "evennia.contrib.grid.mapbuilder.tests.EXAMPLE2_MAP " "evennia.contrib.grid.mapbuilder.tests.EXAMPLE2_LEGEND", """Creating Map...|≈ ≈ ≈ ≈ ≈ ≈ ♣-♣-♣ ≈ ≈ ♣ ♣ ♣ ≈ ≈ ♣-♣-♣ ≈ ≈ ≈ ≈ ≈ ≈ |Creating Landmass...|""", )
[ "evennia.create_object" ]
[((1551, 1575), 'random.choice', 'random.choice', (['room_desc'], {}), '(room_desc)\n', (1564, 1575), False, 'import random\n'), ((4394, 4496), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""south"""', 'aliases': "['s']", 'location': 'north_room', 'destination': 'south_room'}), "(exits.Exit, key='south', aliases=['s'], location=north_room,\n destination=south_room)\n", (4407, 4496), False, 'from evennia import create_object\n'), ((4512, 4614), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""north"""', 'aliases': "['n']", 'location': 'south_room', 'destination': 'north_room'}), "(exits.Exit, key='north', aliases=['n'], location=south_room,\n destination=north_room)\n", (4525, 4614), False, 'from evennia import create_object\n'), ((5027, 5126), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""east"""', 'aliases': "['e']", 'location': 'west_room', 'destination': 'east_room'}), "(exits.Exit, key='east', aliases=['e'], location=west_room,\n destination=east_room)\n", (5040, 5126), False, 'from evennia import create_object\n'), ((5128, 5227), 'evennia.create_object', 'create_object', (['exits.Exit'], {'key': '"""west"""', 'aliases': "['w']", 'location': 'east_room', 'destination': 'west_room'}), "(exits.Exit, key='west', aliases=['w'], location=east_room,\n destination=west_room)\n", (5141, 5227), False, 'from evennia import create_object\n'), ((1658, 1671), 'random.randint', 'randint', (['(0)', '(3)'], {}), '(0, 3)\n', (1665, 1671), False, 'from random import randint\n'), ((1689, 1729), 'evennia.create_object', 'create_object', ([], {'key': '"""Rock"""', 'location': 'room'}), "(key='Rock', location=room)\n", (1702, 1729), False, 'from evennia import create_object\n')]
from evennia.utils.ansi import ANSIString from athanor.gamedb.scripts import AthanorOptionScript from athanor.gamedb.models import ThemeBridge, ThemeParticipant class AthanorTheme(AthanorOptionScript): re_name = re.compile(r"") def create_bridge(self, key, clean_key): if hasattr(self, 'theme_bridge'): return ThemeBridge.objects.create(db_script=self, db_name=clean_key, db_iname=clean_key.lower(), db_cname=key) @classmethod def create_theme(cls, name, description, **kwargs): key = ANSIString(name) clean_key = str(key.clean()) if '|' in clean_key: raise ValueError("Malformed ANSI in Theme Name.") if ThemeBridge.objects.filter(db_iname=clean_key.lower()).count(): raise ValueError("Name conflicts with another Theme.") obj, errors = cls.create(clean_key, **kwargs) if obj: obj.create_bridge(key, clean_key) obj.db.desc = description else: raise ValueError(errors) return obj def add_character(self, character, list_type): return ThemeParticipant.objects.create(db_theme=self.theme_bridge, db_object=character, db_list_type=list_type) def remove_character(self, character): if (participant := self.participants.filter(db_object=character).first()): if character.db._primary_theme == participant: del character.db._primary_theme participant.delete() def __str__(self): return self.db_key def rename(self, key): key = ANSIString(key) clean_key = str(key.clean()) if '|' in clean_key: raise ValueError("Malformed ANSI in Theme Name.") bridge = self.theme_bridge if ThemeBridge.objects.filter(db_iname=clean_key.lower()).exclude(id=bridge).count(): raise ValueError("Name conflicts with another Theme.") self.key = clean_key bridge.db_name = clean_key bridge.db_iname = clean_key.lower() bridge.db_cname = key
[ "evennia.utils.ansi.ANSIString" ]
[((543, 559), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['name'], {}), '(name)\n', (553, 559), False, 'from evennia.utils.ansi import ANSIString\n'), ((1121, 1230), 'athanor.gamedb.models.ThemeParticipant.objects.create', 'ThemeParticipant.objects.create', ([], {'db_theme': 'self.theme_bridge', 'db_object': 'character', 'db_list_type': 'list_type'}), '(db_theme=self.theme_bridge, db_object=\n character, db_list_type=list_type)\n', (1152, 1230), False, 'from athanor.gamedb.models import ThemeBridge, ThemeParticipant\n'), ((1586, 1601), 'evennia.utils.ansi.ANSIString', 'ANSIString', (['key'], {}), '(key)\n', (1596, 1601), False, 'from evennia.utils.ansi import ANSIString\n')]
""" Service for integrating the Evennia Game Index client into Evennia. """ from twisted.internet import reactor from twisted.internet.task import LoopingCall from twisted.application.service import Service from evennia.utils import logger from .client import EvenniaGameIndexClient # How many seconds to wait before triggering the first EGI check-in. _FIRST_UPDATE_DELAY = 10 # How often to sync to the server _CLIENT_UPDATE_RATE = 60 * 30 class EvenniaGameIndexService(Service): """ Twisted Service that contains a LoopingCall for regularly sending game details to the Evennia Game Index. """ # We didn't stick the Evennia prefix on here because it'd get marked as # a core system service. name = "GameIndexClient" def __init__(self): self.client = EvenniaGameIndexClient(on_bad_request=self._die_on_bad_request) self.loop = LoopingCall(self.client.send_game_details) def startService(self): super().startService() # Check to make sure that the client is configured. # Start the loop, but only after a short delay. This allows the # portal and the server time to sync up as far as total player counts. # Prevents always reporting a count of 0. reactor.callLater(_FIRST_UPDATE_DELAY, self.loop.start, _CLIENT_UPDATE_RATE) def stopService(self): if self.running == 0: # reload errors if we've stopped this service. return super().stopService() if self.loop.running: self.loop.stop() def _die_on_bad_request(self): """ If it becomes apparent that our configuration is generating improperly formed messages to EGI, we don't want to keep sending bad messages. Stop the service so we're not wasting resources. """ logger.log_infomsg( "Shutting down Evennia Game Index client service due to " "invalid configuration." ) self.stopService()
[ "evennia.utils.logger.log_infomsg" ]
[((883, 925), 'twisted.internet.task.LoopingCall', 'LoopingCall', (['self.client.send_game_details'], {}), '(self.client.send_game_details)\n', (894, 925), False, 'from twisted.internet.task import LoopingCall\n'), ((1255, 1331), 'twisted.internet.reactor.callLater', 'reactor.callLater', (['_FIRST_UPDATE_DELAY', 'self.loop.start', '_CLIENT_UPDATE_RATE'], {}), '(_FIRST_UPDATE_DELAY, self.loop.start, _CLIENT_UPDATE_RATE)\n', (1272, 1331), False, 'from twisted.internet import reactor\n'), ((1837, 1946), 'evennia.utils.logger.log_infomsg', 'logger.log_infomsg', (['"""Shutting down Evennia Game Index client service due to invalid configuration."""'], {}), "(\n 'Shutting down Evennia Game Index client service due to invalid configuration.'\n )\n", (1855, 1946), False, 'from evennia.utils import logger\n')]
""" The Evennia Portal service acts as an AMP-server, handling AMP communication to the AMP clients connecting to it (by default these are the Evennia Server and the evennia launcher). """ import os import sys from twisted.internet import protocol from evennia.server.portal import amp from django.conf import settings from subprocess import Popen, STDOUT from evennia.utils import logger from evennia.utils.utils import class_from_module def _is_windows(): return os.name == "nt" def getenv(): """ Get current environment and add PYTHONPATH. Returns: env (dict): Environment global dict. """ sep = ";" if _is_windows() else ":" env = os.environ.copy() env["PYTHONPATH"] = sep.join(sys.path) return env class AMPServerFactory(protocol.ServerFactory): """ This factory creates AMP Server connection. This acts as the 'Portal'-side communication to the 'Server' process. """ noisy = False def logPrefix(self): """ How this is named in logs """ return "AMP" def __init__(self, portal): """ Initialize the factory. This is called as the Portal service starts. Args: portal (Portal): The Evennia Portal service instance. protocol (Protocol): The protocol the factory creates instances of. """ self.portal = portal self.protocol = class_from_module(settings.AMP_SERVER_PROTOCOL_CLASS) self.broadcasts = [] self.server_connection = None self.launcher_connection = None self.disconnect_callbacks = {} self.server_connect_callbacks = [] def buildProtocol(self, addr): """ Start a new connection, and store it on the service object. Args: addr (str): Connection address. Not used. Returns: protocol (Protocol): The created protocol. """ self.portal.amp_protocol = self.protocol() self.portal.amp_protocol.factory = self return self.portal.amp_protocol class AMPServerProtocol(amp.AMPMultiConnectionProtocol): """ Protocol subclass for the AMP-server run by the Portal. """ def connectionLost(self, reason): """ Set up a simple callback mechanism to let the amp-server wait for a connection to close. """ # wipe broadcast and data memory super(AMPServerProtocol, self).connectionLost(reason) if self.factory.server_connection == self: self.factory.server_connection = None self.factory.portal.server_info_dict = {} if self.factory.launcher_connection == self: self.factory.launcher_connection = None callback, args, kwargs = self.factory.disconnect_callbacks.pop(self, (None, None, None)) if callback: try: callback(*args, **kwargs) except Exception: logger.log_trace() def get_status(self): """ Return status for the Evennia infrastructure. Returns: status (tuple): The portal/server status and pids (portal_live, server_live, portal_PID, server_PID). """ server_connected = bool( self.factory.server_connection and self.factory.server_connection.transport.connected ) portal_info_dict = self.factory.portal.get_info_dict() server_info_dict = self.factory.portal.server_info_dict server_pid = self.factory.portal.server_process_id portal_pid = os.getpid() return (True, server_connected, portal_pid, server_pid, portal_info_dict, server_info_dict) def data_to_server(self, command, sessid, **kwargs): """ Send data across the wire to the Server. Args: command (AMP Command): A protocol send command. sessid (int): A unique Session id. kwargs (any): Data to send. This will be pickled. Returns: deferred (deferred or None): A deferred with an errback. Notes: Data will be sent across the wire pickled as a tuple (sessid, kwargs). """ # print("portal data_to_server: {}, {}, {}".format(command, sessid, kwargs)) if self.factory.server_connection: return self.factory.server_connection.callRemote( command, packed_data=amp.dumps((sessid, kwargs)) ).addErrback(self.errback, command.key) else: # if no server connection is available, broadcast return self.broadcast(command, sessid, packed_data=amp.dumps((sessid, kwargs))) def start_server(self, server_twistd_cmd): """ (Re-)Launch the Evennia server. Args: server_twisted_cmd (list): The server start instruction to pass to POpen to start the server. """ # start the Server print("Portal starting server ... ") process = None with open(settings.SERVER_LOG_FILE, "a") as logfile: # we link stdout to a file in order to catch # eventual errors happening before the Server has # opened its logger. try: if _is_windows(): # Windows requires special care create_no_window = 0x08000000 process = Popen( server_twistd_cmd, env=getenv(), bufsize=-1, stdout=logfile, stderr=STDOUT, creationflags=create_no_window, ) else: process = Popen( server_twistd_cmd, env=getenv(), bufsize=-1, stdout=logfile, stderr=STDOUT ) except Exception: logger.log_trace() self.factory.portal.server_twistd_cmd = server_twistd_cmd logfile.flush() if process and not _is_windows(): # avoid zombie-process on Unix/BSD process.wait() return def wait_for_disconnect(self, callback, *args, **kwargs): """ Add a callback for when this connection is lost. Args: callback (callable): Will be called with *args, **kwargs once this protocol is disconnected. """ self.factory.disconnect_callbacks[self] = (callback, args, kwargs) def wait_for_server_connect(self, callback, *args, **kwargs): """ Add a callback for when the Server is sure to have connected. Args: callback (callable): Will be called with *args, **kwargs once the Server handshake with Portal is complete. """ self.factory.server_connect_callbacks.append((callback, args, kwargs)) def stop_server(self, mode="shutdown"): """ Shut down server in one or more modes. Args: mode (str): One of 'shutdown', 'reload' or 'reset'. """ if mode == "reload": self.send_AdminPortal2Server(amp.DUMMYSESSION, operation=amp.SRELOAD) elif mode == "reset": self.send_AdminPortal2Server(amp.DUMMYSESSION, operation=amp.SRESET) elif mode == "shutdown": self.send_AdminPortal2Server(amp.DUMMYSESSION, operation=amp.SSHUTD) self.factory.portal.server_restart_mode = mode # sending amp data def send_Status2Launcher(self): """ Send a status stanza to the launcher. """ # print("send status to launcher") # print("self.get_status(): {}".format(self.get_status())) if self.factory.launcher_connection: self.factory.launcher_connection.callRemote( amp.MsgStatus, status=amp.dumps(self.get_status()) ).addErrback(self.errback, amp.MsgStatus.key) def send_MsgPortal2Server(self, session, **kwargs): """ Access method called by the Portal and executed on the Portal. Args: session (session): Session kwargs (any, optional): Optional data. Returns: deferred (Deferred): Asynchronous return. """ return self.data_to_server(amp.MsgPortal2Server, session.sessid, **kwargs) def send_AdminPortal2Server(self, session, operation="", **kwargs): """ Send Admin instructions from the Portal to the Server. Executed on the Portal. Args: session (Session): Session. operation (char, optional): Identifier for the server operation, as defined by the global variables in `evennia/server/amp.py`. data (str or dict, optional): Data used in the administrative operation. """ return self.data_to_server( amp.AdminPortal2Server, session.sessid, operation=operation, **kwargs ) # receive amp data @amp.MsgStatus.responder @amp.catch_traceback def portal_receive_status(self, status): """ Returns run-status for the server/portal. Args: status (str): Not used. Returns: status (dict): The status is a tuple (portal_running, server_running, portal_pid, server_pid). """ # print('Received PSTATUS request') return {"status": amp.dumps(self.get_status())} @amp.MsgLauncher2Portal.responder @amp.catch_traceback def portal_receive_launcher2portal(self, operation, arguments): """ Receives message arriving from evennia_launcher. This method is executed on the Portal. Args: operation (str): The action to perform. arguments (str): Possible argument to the instruction, or the empty string. Returns: result (dict): The result back to the launcher. Notes: This is the entrypoint for controlling the entire Evennia system from the evennia launcher. It can obviously only accessed when the Portal is already up and running. """ # Since the launcher command uses amp.String() we need to convert from byte here. operation = str(operation, "utf-8") self.factory.launcher_connection = self _, server_connected, _, _, _, _ = self.get_status() # logger.log_msg("Evennia Launcher->Portal operation %s:%s received" % (ord(operation), arguments)) # logger.log_msg("operation == amp.SSTART: {}: {}".format(operation == amp.SSTART, amp.loads(arguments))) if operation == amp.SSTART: # portal start #15 # first, check if server is already running if not server_connected: self.wait_for_server_connect(self.send_Status2Launcher) self.start_server(amp.loads(arguments)) elif operation == amp.SRELOAD: # reload server #14 if server_connected: # We let the launcher restart us once they get the signal self.factory.server_connection.wait_for_disconnect(self.send_Status2Launcher) self.stop_server(mode="reload") else: self.wait_for_server_connect(self.send_Status2Launcher) self.start_server(amp.loads(arguments)) elif operation == amp.SRESET: # reload server #19 if server_connected: self.factory.server_connection.wait_for_disconnect(self.send_Status2Launcher) self.stop_server(mode="reset") else: self.wait_for_server_connect(self.send_Status2Launcher) self.start_server(amp.loads(arguments)) elif operation == amp.SSHUTD: # server-only shutdown #17 if server_connected: self.factory.server_connection.wait_for_disconnect(self.send_Status2Launcher) self.stop_server(mode="shutdown") elif operation == amp.PSHUTD: # portal + server shutdown #16 if server_connected: self.factory.server_connection.wait_for_disconnect(self.factory.portal.shutdown) else: self.factory.portal.shutdown() else: logger.log_err("Operation {} not recognized".format(operation)) raise Exception("operation %(op)s not recognized." % {"op": operation}) return {} @amp.MsgServer2Portal.responder @amp.catch_traceback def portal_receive_server2portal(self, packed_data): """ Receives message arriving to Portal from Server. This method is executed on the Portal. Args: packed_data (str): Pickled data (sessid, kwargs) coming over the wire. """ try: sessid, kwargs = self.data_in(packed_data) session = self.factory.portal.sessions.get(sessid, None) if session: self.factory.portal.sessions.data_out(session, **kwargs) except Exception: logger.log_trace("packed_data len {}".format(len(packed_data))) return {} @amp.AdminServer2Portal.responder @amp.catch_traceback def portal_receive_adminserver2portal(self, packed_data): """ Receives and handles admin operations sent to the Portal This is executed on the Portal. Args: packed_data (str): Data received, a pickled tuple (sessid, kwargs). """ self.factory.server_connection = self sessid, kwargs = self.data_in(packed_data) # logger.log_msg("Evennia Server->Portal admin data %s:%s received" % (sessid, kwargs)) operation = kwargs.pop("operation") portal_sessionhandler = self.factory.portal.sessions if operation == amp.SLOGIN: # server_session_login # a session has authenticated; sync it. session = portal_sessionhandler.get(sessid) if session: portal_sessionhandler.server_logged_in(session, kwargs.get("sessiondata")) elif operation == amp.SDISCONN: # server_session_disconnect # the server is ordering to disconnect the session session = portal_sessionhandler.get(sessid) if session: portal_sessionhandler.server_disconnect(session, reason=kwargs.get("reason")) elif operation == amp.SDISCONNALL: # server_session_disconnect_all # server orders all sessions to disconnect portal_sessionhandler.server_disconnect_all(reason=kwargs.get("reason")) elif operation == amp.SRELOAD: # server reload self.factory.server_connection.wait_for_disconnect( self.start_server, self.factory.portal.server_twistd_cmd ) self.stop_server(mode="reload") elif operation == amp.SRESET: # server reset self.factory.server_connection.wait_for_disconnect( self.start_server, self.factory.portal.server_twistd_cmd ) self.stop_server(mode="reset") elif operation == amp.SSHUTD: # server-only shutdown self.stop_server(mode="shutdown") elif operation == amp.PSHUTD: # full server+server shutdown self.factory.server_connection.wait_for_disconnect(self.factory.portal.shutdown) self.stop_server(mode="shutdown") elif operation == amp.PSYNC: # portal sync # Server has (re-)connected and wants the session data from portal self.factory.portal.server_info_dict = kwargs.get("info_dict", {}) self.factory.portal.server_process_id = kwargs.get("spid", None) # this defaults to 'shutdown' or whatever value set in server_stop server_restart_mode = self.factory.portal.server_restart_mode sessdata = self.factory.portal.sessions.get_all_sync_data() self.send_AdminPortal2Server( amp.DUMMYSESSION, amp.PSYNC, server_restart_mode=server_restart_mode, sessiondata=sessdata, portal_start_time=self.factory.portal.start_time, ) self.factory.portal.sessions.at_server_connection() if self.factory.server_connection: # this is an indication the server has successfully connected, so # we trigger any callbacks (usually to tell the launcher server is up) for callback, args, kwargs in self.factory.server_connect_callbacks: try: callback(*args, **kwargs) except Exception: logger.log_trace() self.factory.server_connect_callbacks = [] elif operation == amp.SSYNC: # server_session_sync # server wants to save session data to the portal, # maybe because it's about to shut down. portal_sessionhandler.server_session_sync( kwargs.get("sessiondata"), kwargs.get("clean", True) ) # set a flag in case we are about to shut down soon self.factory.server_restart_mode = True elif operation == amp.SCONN: # server_force_connection (for irc/etc) portal_sessionhandler.server_connect(**kwargs) else: raise Exception("operation %(op)s not recognized." % {"op": operation}) return {}
[ "evennia.utils.utils.class_from_module", "evennia.server.portal.amp.loads", "evennia.utils.logger.log_trace", "evennia.server.portal.amp.dumps" ]
[((678, 695), 'os.environ.copy', 'os.environ.copy', ([], {}), '()\n', (693, 695), False, 'import os\n'), ((1434, 1487), 'evennia.utils.utils.class_from_module', 'class_from_module', (['settings.AMP_SERVER_PROTOCOL_CLASS'], {}), '(settings.AMP_SERVER_PROTOCOL_CLASS)\n', (1451, 1487), False, 'from evennia.utils.utils import class_from_module\n'), ((3592, 3603), 'os.getpid', 'os.getpid', ([], {}), '()\n', (3601, 3603), False, 'import os\n'), ((2971, 2989), 'evennia.utils.logger.log_trace', 'logger.log_trace', ([], {}), '()\n', (2987, 2989), False, 'from evennia.utils import logger\n'), ((4664, 4691), 'evennia.server.portal.amp.dumps', 'amp.dumps', (['(sessid, kwargs)'], {}), '((sessid, kwargs))\n', (4673, 4691), False, 'from evennia.server.portal import amp\n'), ((5942, 5960), 'evennia.utils.logger.log_trace', 'logger.log_trace', ([], {}), '()\n', (5958, 5960), False, 'from evennia.utils import logger\n'), ((10938, 10958), 'evennia.server.portal.amp.loads', 'amp.loads', (['arguments'], {}), '(arguments)\n', (10947, 10958), False, 'from evennia.server.portal import amp\n'), ((11394, 11414), 'evennia.server.portal.amp.loads', 'amp.loads', (['arguments'], {}), '(arguments)\n', (11403, 11414), False, 'from evennia.server.portal import amp\n'), ((4445, 4472), 'evennia.server.portal.amp.dumps', 'amp.dumps', (['(sessid, kwargs)'], {}), '((sessid, kwargs))\n', (4454, 4472), False, 'from evennia.server.portal import amp\n'), ((11774, 11794), 'evennia.server.portal.amp.loads', 'amp.loads', (['arguments'], {}), '(arguments)\n', (11783, 11794), False, 'from evennia.server.portal import amp\n'), ((16776, 16794), 'evennia.utils.logger.log_trace', 'logger.log_trace', ([], {}), '()\n', (16792, 16794), False, 'from evennia.utils import logger\n')]
""" Simple turn-based combat system with spell casting Contrib - <NAME> 2017 This is a version of the 'turnbattle' contrib that includes a basic, expandable framework for a 'magic system', whereby players can spend a limited resource (MP) to achieve a wide variety of effects, both in and out of combat. This does not have to strictly be a system for magic - it can easily be re-flavored to any other sort of resource based mechanic, like psionic powers, special moves and stamina, and so forth. In this system, spells are learned by name with the 'learnspell' command, and then used with the 'cast' command. Spells can be cast in or out of combat - some spells can only be cast in combat, some can only be cast outside of combat, and some can be cast any time. However, if you are in combat, you can only cast a spell on your turn, and doing so will typically use an action (as specified in the spell's funciton). Spells are defined at the end of the module in a database that's a dictionary of dictionaries - each spell is matched by name to a function, along with various parameters that restrict when the spell can be used and what the spell can be cast on. Included is a small variety of spells that damage opponents and heal HP, as well as one that creates an object. Because a spell can call any function, a spell can be made to do just about anything at all. The SPELLS dictionary at the bottom of the module even allows kwargs to be passed to the spell function, so that the same function can be re-used for multiple similar spells. Spells in this system work on a very basic resource: MP, which is spent when casting spells and restored by resting. It shouldn't be too difficult to modify this system to use spell slots, some physical fuel or resource, or whatever else your game requires. To install and test, import this module's TBMagicCharacter object into your game's character.py module: from evennia.contrib.turnbattle.tb_magic import TBMagicCharacter And change your game's character typeclass to inherit from TBMagicCharacter instead of the default: class Character(TBMagicCharacter): Note: If your character already existed you need to also make sure to re-run the creation hooks on it to set the needed Attributes. Use `update self` to try on yourself or use py to call `at_object_creation()` on all existing Characters. Next, import this module into your default_cmdsets.py module: from evennia.contrib.turnbattle import tb_magic And add the battle command set to your default command set: # # any commands you add below will overload the default ones. # self.add(tb_magic.BattleCmdSet()) This module is meant to be heavily expanded on, so you may want to copy it to your game's 'world' folder and modify it there rather than importing it in your game and using it as-is. """ from random import randint from evennia import DefaultCharacter, Command, default_cmds, DefaultScript, create_object from evennia.commands.default.muxcommand import MuxCommand from evennia.commands.default.help import CmdHelp """ ---------------------------------------------------------------------------- OPTIONS ---------------------------------------------------------------------------- """ TURN_TIMEOUT = 30 # Time before turns automatically end, in seconds ACTIONS_PER_TURN = 1 # Number of actions allowed per turn """ ---------------------------------------------------------------------------- COMBAT FUNCTIONS START HERE ---------------------------------------------------------------------------- """ def roll_init(character): """ Rolls a number between 1-1000 to determine initiative. Args: character (obj): The character to determine initiative for Returns: initiative (int): The character's place in initiative - higher numbers go first. Notes: By default, does not reference the character and simply returns a random integer from 1 to 1000. Since the character is passed to this function, you can easily reference a character's stats to determine an initiative roll - for example, if your character has a 'dexterity' attribute, you can use it to give that character an advantage in turn order, like so: return (randint(1,20)) + character.db.dexterity This way, characters with a higher dexterity will go first more often. """ return randint(1, 1000) def get_attack(attacker, defender): """ Returns a value for an attack roll. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: attack_value (int): Attack roll value, compared against a defense value to determine whether an attack hits or misses. Notes: By default, returns a random integer from 1 to 100 without using any properties from either the attacker or defender. This can easily be expanded to return a value based on characters stats, equipment, and abilities. This is why the attacker and defender are passed to this function, even though nothing from either one are used in this example. """ # For this example, just return a random integer up to 100. attack_value = randint(1, 100) return attack_value def get_defense(attacker, defender): """ Returns a value for defense, which an attack roll must equal or exceed in order for an attack to hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Returns: defense_value (int): Defense value, compared against an attack roll to determine whether an attack hits or misses. Notes: By default, returns 50, not taking any properties of the defender or attacker into account. As above, this can be expanded upon based on character stats and equipment. """ # For this example, just return 50, for about a 50/50 chance of hit. defense_value = 50 return defense_value def get_damage(attacker, defender): """ Returns a value for damage to be deducted from the defender's HP after abilities successful hit. Args: attacker (obj): Character doing the attacking defender (obj): Character being damaged Returns: damage_value (int): Damage value, which is to be deducted from the defending character's HP. Notes: By default, returns a random integer from 15 to 25 without using any properties from either the attacker or defender. Again, this can be expanded upon. """ # For this example, just generate a number between 15 and 25. damage_value = randint(15, 25) return damage_value def apply_damage(defender, damage): """ Applies damage to a target, reducing their HP by the damage amount to a minimum of 0. Args: defender (obj): Character taking damage damage (int): Amount of damage being taken """ defender.db.hp -= damage # Reduce defender's HP by the damage dealt. # If this reduces it to 0 or less, set HP to 0. if defender.db.hp <= 0: defender.db.hp = 0 def at_defeat(defeated): """ Announces the defeat of a fighter in combat. Args: defeated (obj): Fighter that's been defeated. Notes: All this does is announce a defeat message by default, but if you want anything else to happen to defeated fighters (like putting them into a dying state or something similar) then this is the place to do it. """ defeated.location.msg_contents("%s has been defeated!" % defeated) def resolve_attack(attacker, defender, attack_value=None, defense_value=None): """ Resolves an attack and outputs the result. Args: attacker (obj): Character doing the attacking defender (obj): Character being attacked Notes: Even though the attack and defense values are calculated extremely simply, they are separated out into their own functions so that they are easier to expand upon. """ # Get an attack roll from the attacker. if not attack_value: attack_value = get_attack(attacker, defender) # Get a defense value from the defender. if not defense_value: defense_value = get_defense(attacker, defender) # If the attack value is lower than the defense value, miss. Otherwise, hit. if attack_value < defense_value: attacker.location.msg_contents("%s's attack misses %s!" % (attacker, defender)) else: damage_value = get_damage(attacker, defender) # Calculate damage value. # Announce damage dealt and apply damage. attacker.location.msg_contents( "%s hits %s for %i damage!" % (attacker, defender, damage_value) ) apply_damage(defender, damage_value) # If defender HP is reduced to 0 or less, call at_defeat. if defender.db.hp <= 0: at_defeat(defender) def combat_cleanup(character): """ Cleans up all the temporary combat-related attributes on a character. Args: character (obj): Character to have their combat attributes removed Notes: Any attribute whose key begins with 'combat_' is temporary and no longer needed once a fight ends. """ for attr in character.attributes.all(): if attr.key[:7] == "combat_": # If the attribute name starts with 'combat_'... character.attributes.remove(key=attr.key) # ...then delete it! def is_in_combat(character): """ Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat """ return bool(character.db.combat_turnhandler) def is_turn(character): """ Returns true if it's currently the given character's turn in combat. Args: character (obj): Character to determine if it is their turn or not Returns: (bool): True if it is their turn or False otherwise """ turnhandler = character.db.combat_turnhandler currentchar = turnhandler.db.fighters[turnhandler.db.turn] return bool(character == currentchar) def spend_action(character, actions, action_name=None): """ Spends a character's available combat actions and checks for end of turn. Args: character (obj): Character spending the action actions (int) or 'all': Number of actions to spend, or 'all' to spend all actions Keyword Args: action_name (str or None): If a string is given, sets character's last action in combat to provided string """ if not is_in_combat(character): return if action_name: character.db.combat_lastaction = action_name if actions == "all": # If spending all actions character.db.combat_actionsleft = 0 # Set actions to 0 else: character.db.combat_actionsleft -= actions # Use up actions. if character.db.combat_actionsleft < 0: character.db.combat_actionsleft = 0 # Can't have fewer than 0 actions character.db.combat_turnhandler.turn_end_check(character) # Signal potential end of turn. """ ---------------------------------------------------------------------------- CHARACTER TYPECLASS ---------------------------------------------------------------------------- """ class TBMagicCharacter(DefaultCharacter): """ A character able to participate in turn-based combat. Has attributes for current and maximum HP, and access to combat commands. """ def at_object_creation(self): """ Called once, when this object is first created. This is the normal hook to overload for most object types. Adds attributes for a character's current and maximum HP. We're just going to set this value at '100' by default. You may want to expand this to include various 'stats' that can be changed at creation and factor into combat calculations. """ self.db.max_hp = 100 # Set maximum HP to 100 self.db.hp = self.db.max_hp # Set current HP to maximum self.db.spells_known = [] # Set empty spells known list self.db.max_mp = 20 # Set maximum MP to 20 self.db.mp = self.db.max_mp # Set current MP to maximum def at_before_move(self, destination): """ Called just before starting to move this object to destination. Args: destination (Object): The object we are moving to Returns: shouldmove (bool): If we should move or not. Notes: If this method returns False/None, the move is cancelled before it is even started. """ # Keep the character from moving if at 0 HP or in combat. if is_in_combat(self): self.msg("You can't exit a room while in combat!") return False # Returning false keeps the character from moving. if self.db.HP <= 0: self.msg("You can't move, you've been defeated!") return False return True """ ---------------------------------------------------------------------------- SCRIPTS START HERE ---------------------------------------------------------------------------- """ class TBMagicTurnHandler(DefaultScript): """ This is the script that handles the progression of combat through turns. On creation (when a fight is started) it adds all combat-ready characters to its roster and then sorts them into a turn order. There can only be one fight going on in a single room at a time, so the script is assigned to a room as its object. Fights persist until only one participant is left with any HP or all remaining participants choose to end the combat with the 'disengage' command. """ def at_script_creation(self): """ Called once, when the script is created. """ self.key = "Combat Turn Handler" self.interval = 5 # Once every 5 seconds self.persistent = True self.db.fighters = [] # Add all fighters in the room with at least 1 HP to the combat." for thing in self.obj.contents: if thing.db.hp: self.db.fighters.append(thing) # Initialize each fighter for combat for fighter in self.db.fighters: self.initialize_for_combat(fighter) # Add a reference to this script to the room self.obj.db.combat_turnhandler = self # Roll initiative and sort the list of fighters depending on who rolls highest to determine turn order. # The initiative roll is determined by the roll_init function and can be customized easily. ordered_by_roll = sorted(self.db.fighters, key=roll_init, reverse=True) self.db.fighters = ordered_by_roll # Announce the turn order. self.obj.msg_contents("Turn order is: %s " % ", ".join(obj.key for obj in self.db.fighters)) # Start first fighter's turn. self.start_turn(self.db.fighters[0]) # Set up the current turn and turn timeout delay. self.db.turn = 0 self.db.timer = TURN_TIMEOUT # Set timer to turn timeout specified in options def at_stop(self): """ Called at script termination. """ for fighter in self.db.fighters: combat_cleanup(fighter) # Clean up the combat attributes for every fighter. self.obj.db.combat_turnhandler = None # Remove reference to turn handler in location def at_repeat(self): """ Called once every self.interval seconds. """ currentchar = self.db.fighters[ self.db.turn ] # Note the current character in the turn order. self.db.timer -= self.interval # Count down the timer. if self.db.timer <= 0: # Force current character to disengage if timer runs out. self.obj.msg_contents("%s's turn timed out!" % currentchar) spend_action( currentchar, "all", action_name="disengage" ) # Spend all remaining actions. return elif self.db.timer <= 10 and not self.db.timeout_warning_given: # 10 seconds left # Warn the current character if they're about to time out. currentchar.msg("WARNING: About to time out!") self.db.timeout_warning_given = True def initialize_for_combat(self, character): """ Prepares a character for combat when starting or entering a fight. Args: character (obj): Character to initialize for combat. """ combat_cleanup(character) # Clean up leftover combat attributes beforehand, just in case. character.db.combat_actionsleft = ( 0 # Actions remaining - start of turn adds to this, turn ends when it reaches 0 ) character.db.combat_turnhandler = ( self # Add a reference to this turn handler script to the character ) character.db.combat_lastaction = "null" # Track last action taken in combat def start_turn(self, character): """ Readies a character for the start of their turn by replenishing their available actions and notifying them that their turn has come up. Args: character (obj): Character to be readied. Notes: Here, you only get one action per turn, but you might want to allow more than one per turn, or even grant a number of actions based on a character's attributes. You can even add multiple different kinds of actions, I.E. actions separated for movement, by adding "character.db.combat_movesleft = 3" or something similar. """ character.db.combat_actionsleft = ACTIONS_PER_TURN # Replenish actions # Prompt the character for their turn and give some information. character.msg("|wIt's your turn! You have %i HP remaining.|n" % character.db.hp) def next_turn(self): """ Advances to the next character in the turn order. """ # Check to see if every character disengaged as their last action. If so, end combat. disengage_check = True for fighter in self.db.fighters: if ( fighter.db.combat_lastaction != "disengage" ): # If a character has done anything but disengage disengage_check = False if disengage_check: # All characters have disengaged self.obj.msg_contents("All fighters have disengaged! Combat is over!") self.stop() # Stop this script and end combat. return # Check to see if only one character is left standing. If so, end combat. defeated_characters = 0 for fighter in self.db.fighters: if fighter.db.HP == 0: defeated_characters += 1 # Add 1 for every fighter with 0 HP left (defeated) if defeated_characters == ( len(self.db.fighters) - 1 ): # If only one character isn't defeated for fighter in self.db.fighters: if fighter.db.HP != 0: LastStanding = fighter # Pick the one fighter left with HP remaining self.obj.msg_contents("Only %s remains! Combat is over!" % LastStanding) self.stop() # Stop this script and end combat. return # Cycle to the next turn. currentchar = self.db.fighters[self.db.turn] self.db.turn += 1 # Go to the next in the turn order. if self.db.turn > len(self.db.fighters) - 1: self.db.turn = 0 # Go back to the first in the turn order once you reach the end. newchar = self.db.fighters[self.db.turn] # Note the new character self.db.timer = TURN_TIMEOUT + self.time_until_next_repeat() # Reset the timer. self.db.timeout_warning_given = False # Reset the timeout warning. self.obj.msg_contents("%s's turn ends - %s's turn begins!" % (currentchar, newchar)) self.start_turn(newchar) # Start the new character's turn. def turn_end_check(self, character): """ Tests to see if a character's turn is over, and cycles to the next turn if it is. Args: character (obj): Character to test for end of turn """ if not character.db.combat_actionsleft: # Character has no actions remaining self.next_turn() return def join_fight(self, character): """ Adds a new character to a fight already in progress. Args: character (obj): Character to be added to the fight. """ # Inserts the fighter to the turn order, right behind whoever's turn it currently is. self.db.fighters.insert(self.db.turn, character) # Tick the turn counter forward one to compensate. self.db.turn += 1 # Initialize the character like you do at the start. self.initialize_for_combat(character) """ ---------------------------------------------------------------------------- COMMANDS START HERE ---------------------------------------------------------------------------- """ class CmdFight(Command): """ Starts a fight with everyone in the same room as you. Usage: fight When you start a fight, everyone in the room who is able to fight is added to combat, and a turn order is randomly rolled. When it's your turn, you can attack other characters. """ key = "fight" help_category = "combat" def func(self): """ This performs the actual command. """ here = self.caller.location fighters = [] if not self.caller.db.hp: # If you don't have any hp self.caller.msg("You can't start a fight if you've been defeated!") return if is_in_combat(self.caller): # Already in a fight self.caller.msg("You're already in a fight!") return for thing in here.contents: # Test everything in the room to add it to the fight. if thing.db.HP: # If the object has HP... fighters.append(thing) # ...then add it to the fight. if len(fighters) <= 1: # If you're the only able fighter in the room self.caller.msg("There's nobody here to fight!") return if here.db.combat_turnhandler: # If there's already a fight going on... here.msg_contents("%s joins the fight!" % self.caller) here.db.combat_turnhandler.join_fight(self.caller) # Join the fight! return here.msg_contents("%s starts a fight!" % self.caller) # Add a turn handler script to the room, which starts combat. here.scripts.add("contrib.turnbattle.tb_magic.TBMagicTurnHandler") # Remember you'll have to change the path to the script if you copy this code to your own modules! class CmdAttack(Command): """ Attacks another character. Usage: attack <target> When in a fight, you may attack another character. The attack has a chance to hit, and if successful, will deal damage. """ key = "attack" help_category = "combat" def func(self): "This performs the actual command." "Set the attacker to the caller and the defender to the target." if not is_in_combat(self.caller): # If not in combat, can't attack. self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # If it's not your turn, can't attack. self.caller.msg("You can only do that on your turn.") return if not self.caller.db.hp: # Can't attack if you have no HP. self.caller.msg("You can't attack, you've been defeated.") return attacker = self.caller defender = self.caller.search(self.args) if not defender: # No valid target given. return if not defender.db.hp: # Target object has no HP left or to begin with self.caller.msg("You can't fight that!") return if attacker == defender: # Target and attacker are the same self.caller.msg("You can't attack yourself!") return "If everything checks out, call the attack resolving function." resolve_attack(attacker, defender) spend_action(self.caller, 1, action_name="attack") # Use up one action. class CmdPass(Command): """ Passes on your turn. Usage: pass When in a fight, you can use this command to end your turn early, even if there are still any actions you can take. """ key = "pass" aliases = ["wait", "hold"] help_category = "combat" def func(self): """ This performs the actual command. """ if not is_in_combat(self.caller): # Can only pass a turn in combat. self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # Can only pass if it's your turn. self.caller.msg("You can only do that on your turn.") return self.caller.location.msg_contents( "%s takes no further action, passing the turn." % self.caller ) spend_action(self.caller, "all", action_name="pass") # Spend all remaining actions. class CmdDisengage(Command): """ Passes your turn and attempts to end combat. Usage: disengage Ends your turn early and signals that you're trying to end the fight. If all participants in a fight disengage, the fight ends. """ key = "disengage" aliases = ["spare"] help_category = "combat" def func(self): """ This performs the actual command. """ if not is_in_combat(self.caller): # If you're not in combat self.caller.msg("You can only do that in combat. (see: help fight)") return if not is_turn(self.caller): # If it's not your turn self.caller.msg("You can only do that on your turn.") return self.caller.location.msg_contents("%s disengages, ready to stop fighting." % self.caller) spend_action(self.caller, "all", action_name="disengage") # Spend all remaining actions. """ The action_name kwarg sets the character's last action to "disengage", which is checked by the turn handler script to see if all fighters have disengaged. """ class CmdLearnSpell(Command): """ Learn a magic spell. Usage: learnspell <spell name> Adds a spell by name to your list of spells known. The following spells are provided as examples: |wmagic missile|n (3 MP): Fires three missiles that never miss. Can target up to three different enemies. |wflame shot|n (3 MP): Shoots a high-damage jet of flame at one target. |wcure wounds|n (5 MP): Heals damage on one target. |wmass cure wounds|n (10 MP): Like 'cure wounds', but can heal up to 5 targets at once. |wfull heal|n (12 MP): Heals one target back to full HP. |wcactus conjuration|n (2 MP): Creates a cactus. """ key = "learnspell" help_category = "magic" def func(self): """ This performs the actual command. """ spell_list = sorted(SPELLS.keys()) args = self.args.lower() args = args.strip(" ") caller = self.caller spell_to_learn = [] if not args or len(args) < 3: # No spell given caller.msg("Usage: learnspell <spell name>") return for spell in spell_list: # Match inputs to spells if args in spell.lower(): spell_to_learn.append(spell) if spell_to_learn == []: # No spells matched caller.msg("There is no spell with that name.") return if len(spell_to_learn) > 1: # More than one match matched_spells = ", ".join(spell_to_learn) caller.msg("Which spell do you mean: %s?" % matched_spells) return if len(spell_to_learn) == 1: # If one match, extract the string spell_to_learn = spell_to_learn[0] if spell_to_learn not in self.caller.db.spells_known: # If the spell isn't known... caller.db.spells_known.append(spell_to_learn) # ...then add the spell to the character caller.msg("You learn the spell '%s'!" % spell_to_learn) return if spell_to_learn in self.caller.db.spells_known: # Already has the spell specified caller.msg("You already know the spell '%s'!" % spell_to_learn) """ You will almost definitely want to replace this with your own system for learning spells, perhaps tied to character advancement or finding items in the game world that spells can be learned from. """ class CmdCast(MuxCommand): """ Cast a magic spell that you know, provided you have the MP to spend on its casting. Usage: cast <spellname> [= <target1>, <target2>, etc...] Some spells can be cast on multiple targets, some can be cast on only yourself, and some don't need a target specified at all. Typing 'cast' by itself will give you a list of spells you know. """ key = "cast" help_category = "magic" def func(self): """ This performs the actual command. Note: This is a quite long command, since it has to cope with all the different circumstances in which you may or may not be able to cast a spell. None of the spell's effects are handled by the command - all the command does is verify that the player's input is valid for the spell being cast and then call the spell's function. """ caller = self.caller if not self.lhs or len(self.lhs) < 3: # No spell name given caller.msg("Usage: cast <spell name> = <target>, <target2>, ...") if not caller.db.spells_known: caller.msg("You don't know any spells.") return else: caller.db.spells_known = sorted(caller.db.spells_known) spells_known_msg = "You know the following spells:|/" + "|/".join( caller.db.spells_known ) caller.msg(spells_known_msg) # List the spells the player knows return spellname = self.lhs.lower() spell_to_cast = [] spell_targets = [] if not self.rhs: spell_targets = [] elif self.rhs.lower() in ["me", "self", "myself"]: spell_targets = [caller] elif len(self.rhs) > 2: spell_targets = self.rhslist for spell in caller.db.spells_known: # Match inputs to spells if self.lhs in spell.lower(): spell_to_cast.append(spell) if spell_to_cast == []: # No spells matched caller.msg("You don't know a spell of that name.") return if len(spell_to_cast) > 1: # More than one match matched_spells = ", ".join(spell_to_cast) caller.msg("Which spell do you mean: %s?" % matched_spells) return if len(spell_to_cast) == 1: # If one match, extract the string spell_to_cast = spell_to_cast[0] if spell_to_cast not in SPELLS: # Spell isn't defined caller.msg("ERROR: Spell %s is undefined" % spell_to_cast) return # Time to extract some info from the chosen spell! spelldata = SPELLS[spell_to_cast] # Add in some default data if optional parameters aren't specified if "combat_spell" not in spelldata: spelldata.update({"combat_spell": True}) if "noncombat_spell" not in spelldata: spelldata.update({"noncombat_spell": True}) if "max_targets" not in spelldata: spelldata.update({"max_targets": 1}) # Store any superfluous options as kwargs to pass to the spell function kwargs = {} spelldata_opts = [ "spellfunc", "target", "cost", "combat_spell", "noncombat_spell", "max_targets", ] for key in spelldata: if key not in spelldata_opts: kwargs.update({key: spelldata[key]}) # If caster doesn't have enough MP to cover the spell's cost, give error and return if spelldata["cost"] > caller.db.mp: caller.msg("You don't have enough MP to cast '%s'." % spell_to_cast) return # If in combat and the spell isn't a combat spell, give error message and return if spelldata["combat_spell"] == False and is_in_combat(caller): caller.msg("You can't use the spell '%s' in combat." % spell_to_cast) return # If not in combat and the spell isn't a non-combat spell, error ms and return. if spelldata["noncombat_spell"] == False and is_in_combat(caller) == False: caller.msg("You can't use the spell '%s' outside of combat." % spell_to_cast) return # If spell takes no targets and one is given, give error message and return if len(spell_targets) > 0 and spelldata["target"] == "none": caller.msg("The spell '%s' isn't cast on a target." % spell_to_cast) return # If no target is given and spell requires a target, give error message if spelldata["target"] not in ["self", "none"]: if len(spell_targets) == 0: caller.msg("The spell '%s' requires a target." % spell_to_cast) return # If more targets given than maximum, give error message if len(spell_targets) > spelldata["max_targets"]: targplural = "target" if spelldata["max_targets"] > 1: targplural = "targets" caller.msg( "The spell '%s' can only be cast on %i %s." % (spell_to_cast, spelldata["max_targets"], targplural) ) return # Set up our candidates for targets target_candidates = [] # If spell targets 'any' or 'other', any object in caster's inventory or location # can be targeted by the spell. if spelldata["target"] in ["any", "other"]: target_candidates = caller.location.contents + caller.contents # If spell targets 'anyobj', only non-character objects can be targeted. if spelldata["target"] == "anyobj": prefilter_candidates = caller.location.contents + caller.contents for thing in prefilter_candidates: if not thing.attributes.has("max_hp"): # Has no max HP, isn't a fighter target_candidates.append(thing) # If spell targets 'anychar' or 'otherchar', only characters can be targeted. if spelldata["target"] in ["anychar", "otherchar"]: prefilter_candidates = caller.location.contents for thing in prefilter_candidates: if thing.attributes.has("max_hp"): # Has max HP, is a fighter target_candidates.append(thing) # Now, match each entry in spell_targets to an object in the search candidates matched_targets = [] for target in spell_targets: match = caller.search(target, candidates=target_candidates) matched_targets.append(match) spell_targets = matched_targets # If no target is given and the spell's target is 'self', set target to self if len(spell_targets) == 0 and spelldata["target"] == "self": spell_targets = [caller] # Give error message if trying to cast an "other" target spell on yourself if spelldata["target"] in ["other", "otherchar"]: if caller in spell_targets: caller.msg("You can't cast '%s' on yourself." % spell_to_cast) return # Return if "None" in target list, indicating failed match if None in spell_targets: # No need to give an error message, as 'search' gives one by default. return # Give error message if repeats in target list if len(spell_targets) != len(set(spell_targets)): caller.msg("You can't specify the same target more than once!") return # Finally, we can cast the spell itself. Note that MP is not deducted here! try: spelldata["spellfunc"]( caller, spell_to_cast, spell_targets, spelldata["cost"], **kwargs ) except Exception: log_trace("Error in callback for spell: %s." % spell_to_cast) class CmdRest(Command): """ Recovers damage and restores MP. Usage: rest Resting recovers your HP and MP to their maximum, but you can only rest if you're not in a fight. """ key = "rest" help_category = "combat" def func(self): "This performs the actual command." if is_in_combat(self.caller): # If you're in combat self.caller.msg("You can't rest while you're in combat.") return self.caller.db.hp = self.caller.db.max_hp # Set current HP to maximum self.caller.db.mp = self.caller.db.max_mp # Set current MP to maximum self.caller.location.msg_contents("%s rests to recover HP and MP." % self.caller) # You'll probably want to replace this with your own system for recovering HP and MP. class CmdStatus(Command): """ Gives combat information. Usage: status Shows your current and maximum HP and your distance from other targets in combat. """ key = "status" help_category = "combat" def func(self): "This performs the actual command." char = self.caller if not char.db.max_hp: # Character not initialized, IE in unit tests char.db.hp = 100 char.db.max_hp = 100 char.db.spells_known = [] char.db.max_mp = 20 char.db.mp = char.db.max_mp char.msg( "You have %i / %i HP and %i / %i MP." % (char.db.hp, char.db.max_hp, char.db.mp, char.db.max_mp) ) class CmdCombatHelp(CmdHelp): """ View help or a list of topics Usage: help <topic or command> help list help all This will search for help on commands and other topics related to the game. """ # Just like the default help command, but will give quick # tips on combat when used in a fight with no arguments. def func(self): if is_in_combat(self.caller) and not self.args: # In combat and entered 'help' alone self.caller.msg( "Available combat commands:|/" + "|wAttack:|n Attack a target, attempting to deal damage.|/" + "|wPass:|n Pass your turn without further action.|/" + "|wDisengage:|n End your turn and attempt to end combat.|/" ) else: super(CmdCombatHelp, self).func() # Call the default help command class BattleCmdSet(default_cmds.CharacterCmdSet): """ This command set includes all the commmands used in the battle system. """ key = "DefaultCharacter" def at_cmdset_creation(self): """ Populates the cmdset """ self.add(CmdFight()) self.add(CmdAttack()) self.add(CmdRest()) self.add(CmdPass()) self.add(CmdDisengage()) self.add(CmdCombatHelp()) self.add(CmdLearnSpell()) self.add(CmdCast()) self.add(CmdStatus()) """ ---------------------------------------------------------------------------- SPELL FUNCTIONS START HERE ---------------------------------------------------------------------------- These are the functions that are called by the 'cast' command to perform the effects of various spells. Which spells execute which functions and what parameters are passed to them are specified at the bottom of the module, in the 'SPELLS' dictionary. All of these functions take the same arguments: caster (obj): Character casting the spell spell_name (str): Name of the spell being cast targets (list): List of objects targeted by the spell cost (int): MP cost of casting the spell These functions also all accept **kwargs, and how these are used is specified in the docstring for each function. """ def spell_healing(caster, spell_name, targets, cost, **kwargs): """ Spell that restores HP to a target or targets. kwargs: healing_range (tuple): Minimum and maximum amount healed to each target. (20, 40) by default. """ spell_msg = "%s casts %s!" % (caster, spell_name) min_healing = 20 max_healing = 40 # Retrieve healing range from kwargs, if present if "healing_range" in kwargs: min_healing = kwargs["healing_range"][0] max_healing = kwargs["healing_range"][1] for character in targets: to_heal = randint(min_healing, max_healing) # Restore 20 to 40 hp if character.db.hp + to_heal > character.db.max_hp: to_heal = character.db.max_hp - character.db.hp # Cap healing to max HP character.db.hp += to_heal spell_msg += " %s regains %i HP!" % (character, to_heal) caster.db.mp -= cost # Deduct MP cost caster.location.msg_contents(spell_msg) # Message the room with spell results if is_in_combat(caster): # Spend action if in combat spend_action(caster, 1, action_name="cast") def spell_attack(caster, spell_name, targets, cost, **kwargs): """ Spell that deals damage in combat. Similar to resolve_attack. kwargs: attack_name (tuple): Single and plural describing the sort of attack or projectile that strikes each enemy. damage_range (tuple): Minimum and maximum damage dealt by the spell. (10, 20) by default. accuracy (int): Modifier to the spell's attack roll, determining an increased or decreased chance to hit. 0 by default. attack_count (int): How many individual attacks are made as part of the spell. If the number of attacks exceeds the number of targets, the first target specified will be attacked more than once. Just 1 by default - if the attack_count is less than the number targets given, each target will only be attacked once. """ spell_msg = "%s casts %s!" % (caster, spell_name) atkname_single = "The spell" atkname_plural = "spells" min_damage = 10 max_damage = 20 accuracy = 0 attack_count = 1 # Retrieve some variables from kwargs, if present if "attack_name" in kwargs: atkname_single = kwargs["attack_name"][0] atkname_plural = kwargs["attack_name"][1] if "damage_range" in kwargs: min_damage = kwargs["damage_range"][0] max_damage = kwargs["damage_range"][1] if "accuracy" in kwargs: accuracy = kwargs["accuracy"] if "attack_count" in kwargs: attack_count = kwargs["attack_count"] to_attack = [] # If there are more attacks than targets given, attack first target multiple times if len(targets) < attack_count: to_attack = to_attack + targets extra_attacks = attack_count - len(targets) for n in range(extra_attacks): to_attack.insert(0, targets[0]) else: to_attack = to_attack + targets # Set up dictionaries to track number of hits and total damage total_hits = {} total_damage = {} for fighter in targets: total_hits.update({fighter: 0}) total_damage.update({fighter: 0}) # Resolve attack for each target for fighter in to_attack: attack_value = randint(1, 100) + accuracy # Spell attack roll defense_value = get_defense(caster, fighter) if attack_value >= defense_value: spell_dmg = randint(min_damage, max_damage) # Get spell damage total_hits[fighter] += 1 total_damage[fighter] += spell_dmg for fighter in targets: # Construct combat message if total_hits[fighter] == 0: spell_msg += " The spell misses %s!" % fighter elif total_hits[fighter] > 0: attack_count_str = atkname_single + " hits" if total_hits[fighter] > 1: attack_count_str = "%i %s hit" % (total_hits[fighter], atkname_plural) spell_msg += " %s %s for %i damage!" % ( attack_count_str, fighter, total_damage[fighter], ) caster.db.mp -= cost # Deduct MP cost caster.location.msg_contents(spell_msg) # Message the room with spell results for fighter in targets: # Apply damage apply_damage(fighter, total_damage[fighter]) # If fighter HP is reduced to 0 or less, call at_defeat. if fighter.db.hp <= 0: at_defeat(fighter) if is_in_combat(caster): # Spend action if in combat spend_action(caster, 1, action_name="cast") def spell_conjure(caster, spell_name, targets, cost, **kwargs): """ Spell that creates an object. kwargs: obj_key (str): Key of the created object. obj_desc (str): Desc of the created object. obj_typeclass (str): Typeclass path of the object. If you want to make more use of this particular spell funciton, you may want to modify it to use the spawner (in evennia.utils.spawner) instead of creating objects directly. """ obj_key = "a nondescript object" obj_desc = "A perfectly generic object." obj_typeclass = "evennia.objects.objects.DefaultObject" # Retrieve some variables from kwargs, if present if "obj_key" in kwargs: obj_key = kwargs["obj_key"] if "obj_desc" in kwargs: obj_desc = kwargs["obj_desc"] if "obj_typeclass" in kwargs: obj_typeclass = kwargs["obj_typeclass"] conjured_obj = create_object( obj_typeclass, key=obj_key, location=caster.location ) # Create object conjured_obj.db.desc = obj_desc # Add object desc caster.db.mp -= cost # Deduct MP cost # Message the room to announce the creation of the object caster.location.msg_contents( "%s casts %s, and %s appears!" % (caster, spell_name, conjured_obj) ) """ ---------------------------------------------------------------------------- SPELL DEFINITIONS START HERE ---------------------------------------------------------------------------- In this section, each spell is matched to a function, and given parameters that determine its MP cost, valid type and number of targets, and what function casting the spell executes. This data is given as a dictionary of dictionaries - the key of each entry is the spell's name, and the value is a dictionary of various options and parameters, some of which are required and others which are optional. Required values for spells: cost (int): MP cost of casting the spell target (str): Valid targets for the spell. Can be any of: "none" - No target needed "self" - Self only "any" - Any object "anyobj" - Any object that isn't a character "anychar" - Any character "other" - Any object excluding the caster "otherchar" - Any character excluding the caster spellfunc (callable): Function that performs the action of the spell. Must take the following arguments: caster (obj), spell_name (str), targets (list), and cost (int), as well as **kwargs. Optional values for spells: combat_spell (bool): If the spell can be cast in combat. True by default. noncombat_spell (bool): If the spell can be cast out of combat. True by default. max_targets (int): Maximum number of objects that can be targeted by the spell. 1 by default - unused if target is "none" or "self" Any other values specified besides the above will be passed as kwargs to 'spellfunc'. You can use kwargs to effectively re-use the same function for different but similar spells - for example, 'magic missile' and 'flame shot' use the same function, but behave differently, as they have different damage ranges, accuracy, amount of attacks made as part of the spell, and so forth. If you make your spell functions flexible enough, you can make a wide variety of spells just by adding more entries to this dictionary. """ SPELLS = { "magic missile": { "spellfunc": spell_attack, "target": "otherchar", "cost": 3, "noncombat_spell": False, "max_targets": 3, "attack_name": ("A bolt", "bolts"), "damage_range": (4, 7), "accuracy": 999, "attack_count": 3, }, "flame shot": { "spellfunc": spell_attack, "target": "otherchar", "cost": 3, "noncombat_spell": False, "attack_name": ("A jet of flame", "jets of flame"), "damage_range": (25, 35), }, "cure wounds": {"spellfunc": spell_healing, "target": "anychar", "cost": 5}, "mass cure wounds": { "spellfunc": spell_healing, "target": "anychar", "cost": 10, "max_targets": 5, }, "full heal": { "spellfunc": spell_healing, "target": "anychar", "cost": 12, "healing_range": (100, 100), }, "cactus conjuration": { "spellfunc": spell_conjure, "target": "none", "cost": 2, "combat_spell": False, "obj_key": "a cactus", "obj_desc": "An ordinary green cactus with little spines.", }, }
[ "evennia.create_object" ]
[((4421, 4437), 'random.randint', 'randint', (['(1)', '(1000)'], {}), '(1, 1000)\n', (4428, 4437), False, 'from random import randint\n'), ((5281, 5296), 'random.randint', 'randint', (['(1)', '(100)'], {}), '(1, 100)\n', (5288, 5296), False, 'from random import randint\n'), ((6748, 6763), 'random.randint', 'randint', (['(15)', '(25)'], {}), '(15, 25)\n', (6755, 6763), False, 'from random import randint\n'), ((46622, 46689), 'evennia.create_object', 'create_object', (['obj_typeclass'], {'key': 'obj_key', 'location': 'caster.location'}), '(obj_typeclass, key=obj_key, location=caster.location)\n', (46635, 46689), False, 'from evennia import DefaultCharacter, Command, default_cmds, DefaultScript, create_object\n'), ((41598, 41631), 'random.randint', 'randint', (['min_healing', 'max_healing'], {}), '(min_healing, max_healing)\n', (41605, 41631), False, 'from random import randint\n'), ((44394, 44409), 'random.randint', 'randint', (['(1)', '(100)'], {}), '(1, 100)\n', (44401, 44409), False, 'from random import randint\n'), ((44561, 44592), 'random.randint', 'randint', (['min_damage', 'max_damage'], {}), '(min_damage, max_damage)\n', (44568, 44592), False, 'from random import randint\n')]
""" The Evennia Server service acts as an AMP-client when talking to the Portal. This module sets up the Client-side communication. """ import os from evennia.server.portal import amp from twisted.internet import protocol from evennia.utils import logger class AMPClientFactory(protocol.ReconnectingClientFactory): """ This factory creates an instance of an AMP client connection. This handles communication from the be the Evennia 'Server' service to the 'Portal'. The client will try to auto-reconnect on a connection error. """ # Initial reconnect delay in seconds. initialDelay = 1 factor = 1.5 maxDelay = 1 noisy = False def __init__(self, server): """ Initializes the client factory. Args: server (server): server instance. """ self.server = server self.protocol = AMPServerClientProtocol self.maxDelay = 10 # not really used unless connecting to multiple servers, but # avoids having to check for its existence on the protocol self.broadcasts = [] def startedConnecting(self, connector): """ Called when starting to try to connect to the MUD server. Args: connector (Connector): Twisted Connector instance representing this connection. """ pass def buildProtocol(self, addr): """ Creates an AMPProtocol instance when connecting to the AMP server. Args: addr (str): Connection address. Not used. """ self.resetDelay() self.server.amp_protocol = AMPServerClientProtocol() self.server.amp_protocol.factory = self return self.server.amp_protocol def clientConnectionLost(self, connector, reason): """ Called when the AMP connection to the MUD server is lost. Args: connector (Connector): Twisted Connector instance representing this connection. reason (str): Eventual text describing why connection was lost. """ logger.log_info("Server disconnected from the portal.") protocol.ReconnectingClientFactory.clientConnectionLost(self, connector, reason) def clientConnectionFailed(self, connector, reason): """ Called when an AMP connection attempt to the MUD server fails. Args: connector (Connector): Twisted Connector instance representing this connection. reason (str): Eventual text describing why connection failed. """ logger.log_msg("Attempting to reconnect to Portal ...") protocol.ReconnectingClientFactory.clientConnectionFailed(self, connector, reason) class AMPServerClientProtocol(amp.AMPMultiConnectionProtocol): """ This protocol describes the Server service (acting as an AMP-client)'s communication with the Portal (which acts as the AMP-server) """ # sending AMP data def connectionMade(self): """ Called when a new connection is established. """ info_dict = self.factory.server.get_info_dict() super(AMPServerClientProtocol, self).connectionMade() # first thing we do is to request the Portal to sync all sessions # back with the Server side. We also need the startup mode (reload, reset, shutdown) self.send_AdminServer2Portal( amp.DUMMYSESSION, operation=amp.PSYNC, spid=os.getpid(), info_dict=info_dict) # run the intial setup if needed self.factory.server.run_initial_setup() def data_to_portal(self, command, sessid, **kwargs): """ Send data across the wire to the Portal Args: command (AMP Command): A protocol send command. sessid (int): A unique Session id. kwargs (any): Any data to pickle into the command. Returns: deferred (deferred or None): A deferred with an errback. Notes: Data will be sent across the wire pickled as a tuple (sessid, kwargs). """ return self.callRemote(command, packed_data=amp.dumps((sessid, kwargs))).addErrback( self.errback, command.key) def send_MsgServer2Portal(self, session, **kwargs): """ Access method - executed on the Server for sending data to Portal. Args: session (Session): Unique Session. kwargs (any, optiona): Extra data. """ return self.data_to_portal(amp.MsgServer2Portal, session.sessid, **kwargs) def send_AdminServer2Portal(self, session, operation="", **kwargs): """ Administrative access method called by the Server to send an instruction to the Portal. Args: session (Session): Session. operation (char, optional): Identifier for the server operation, as defined by the global variables in `evennia/server/amp.py`. kwargs (dict, optional): Data going into the adminstrative. """ return self.data_to_portal(amp.AdminServer2Portal, session.sessid, operation=operation, **kwargs) # receiving AMP data @amp.MsgStatus.responder def server_receive_status(self, question): return {"status": "OK"} @amp.MsgPortal2Server.responder @amp.catch_traceback def server_receive_msgportal2server(self, packed_data): """ Receives message arriving to server. This method is executed on the Server. Args: packed_data (str): Data to receive (a pickled tuple (sessid,kwargs)) """ sessid, kwargs = self.data_in(packed_data) session = self.factory.server.sessions.get(sessid, None) if session: self.factory.server.sessions.data_in(session, **kwargs) return {} @amp.AdminPortal2Server.responder @amp.catch_traceback def server_receive_adminportal2server(self, packed_data): """ Receives admin data from the Portal (allows the portal to perform admin operations on the server). This is executed on the Server. Args: packed_data (str): Incoming, pickled data. """ sessid, kwargs = self.data_in(packed_data) operation = kwargs.pop("operation", "") server_sessionhandler = self.factory.server.sessions try: if operation == amp.PCONN: # portal_session_connect # create a new session and sync it server_sessionhandler.portal_connect(kwargs.get("sessiondata")) elif operation == amp.PCONNSYNC: # portal_session_sync server_sessionhandler.portal_session_sync(kwargs.get("sessiondata")) elif operation == amp.PDISCONN: # portal_session_disconnect # session closed from portal sid session = server_sessionhandler.get(sessid) if session: server_sessionhandler.portal_disconnect(session) elif operation == amp.PDISCONNALL: # portal_disconnect_all # portal orders all sessions to close server_sessionhandler.portal_disconnect_all() elif operation == amp.PSYNC: # portal_session_sync # force a resync of sessions from the portal side. This happens on # first server-connect. server_restart_mode = kwargs.get("server_restart_mode", "shutdown") self.factory.server.run_init_hooks(server_restart_mode) server_sessionhandler.portal_sessions_sync(kwargs.get("sessiondata")) elif operation == amp.SRELOAD: # server reload # shut down in reload mode server_sessionhandler.all_sessions_portal_sync() server_sessionhandler.server.shutdown(mode='reload') elif operation == amp.SRESET: # shut down in reset mode server_sessionhandler.all_sessions_portal_sync() server_sessionhandler.server.shutdown(mode='reset') elif operation == amp.SSHUTD: # server shutdown # shutdown in stop mode server_sessionhandler.server.shutdown(mode='shutdown') else: raise Exception("operation %(op)s not recognized." % {'op': operation}) except Exception: logger.log_trace() return {}
[ "evennia.utils.logger.log_msg", "evennia.utils.logger.log_trace", "evennia.server.portal.amp.dumps", "evennia.utils.logger.log_info" ]
[((2105, 2160), 'evennia.utils.logger.log_info', 'logger.log_info', (['"""Server disconnected from the portal."""'], {}), "('Server disconnected from the portal.')\n", (2120, 2160), False, 'from evennia.utils import logger\n'), ((2169, 2254), 'twisted.internet.protocol.ReconnectingClientFactory.clientConnectionLost', 'protocol.ReconnectingClientFactory.clientConnectionLost', (['self', 'connector', 'reason'], {}), '(self, connector, reason\n )\n', (2224, 2254), False, 'from twisted.internet import protocol\n'), ((2609, 2664), 'evennia.utils.logger.log_msg', 'logger.log_msg', (['"""Attempting to reconnect to Portal ..."""'], {}), "('Attempting to reconnect to Portal ...')\n", (2623, 2664), False, 'from evennia.utils import logger\n'), ((2673, 2759), 'twisted.internet.protocol.ReconnectingClientFactory.clientConnectionFailed', 'protocol.ReconnectingClientFactory.clientConnectionFailed', (['self', 'connector', 'reason'], {}), '(self, connector,\n reason)\n', (2730, 2759), False, 'from twisted.internet import protocol\n'), ((3493, 3504), 'os.getpid', 'os.getpid', ([], {}), '()\n', (3502, 3504), False, 'import os\n'), ((8534, 8552), 'evennia.utils.logger.log_trace', 'logger.log_trace', ([], {}), '()\n', (8550, 8552), False, 'from evennia.utils import logger\n'), ((4182, 4209), 'evennia.server.portal.amp.dumps', 'amp.dumps', (['(sessid, kwargs)'], {}), '((sessid, kwargs))\n', (4191, 4209), False, 'from evennia.server.portal import amp\n')]
""" Head - Crown/Helmet/Hat Neck - Necklace/Amulet Shoulders - Shoulder Pads Chest - Chest Armor Arms - Sleeves Hands - Pair of Gloves Fingers - Up to 4 Rings Waist - Belt/Sash Thighs - Greaves Calves - Greaves Feet - Boots/Shoes/Sandals Bag - Satchel/Backpack/Sack/Bag - Determines maximum inventory slots. Weapons - Any weapon can be wielded from the inventory or the ground Equipped weapons are used automatically if no other is wielded. Shields and other offhands can also be equipped. Equipped weapons have 1 slot per type of 2H and 1 slot per offhand type. 2 slots for 1H weapons for dual wielding. """ from evennia.prototypes.spawner import spawn from evennia.utils.evtable import EvTable, EvCell from misc import generic_str class EquipmentHandler: def __init__(self, owner): self.owner = owner def _get_equipment(self): equipment = self.equipment if equipment is None: # Get the equipment from the owner's attributes. equipment = self.owner.attributes.get('equipment', default=None) if equipment is None: # The owner has no equipment attribute, create it. self.initialize_equipment_attribute() equipment = self.owner.attributes.get('equipment') return equipment def _set_equipment(self, equipment): self.equipment = equipment def _save_equipment(self): self.owner.db.equipment = self.equipment def initialize_equipment_attribute(self): owner = self.owner equip_dict = {'Head': None, 'Neck': None, 'Shoulders': None, 'Chest': None, 'Arms': None, 'Hands': None, 'Fingers': None, 'Waist': None, 'Thighs': None, 'Calves': None, 'Feet': None, 'Inventory Container': None, 'Main Hand Weapon Slot 1': None, 'Main Hand Weapon Slot 2': None, 'Off-hand Weapon Slot 1': None, 'Off-hand Weapon Slot 2': None } owner.attributes.add('equipment', equip_dict) def generate_starting_equipment(self): owner = self.owner if owner.db.equipment['Inventory Container'] is None: basic_bag = spawn('inventory_bag') if basic_bag: basic_bag = basic_bag[0] basic_bag.move_to(owner) self.equipment['Inventory Container'] = basic_bag self._save_equipment owner.db.inventory_slots['max_slots'] = basic_bag.db.max_slots def list_equipment(self): owner = self.owner owner_possessive = generic_str.possessive(owner.key) equip_dict = self.equipment equipment_header = EvCell(f"{owner_possessive} Equipment", align='c', width=25) equipment_table = EvTable(border=None, pad_width=0) for key, value in equip_dict.items(): equipment_table.add_row(f"{key} ", f"{value}") equipment_table.reformat_column(0, fill_char='.') equipment_table.reformat_column(1, pad_left=1, width=20) owner.msg(f"{equipment_header}\n{equipment_table}") def wield(self, weapon=None): owner = self.owner equipment = self.equipment # Get the owner's current wielding and hand occupancy status. main_wield, off_wield, both_wield = self.get_wielding() main_hand, off_hand = owner.inv.get_hands() main_desc, off_desc = owner.db.hands_desc.values() if weapon is None: # Check each equipment slot for a mainhand weapon to wield. if equipment['Main Hand Weapon Slot 1'] is not None: weapon = equipment['Main Hand Weapon Slot 1'] elif equipment['Main Hand Weapon Slot 2'] is not None: weapon = equipment['Main Hand Weapon Slot 2'] else: owner.msg("No suitable weapon could be found to wield!") return else: weapon = owner.search(weapon, nofound_string="You must be holding a weapon to wield it.", multimatch_string=f"There are more than one {weapon}.") # A weapon object has been found. Perform some additional checks on it. if not weapon.tags.get('wieldable'): owner.msg("That's not a wieldable item.") return if weapon in [main_wield, off_wield, both_wield]: # Check for an item already wielded. owner.msg(f"You are already wielding {weapon.name}.") return hands_req = weapon.attributes.get('wieldable') if weapon not in [main_hand, off_hand]: # Automagically get the object from the inventory. owner.inv.force_item_into_hand(weapon, hand=hands_req) """ Decide which hand to put the item in. Preference Order ------------------- Prefer the main hand first when unoccupied. If main hand is occupied, use the off hand if it is unoccupied. Both hands are occupied, prefer dominate hand if not wielding. If both hands are occupied anddominate hand is wielding, prefer offhand if not wielding. If both hands are occupied and wielding, use the main hand. """ if (not main_hand) or (off_hand and not main_wield) or (off_hand and off_wield): hand = 'main' else: hand = 'off' if main_hand and not main_wield: owner.msg(f"You stow away {main_hand.name}.") owner.location.msg_contents(f"{owner.name} stows away {main_hand.name}.", exclude=owner) owner.db.hands['main'] = None owner.msg(f"You get {weapon.name} from your inventory.") owner.location.msg_contents(f"{owner.name} gets {weapon.name} from their inventory.", exclude=owner) owner.db.hands['main'] = weapon # Refresh hand variables before the next check. main_hand, off_hand = owner.db.hands.values() if weapon in [main_hand, off_hand]: if hands_req == 1: if weapon.tags.get('off_hand'): #For wielding shields. if weapon == main_hand and not main_wield: owner.inv.off_hand(item=weapon) # Offhand item is certainly already in the off hand. owner.msg(f"You wield {weapon.name} in your {off_desc} hand.") owner.location.msg_contents(f"{owner.name} wields {weapon.name} in their {off_desc} hand.", exclude=owner) owner.db.wielding['off'] = weapon # Make sure the item is a main hand wield. elif weapon == off_hand and not weapon.tags.get('off_hand'): owner.msg(f"You swap the contents of your hands and wield {weapon.name} in your {main_desc} hand.") owner.location.msg_contents(f"{owner.name} swaps the content of their hands " f"and wields {weapon.name} in their {main_desc} hand.", exclude=owner) owner.db.hands['main'] = weapon if main_hand: owner.db.hands['main'] = None owner.db.hands['off'] = weapon owner.db.wielding['main'] = weapon elif weapon == main_hand and not inherits_from(weapon, 'items.objects.OffHand'): # Make sure the item is a main hand wield. owner.msg(f"You wield {weapon.name} in your {main_desc} hand.") owner.location.msg_contents(f"{owner.name} wields {weapon.name} in their {main_desc} hand.", exclude=owner) owner.db.wielding['main'] = weapon elif hands_req == 2: if weapon == off_hand: if main_hand: owner.msg(f"You stow away {main_hand.name}.") owner.location.msg_contents(f"{owner.name} stows away {main_hand}.", exclude=owner) owner.db.hands['main'] = None elif weapon == main_hand: if off_hand: owner.msg(f"You stow away {off_hand.name}.") owner.location.msg_contents(f"{owner.name} stows away {off_hand}.", exclude=owner) owner.db.hands['off'] = None owner.msg(f"You wield {weapon.name} in both hands.") owner.location.msg_contents(f"{owner.name} wields {weapon.name} in both hands.", exclude=owner) owner.db.wielding['both'] = weapon owner.db.hands['main'] = weapon elif weapon.location == owner.location: owner.msg(f"You must be carrying a weapon to wield it.") return def stop_wielding_item(self, item): owner = self.owner main_wield, off_wield, both_wield = self.wielding.values() for looker in owner.location.contents: if looker == owner: looker.msg(f"You stop wielding {item.get_display_name(looker)}.") else: looker.msg(f"{owner.get_display_name(looker)} stops wielding " f"{item.get_display_name(looker)}.") if item == main_wield: self.set_wielding('main') elif item == off_wield: self.set_wielding('off') elif item == both_wield: self.set_wielding('both') def get_wielding(self, hand=None): """ Returns the requested wielded status of the owner, based on the kwarg provided. """ if self.wielding is None: self.wielding = self.owner.attributes.get('wielding') if hand is None: return self.wielding.values() else: return self.wielding.get(hand) def set_wielding(self, hand, item=None): self.wielding[hand] = item self._save_wielding() def _save_wielding(self): self.owner.db.wielding = self.wielding
[ "evennia.utils.evtable.EvTable", "evennia.prototypes.spawner.spawn", "evennia.utils.evtable.EvCell" ]
[((2589, 2622), 'misc.generic_str.possessive', 'generic_str.possessive', (['owner.key'], {}), '(owner.key)\n', (2611, 2622), False, 'from misc import generic_str\n'), ((2688, 2748), 'evennia.utils.evtable.EvCell', 'EvCell', (['f"""{owner_possessive} Equipment"""'], {'align': '"""c"""', 'width': '(25)'}), "(f'{owner_possessive} Equipment', align='c', width=25)\n", (2694, 2748), False, 'from evennia.utils.evtable import EvTable, EvCell\n'), ((2775, 2808), 'evennia.utils.evtable.EvTable', 'EvTable', ([], {'border': 'None', 'pad_width': '(0)'}), '(border=None, pad_width=0)\n', (2782, 2808), False, 'from evennia.utils.evtable import EvTable, EvCell\n'), ((2187, 2209), 'evennia.prototypes.spawner.spawn', 'spawn', (['"""inventory_bag"""'], {}), "('inventory_bag')\n", (2192, 2209), False, 'from evennia.prototypes.spawner import spawn\n')]
""" Places for tabletalk """ from typeclasses.objects import Object from typeclasses.places.cmdset_places import DefaultCmdSet, SittingCmdSet from evennia.utils.utils import make_iter from world.crafting.craft_data_handlers import PlaceDataHandler class Place(Object): """ Class for placed objects that allow the 'tabletalk' command. """ item_data_class = PlaceDataHandler default_max_spots = 6 default_desc = "A place for people to privately chat. Dropping it in a room will make it part of the room." PLACE_LOCKS = ( "call:true();control:perm(Wizards);delete:perm(Wizards);examine:perm(Builders);" "get:perm(Builders) or decorators();puppet:perm(Immortals);tell:all();view:all()" ) TT_SAY = 1 TT_POSE = 2 TT_EMIT = 3 @property def default_occupants(self): return [] def at_object_creation(self): """ Run at Place creation. """ # locks so characters cannot 'get' it self.locks.add(self.PLACE_LOCKS) self.at_init() def leave(self, character): """ Character leaving the table. """ occupants = self.item_data.occupants or [] if character in occupants: occupants.remove(character) self.item_data.occupants = occupants character.cmdset.delete(SittingCmdSet) character.db.sitting_at_table = None self.location.msg_contents( "%s has left the %s." % (character.name, self.key), exclude=character ) return def join(self, character): """ Character joins the table """ occupants = self.item_data.occupants or [] character.cmdset.add(SittingCmdSet, permanent=True) character.db.sitting_at_table = self occupants.append(character) self.item_data.occupants = occupants self.location.msg_contents( "%s has joined the %s." % (character.name, self.key), exclude=character ) def build_tt_msg( self, from_obj, to_obj, msg: str, is_ooc=False, msg_type=TT_SAY ) -> str: say_msg = '{ooc}At the {place_color}{place_name}|n, {name} says, "{msg}"' pose_msg = "{ooc}At the {place_color}{place_name}|n, {name}{msg}" emit_msg = "{ooc}{emit_label}At the {place_color}{place_name}|n, {msg}" ooc = "|w(OOC)|n " if is_ooc else "" place_name = self.key # If highlighting place name for rcvr. highlight = to_obj.player_ob.db.highlight_place if highlight: place_color = to_obj.char_ob.db.place_color or "" # Beware of None else: place_color = "" if msg_type == self.TT_SAY: place_msg = say_msg.format( ooc=ooc, place_color=place_color, place_name=place_name, name=from_obj.name, msg=msg, ) elif msg_type == self.TT_POSE: place_msg = pose_msg.format( ooc=ooc, place_color=place_color, place_name=place_name, name=from_obj.name, msg=msg, ) elif msg_type == self.TT_EMIT: if to_obj.tags.get("emit_label"): emit_label = "{w[{c%s{w]{n " % from_obj.name else: emit_label = "" place_msg = emit_msg.format( ooc=ooc, emit_label=emit_label, place_color=place_color, place_name=place_name, msg=msg, ) else: raise ValueError("Invalid message type in Places.build_tt_msg()") return place_msg def tt_msg( self, message, from_obj, exclude=None, is_ooc=False, msg_type=TT_SAY, options=None, ): """ Send msg to characters at table. Note that if this method was simply named 'msg' rather than tt_msg, it would be called by msg_contents in rooms, causing characters at the places to receive redundant messages, since they are still objects in the room as well. """ # utils.make_iter checks to see if an object is a list, set, etc, and encloses it in a list if not # needed so that 'ob not in exclude' can function if we're just passed a character exclude = make_iter(exclude) for ob in self.item_data.occupants: if ob not in exclude: place_msg = self.build_tt_msg(from_obj, ob, message, is_ooc, msg_type) ob.msg(place_msg, from_obj=from_obj, options=options) from_obj.posecount += 1 def at_after_move(self, source_location, **kwargs): """If new location is not our wearer, remove.""" location = self.location # first, remove ourself from the source location's places, if it exists if ( source_location and hasattr(source_location, "is_room") and source_location.is_room ): if source_location.db.places and self in source_location.db.places: source_location.db.places.remove(self) # if location is a room, add cmdset if location and location.is_room: places = location.db.places or [] self.cmdset.add_default(DefaultCmdSet, permanent=True) places.append(self) location.db.places = places # if location not a room, remove cmdset else: self.cmdset.delete_default()
[ "evennia.utils.utils.make_iter" ]
[((4456, 4474), 'evennia.utils.utils.make_iter', 'make_iter', (['exclude'], {}), '(exclude)\n', (4465, 4474), False, 'from evennia.utils.utils import make_iter\n')]
""" Channel The channel class represents the out-of-character chat-room usable by Accounts in-game. It is mostly overloaded to change its appearance, but channels can be used to implement many different forms of message distribution systems. Note that sending data to channels are handled via the CMD_CHANNEL syscommand (see evennia.syscmds). The sending should normally not need to be modified. """ import re from evennia import DefaultChannel from evennia.utils.ansi import strip_ansi from evennia.utils import logger from server.utils.utils import get_sw, wrap class Channel(DefaultChannel): """ Working methods: at_channel_creation() - called once, when the channel is created has_connection(account) - check if the given account listens to this channel connect(account) - connect account to this channel disconnect(account) - disconnect account from channel access(access_obj, access_type='listen', default=False) - check the access on this channel (default access_type is listen) delete() - delete this channel message_transform(msg, emit=False, prefix=True, sender_strings=None, external=False) - called by the comm system and triggers the hooks below msg(msgobj, header=None, senders=None, sender_strings=None, persistent=None, online=False, emit=False, external=False) - main send method, builds and sends a new message to channel. tempmsg(msg, header=None, senders=None) - wrapper for sending non-persistent messages. distribute_message(msg, online=False) - send a message to all connected accounts on channel, optionally sending only to accounts that are currently online (optimized for very large sends) Useful hooks: channel_prefix(msg, emit=False) - how the channel should be prefixed when returning to user. Returns a string format_senders(senders) - should return how to display multiple senders to a channel pose_transform(msg, sender_string) - should detect if the sender is posing, and if so, modify the string format_external(msg, senders, emit=False) - format messages sent from outside the game, like from IRC format_message(msg, emit=False) - format the message body before displaying it to the user. 'emit' generally means that the message should not be displayed with the sender's name. pre_join_channel(joiner) - if returning False, abort join post_join_channel(joiner) - called right after successful join pre_leave_channel(leaver) - if returning False, abort leave post_leave_channel(leaver) - called right after successful leave pre_send_message(msg) - runs just before a message is sent to channel post_send_message(msg) - called just after message was sent to channel """ def at_channel_creation(self): if self.key == "Chat": self.db.colorstr = "|M" elif self.key == "Question": self.db.colorstr = "|G" elif self.key == "OOC": self.db.colorstr = "|Y" def channel_prefix(self, msg=None, emit=False): """ How the channel should prefix itself for users. Return a string. """ # use color if defined if self.db.colorstr: #return " %s%s <%s> " % (self.db.colorstr, msg.senders[0], self.key) return " %s<%s> " % (self.db.colorstr, self.key) # else default is whether it's private or not if self.locks.get("listen").strip() != "listen:all()": return " |y<%s> " % self.key return " |w<%s> " % self.key def pose_transform(self, msgobj, sender_string, **kwargs): """ Hook method. Detects if the sender is posing and modifies the message accordingly. Args: msgobj (Msg or TempMsg): Message to analyze. sender_string (str): Name of the sender. **kwargs (dict): Optional arguments. Returns: string (str): Message that combines the sender_string component with `msg` in different ways depending on whether an emote was performed or not. """ pose = False message = msgobj.message message_start = message.lstrip() if message_start.startswith((":", ";")): pose = True message = message[1:] if not message.startswith((":", "'", ",")): if not message.startswith(" "): message = " " + message if pose: pre_text = f" <{self.key}> {sender_string} " message = sender_string + message else: pre_text = f" <{self.key}> {sender_string}: " message = sender_string + ": " + message message = strip_ansi(message) #message = wrap(message, pre_text=pre_text, omit_pre_text=True) return "|n%s" % message def distribute_message(self, msgobj, online=False, **kwargs): """ Method for grabbing all listeners that a message should be sent to on this channel, and sending them a message. Args: msgobj (Msg or TempMsg): Message to distribute. online (bool): Only send to receivers who are actually online (not currently used): **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). Notes: This is also where logging happens, if enabled. """ # get all accounts or objects connected to this channel and send to them if online: subs = self.subscriptions.online() else: subs = self.subscriptions.all() for entity in subs: # if the entity is muted, we don't send them a message if entity in self.mutelist: continue try: # note our addition of the from_channel keyword here. This could be checked # by a custom account.msg() to treat channel-receives differently. message = msgobj.message.split(" ") #Separate pre_text to readd during wrap process. pre_text = " ".join(message[0:3]) + " " message = " ".join(message[3:]) #Grab wrapping dimensions from entity. message = wrap(message, get_sw(entity), get_sw(entity), pre_text) entity.msg( message, from_obj=msgobj.senders, options={"from_channel": self.id} ) except AttributeError as e: logger.log_trace("%s\nCannot send msg to '%s'." % (e, entity)) if msgobj.keep_log: # log to file logger.log_file( msgobj.message, self.attributes.get("log_file") or "channel_%s.log" % self.key ) def post_send_message(self, msg, **kwargs): """ Hook method. Run after message is sent to a channel. Args: msg (Msg or TempMsg): Message sent. **kwargs (dict): Optional arguments. """ for sender in msg.senders: sender.msg(prompt="> ") pass
[ "evennia.utils.logger.log_trace", "evennia.utils.ansi.strip_ansi" ]
[((5060, 5079), 'evennia.utils.ansi.strip_ansi', 'strip_ansi', (['message'], {}), '(message)\n', (5070, 5079), False, 'from evennia.utils.ansi import strip_ansi\n'), ((6667, 6681), 'server.utils.utils.get_sw', 'get_sw', (['entity'], {}), '(entity)\n', (6673, 6681), False, 'from server.utils.utils import get_sw, wrap\n'), ((6683, 6697), 'server.utils.utils.get_sw', 'get_sw', (['entity'], {}), '(entity)\n', (6689, 6697), False, 'from server.utils.utils import get_sw, wrap\n'), ((6899, 6964), 'evennia.utils.logger.log_trace', 'logger.log_trace', (['("""%s\nCannot send msg to \'%s\'.""" % (e, entity))'], {}), '("""%s\nCannot send msg to \'%s\'.""" % (e, entity))\n', (6915, 6964), False, 'from evennia.utils import logger\n')]
"""Tests for text2html """ import unittest from django.test import TestCase from evennia.utils import ansi, text2html import mock class TestText2Html(TestCase): def test_re_color(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_color("foo")) self.assertEqual( '<span class="color-001">red</span>foo', parser.re_color(ansi.ANSI_UNHILITE + ansi.ANSI_RED + "red" + ansi.ANSI_NORMAL + "foo"), ) self.assertEqual( '<span class="bgcolor-001">red</span>foo', parser.re_color(ansi.ANSI_BACK_RED + "red" + ansi.ANSI_NORMAL + "foo"), ) self.assertEqual( '<span class="bgcolor-001"><span class="color-002">red</span></span>foo', parser.re_color( ansi.ANSI_BACK_RED + ansi.ANSI_UNHILITE + ansi.ANSI_GREEN + "red" + ansi.ANSI_NORMAL + "foo" ), ) @unittest.skip("parser issues") def test_re_bold(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_bold("foo")) self.assertEqual( # "a <strong>red</strong>foo", # TODO: why not? "a <strong>redfoo</strong>", parser.re_bold("a " + ansi.ANSI_HILITE + "red" + ansi.ANSI_UNHILITE + "foo"), ) @unittest.skip("parser issues") def test_re_underline(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_underline("foo")) self.assertEqual( 'a <span class="underline">red</span>' + ansi.ANSI_NORMAL + "foo", parser.re_underline( "a " + ansi.ANSI_UNDERLINE + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) @unittest.skip("parser issues") def test_re_blinking(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_blinking("foo")) self.assertEqual( 'a <span class="blink">red</span>' + ansi.ANSI_NORMAL + "foo", parser.re_blinking( "a " + ansi.ANSI_BLINK + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) @unittest.skip("parser issues") def test_re_inversing(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_inversing("foo")) self.assertEqual( 'a <span class="inverse">red</span>' + ansi.ANSI_NORMAL + "foo", parser.re_inversing( "a " + ansi.ANSI_INVERSE + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) @unittest.skip("parser issues") def test_remove_bells(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.remove_bells("foo")) self.assertEqual( "a red" + ansi.ANSI_NORMAL + "foo", parser.remove_bells( "a " + ansi.ANSI_BEEP + "red" + ansi.ANSI_NORMAL # TODO: why does it keep it? + "foo" ), ) def test_remove_backspaces(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.remove_backspaces("foo")) self.assertEqual("redfoo", parser.remove_backspaces("a\010redfoo")) def test_convert_linebreaks(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.convert_linebreaks("foo")) self.assertEqual("a<br> redfoo<br>", parser.convert_linebreaks("a\n redfoo\n")) @unittest.skip("parser issues") def test_convert_urls(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.convert_urls("foo")) self.assertEqual( 'a <a href="http://redfoo" target="_blank">http://redfoo</a> runs', parser.convert_urls("a http://redfoo runs"), ) # TODO: doesn't URL encode correctly def test_re_double_space(self): parser = text2html.HTML_PARSER self.assertEqual("foo", parser.re_double_space("foo")) self.assertEqual( "a &nbsp;red &nbsp;&nbsp;&nbsp;foo", parser.re_double_space("a red foo") ) def test_sub_mxp_links(self): parser = text2html.HTML_PARSER mocked_match = mock.Mock() mocked_match.groups.return_value = ["cmd", "text"] self.assertEqual( r"""<a id="mxplink" href="#" """ """onclick="Evennia.msg(&quot;text&quot;,[&quot;cmd&quot;],{});""" """return false;">text</a>""", parser.sub_mxp_links(mocked_match), ) def test_sub_text(self): parser = text2html.HTML_PARSER mocked_match = mock.Mock() mocked_match.groupdict.return_value = {"htmlchars": "foo"} self.assertEqual("foo", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = {"htmlchars": "", "lineend": "foo"} self.assertEqual("<br>", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = {"htmlchars": "", "lineend": "", "firstspace": "foo"} self.assertEqual(" &nbsp;", parser.sub_text(mocked_match)) parser.tabstop = 2 mocked_match.groupdict.return_value = { "htmlchars": "", "lineend": "", "firstspace": "", "space": "\t", } self.assertEqual(" &nbsp;&nbsp;", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = { "htmlchars": "", "lineend": "", "firstspace": "", "space": " ", "spacestart": " ", } mocked_match.group.return_value = " \t " self.assertEqual("&nbsp;&nbsp;&nbsp;&nbsp;", parser.sub_text(mocked_match)) mocked_match.groupdict.return_value = { "htmlchars": "", "lineend": "", "firstspace": "", "space": "", "spacestart": "", } self.assertEqual(None, parser.sub_text(mocked_match)) def test_parse_html(self): self.assertEqual("foo", text2html.parse_html("foo")) self.maxDiff = None self.assertEqual( """<span class="blink"><span class="bgcolor-006">Hello </span><span class="underline"><span class="err">W</span><span class="err">o</span><span class="err">r</span><span class="err">l</span><span class="err">d</span><span class="err">!<span class="bgcolor-002">!</span></span></span></span>""", text2html.parse_html( ansi.ANSI_BLINK + ansi.ANSI_BACK_CYAN + "Hello " + ansi.ANSI_NORMAL + ansi.ANSI_UNDERLINE + ansi.ANSI_RED + "W" + ansi.ANSI_GREEN + "o" + ansi.ANSI_YELLOW + "r" + ansi.ANSI_BLUE + "l" + ansi.ANSI_MAGENTA + "d" + ansi.ANSI_CYAN + "!" + ansi.ANSI_BACK_GREEN + "!" ), )
[ "evennia.utils.text2html.parse_html" ]
[((1013, 1043), 'unittest.skip', 'unittest.skip', (['"""parser issues"""'], {}), "('parser issues')\n", (1026, 1043), False, 'import unittest\n'), ((1400, 1430), 'unittest.skip', 'unittest.skip', (['"""parser issues"""'], {}), "('parser issues')\n", (1413, 1430), False, 'import unittest\n'), ((1904, 1934), 'unittest.skip', 'unittest.skip', (['"""parser issues"""'], {}), "('parser issues')\n", (1917, 1934), False, 'import unittest\n'), ((2397, 2427), 'unittest.skip', 'unittest.skip', (['"""parser issues"""'], {}), "('parser issues')\n", (2410, 2427), False, 'import unittest\n'), ((2897, 2927), 'unittest.skip', 'unittest.skip', (['"""parser issues"""'], {}), "('parser issues')\n", (2910, 2927), False, 'import unittest\n'), ((3817, 3847), 'unittest.skip', 'unittest.skip', (['"""parser issues"""'], {}), "('parser issues')\n", (3830, 3847), False, 'import unittest\n'), ((4559, 4570), 'mock.Mock', 'mock.Mock', ([], {}), '()\n', (4568, 4570), False, 'import mock\n'), ((4973, 4984), 'mock.Mock', 'mock.Mock', ([], {}), '()\n', (4982, 4984), False, 'import mock\n'), ((6358, 6385), 'evennia.utils.text2html.parse_html', 'text2html.parse_html', (['"""foo"""'], {}), "('foo')\n", (6378, 6385), False, 'from evennia.utils import ansi, text2html\n'), ((6760, 7057), 'evennia.utils.text2html.parse_html', 'text2html.parse_html', (["(ansi.ANSI_BLINK + ansi.ANSI_BACK_CYAN + 'Hello ' + ansi.ANSI_NORMAL + ansi\n .ANSI_UNDERLINE + ansi.ANSI_RED + 'W' + ansi.ANSI_GREEN + 'o' + ansi.\n ANSI_YELLOW + 'r' + ansi.ANSI_BLUE + 'l' + ansi.ANSI_MAGENTA + 'd' +\n ansi.ANSI_CYAN + '!' + ansi.ANSI_BACK_GREEN + '!')"], {}), "(ansi.ANSI_BLINK + ansi.ANSI_BACK_CYAN + 'Hello ' +\n ansi.ANSI_NORMAL + ansi.ANSI_UNDERLINE + ansi.ANSI_RED + 'W' + ansi.\n ANSI_GREEN + 'o' + ansi.ANSI_YELLOW + 'r' + ansi.ANSI_BLUE + 'l' + ansi\n .ANSI_MAGENTA + 'd' + ansi.ANSI_CYAN + '!' + ansi.ANSI_BACK_GREEN + '!')\n", (6780, 7057), False, 'from evennia.utils import ansi, text2html\n')]