Exemple #1
0
    def typeclass_search(self,
                         typeclass,
                         include_children=False,
                         include_parents=False):
        """
        Searches through all objects returning those which has a
        certain typeclass. If location is set, limit search to objects
        in that location.

        Args:
            typeclass (str or class): A typeclass class or a python path to a typeclass.
            include_children (bool, optional): Return objects with
                given typeclass *and* all children inheriting from this
                typeclass. Mutuall exclusive to `include_parents`.
            include_parents (bool, optional): Return objects with
                given typeclass *and* all parents to this typeclass.
                Mutually exclusive to `include_children`.

        Returns:
            objects (list): The objects found with the given typeclasses.

        """

        if callable(typeclass):
            cls = typeclass.__class__
            typeclass = "%s.%s" % (cls.__module__, cls.__name__)
        elif not isinstance(typeclass, basestring) and hasattr(
                typeclass, "path"):
            typeclass = typeclass.path

        # query objects of exact typeclass
        query = Q(db_typeclass_path__exact=typeclass)

        if include_children:
            # build requests for child typeclass objects
            clsmodule, clsname = typeclass.rsplit(".", 1)
            cls = variable_from_module(clsmodule, clsname)
            subclasses = cls.__subclasses__()
            if subclasses:
                for child in (child for child in subclasses
                              if hasattr(child, "path")):
                    query = query | Q(db_typeclass_path__exact=child.path)
        elif include_parents:
            # build requests for parent typeclass objects
            clsmodule, clsname = typeclass.rsplit(".", 1)
            cls = variable_from_module(clsmodule, clsname)
            parents = cls.__mro__
            if parents:
                for parent in (parent for parent in parents
                               if hasattr(parent, "path")):
                    query = query | Q(db_typeclass_path__exact=parent.path)
        # actually query the database
        return self.filter(query)
Exemple #2
0
    def receive_functioncall(self, module, function, func_args, func_kwargs):
        """
        This allows Portal- and Server-process to call an arbitrary
        function in the other process. It is intended for use by
        plugin modules.

        Args:
            module (str or module): The module containing the
                `function` to call.
            function (str): The name of the function to call in
                `module`.
            func_args (str): Pickled args tuple for use in `function` call.
            func_kwargs (str): Pickled kwargs dict for use in `function` call.

        """
        args = loads(func_args)
        kwargs = loads(func_kwargs)

        # call the function (don't catch tracebacks here)
        result = variable_from_module(module, function)(*args, **kwargs)

        if isinstance(result, Deferred):
            # if result is a deferred, attach handler to properly
            # wrap the return value
            result.addCallback(lambda r: {"result": dumps(r)})
            return result
        else:
            return {'result': dumps(result)}
Exemple #3
0
 def search(self,  # type: Character
            searchdata, global_search=False, use_nicks=True, typeclass=None, location=None,
            attribute_name=None, quiet=False, exact=False, candidates=None, nofound_string=None,
            multimatch_string=None, use_dbref=True):
     from django.conf import settings
     # if we're staff, we just use the regular search method
     if self.check_permstring("builders"):
         return super(Character, self).search(searchdata, global_search=global_search, use_nicks=use_nicks,
                                              typeclass=typeclass, location=location,
                                              attribute_name=attribute_name, quiet=quiet, exact=exact,
                                              candidates=candidates, nofound_string=nofound_string,
                                              multimatch_string=multimatch_string, use_dbref=use_dbref)
     # we're not staff. We get search results, then throw out matches of people wearing masks that were by their key
     results = super(Character, self).search(searchdata, global_search=global_search, use_nicks=use_nicks,
                                             typeclass=typeclass, location=location, attribute_name=attribute_name,
                                             quiet=True, exact=exact, candidates=candidates,
                                             nofound_string=nofound_string, multimatch_string=multimatch_string,
                                             use_dbref=use_dbref)
     # we prune results of keys for masked (false_name) objects in results
     results = [ob for ob in results if not ob.db.false_name or searchdata.lower() != ob.key.lower()]
     # quiet means that messaging is handled elsewhere
     if quiet:
         return results
     if location == self:
         nofound_string = nofound_string or "You don't carry '%s'." % searchdata
         multimatch_string = multimatch_string or "You carry more than one '%s':" % searchdata
     # call the _AT_SEARCH_RESULT func to transform our results and send messages
     _AT_SEARCH_RESULT = variable_from_module(*settings.SEARCH_AT_RESULT.rsplit('.', 1))
     return _AT_SEARCH_RESULT(results, self, query=searchdata,  nofound_string=nofound_string,
                              multimatch_string=multimatch_string)
