Example #1
0
def create_object(typeclass=None, key=None, location=None,
                  home=None, permissions=None, locks=None,
                  aliases=None, tags=None, destination=None, report_to=None, nohome=False):
    """

    Create a new in-game object.

    keywords:
        typeclass - class or python path to a typeclass
        key - name of the new object. If not set, a name of #dbref will be set.
        home - obj or #dbref to use as the object's home location
        permissions - a comma-separated string of permissions
        locks - one or more lockstrings, separated by semicolons
        aliases - a list of alternative keys
        tags - a list of tag keys (using no category)
        destination - obj or #dbref to use as an Exit's target

        nohome - this allows the creation of objects without a default home location;
                 only used when creating the default location itself or during unittests
    """
    global _ObjectDB
    if not _ObjectDB:
        from evennia.objects.models import ObjectDB as _ObjectDB


    typeclass = typeclass if typeclass else settings.BASE_OBJECT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # Setup input for the create command. We use ObjectDB as baseclass here
    # to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    location = dbid_to_obj(location, _ObjectDB)
    destination = dbid_to_obj(destination, _ObjectDB)
    home = dbid_to_obj(home, _ObjectDB)
    if not home:
        try:
            home = dbid_to_obj(settings.DEFAULT_HOME, _ObjectDB) if not nohome else None
        except _ObjectDB.DoesNotExist:
            raise _ObjectDB.DoesNotExist("settings.DEFAULT_HOME (= '%s') does not exist, or the setting is malformed." %
                                         settings.DEFAULT_HOME)

    # create new instance
    new_object = typeclass(db_key=key, db_location=location,
                              db_destination=destination, db_home=home,
                              db_typeclass_path=typeclass.path)
    # store the call signature for the signal
    new_object._createdict = {"key":key, "location":location, "destination":destination,
                              "home":home, "typeclass":typeclass.path, "permissions":permissions,
                              "locks":locks, "aliases":aliases, "tags": tags, "destination":destination,
                              "report_to":report_to, "nohome":nohome}
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict can be
    # used.
    new_object.save()
    return new_object
Example #2
0
def value_to_obj(value, force=True):
    "Always convert value(s) to Object, or None"
    stype = type(value)
    if is_iter(value):
        if stype == dict:
            return {value_to_obj_or_any(key): value_to_obj_or_any(val) for key, val in value.iter()}
        else:
            return stype([value_to_obj_or_any(val) for val in value])
    return dbid_to_obj(value, ObjectDB)
Example #3
0
def value_to_obj_or_any(value):
    "Convert value(s) to Object if possible, otherwise keep original value"
    stype = type(value)
    if is_iter(value):
        if stype == dict:
            return {value_to_obj_or_any(key):
                    value_to_obj_or_any(val) for key, val in value.items()}
        else:
            return stype([value_to_obj_or_any(val) for val in value])
    obj = dbid_to_obj(value, ObjectDB)
    return obj if obj is not None else value
Example #4
0
def create_object(typeclass=None, key=None, location=None, home=None,
                  permissions=None, locks=None, aliases=None, tags=None,
                  destination=None, report_to=None, nohome=False):
    """

    Create a new in-game object.

    Kwargs:
        typeclass (class or str): Class or python path to a typeclass.
        key (str): Name of the new object. If not set, a name of
            #dbref will be set.
        home (Object or str): Obj or #dbref to use as the object's
            home location.
        permissions (str): A comma-separated string of permissions.
        locks (str): one or more lockstrings, separated by semicolons.
        aliases (list): A list of alternative keys.
        tags (list): List of tag keys (using no category).
        destination (Object or str): Obj or #dbref to use as an Exit's
            target.
        report_to (Object): The object to return error messages to.
        nohome (bool): This allows the creation of objects without a
            default home location; only used when creating the default
            location itself or during unittests.

    Returns:
        object (Object): A newly created object of the given typeclass.

    Raises:
        ObjectDB.DoesNotExist: If trying to create an Object with
            `location` or `home` that can't be found.

    """
    global _ObjectDB
    if not _ObjectDB:
        from evennia.objects.models import ObjectDB as _ObjectDB

    typeclass = typeclass if typeclass else settings.BASE_OBJECT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # Setup input for the create command. We use ObjectDB as baseclass here
    # to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    location = dbid_to_obj(location, _ObjectDB)
    destination = dbid_to_obj(destination, _ObjectDB)
    home = dbid_to_obj(home, _ObjectDB)
    if not home:
        try:
            home = dbid_to_obj(settings.DEFAULT_HOME, _ObjectDB) if not nohome else None
        except _ObjectDB.DoesNotExist:
            raise _ObjectDB.DoesNotExist("settings.DEFAULT_HOME (= '%s') does not exist, or the setting is malformed." %
                                         settings.DEFAULT_HOME)

    # create new instance
    new_object = typeclass(db_key=key, db_location=location,
                           db_destination=destination, db_home=home,
                           db_typeclass_path=typeclass.path)
    # store the call signature for the signal
    new_object._createdict = dict(key=key, location=location, destination=destination, home=home,
                                  typeclass=typeclass.path, permissions=permissions, locks=locks,
                                  aliases=aliases, tags=tags, report_to=report_to, nohome=nohome)
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict can be
    # used.
    new_object.save()
    return new_object
