code stringlengths 321 95.4k | apis sequence | 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')] |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 6