Exemple #4
0
    def receive_functioncall(self, module, function, func_args, func_kwargs):
        """
        This allows Portal- and Server-process to call an arbitrary
        function in the other process. It is intended for use by
        plugin modules.

        Args:
            module (str or module): The module containing the
                `function` to call.
            function (str): The name of the function to call in
                `module`.
            func_args (str): Pickled args tuple for use in `function` call.
            func_kwargs (str): Pickled kwargs dict for use in `function` call.

        """
        args = loads(func_args)
        kwargs = loads(func_kwargs)

        # call the function (don't catch tracebacks here)
        result = variable_from_module(module, function)(*args, **kwargs)

        if isinstance(result, Deferred):
            # if result is a deferred, attach handler to properly
            # wrap the return value
            result.addCallback(lambda r: {"result": dumps(r)})
            return result
        else:
            return {'result': dumps(result)}
Exemple #5
0
    def typeclass_search(self, typeclass, include_children=False, include_parents=False):
        """
        Searches through all objects returning those which has a
        certain typeclass. If location is set, limit search to objects
        in that location.

        Args:
            typeclass (str or class): A typeclass class or a python path to a typeclass.
            include_children (bool, optional): Return objects with
                given typeclass *and* all children inheriting from this
                typeclass. Mutuall exclusive to `include_parents`.
            include_parents (bool, optional): Return objects with
                given typeclass *and* all parents to this typeclass.
                Mutually exclusive to `include_children`.

        Returns:
            objects (list): The objects found with the given typeclasses.

        """

        if callable(typeclass):
            cls = typeclass.__class__
            typeclass = "%s.%s" % (cls.__module__, cls.__name__)
        elif not isinstance(typeclass, basestring) and hasattr(typeclass, "path"):
            typeclass = typeclass.path

        # query objects of exact typeclass
        query = Q(db_typeclass_path__exact=typeclass)

        if include_children:
            # build requests for child typeclass objects
            clsmodule, clsname = typeclass.rsplit(".", 1)
            cls = variable_from_module(clsmodule, clsname)
            subclasses = cls.__subclasses__()
            if subclasses:
                for child in (child for child in subclasses if hasattr(child, "path")):
                    query = query | Q(db_typeclass_path__exact=child.path)
        elif include_parents:
            # build requests for parent typeclass objects
            clsmodule, clsname = typeclass.rsplit(".", 1)
            cls = variable_from_module(clsmodule, clsname)
            parents = cls.__mro__
            if parents:
                for parent in (parent for parent in parents if hasattr(parent, "path")):
                    query = query | Q(db_typeclass_path__exact=parent.path)
        # actually query the database
        return self.filter(query)
Exemple #6
0
def delayed_import():
    "Helper method for delayed import of all needed entities"
    global _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
    if not _ServerSession:
        # we allow optional arbitrary serversession class for overloading
        modulename, classname = settings.SERVER_SESSION_CLASS.rsplit(".", 1)
        _ServerSession = variable_from_module(modulename, classname)
    if not _PlayerDB:
        from evennia.players.models import PlayerDB as _PlayerDB
    if not _ServerConfig:
        from evennia.server.models import ServerConfig as _ServerConfig
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB
    # including once to avoid warnings in Python syntax checkers
    _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
Exemple #7
0
def delayed_import():
    "Helper method for delayed import of all needed entities"
    global _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
    if not _ServerSession:
        # we allow optional arbitrary serversession class for overloading
        modulename, classname = settings.SERVER_SESSION_CLASS.rsplit(".", 1)
        _ServerSession = variable_from_module(modulename, classname)
    if not _PlayerDB:
        from evennia.players.models import PlayerDB as _PlayerDB
    if not _ServerConfig:
        from evennia.server.models import ServerConfig as _ServerConfig
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB
    # including once to avoid warnings in Python syntax checkers
    _ServerSession, _PlayerDB, _ServerConfig, _ScriptDB
Exemple #8
0
    def amp_function_call(self, module, function, args, **kwargs):
        """
        This allows Portal- and Server-process to call an arbitrary function
        in the other process. It is intended for use by plugin modules.
        """
        args = loads(args)
        kwargs = loads(kwargs)

        # call the function (don't catch tracebacks here)
        result = variable_from_module(module, function)(*args, **kwargs)

        if isinstance(result, Deferred):
            # if result is a deferred, attach handler to properly
            # wrap the return value
            result.addCallback(lambda r: {"result": dumps(r)})
            return result
        else:
            return {'result': dumps(result)}
Exemple #9
0
    def amp_function_call(self, module, function, args, **kwargs):
        """
        This allows Portal- and Server-process to call an arbitrary function
        in the other process. It is intended for use by plugin modules.
        """
        args = loads(args)
        kwargs = loads(kwargs)

        # call the function (don't catch tracebacks here)
        result = variable_from_module(module, function)(*args, **kwargs)

        if isinstance(result, Deferred):
            # if result is a deferred, attach handler to properly
            # wrap the return value
            result.addCallback(lambda r: {"result": dumps(r)})
            return result
        else:
            return {'result': dumps(result)}