Example #5
0
def create_player(key, email, password,
                  typeclass=None,
                  is_superuser=False,
                  locks=None, permissions=None,
                  report_to=None):

    """
    This creates a new player.

    Args:
        key (str): The player's name. This should be unique.
        email (str): Email on valid [email protected] form. This is
            technically required but if set to `None`, an email of
            `[email protected]` will be used as a placeholder.
        password (str): Password in cleartext.

    Kwargs:
        is_superuser (bool): Wether or not this player is to be a superuser
        locks (str): Lockstring.
        permission (list): List of permission strings.
        report_to (Object): An object with a msg() method to report
            errors to. If not given, errors will be logged.

    Raises:
        ValueError: If `key` already exists in database.

    Notes:
        Usually only the server admin should need to be superuser, all
        other access levels can be handled with more fine-grained
        permissions or groups. A superuser bypasses all lock checking
        operations and is thus not suitable for play-testing the game.

    """
    global _PlayerDB
    if not _PlayerDB:
        from evennia.players.models import PlayerDB as _PlayerDB

    typeclass = typeclass if typeclass else settings.BASE_PLAYER_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass.
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # setup input for the create command. We use PlayerDB as baseclass
    # here to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    if not email:
        email = "*****@*****.**"
    if _PlayerDB.objects.filter(username__iexact=key):
        raise ValueError("A Player with the name '%s' already exists." % key)

    # this handles a given dbref-relocate to a player.
    report_to = dbid_to_obj(report_to, _PlayerDB)

    # create the correct player entity, using the setup from
    # base django auth.
    now = timezone.now()
    email = typeclass.objects.normalize_email(email)
    new_player = typeclass(username=key, email=email,
                           is_staff=is_superuser, is_superuser=is_superuser,
                           last_login=now, date_joined=now)
    new_player.set_password(password)
    new_player._createdict = dict(locks=locks, permissions=permissions, report_to=report_to)
    # saving will trigger the signal that calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_player.save()
    return new_player
Example #6
0
def create_script(typeclass=None, key=None, obj=None, player=None, locks=None,
                  interval=None, start_delay=None, repeats=None,
                  persistent=None, autostart=True, report_to=None, desc=None):
    """
    Create a new script. All scripts are a combination of a database
    object that communicates with the database, and an typeclass that
    'decorates' the database object into being different types of
    scripts.  It's behaviour is similar to the game objects except
    scripts has a time component and are more limited in scope.

    Kwargs:
        typeclass (class or str): Class or python path to a typeclass.
        key (str): Name of the new object. If not set, a name of
            #dbref will be set.
        obj (Object): The entity on which this Script sits. If this
            is `None`, we are creating a "global" script.
        player (Player): The player on which this Script sits. It is
            exclusiv to `obj`.
        locks (str): one or more lockstrings, separated by semicolons.
        interval (int): The triggering interval for this Script, in
            seconds. If unset, the Script will not have a timing
            component.
        start_delay (bool): If `True`, will wait `interval` seconds
            before triggering the first time.
        repeats (int): The number of times to trigger before stopping.
            If unset, will repeat indefinitely.
        persistent (bool): If this Script survives a server shutdown
            or not (all Scripts will survive a reload).
        autostart (bool): If this Script will start immediately when
            created or if the `start` method must be called explicitly.
        report_to (Object): The object to return error messages to.
        desc (str): Optional description of script


    See evennia.scripts.manager for methods to manipulate existing
    scripts in the database.

    """
    global _ScriptDB
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB

    typeclass = typeclass if typeclass else settings.BASE_SCRIPT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # validate input
    kwarg = {}
    if key: kwarg["db_key"] = key
    if player: kwarg["db_player"] = dbid_to_obj(player, _ScriptDB)
    if obj: kwarg["db_obj"] = dbid_to_obj(obj, _ScriptDB)
    if interval: kwarg["db_interval"] = interval
    if start_delay: kwarg["db_start_delay"] = start_delay
    if repeats: kwarg["db_repeats"] = repeats
    if persistent: kwarg["db_persistent"] = persistent
    if desc: kwarg["db_desc"] = desc

    # create new instance
    new_script = typeclass(**kwarg)

    # store the call signature for the signal
    new_script._createdict = dict(key=key, obj=obj, player=player, locks=locks, interval=interval,
                                  start_delay=start_delay, repeats=repeats, persistent=persistent,
                                  autostart=autostart, report_to=report_to)
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_script.save()
    return new_script