Exemple #10
0
    def __init__(self, owner):
        """
        This handler's owner is the zone_script, created by the RoomHandler 
        and stored on the zone_ledger. The zone_script's key is a unique identifier, used to 
        reference it on the zone_ledger. The zone_script represents the zone as a whole and 
        tracks entities within it, as well as zone specific information. The SpawnHandler 
        lives on the zone_script and is a centralized mechanism that handles all spawn for the zone.

        The room list and the zone_type are both set on the zone_script, within the RoomHandler.

        The pool of sentients that spawn in this zone is set in the sentients.py module.

        This module spawns objects that are throw-aways. These objects have their default home
        designated as the black_hole room, which automatically deletes any entity that enters it.
        """
        self.owner = owner
        self.zone_rooms = list(self.owner.attributes.get('rooms'))
        zone_type = self.owner.tags.get(category='zone_type')
        self.sentient_pool = utils.variable_from_module("sentients.sentients",
                                                        variable=zone_type)
        self.black_hole = search_object_by_tag(key='black_hole',
                                               category='rooms')[0]
Exemple #11
0
from evennia.commands import cmdhandler
from evennia.utils import logger
from evennia.utils.utils import (lazy_property, to_str, make_iter, to_unicode,
                                 is_iter, variable_from_module)
from evennia.typeclasses.attributes import NickHandler
from evennia.scripts.scripthandler import ScriptHandler
from evennia.commands.cmdsethandler import CmdSetHandler

from django.utils.translation import ugettext as _
from future.utils import with_metaclass

__all__ = ("DefaultAccount", )

_SESSIONS = None

_AT_SEARCH_RESULT = variable_from_module(
    *settings.SEARCH_AT_RESULT.rsplit('.', 1))
_MULTISESSION_MODE = settings.MULTISESSION_MODE
_MAX_NR_CHARACTERS = settings.MAX_NR_CHARACTERS
_CMDSET_ACCOUNT = settings.CMDSET_ACCOUNT
_CONNECT_CHANNEL = None


class Account(DefaultAccount):
    """
    This class describes the actual OOC account (i.e. the user connecting
    to the MUD). It does NOT have visual appearance in the game world (that
    is handled by the character which is connected to this). Comm channels
    are attended/joined using this object.

    It can be useful e.g. for storing configuration options for your game, but
    should generally not hold any character-related info (that's best handled
Exemple #12
0
    `_do_*` function to carry out the next action, executes it, and sets a
    delayed call back to itself to handle the next action. After all actions
    are processed for a turn, control is returned to the `CombatHandler` to
    get input for the next turn.
"""

import re
import random
from math import floor
from collections import defaultdict
from evennia.utils import utils, make_iter

COMBAT_DELAY = 2
ACTIONS_PER_TURN = 2

COMBAT_DISTANCES = utils.variable_from_module('typeclasses.combat_handler',
                                              'COMBAT_DISTANCES')
WRESTLING_POSITIONS = utils.variable_from_module('typeclasses.combat_handler',
                                                 'WRESTLING_POSITIONS')


class DiceRollError(Exception):
    """Default error class in die rolls/skill checks.

    Args:
        msg (str): a descriptive error message
    """
    def __init__(self, msg):
        self.msg = msg


def _parse_roll(xdyz):
Exemple #13
0
    def func(self):
        """Starts the processor."""

        caller = self.caller
        args = self.args.split()

        # Check if arguments passed.
        if not self.args or (len(args) != 2):
            caller.msg("Usage: @mapbuilder <path.to.module.VARNAME> "
                       "<path.to.module.MAP_LEGEND>")
            return

        # Set up base variables.
        game_map = None
        legend = None

        # OBTAIN MAP FROM MODULE

        # Breaks down path_to_map into [PATH, VARIABLE]
        path_to_map = args[0]
        path_to_map = path_to_map.rsplit(".", 1)

        try:
            # Retrieves map variable from module or raises error.
            game_map = utils.variable_from_module(path_to_map[0],
                                                  path_to_map[1])
            if not game_map:
                raise ValueError("Command Aborted!\n"
                                 "Path to map variable failed.\n"
                                 "Usage: @mapbuilder <path.to.module."
                                 "VARNAME> <path.to.module.MAP_LEGEND>")

        except Exception as exc:
            # Or relays error message if fails.
            caller.msg(exc)
            return

        # OBTAIN MAP_LEGEND FROM MODULE

        # Breaks down path_to_legend into [PATH, VARIABLE]
        path_to_legend = args[1]
        path_to_legend = path_to_legend.rsplit(".", 1)

        # If no path given default to path_to_map's path
        if len(path_to_legend) == 1:
            path_to_legend.insert(0, path_to_map[0])

        try:
            # Retrieves legend variable from module or raises error if fails.
            legend = utils.variable_from_module(path_to_legend[0],
                                                path_to_legend[1])
            if not legend:
                raise ValueError("Command Aborted!\n"
                                 "Path to legend variable failed.\n"
                                 "Usage: @mapbuilder <path.to.module."
                                 "VARNAME> <path.to.module.MAP_LEGEND>")

        except Exception as exc:
            # Or relays error message if fails.
            caller.msg(exc)
            return

        # Set up build_map arguments from switches
        iterations = 1
        build_exits = True

        if "one" in self.switches:
            build_exits = False

        if "two" in self.switches:
            iterations = 2
            build_exits = False

        # Pass map and legend to the build function.
        build_map(caller, game_map, legend, iterations, build_exits)
Exemple #14
0
from django.utils.translation import ugettext as _

_IN_GAME_ERRORS = settings.IN_GAME_ERRORS

__all__ = ("cmdhandler", )
_GA = object.__getattribute__
_CMDSET_MERGE_CACHE = WeakValueDictionary()

# tracks recursive calls by each caller
# to avoid infinite loops (commands calling themselves)
_COMMAND_NESTING = defaultdict(lambda: 0)
_COMMAND_RECURSION_LIMIT = 10

# This decides which command parser is to be used.
# You have to restart the server for changes to take effect.
_COMMAND_PARSER = utils.variable_from_module(
    *settings.COMMAND_PARSER.rsplit('.', 1))

# System command names - import these variables rather than trying to
# remember the actual string constants. If not defined, Evennia
# hard-coded defaults are used instead.

# command to call if user just presses <return> with no input
CMD_NOINPUT = "__noinput_command"
# command to call if no command match was found
CMD_NOMATCH = "__nomatch_command"
# command to call if multiple command matches were found
CMD_MULTIMATCH = "__multimatch_command"
# command to call if found command is the name of a channel
CMD_CHANNEL = "__send_to_channel_command"
# command to call as the very first one when the user connects.
# (is expected to display the login screen)
Exemple #15
0
from builtins import object
from django.conf import settings
from evennia.utils import utils

MSSP = chr(70)
MSSP_VAR = chr(1)
MSSP_VAL = chr(2)


# try to get the customized mssp info, if it exists.
MSSPTable_CUSTOM = utils.variable_from_module(settings.MSSP_META_MODULE, "MSSPTable", default={})

class Mssp(object):
    """
    Implements the MSSP protocol. Add this to a variable on the telnet
    protocol to set it up.

    """
    def __init__(self, protocol):
        """
        initialize MSSP by storing protocol on ourselves and calling
        the client to see if it supports MSSP.

        Args:
            protocol (Protocol): The active protocol instance.

        """
        self.protocol = protocol
        self.protocol.will(MSSP).addCallbacks(self.do_mssp, self.no_mssp)

    def do_mssp(self, option):
Exemple #16
0
from twisted.internet.defer import inlineCallbacks, returnValue
from django.conf import settings
from evennia.comms.channelhandler import CHANNELHANDLER
from evennia.utils import logger, utils
from evennia.commands.cmdparser import at_multimatch_cmd
from evennia.utils.utils import string_suggestions, to_unicode

from django.utils.translation import ugettext as _

__all__ = ("cmdhandler", )
_GA = object.__getattribute__
_CMDSET_MERGE_CACHE = WeakValueDictionary()

# This decides which command parser is to be used.
# You have to restart the server for changes to take effect.
_COMMAND_PARSER = utils.variable_from_module(
    *settings.COMMAND_PARSER.rsplit('.', 1))

# System command names - import these variables rather than trying to
# remember the actual string constants. If not defined, Evennia
# hard-coded defaults are used instead.

# command to call if user just presses <return> with no input
CMD_NOINPUT = "__noinput_command"
# command to call if no command match was found
CMD_NOMATCH = "__nomatch_command"
# command to call if multiple command matches were found
CMD_MULTIMATCH = "__multimatch_command"
# command to call if found command is the name of a channel
CMD_CHANNEL = "__send_to_channel_command"
# command to call as the very first one when the user connects.
# (is expected to display the login screen)
Exemple #17
0
    def func(self):
        """Starts the processor."""

        caller = self.caller
        args = self.args.split()

        # Check if arguments passed.
        if not self.args or (len(args) != 1):
            caller.msg("Usage: @shipbuilder <CLASS>")
            return

        # Set up base variables.
        game_map = None
        legend = None

        # OBTAIN MAP FROM MODULE

        # Breaks down path_to_map into [PATH, VARIABLE]
        ship_class = args[0]
        path_to_ship_class = ship_class.rsplit('.', 1)

        try:
            # Retrieves map variable from module or raises error.
            game_map = utils.variable_from_module(path_to_ship_class[0],
                                                  path_to_ship_class[1])
            if not game_map:
                raise ValueError(
                    "Command Aborted!\n"
                    "Path to map variable failed.\n"
                    "Usage: @shipbuilder <world.ships.TYPE.SHIPCLASS>")

        except Exception as exc:
            # Or relays error message if fails.
            caller.msg(exc)
            return

        # OBTAIN MAP_LEGEND FROM MODULE

        # Breaks down path_to_legend into [PATH, VARIABLE]
        legend = args[0]
        # Strong arming the legend from the module. Need a better method me thinks
        path_to_legend = ['.'.join(legend.split('.')[:3]), 'LEGEND']

        try:
            # Retrieves legend variable from module or raises error if fails.
            legend = utils.variable_from_module(path_to_legend[0],
                                                path_to_legend[1])
            if not legend:
                raise ValueError(
                    "Command Aborted!\n"
                    "Path to map variable failed.\n"
                    "Usage: @shipbuilder <world.ships.TYPE.SHIPCLASS>")

        except Exception as exc:
            # Or relays error message if fails.
            caller.msg(exc)
            return

        # Set up build_map arguments from switches
        iterations = 1
        build_exits = True

        # Pass map and legend to the build function.
        build_map(caller, game_map, legend, iterations, build_exits)