Example #7
0
def create_object(typeclass=None,
                  key=None,
                  location=None,
                  home=None,
                  permissions=None,
                  locks=None,
                  aliases=None,
                  tags=None,
                  destination=None,
                  report_to=None,
                  nohome=False):
    """

    Create a new in-game object.

    Kwargs:
        typeclass (class or str): Class or python path to a typeclass.
        key (str): Name of the new object. If not set, a name of
            #dbref will be set.
        home (Object or str): Obj or #dbref to use as the object's
            home location.
        permissions (str): A comma-separated string of permissions.
        locks (str): one or more lockstrings, separated by semicolons.
        aliases (list): A list of alternative keys.
        tags (list): List of tag keys (using no category).
        destination (Object or str): Obj or #dbref to use as an Exit's
            target.
        report_to (Object): The object to return error messages to.
        nohome (bool): This allows the creation of objects without a
            default home location; only used when creating the default
            location itself or during unittests.

    Returns:
        object (Object): A newly created object of the given typeclass.

    Raises:
        ObjectDB.DoesNotExist: If trying to create an Object with
            `location` or `home` that can't be found.

    """
    global _ObjectDB
    if not _ObjectDB:
        from evennia.objects.models import ObjectDB as _ObjectDB

    typeclass = typeclass if typeclass else settings.BASE_OBJECT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # Setup input for the create command. We use ObjectDB as baseclass here
    # to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    location = dbid_to_obj(location, _ObjectDB)
    destination = dbid_to_obj(destination, _ObjectDB)
    home = dbid_to_obj(home, _ObjectDB)
    if not home:
        try:
            home = dbid_to_obj(settings.DEFAULT_HOME,
                               _ObjectDB) if not nohome else None
        except _ObjectDB.DoesNotExist:
            raise _ObjectDB.DoesNotExist(
                "settings.DEFAULT_HOME (= '%s') does not exist, or the setting is malformed."
                % settings.DEFAULT_HOME)

    # create new instance
    new_object = typeclass(db_key=key,
                           db_location=location,
                           db_destination=destination,
                           db_home=home,
                           db_typeclass_path=typeclass.path)
    # store the call signature for the signal
    new_object._createdict = dict(key=key,
                                  location=location,
                                  destination=destination,
                                  home=home,
                                  typeclass=typeclass.path,
                                  permissions=permissions,
                                  locks=locks,
                                  aliases=aliases,
                                  tags=tags,
                                  report_to=report_to,
                                  nohome=nohome)
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict can be
    # used.
    new_object.save()
    return new_object
Example #8
0
def create_player(key,
                  email,
                  password,
                  typeclass=None,
                  is_superuser=False,
                  locks=None,
                  permissions=None,
                  report_to=None):
    """
    This creates a new player.

    key - the player's name. This should be unique.
    email - email on valid [email protected] form.
    password - password in cleartext
    is_superuser - wether or not this player is to be a superuser
    locks - lockstring
    permission - list of permissions
    report_to - an object with a msg() method to report errors to. If
                not given, errors will be logged.

    Will return the Player-typeclass or None/raise Exception if the
    Typeclass given failed to load.

    Concerning is_superuser:
     Usually only the server admin should need to be superuser, all
     other access levels can be handled with more fine-grained
     permissions or groups. A superuser bypasses all lock checking
     operations and is thus not suitable for play-testing the game.

    """
    global _PlayerDB
    if not _PlayerDB:
        from evennia.players.models import PlayerDB as _PlayerDB

    typeclass = typeclass if typeclass else settings.BASE_PLAYER_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass.
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # setup input for the create command. We use PlayerDB as baseclass
    # here to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    if not email:
        email = "*****@*****.**"
    if _PlayerDB.objects.filter(username__iexact=key):
        raise ValueError("A Player with the name '%s' already exists." % key)

    # this handles a given dbref-relocate to a player.
    report_to = dbid_to_obj(report_to, _PlayerDB)

    # create the correct player entity, using the setup from
    # base django auth.
    now = timezone.now()
    email = typeclass.objects.normalize_email(email)
    new_player = typeclass(username=key,
                           email=email,
                           is_staff=is_superuser,
                           is_superuser=is_superuser,
                           last_login=now,
                           date_joined=now)
    new_player.set_password(password)
    new_player._createdict = {
        "locks": locks,
        "permissions": permissions,
        "report_to": report_to
    }
    # saving will trigger the signal that calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_player.save()
    return new_player