Exemple #18
0
from evennia.utils import logger
from evennia.utils.utils import (lazy_property, to_str,
                                 make_iter, to_unicode, is_iter,
                                 variable_from_module)
from evennia.typeclasses.attributes import NickHandler
from evennia.scripts.scripthandler import ScriptHandler
from evennia.commands.cmdsethandler import CmdSetHandler

from django.utils.translation import ugettext as _
from future.utils import with_metaclass

__all__ = ("DefaultPlayer",)

_SESSIONS = None

_AT_SEARCH_RESULT = variable_from_module(*settings.SEARCH_AT_RESULT.rsplit('.', 1))
_MULTISESSION_MODE = settings.MULTISESSION_MODE
_MAX_NR_CHARACTERS = settings.MAX_NR_CHARACTERS
_CMDSET_PLAYER = settings.CMDSET_PLAYER
_CONNECT_CHANNEL = None

class PlayerSessionHandler(object):
    """
    Manages the session(s) attached to a player.

    """

    def __init__(self, player):
        """
        Initializes the handler.
Exemple #19
0
from twisted.internet.defer import inlineCallbacks, returnValue
from django.conf import settings
from evennia.comms.channelhandler import CHANNELHANDLER
from evennia.utils import logger, utils
from evennia.commands.cmdparser import at_multimatch_cmd
from evennia.utils.utils import string_suggestions, to_unicode

from django.utils.translation import ugettext as _

__all__ = ("cmdhandler",)
_GA = object.__getattribute__
_CMDSET_MERGE_CACHE = WeakValueDictionary()

# This decides which command parser is to be used.
# You have to restart the server for changes to take effect.
_COMMAND_PARSER = utils.variable_from_module(*settings.COMMAND_PARSER.rsplit('.', 1))

# System command names - import these variables rather than trying to
# remember the actual string constants. If not defined, Evennia
# hard-coded defaults are used instead.

# command to call if user just presses <return> with no input
CMD_NOINPUT = "__noinput_command"
# command to call if no command match was found
CMD_NOMATCH = "__nomatch_command"
# command to call if multiple command matches were found
CMD_MULTIMATCH = "__multimatch_command"
# command to call if found command is the name of a channel
CMD_CHANNEL = "__send_to_channel_command"
# command to call as the very first one when the user connects.
# (is expected to display the login screen)
Exemple #20
0
from traceback import format_exc
from twisted.internet.defer import inlineCallbacks, returnValue
from django.conf import settings
from evennia.comms.channelhandler import CHANNELHANDLER
from evennia.utils import logger, utils
from evennia.utils.utils import string_suggestions, to_unicode

from django.utils.translation import ugettext as _

__all__ = ("cmdhandler",)
_GA = object.__getattribute__
_CMDSET_MERGE_CACHE = WeakValueDictionary()

# This decides which command parser is to be used.
# You have to restart the server for changes to take effect.
_COMMAND_PARSER = utils.variable_from_module(*settings.COMMAND_PARSER.rsplit('.', 1))

# System command names - import these variables rather than trying to
# remember the actual string constants. If not defined, Evennia
# hard-coded defaults are used instead.

# command to call if user just presses <return> with no input
CMD_NOINPUT = "__noinput_command"
# command to call if no command match was found
CMD_NOMATCH = "__nomatch_command"
# command to call if multiple command matches were found
CMD_MULTIMATCH = "__multimatch_command"
# command to call if found command is the name of a channel
CMD_CHANNEL = "__send_to_channel_command"
# command to call as the very first one when the user connects.
# (is expected to display the login screen)
Exemple #21
0
from django.conf import settings
from django.db.models.fields import exceptions
from evennia.typeclasses.managers import TypedObjectManager, TypeclassManager
from evennia.typeclasses.managers import returns_typeclass, returns_typeclass_list
from evennia.utils import utils
from evennia.utils.utils import to_unicode, is_iter, make_iter, string_partial_matching

__all__ = ("ObjectManager", )
_GA = object.__getattribute__

# delayed import
_ATTR = None

# Try to use a custom way to parse id-tagged multimatches.

_AT_MULTIMATCH_INPUT = utils.variable_from_module(
    *settings.SEARCH_AT_MULTIMATCH_INPUT.rsplit('.', 1))


class ObjectDBManager(TypedObjectManager):
    """
    This ObjectManager implements methods for searching
    and manipulating Objects directly from the database.

    Evennia-specific search methods (will return Typeclasses or
    lists of Typeclasses, whereas Django-general methods will return
    Querysets or database objects).

    dbref (converter)
    get_id (alias: dbref_search)
    get_dbref_range
    object_totals