Example #9
0
def create_account(
    key,
    email,
    password,
    typeclass=None,
    is_superuser=False,
    locks=None,
    permissions=None,
    tags=None,
    attributes=None,
    report_to=None,
):
    """
    This creates a new account.

    Args:
        key (str): The account's name. This should be unique.
        email (str or None): Email on valid [email protected] form. If
            the empty string, will be set to None.
        password (str): Password in cleartext.

    Kwargs:
        typeclass (str): The typeclass to use for the account.
        is_superuser (bool): Wether or not this account is to be a superuser
        locks (str): Lockstring.
        permission (list): List of permission strings.
        tags (list): List of Tags on form `(key, category[, data])`
        attributes (list): List of Attributes on form
             `(key, value [, category, [,lockstring [, default_pass]]])`
        report_to (Object): An object with a msg() method to report
            errors to. If not given, errors will be logged.

    Returns:
        Account: The newly created Account.
    Raises:
        ValueError: If `key` already exists in database.


    Notes:
        Usually only the server admin should need to be superuser, all
        other access levels can be handled with more fine-grained
        permissions or groups. A superuser bypasses all lock checking
        operations and is thus not suitable for play-testing the game.

    """
    global _AccountDB
    if not _AccountDB:
        from evennia.accounts.models import AccountDB as _AccountDB

    typeclass = typeclass if typeclass else settings.BASE_ACCOUNT_TYPECLASS
    locks = make_iter(locks) if locks is not None else None
    permissions = make_iter(permissions) if permissions is not None else None
    tags = make_iter(tags) if tags is not None else None
    attributes = make_iter(attributes) if attributes is not None else None

    if isinstance(typeclass, str):
        # a path is given. Load the actual typeclass.
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # setup input for the create command. We use AccountDB as baseclass
    # here to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    if not email:
        email = None
    if _AccountDB.objects.filter(username__iexact=key):
        raise ValueError("An Account with the name '%s' already exists." % key)

    # this handles a given dbref-relocate to an account.
    report_to = dbid_to_obj(report_to, _AccountDB)

    # create the correct account entity, using the setup from
    # base django auth.
    now = timezone.now()
    email = typeclass.objects.normalize_email(email)
    new_account = typeclass(
        username=key,
        email=email,
        is_staff=is_superuser,
        is_superuser=is_superuser,
        last_login=now,
        date_joined=now,
    )
    if password is not None:
        # the password may be None for 'fake' accounts, like bots
        valid, error = new_account.validate_password(password, new_account)
        if not valid:
            raise error

        new_account.set_password(password)

    new_account._createdict = dict(locks=locks,
                                   permissions=permissions,
                                   report_to=report_to,
                                   tags=tags,
                                   attributes=attributes)
    # saving will trigger the signal that calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_account.save()

    # note that we don't send a signal here, that is sent from the Account.create helper method
    # instead.

    return new_account