Exemple #22
0
    def search(
        self,  # type: Character
        searchdata,
        global_search=False,
        use_nicks=True,
        typeclass=None,
        location=None,
        attribute_name=None,
        quiet=False,
        exact=False,
        candidates=None,
        nofound_string=None,
        multimatch_string=None,
        use_dbref=True,
    ):
        from django.conf import settings

        # if we're staff, we just return the regular search method:
        if self.check_permstring("builders"):
            return super(Character, self).search(
                searchdata,
                global_search=global_search,
                use_nicks=use_nicks,
                typeclass=typeclass,
                location=location,
                attribute_name=attribute_name,
                quiet=quiet,
                exact=exact,
                candidates=candidates,
                nofound_string=nofound_string,
                multimatch_string=multimatch_string,
                use_dbref=use_dbref,
            )
        # we're not staff. Our search results must filter objects out:
        results = super(Character, self).search(
            searchdata,
            global_search=global_search,
            use_nicks=use_nicks,
            typeclass=typeclass,
            location=location,
            attribute_name=attribute_name,
            quiet=True,
            exact=exact,
            candidates=candidates,
            nofound_string=nofound_string,
            multimatch_string=multimatch_string,
            use_dbref=use_dbref,
        )
        # filter out objects we can't see:
        results = [ob for ob in results if ob.access(self, "view")]
        # filter out masked objects unless our search wasn't by their real name:
        results = [
            ob for ob in results
            if not ob.db.false_name or searchdata.lower() != ob.key.lower()
        ]
        # quiet means that messaging is handled elsewhere
        if quiet:
            return results
        if location == self:
            nofound_string = nofound_string or "You don't carry '%s'." % searchdata
            multimatch_string = (multimatch_string or
                                 "You carry more than one '%s':" % searchdata)
        # call the _AT_SEARCH_RESULT func to transform our results and send messages
        _AT_SEARCH_RESULT = variable_from_module(
            *settings.SEARCH_AT_RESULT.rsplit(".", 1))
        return _AT_SEARCH_RESULT(
            results,
            self,
            query=searchdata,
            nofound_string=nofound_string,
            multimatch_string=multimatch_string,
        )
Exemple #23
0
from traceback import format_exc
from twisted.internet.defer import inlineCallbacks, returnValue
from django.conf import settings
from evennia.comms.channelhandler import CHANNELHANDLER
from evennia.utils import logger, utils
from evennia.utils.utils import string_suggestions, to_unicode

from django.utils.translation import ugettext as _

__all__ = ("cmdhandler", )
_GA = object.__getattribute__
_CMDSET_MERGE_CACHE = WeakValueDictionary()

# This decides which command parser is to be used.
# You have to restart the server for changes to take effect.
_COMMAND_PARSER = utils.variable_from_module(
    *settings.COMMAND_PARSER.rsplit('.', 1))

# System command names - import these variables rather than trying to
# remember the actual string constants. If not defined, Evennia
# hard-coded defaults are used instead.

# command to call if user just presses <return> with no input
CMD_NOINPUT = "__noinput_command"
# command to call if no command match was found
CMD_NOMATCH = "__nomatch_command"
# command to call if multiple command matches were found
CMD_MULTIMATCH = "__multimatch_command"
# command to call if found command is the name of a channel
CMD_CHANNEL = "__send_to_channel_command"
# command to call as the very first one when the user connects.
# (is expected to display the login screen)
Exemple #24
0
    delayed call back to itself to handle the next action. After all actions
    are processed for a turn, control is returned to the `CombatHandler` to
    get input for the next turn.
"""

import re
import random
from math import floor
from collections import defaultdict
from evennia.utils import utils, make_iter


COMBAT_DELAY = 2
ACTIONS_PER_TURN = 2

COMBAT_DISTANCES = utils.variable_from_module('typeclasses.combat_handler', 'COMBAT_DISTANCES')
WRESTLING_POSITIONS = utils.variable_from_module('typeclasses.combat_handler', 'WRESTLING_POSITIONS')


class DiceRollError(Exception):
    """Default error class in die rolls/skill checks.

    Args:
        msg (str): a descriptive error message
    """
    def __init__(self, msg):
        self.msg = msg


def _parse_roll(xdyz):
    """Parser for XdY+Z dice roll notation.
Exemple #25
0
from django.utils.translation import ugettext as _

_IN_GAME_ERRORS = settings.IN_GAME_ERRORS

__all__ = ("cmdhandler",)
_GA = object.__getattribute__
_CMDSET_MERGE_CACHE = WeakValueDictionary()

# tracks recursive calls by each caller
# to avoid infinite loops (commands calling themselves)
_COMMAND_NESTING = defaultdict(lambda: 0)
_COMMAND_RECURSION_LIMIT = 10

# This decides which command parser is to be used.
# You have to restart the server for changes to take effect.
_COMMAND_PARSER = utils.variable_from_module(*settings.COMMAND_PARSER.rsplit('.', 1))

# System command names - import these variables rather than trying to
# remember the actual string constants. If not defined, Evennia
# hard-coded defaults are used instead.