Example #10
0
"""

import copy

# TODO
# sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings'

from django.conf import settings
from random import randint
from evennia.objects.models import ObjectDB
from evennia.utils.utils import make_iter, all_from_module, dbid_to_obj

_CREATE_OBJECT_KWARGS = ("key", "location", "home", "destination")

_handle_dbref = lambda inp: dbid_to_obj(inp, ObjectDB)


def _validate_prototype(key, prototype, protparents, visited):
    """
    Run validation on a prototype, checking for inifinite regress.

    """
    assert isinstance(prototype, dict)
    if id(prototype) in visited:
        raise RuntimeError("%s has infinite nesting of prototypes." % key or prototype)
    visited.append(id(prototype))
    protstrings = prototype.get("prototype")
    if protstrings:
        for protstring in make_iter(protstrings):
            if key is not None and protstring == key:
Example #11
0
def create_player(key, email, password,
                  typeclass=None,
                  is_superuser=False,
                  locks=None, permissions=None,
                  report_to=None):

    """
    This creates a new player.

    key - the player's name. This should be unique.
    email - email on valid [email protected] form.
    password - password in cleartext
    is_superuser - wether or not this player is to be a superuser
    locks - lockstring
    permission - list of permissions
    report_to - an object with a msg() method to report errors to. If
                not given, errors will be logged.

    Will return the Player-typeclass or None/raise Exception if the
    Typeclass given failed to load.

    Concerning is_superuser:
     Usually only the server admin should need to be superuser, all
     other access levels can be handled with more fine-grained
     permissions or groups. A superuser bypasses all lock checking
     operations and is thus not suitable for play-testing the game.

    """
    global _PlayerDB
    if not _PlayerDB:
        from evennia.players.models import PlayerDB as _PlayerDB

    typeclass = typeclass if typeclass else settings.BASE_PLAYER_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass.
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # setup input for the create command. We use PlayerDB as baseclass
    # here to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    if not email:
        email = "*****@*****.**"
    if _PlayerDB.objects.filter(username__iexact=key):
        raise ValueError("A Player with the name '%s' already exists." % key)

    # this handles a given dbref-relocate to a player.
    report_to = dbid_to_obj(report_to, _PlayerDB)

    # create the correct player entity, using the setup from
    # base django auth.
    now = timezone.now()
    email = typeclass.objects.normalize_email(email)
    new_player = typeclass(username=key, email=email,
                           is_staff=is_superuser, is_superuser=is_superuser,
                           last_login=now, date_joined=now)
    new_player.set_password(password)
    new_player._createdict = {"locks":locks, "permissions":permissions,
                              "report_to":report_to}
    # saving will trigger the signal that calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_player.save()
    return new_player
Example #12
0
def create_script(typeclass, key=None, obj=None, player=None, locks=None,
                  interval=None, start_delay=None, repeats=None,
                  persistent=None, autostart=True, report_to=None):
    """
    Create a new script. All scripts are a combination
    of a database object that communicates with the
    database, and an typeclass that 'decorates' the
    database object into being different types of scripts.
    It's behaviour is similar to the game objects except
    scripts has a time component and are more limited in
    scope.

    Argument 'typeclass' can be either an actual
    typeclass object or a python path to such an object.
    Only set key here if you want a unique name for this
    particular script (set it in config to give
    same key to all scripts of the same type). Set obj
    to tie this script to a particular object.

    See evennia.scripts.manager for methods to manipulate existing
    scripts in the database.

    report_to is an obtional object to receive error messages.
              If report_to is not set, an Exception with the
              error will be raised. If set, this method will
              return None upon errors.
    """
    global _ScriptDB
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB

    typeclass = typeclass if typeclass else settings.BASE_SCRIPT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # validate input
    kwarg = {}
    if key: kwarg["db_key"] = key
    if player: kwarg["db_player"] = dbid_to_obj(player, _ScriptDB)
    if obj: kwarg["db_obj"] = dbid_to_obj(obj, _ScriptDB)
    if interval: kwarg["db_interval"] = interval
    if start_delay: kwarg["db_start_delay"] = start_delay
    if repeats: kwarg["db_repeats"] = repeats
    if persistent: kwarg["db_persistent"] = persistent

    # create new instance
    new_script = typeclass(**kwarg)

    # store the call signature for the signal
    new_script._createdict = {"key":key, "obj":obj, "player":player,
                              "locks":locks, "interval":interval,
                              "start_delay":start_delay, "repeats":repeats,
                              "persistent":persistent, "autostart":autostart,
                              "report_to":report_to}

    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the tyepclass, where the _createdict
    # can be used.
    new_script.save()
    return new_script
Example #13
0
def _handle_dbref(inp):
    dbid_to_obj(inp, ObjectDB)
Example #14
0
def create_object(typeclass=None,
                  key=None,
                  location=None,
                  home=None,
                  permissions=None,
                  locks=None,
                  aliases=None,
                  destination=None,
                  report_to=None,
                  nohome=False):
    """

    Create a new in-game object.

    keywords:
        typeclass - class or python path to a typeclass
        key - name of the new object. If not set, a name of #dbref will be set.
        home - obj or #dbref to use as the object's home location
        permissions - a comma-separated string of permissions
        locks - one or more lockstrings, separated by semicolons
        aliases - a list of alternative keys
        destination - obj or #dbref to use as an Exit's target

        nohome - this allows the creation of objects without a default home location;
                 only used when creating the default location itself or during unittests
    """
    global _ObjectDB
    if not _ObjectDB:
        from evennia.objects.models import ObjectDB as _ObjectDB

    typeclass = typeclass if typeclass else settings.BASE_OBJECT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # Setup input for the create command. We use ObjectDB as baseclass here
    # to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    location = dbid_to_obj(location, _ObjectDB)
    destination = dbid_to_obj(destination, _ObjectDB)
    home = dbid_to_obj(home, _ObjectDB)
    if not home:
        try:
            home = dbid_to_obj(settings.DEFAULT_HOME,
                               _ObjectDB) if not nohome else None
        except _ObjectDB.DoesNotExist:
            raise _ObjectDB.DoesNotExist(
                "settings.DEFAULT_HOME (= '%s') does not exist, or the setting is malformed."
                % settings.DEFAULT_HOME)

    # create new instance
    new_object = typeclass(db_key=key,
                           db_location=location,
                           db_destination=destination,
                           db_home=home,
                           db_typeclass_path=typeclass.path)
    # store the call signature for the signal
    new_object._createdict = {
        "key": key,
        "location": location,
        "destination": destination,
        "home": home,
        "typeclass": typeclass.path,
        "permissions": permissions,
        "locks": locks,
        "aliases": aliases,
        "destination": destination,
        "report_to": report_to,
        "nohome": nohome
    }
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict can be
    # used.
    new_object.save()
    return new_object
Example #15
0
"""

import copy
#TODO
#sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
#os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings'

from django.conf import settings
from random import randint
from evennia.objects.models import ObjectDB
from evennia.utils.utils import make_iter, all_from_module, dbid_to_obj

_CREATE_OBJECT_KWARGS = ("key", "location", "home", "destination")

_handle_dbref = lambda inp: dbid_to_obj(inp, ObjectDB)


def _validate_prototype(key, prototype, protparents, visited):
    "Run validation on a prototype, checking for inifinite regress"
    assert isinstance(prototype, dict)
    if id(prototype) in visited:
        raise RuntimeError("%s has infinite nesting of prototypes." % key
                           or prototype)
    visited.append(id(prototype))
    protstrings = prototype.get("prototype")
    if protstrings:
        for protstring in make_iter(protstrings):
            if key is not None and protstring == key:
                raise RuntimeError("%s tries to prototype itself." % key
                                   or prototype)
Example #16
0
def create_script(
    typeclass=None,
    key=None,
    obj=None,
    account=None,
    locks=None,
    interval=None,
    start_delay=None,
    repeats=None,
    persistent=None,
    autostart=True,
    report_to=None,
    desc=None,
    tags=None,
    attributes=None,
):
    """
    Create a new script. All scripts are a combination of a database
    object that communicates with the database, and an typeclass that
    'decorates' the database object into being different types of
    scripts.  It's behaviour is similar to the game objects except
    scripts has a time component and are more limited in scope.

    Kwargs:
        typeclass (class or str): Class or python path to a typeclass.
        key (str): Name of the new object. If not set, a name of
            #dbref will be set.
        obj (Object): The entity on which this Script sits. If this
            is `None`, we are creating a "global" script.
        account (Account): The account on which this Script sits. It is
            exclusiv to `obj`.
        locks (str): one or more lockstrings, separated by semicolons.
        interval (int): The triggering interval for this Script, in
            seconds. If unset, the Script will not have a timing
            component.
        start_delay (bool): If `True`, will wait `interval` seconds
            before triggering the first time.
        repeats (int): The number of times to trigger before stopping.
            If unset, will repeat indefinitely.
        persistent (bool): If this Script survives a server shutdown
            or not (all Scripts will survive a reload).
        autostart (bool): If this Script will start immediately when
            created or if the `start` method must be called explicitly.
        report_to (Object): The object to return error messages to.
        desc (str): Optional description of script
        tags (list): List of tags or tuples (tag, category).
        attributes (list): List if tuples (key, value) or (key, value, category)
           (key, value, lockstring) or (key, value, lockstring, default_access).

    See evennia.scripts.manager for methods to manipulate existing
    scripts in the database.

    """
    global _ScriptDB
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB

    typeclass = typeclass if typeclass else settings.BASE_SCRIPT_TYPECLASS

    if isinstance(typeclass, str):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # validate input
    kwarg = {}
    if key:
        kwarg["db_key"] = key
    if account:
        kwarg["db_account"] = dbid_to_obj(account, _AccountDB)
    if obj:
        kwarg["db_obj"] = dbid_to_obj(obj, _ObjectDB)
    if interval:
        kwarg["db_interval"] = max(0, interval)
    if start_delay:
        kwarg["db_start_delay"] = start_delay
    if repeats:
        kwarg["db_repeats"] = max(0, repeats)
    if persistent:
        kwarg["db_persistent"] = persistent
    if desc:
        kwarg["db_desc"] = desc
    tags = make_iter(tags) if tags is not None else None
    attributes = make_iter(attributes) if attributes is not None else None

    # create new instance
    new_script = typeclass(**kwarg)

    # store the call signature for the signal
    new_script._createdict = dict(
        key=key,
        obj=obj,
        account=account,
        locks=locks,
        interval=interval,
        start_delay=start_delay,
        repeats=repeats,
        persistent=persistent,
        autostart=autostart,
        report_to=report_to,
        desc=desc,
        tags=tags,
        attributes=attributes,
    )
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_script.save()

    if not new_script.id:
        # this happens in the case of having a repeating script with `repeats=1` and
        # `start_delay=False` - the script will run once and immediately stop before save is over.
        return None

    signals.SIGNAL_SCRIPT_POST_CREATE.send(sender=new_script)

    return new_script
Example #17
0
def _handle_dbref(inp):
    return dbid_to_obj(inp, ObjectDB)