# command to call if user just presses <return> with no input
CMD_NOINPUT = "__noinput_command"
# command to call if no command match was found
CMD_NOMATCH = "__nomatch_command"
# command to call if multiple command matches were found
CMD_MULTIMATCH = "__multimatch_command"
# command to call if found command is the name of a channel
CMD_CHANNEL = "__send_to_channel_command"
# command to call as the very first one when the user connects.
# (is expected to display the login screen)
Exemple #26
0
extract relevant information about it, such as genre, how many
active players and so on.


"""
from builtins import object
from django.conf import settings
from evennia.utils import utils

MSSP = chr(70)
MSSP_VAR = chr(1)
MSSP_VAL = chr(2)

# try to get the customized mssp info, if it exists.
MSSPTable_CUSTOM = utils.variable_from_module(settings.MSSP_META_MODULE,
                                              "MSSPTable",
                                              default={})


class Mssp(object):
    """
    Implements the MSSP protocol. Add this to a variable on the telnet
    protocol to set it up.

    """
    def __init__(self, protocol):
        """
        initialize MSSP by storing protocol on ourselves and calling
        the client to see if it supports MSSP.

        Args:
Exemple #27
0
    def func(self):
        """Starts the processor."""

        caller = self.caller
        args = self.args.split()

        # Check if arguments passed.
        if not self.args or (len(args) != 2):
            caller.msg("Usage: @mapbuilder <path.to.module.VARNAME> "
                       "<path.to.module.MAP_LEGEND>")
            return

        # Set up base variables.
        game_map = None
        legend = None

        # OBTAIN MAP FROM MODULE

        # Breaks down path_to_map into [PATH, VARIABLE]
        path_to_map = args[0]
        path_to_map = path_to_map.rsplit('.', 1)

        try:
            # Retrieves map variable from module or raises error.
            game_map = utils.variable_from_module(path_to_map[0],
                                                  path_to_map[1])
            if not game_map:
                raise ValueError("Command Aborted!\n"
                                 "Path to map variable failed.\n"
                                 "Usage: @mapbuilder <path.to.module."
                                 "VARNAME> <path.to.module.MAP_LEGEND>")

        except Exception as exc:
            # Or relays error message if fails.
            caller.msg(exc)
            return

        # OBTAIN MAP_LEGEND FROM MODULE

        # Breaks down path_to_legend into [PATH, VARIABLE]
        path_to_legend = args[1]
        path_to_legend = path_to_legend.rsplit('.', 1)

        # If no path given default to path_to_map's path
        if len(path_to_legend) == 1:
            path_to_legend.insert(0, path_to_map[0])

        try:
            # Retrieves legend variable from module or raises error if fails.
            legend = utils.variable_from_module(path_to_legend[0],
                                                path_to_legend[1])
            if not legend:
                raise ValueError("Command Aborted!\n"
                                 "Path to legend variable failed.\n"
                                 "Usage: @mapbuilder <path.to.module."
                                 "VARNAME> <path.to.module.MAP_LEGEND>")

        except Exception as exc:
            # Or relays error message if fails.
            caller.msg(exc)
            return

        # Set up build_map arguments from switches
        iterations = 1
        build_exits = True

        if "one" in self.switches:
            build_exits = False

        if "two" in self.switches:
            iterations = 2
            build_exits = False

        # Pass map and legend to the build function.
        build_map(caller, game_map, legend, iterations, build_exits)
Exemple #28
0
This defines the cmdset for the red_button. Here we have defined
the commands and the cmdset in the same module, but if you
have many different commands to merge it is often better
to define the cmdset separately, picking and choosing from
among the available commands as to what should be included in the
cmdset - this way you can often re-use the commands too.
"""

from django.conf import settings
from evennia.commands.cmdset import CmdSet
from evennia.utils import utils
from commands.base import ArxCommand
from typeclasses.exceptions import EquipError

# error return function, needed by wear/remove command
AT_SEARCH_RESULT = utils.variable_from_module(
    *settings.SEARCH_AT_RESULT.rsplit(".", 1))

# ------------------------------------------------------------
# Commands defined for wearable
# ------------------------------------------------------------


class CmdWield(ArxCommand):
    """
    Manages the weapon you use to attack.
    Usage:
        wield <weapon name>
        sheathe <weapon name>
        remove <weapon name>

    Wield makes a weapon ready for combat, showing your intent and readiness
Exemple #29
0
from collections import deque, OrderedDict
from operator import add
import random
from .scripts import Script
from evennia import TICKER_HANDLER as tickerhandler
from evennia.utils import utils, make_iter


COMBAT_DISTANCES = ['melee', 'reach', 'ranged']
WRESTLING_POSITIONS = ('STANDING', 'CLINCHED', 'TAKE DOWN', 'PINNED')

_ACTIONS_PER_TURN = utils.variable_from_module('world.rulebook', 'ACTIONS_PER_TURN')
_COMBAT_PROMPT = ("|M[|n HP: |g{tr.HP.actual}|n "
                  "|| WM: |w{tr.WM.actual}|n "
                  "|| BM: |x{tr.BM.actual}|n "
                  "|| SP: |y{tr.SP.actual}|n |M]|n")


class CombatHandler(Script):
    """
    This implements the combat handler.
    """

    # standard Script hooks

    def at_script_creation(self):
        "Called when script is first created"

        self.key = "combat_handler_%i" % random.randint(1, 1000)
        self.desc = "handles combat"
Exemple #30
0
 def add_cmds(module):
     "helper method for populating this object with cmds"
     from evennia.utils import utils
     cmdlist = utils.variable_from_module(module, module.__all__)
     self.__dict__.update(dict([(c.__name__, c) for c in cmdlist]))
Exemple #31
0
from django.db.models.fields import exceptions
from evennia.typeclasses.managers import TypedObjectManager, TypeclassManager
from evennia.typeclasses.managers import returns_typeclass, returns_typeclass_list
from evennia.utils import utils
from evennia.utils.utils import to_unicode, is_iter, make_iter, string_partial_matching

__all__ = ("ObjectManager",)
_GA = object.__getattribute__

# delayed import
_ATTR = None


# Try to use a custom way to parse id-tagged multimatches.

_AT_MULTIMATCH_INPUT = utils.variable_from_module(*settings.SEARCH_AT_MULTIMATCH_INPUT.rsplit('.', 1))


class ObjectDBManager(TypedObjectManager):
    """
    This ObjectManager implements methods for searching
    and manipulating Objects directly from the database.

    Evennia-specific search methods (will return Typeclasses or
    lists of Typeclasses, whereas Django-general methods will return
    Querysets or database objects).

    dbref (converter)
    get_id (alias: dbref_search)
    get_dbref_range
    object_totals
Exemple #32
0
            def add_cmds(module):
                "helper method for populating this object with cmds"
                from evennia.utils import utils

                cmdlist = utils.variable_from_module(module, module.__all__)
                self.__dict__.update(dict([(c.__name__, c) for c in cmdlist]))
def run_update(no_autodoc=False):

    if no_autodoc:
        return

    cmdsets = (
        ("evennia.commands.default.cmdset_character", "CharacterCmdSet"),
        ("evennia.commands.default.cmdset_account", "AccountCmdSet"),
        ("evennia.commands.default.cmdset_unloggedin", "UnloggedinCmdSet"),
        ("evennia.commands.default.cmdset_session", "SessionCmdSet"),
    )
    cmd_modules = (
        "evennia.commands.default.account",
        "evennia.commands.default.batchprocess",
        "evennia.commands.default.building",
        "evennia.commands.default.comms",
        "evennia.commands.default.general",
        "evennia.commands.default.help",
        "evennia.commands.default.syscommandsyyp",
        "evennia.commands.default.system",
        "evennia.commands.default.unloggedin",
    )

    cmds_per_cmdset = {}
    cmd_to_cmdset_map = {}
    for modname, cmdsetname in cmdsets:
        cmdset = variable_from_module(modname, variable=cmdsetname)()
        cmdset.at_cmdset_creation()
        cmds_per_cmdset[cmdsetname] = cmdset.commands
        for cmd in cmdset.commands:
            cmd_to_cmdset_map[f"{cmd.__module__}.{cmd.__class__.__name__}"] = cmdset

    cmds_per_module = {}
    cmd_to_module_map = {}
    cmds_alphabetically = []
    for modname in cmd_modules:
        module = mod_import(modname)
        cmds_per_module[module] = [
            cmd for cmd in callables_from_module(module).values() if cmd.__name__.startswith("Cmd")]
        for cmd in cmds_per_module[module]:
            cmd_to_module_map[cmd] = module
            cmds_alphabetically.append(cmd)
    cmds_alphabetically = list(sorted(cmds_alphabetically, key=lambda c: c.key))

    cmd_infos = []
    for cmd in cmds_alphabetically:
        aliases = f" [{', '.join(cmd.aliases)}]" if cmd.aliases else ""
        cmdlink = f"[**{cmd.key}**{aliases}]({cmd.__module__}.{cmd.__name__})"
        category = f"help-category: _{cmd.help_category.capitalize()}_"
        cmdset = cmd_to_cmdset_map.get(f"{cmd.__module__}.{cmd.__name__}", None)
        if cmdset:
            cmodule = cmdset.__module__
            cname = cmdset.__class__.__name__
            cmdsetlink = f"cmdset: [{cname}]({cmodule}.{cname}), "
        else:
            # we skip commands not in the default cmdsets
            continue

        cmd_infos.append(f"{cmdlink} ({cmdsetlink}{category})")

    txt = PAGE.format(
        ncommands=len(cmd_to_cmdset_map),
        nfiles=len(cmds_per_module),
        alphabetical="\n".join(f"- {info}" for info in cmd_infos))

    outdir = pathjoin(dirname(dirname(abspath(__file__))), "source")
    fname = pathjoin(outdir, "Default-Commands.md")

    with open(fname, 'w') as fil:
        fil.write(txt)

    print("  -- Updated Default Command index.")