Example #18
0
def create_object(
    typeclass=None,
    key=None,
    location=None,
    home=None,
    permissions=None,
    locks=None,
    aliases=None,
    tags=None,
    destination=None,
    report_to=None,
    nohome=False,
    attributes=None,
    nattributes=None,
):
    """

    Create a new in-game object.

    Kwargs:
        typeclass (class or str): Class or python path to a typeclass.
        key (str): Name of the new object. If not set, a name of
            #dbref will be set.
        home (Object or str): Obj or #dbref to use as the object's
            home location.
        permissions (list): A list of permission strings or tuples (permstring, category).
        locks (str): one or more lockstrings, separated by semicolons.
        aliases (list): A list of alternative keys or tuples (aliasstring, category).
        tags (list): List of tag keys or tuples (tagkey, category) or (tagkey, category, data).
        destination (Object or str): Obj or #dbref to use as an Exit's
            target.
        report_to (Object): The object to return error messages to.
        nohome (bool): This allows the creation of objects without a
            default home location; only used when creating the default
            location itself or during unittests.
        attributes (list): Tuples on the form (key, value) or (key, value, category),
           (key, value, lockstring) or (key, value, lockstring, default_access).
            to set as Attributes on the new object.
        nattributes (list): Non-persistent tuples on the form (key, value). Note that
            adding this rarely makes sense since this data will not survive a reload.

    Returns:
        object (Object): A newly created object of the given typeclass.

    Raises:
        ObjectDB.DoesNotExist: If trying to create an Object with
            `location` or `home` that can't be found.

    """
    global _ObjectDB
    if not _ObjectDB:
        from evennia.objects.models import ObjectDB as _ObjectDB

    typeclass = typeclass if typeclass else settings.BASE_OBJECT_TYPECLASS

    # convenience converters to avoid common usage mistake
    permissions = make_iter(permissions) if permissions is not None else None
    locks = make_iter(locks) if locks is not None else None
    aliases = make_iter(aliases) if aliases is not None else None
    tags = make_iter(tags) if tags is not None else None
    attributes = make_iter(attributes) if attributes is not None else None

    if isinstance(typeclass, str):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # Setup input for the create command. We use ObjectDB as baseclass here
    # to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    location = dbid_to_obj(location, _ObjectDB)
    destination = dbid_to_obj(destination, _ObjectDB)
    home = dbid_to_obj(home, _ObjectDB)
    if not home:
        try:
            home = dbid_to_obj(settings.DEFAULT_HOME,
                               _ObjectDB) if not nohome else None
        except _ObjectDB.DoesNotExist:
            raise _ObjectDB.DoesNotExist(
                "settings.DEFAULT_HOME (= '%s') does not exist, or the setting is malformed."
                % settings.DEFAULT_HOME)

    # create new instance
    new_object = typeclass(
        db_key=key,
        db_location=location,
        db_destination=destination,
        db_home=home,
        db_typeclass_path=typeclass.path,
    )
    # store the call signature for the signal
    new_object._createdict = dict(
        key=key,
        location=location,
        destination=destination,
        home=home,
        typeclass=typeclass.path,
        permissions=permissions,
        locks=locks,
        aliases=aliases,
        tags=tags,
        report_to=report_to,
        nohome=nohome,
        attributes=attributes,
        nattributes=nattributes,
    )
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict can be
    # used.
    new_object.save()

    signals.SIGNAL_OBJECT_POST_CREATE.send(sender=new_object)

    return new_object
Example #19
0
def create_script(typeclass=None,
                  key=None,
                  obj=None,
                  player=None,
                  locks=None,
                  interval=None,
                  start_delay=None,
                  repeats=None,
                  persistent=None,
                  autostart=True,
                  report_to=None,
                  desc=None):
    """
    Create a new script. All scripts are a combination of a database
    object that communicates with the database, and an typeclass that
    'decorates' the database object into being different types of
    scripts.  It's behaviour is similar to the game objects except
    scripts has a time component and are more limited in scope.

    Kwargs:
        typeclass (class or str): Class or python path to a typeclass.
        key (str): Name of the new object. If not set, a name of
            #dbref will be set.
        obj (Object): The entity on which this Script sits. If this
            is `None`, we are creating a "global" script.
        player (Player): The player on which this Script sits. It is
            exclusiv to `obj`.
        locks (str): one or more lockstrings, separated by semicolons.
        interval (int): The triggering interval for this Script, in
            seconds. If unset, the Script will not have a timing
            component.
        start_delay (bool): If `True`, will wait `interval` seconds
            before triggering the first time.
        repeats (int): The number of times to trigger before stopping.
            If unset, will repeat indefinitely.
        persistent (bool): If this Script survives a server shutdown
            or not (all Scripts will survive a reload).
        autostart (bool): If this Script will start immediately when
            created or if the `start` method must be called explicitly.
        report_to (Object): The object to return error messages to.
        desc (str): Optional description of script


    See evennia.scripts.manager for methods to manipulate existing
    scripts in the database.

    """
    global _ScriptDB
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB

    typeclass = typeclass if typeclass else settings.BASE_SCRIPT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # validate input
    kwarg = {}
    if key: kwarg["db_key"] = key
    if player: kwarg["db_player"] = dbid_to_obj(player, _ScriptDB)
    if obj: kwarg["db_obj"] = dbid_to_obj(obj, _ScriptDB)
    if interval: kwarg["db_interval"] = interval
    if start_delay: kwarg["db_start_delay"] = start_delay
    if repeats: kwarg["db_repeats"] = repeats
    if persistent: kwarg["db_persistent"] = persistent
    if desc: kwarg["db_desc"] = desc

    # create new instance
    new_script = typeclass(**kwarg)

    # store the call signature for the signal
    new_script._createdict = dict(key=key,
                                  obj=obj,
                                  player=player,
                                  locks=locks,
                                  interval=interval,
                                  start_delay=start_delay,
                                  repeats=repeats,
                                  persistent=persistent,
                                  autostart=autostart,
                                  report_to=report_to)
    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_script.save()
    return new_script
Example #20
0
def create_player(key,
                  email,
                  password,
                  typeclass=None,
                  is_superuser=False,
                  locks=None,
                  permissions=None,
                  report_to=None):
    """
    This creates a new player.

    Args:
        key (str): The player's name. This should be unique.
        email (str): Email on valid [email protected] form. This is
            technically required but if set to `None`, an email of
            `[email protected]` will be used as a placeholder.
        password (str): Password in cleartext.

    Kwargs:
        is_superuser (bool): Wether or not this player is to be a superuser
        locks (str): Lockstring.
        permission (list): List of permission strings.
        report_to (Object): An object with a msg() method to report
            errors to. If not given, errors will be logged.

    Raises:
        ValueError: If `key` already exists in database.

    Notes:
        Usually only the server admin should need to be superuser, all
        other access levels can be handled with more fine-grained
        permissions or groups. A superuser bypasses all lock checking
        operations and is thus not suitable for play-testing the game.

    """
    global _PlayerDB
    if not _PlayerDB:
        from evennia.players.models import PlayerDB as _PlayerDB

    typeclass = typeclass if typeclass else settings.BASE_PLAYER_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass.
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # setup input for the create command. We use PlayerDB as baseclass
    # here to give us maximum freedom (the typeclasses will load
    # correctly when each object is recovered).

    if not email:
        email = "*****@*****.**"
    if _PlayerDB.objects.filter(username__iexact=key):
        raise ValueError("A Player with the name '%s' already exists." % key)

    # this handles a given dbref-relocate to a player.
    report_to = dbid_to_obj(report_to, _PlayerDB)

    # create the correct player entity, using the setup from
    # base django auth.
    now = timezone.now()
    email = typeclass.objects.normalize_email(email)
    new_player = typeclass(username=key,
                           email=email,
                           is_staff=is_superuser,
                           is_superuser=is_superuser,
                           last_login=now,
                           date_joined=now)
    new_player.set_password(password)
    new_player._createdict = dict(locks=locks,
                                  permissions=permissions,
                                  report_to=report_to)
    # saving will trigger the signal that calls the
    # at_first_save hook on the typeclass, where the _createdict
    # can be used.
    new_player.save()
    return new_player
Example #21
0
def create_script(typeclass,
                  key=None,
                  obj=None,
                  player=None,
                  locks=None,
                  interval=None,
                  start_delay=None,
                  repeats=None,
                  persistent=None,
                  autostart=True,
                  report_to=None):
    """
    Create a new script. All scripts are a combination
    of a database object that communicates with the
    database, and an typeclass that 'decorates' the
    database object into being different types of scripts.
    It's behaviour is similar to the game objects except
    scripts has a time component and are more limited in
    scope.

    Argument 'typeclass' can be either an actual
    typeclass object or a python path to such an object.
    Only set key here if you want a unique name for this
    particular script (set it in config to give
    same key to all scripts of the same type). Set obj
    to tie this script to a particular object.

    See evennia.scripts.manager for methods to manipulate existing
    scripts in the database.

    report_to is an obtional object to receive error messages.
              If report_to is not set, an Exception with the
              error will be raised. If set, this method will
              return None upon errors.
    """
    global _ScriptDB
    if not _ScriptDB:
        from evennia.scripts.models import ScriptDB as _ScriptDB

    typeclass = typeclass if typeclass else settings.BASE_SCRIPT_TYPECLASS

    if isinstance(typeclass, basestring):
        # a path is given. Load the actual typeclass
        typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)

    # validate input
    kwarg = {}
    if key: kwarg["db_key"] = key
    if player: kwarg["db_player"] = dbid_to_obj(player, _ScriptDB)
    if obj: kwarg["db_obj"] = dbid_to_obj(obj, _ScriptDB)
    if interval: kwarg["db_interval"] = interval
    if start_delay: kwarg["db_start_delay"] = start_delay
    if repeats: kwarg["db_repeats"] = repeats
    if persistent: kwarg["db_persistent"] = persistent

    # create new instance
    new_script = typeclass(**kwarg)

    # store the call signature for the signal
    new_script._createdict = {
        "key": key,
        "obj": obj,
        "player": player,
        "locks": locks,
        "interval": interval,
        "start_delay": start_delay,
        "repeats": repeats,
        "persistent": persistent,
        "autostart": autostart,
        "report_to": report_to
    }

    # this will trigger the save signal which in turn calls the
    # at_first_save hook on the tyepclass, where the _createdict
    # can be used.
    new_script.save()
    return new_script