本文整理汇总了Python中src.utils.utils.inherits_from函数的典型用法代码示例。如果您正苦于以下问题:Python inherits_from函数的具体用法?Python inherits_from怎么用?Python inherits_from使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inherits_from函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: func
def func(self):
"implements the command."
caller = self.caller
if not self.args:
caller.msg("Get what?")
return
#print "general/get:", caller, caller.location, self.args, caller.location.contents
parsed = self.args.split(" ")
if len(parsed) == 3 and parsed[1] == "from":
target = caller.search(parsed[2])
if target != None:
if utils.inherits_from(target, "game.gamesrc.objects.container.Container") == False:
if target == caller:
obj = caller.search(parsed[0], location=target)
if obj == None:
return
else:
caller.msg("You already have that.")
elif utils.inherits_from(target, "game.gamesrc.objects.kc.Character"):
caller.msg("You can't steal from others!")
elif target == caller.location:
caller.msg("Isn't that a bit overcomplicated?")
else:
caller.msg("It's not possible to take something out of that.")
return
elif utils.inherits_from(target, "game.gamesrc.objects.container.Container") == True:
if target.db.con_closed:
caller.msg("You have to open the %s first." % target.name)
return
obj = caller.search(parsed[0], location=target)
else:
obj = caller.search(parsed[0], location=caller.location)
if not obj:
return
if caller == obj:
caller.msg("You can't get yourself.")
return
#print obj, obj.location, caller, caller==obj.location
if caller == obj.location:
caller.msg("You already have that.")
return
if not obj.access(caller, 'get'):
if obj.db.get_err_msg:
caller.msg(obj.db.get_err_msg)
else:
caller.msg("You can't get that.")
return
obj.move_to(caller, quiet=True)
if len(parsed) == 3 and parsed[1] == "from" and not target == caller.location:
caller.msg("You get the %s from the %s." % (obj.name, target.name))
caller.location.msg_contents("%s gets the %s from the %s." % (caller.name, obj.name, target.name), exclude=caller)
else:
caller.msg("You pick up the %s." % obj.name)
caller.location.msg_contents("%s picks up the %s." % (caller.name, obj.name), exclude=caller)
# calling hook method
obj.at_get(caller)
开发者ID:KittyTristy,项目名称:KittyCraft,代码行数:59,代码来源:custom.py
示例2: display_mail
def display_mail(self, message):
"""
Display a mail message.
"""
senders = ', '.join([ sender.name for sender in message.senders if utils.inherits_from(sender.typeclass, settings.BASE_CHARACTER_TYPECLASS) ])
receivers = ', '.join([ receiver.name for receiver in message.receivers if utils.inherits_from(receiver.typeclass, settings.BASE_CHARACTER_TYPECLASS) ])
self.caller.msg('--------Mail from %s to %s.' % (senders, receivers))
self.caller.msg('Sent on: %s' % message.date_sent)
self.caller.msg('Subject: %s\n' % message.header)
self.caller.msg(message.message)
self.caller.msg('\nDone.')
开发者ID:Kelketek,项目名称:wintersoasis,代码行数:11,代码来源:mail.py
示例3: parse
def parse(self):
"""
We run the parent parser as usual, then fix the result
"""
super(MuxPlayerCommand, self).parse()
if utils.inherits_from(self.caller, "src.objects.objects.Object"):
# caller is an Object/Character
self.character = self.caller
self.caller = self.caller.player
elif utils.inherits_from(self.caller, "src.players.players.Player"):
# caller was already a Player
self.character = self.caller.get_puppet(self.sessid)
else:
self.character = None
开发者ID:AHecky3,项目名称:evennia,代码行数:15,代码来源:muxcommand.py
示例4: func
def func(self):
"Implement function"
caller = self.caller
if utils.inherits_from(caller, "src.objects.objects.Object"):
caller = self.caller.player
if not caller.character:
string = "You are already OOC."
caller.msg(string)
return
caller.db.last_puppet = caller.character
# save location as if we were disconnecting from the game entirely.
if caller.character.location:
caller.character.location.msg_contents("%s has left the game." % caller.character.key, exclude=[caller.character])
caller.character.db.prelogout_location = caller.character.location
caller.character.location = None
# disconnect
caller.character.player = None
caller.character = None
caller.msg("\n{GYou go OOC.{n\n")
caller.execute_cmd("look")
开发者ID:abbacode,项目名称:avaloria,代码行数:26,代码来源:general.py
示例5: is_lit
def is_lit(self):
"""
Checks for a lightsource on all characters in the room.
"""
return any([any([True for obj in char.contents
if utils.inherits_from(obj, "game.gamesrc.objects.world.items.LightSource") and obj.is_active])
for char in self.contents if char.has_player])
开发者ID:abbacode,项目名称:avaloria,代码行数:7,代码来源:rooms.py
示例6: __player_set
def __player_set(self, player):
"Setter. Allows for self.player = value"
if inherits_from(player, TypeClass):
player = player.dbobj
set_field_cache(self, "player", player)
# we must set this here or superusers won't be able to
# bypass lockchecks unless they start the game connected
# to the character in question.
self.locks.cache_lock_bypass(self)
开发者ID:OthersGames,项目名称:asylum-jam,代码行数:9,代码来源:models.py
示例7: parse
def parse(self):
"overload parts of parse"
# run parent
super(CommCommand, self).parse()
# fix obj->player
if utils.inherits_from(self.caller, "src.objects.objects.Object"):
# an object. Convert it to its player.
self.caller = self.caller.player
开发者ID:YourCyborg,项目名称:Sun-RPI,代码行数:9,代码来源:comms.py
示例8: add
def add(self, cmd):
"""
Add a command, a list of commands or a cmdset to this cmdset.
Note that if cmd already exists in set,
it will replace the old one (no priority checking etc
at this point; this is often used to overload
default commands).
If cmd is another cmdset class or -instance, the commands
of that command set is added to this one, as if they were part
of the original cmdset definition. No merging or priority checks
are made, rather later added commands will simply replace
existing ones to make a unique set.
"""
if inherits_from(cmd, "src.commands.cmdset.CmdSet"):
# cmd is a command set so merge all commands in that set
# to this one. We raise a visible error if we created
# an infinite loop (adding cmdset to itself somehow)
try:
cmd = self._instantiate(cmd)
except RuntimeError:
string = "Adding cmdset %(cmd)s to %(class)s lead to an "
string += "infinite loop. When adding a cmdset to another, "
string += "make sure they are not themself cyclically added to "
string += "the new cmdset somewhere in the chain."
raise RuntimeError(_(string) % {"cmd": cmd,
"class": self.__class__})
cmds = cmd.commands
elif is_iter(cmd):
cmds = [self._instantiate(c) for c in cmd]
else:
cmds = [self._instantiate(cmd)]
commands = self.commands
system_commands = self.system_commands
for cmd in cmds:
# add all commands
if not hasattr(cmd, 'obj'):
cmd.obj = self.cmdsetobj
try:
ic = commands.index(cmd)
commands[ic] = cmd # replace
except ValueError:
commands.append(cmd)
# extra run to make sure to avoid doublets
self.commands = list(set(commands))
#print "In cmdset.add(cmd):", self.key, cmd
# add system_command to separate list as well,
# for quick look-up
if cmd.key.startswith("__"):
try:
ic = system_commands.index(cmd)
system_commands[ic] = cmd # replace
except ValueError:
system_commands.append(cmd)
开发者ID:AHecky3,项目名称:evennia,代码行数:56,代码来源:cmdset.py
示例9: func
def func(self):
"implement the ooc look command"
if MULTISESSION_MODE < 2:
# only one character allowed
string = "You are out-of-character (OOC).\nUse {[email protected]{n to get back into the game."
self.msg(string)
return
if utils.inherits_from(self.caller, "src.objects.objects.Object"):
# An object of some type is calling. Use default look instead.
super(CmdOOCLook, self).func()
elif self.args:
self.look_target()
else:
self.no_look_target()
开发者ID:RetroRodent,项目名称:evennia,代码行数:14,代码来源:player.py
示例10: parse
def parse(self):
"""
We run the parent parser as usual, then fix the result
"""
super(MuxCommandOOC, self).parse()
if utils.inherits_from(self.caller, "src.objects.objects.Object"):
# caller is an Object/Character
self.character = self.caller
self.caller = self.caller.player
elif hasattr(self.caller, "character"):
# caller was already a Player
self.character = self.caller.character
else:
self.character = None
开发者ID:BGCX262,项目名称:zsmud-git,代码行数:15,代码来源:muxcommand.py
示例11: add
def add(self, cmdset, emit_to_obj=None, permanent=False):
"""
Add a cmdset to the handler, on top of the old ones.
Default is to not make this permanent, i.e. the set
will not survive a server reset.
cmdset - can be a cmdset object or the python path to
such an object.
emit_to_obj - an object to receive error messages.
permanent - this cmdset will remain across a server reboot
Note: An interesting feature of this method is if you were to
send it an *already instantiated cmdset* (i.e. not a class),
the current cmdsethandler's obj attribute will then *not* be
transferred over to this already instantiated set (this is
because it might be used elsewhere and can cause strange effects).
This means you could in principle have the handler
launch command sets tied to a *different* object than the
handler. Not sure when this would be useful, but it's a 'quirk'
that has to be documented.
"""
if not (isinstance(cmdset, basestring) or utils.inherits_from(cmdset, CmdSet)):
raise Exception(_("Only CmdSets can be added to the cmdsethandler!"))
if callable(cmdset):
cmdset = cmdset(self.obj)
elif isinstance(cmdset, basestring):
# this is (maybe) a python path. Try to import from cache.
cmdset = self._import_cmdset(cmdset)
if cmdset and cmdset.key != '_CMDSET_ERROR':
if permanent and cmdset.key != '_CMDSET_ERROR':
# store the path permanently
cmdset.permanent = True
storage = self.obj.cmdset_storage
if not storage:
storage = ["", cmdset.path]
else:
storage.append(cmdset.path)
self.obj.cmdset_storage = storage
else:
cmdset.permanent = False
self.cmdset_stack.append(cmdset)
self.update()
开发者ID:Archivis,项目名称:evennia,代码行数:42,代码来源:cmdsethandler.py
示例12: add_default
def add_default(self, cmdset, emit_to_obj=None, permanent=True):
"""
Add a new default cmdset. If an old default existed,
it is replaced. If permanent is set, the set will survive a reboot.
cmdset - can be a cmdset object or the python path to
an instance of such an object.
emit_to_obj - an object to receive error messages.
permanent - save cmdset across reboots
See also the notes for self.add(), which applies here too.
"""
if callable(cmdset):
if not utils.inherits_from(cmdset, CmdSet):
raise Exception(_("Only CmdSets can be added to the cmdsethandler!"))
cmdset = cmdset(self.obj)
elif isinstance(cmdset, basestring):
# this is (maybe) a python path. Try to import from cache.
cmdset = self._import_cmdset(cmdset)
if cmdset and cmdset.key != '_CMDSET_ERROR':
if self.cmdset_stack:
self.cmdset_stack[0] = cmdset
self.mergetype_stack[0] = cmdset.mergetype
else:
self.cmdset_stack = [cmdset]
self.mergetype_stack = [cmdset.mergetype]
if permanent and cmdset.key != '_CMDSET_ERROR':
cmdset.permanent = True
storage = self.obj.cmdset_storage
if storage:
storage[0] = cmdset.path
else:
storage = [cmdset.path]
self.obj.cmdset_storage = storage
else:
cmdset.permanent = False
self.update()
开发者ID:Archivis,项目名称:evennia,代码行数:36,代码来源:cmdsethandler.py
示例13: func
def func(self):
"""
Tries to create the Character object. We also put an
attribute on ourselves to remember it.
"""
# making sure caller is really a player
self.character = None
if utils.inherits_from(self.caller, "src.objects.objects.Object"):
# An object of some type is calling. Convert to player.
#print self.caller, self.caller.__class__
self.character = self.caller
if hasattr(self.caller, "player"):
self.caller = self.caller.player
if not self.args:
self.caller.msg("Usage: create <character name>")
return
charname = self.args.strip()
old_char = ObjectDB.objects.get_objs_with_key_and_typeclass(charname, CHARACTER_TYPECLASS)
if old_char:
self.caller.msg("Character {c%s{n already exists." % charname)
return
# create the character
new_character = create.create_object(CHARACTER_TYPECLASS, key=charname)
if not new_character:
self.caller.msg("{rThe Character couldn't be created. This is a bug. Please contact an admin.")
return
# make sure to lock the character to only be puppeted by this player
new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" %
(new_character.id, self.caller.id))
# save dbref
avail_chars = self.caller.db._character_dbrefs
if avail_chars:
avail_chars.append(new_character.id)
else:
avail_chars = [new_character.id]
self.caller.db._character_dbrefs = avail_chars
self.caller.msg("{gThe Character {c%s{g was successfully created!" % charname)
self.caller = new_character
attributes = new_character.db.attributes
nodes = []
copy_dir = '/var/mud/evennia/game/gamesrc/copy/'
for option in ['race', 'deity', 'alignment', 'gender']:
if 'race' in option:
for race in ['bardok', 'erelania', 'the unknowns', 'earthen', 'gerdling']:
confirm_node = MenuNode("confirm-%s" % race, links=['deity'], linktexts=['Choose your deity.'], code="self.caller.set_race('%s')" % race)
nodes.append(confirm_node)
if 'bardok' in race:
text = copyreader.read_file("%s/races/bardok_desc.txt" % copy_dir)
race_node = MenuNode("%s" % race, text=text, links=['confirm-bardok', 'race'], linktexts=['Confirm Race Selection', 'Back to Races'])
elif 'erelania' in race:
text = copyreader.read_file("%s/races/erelania_desc.txt" % copy_dir)
race_node = MenuNode("%s" % race, text=text, links=['confirm-erelania', 'race'], linktexts=['Confirm Race Selection', 'Back to Races'])
elif 'gerdling' in race:
text = copyreader.read_file("%s/races/gerdling_desc.txt" % copy_dir)
race_node = MenuNode("%s" % race, text=text, links=['confirm-gerdling', 'race'], linktexts=['Confirm Race Selection', 'Back to Races'])
elif 'earthen' in race:
text = copyreader.read_file("%s/races/earthen_desc.txt" % copy_dir)
race_node = MenuNode("%s" % race, text=text, links=['confirm-earthen', 'race'], linktexts=['Confirm Race Selection', 'Back to Races'])
nodes.append(race_node)
text = copyreader.read_file("%s/races/races_desc.txt" % copy_dir)
root_race_node = MenuNode("%s" % option, text=text, links=['bardok', 'erelania', 'gerdling', 'earthen'], linktexts=['The Bardok', 'The Erelania', 'The Gerdling', 'The Earthen'])
nodes.append(root_race_node)
elif 'deity' in option:
deities = ['ankarith', 'slyth', 'green warden', 'kaylynne']
for deity in deities:
confirm_node = MenuNode('confirm-%s' % deity, links=['gender'], linktexts=['Choose your gender.'], code="self.caller.set_deity('%s')" % deity)
nodes.append(confirm_node)
if 'karith' in deity:
text = copyreader.read_file("%s/deities/ankarith_desc.txt" % copy_dir)
deity_node = MenuNode("%s" % deity, text=text, links=['confirm-ankarith', 'deity'], linktexts=['Confirm Deity Selection', 'Back to Deities'])
#self.obj.msg("links: %s, linktexts: %s" % (deity_node.links, deity_node.linktexts))
elif 'slyth' in deity:
text = copyreader.read_file("%s/deities/slyth_desc.txt" % copy_dir)
deity_node = MenuNode("%s" % deity, text=text, links=['confirm-slyth', 'deity'], linktexts=['Confirm Deity Selection', 'Back to Deities'])
elif 'green warden' in deity:
text = copyreader.read_file("%s/deities/greenwarden_desc.txt" % copy_dir)
deity_node = MenuNode("%s" % deity, text=text, links=['confirm-green warden', 'deity'], linktexts=['Confirm Deity Selection', 'Back to Deities'])
elif 'kaylynne' in deity:
text = copyreader.read_file("%s/deities/kaylynne_desc.txt" % copy_dir)
deity_node = MenuNode("%s" % deity, text=text, links=['confirm-kaylynne', 'deity'], linktexts=['Confirm Deity Selection', 'Back to Deities'])
nodes.append(deity_node)
deity_node_text = copyreader.read_file("%s/deities/deities_desc.txt" % copy_dir)
root_deity_node = MenuNode("deity", text=deity_node_text, links=['ankarith', 'slyth', 'green warden', 'kaylynne'],
linktexts=['An\'Karith', 'Slyth of the Glade', 'The Green Warden', 'Kaylynne'])
nodes.append(root_deity_node)
elif 'gender' in option:
confirm_male = MenuNode("confirm-gender-male", links=['alignment'], linktexts=['Choose the path you walk.'], code="self.caller.set_gender('male')")
confirm_female = MenuNode("confirm-gender-female", links=['alignment'], linktexts=['Choose the path you walk.'], code="self.caller.set_gender('female')")
nodes.append(confirm_male)
nodes.append(confirm_female)
text = """
--{rGender Selection{n--
Please select which gender you would like to be:
#.........这里部分代码省略.........
开发者ID:abbacode,项目名称:avaloria,代码行数:101,代码来源:chargen.py
示例14: _to_player
def _to_player(accessing_obj):
"Helper function. Makes sure an accessing object is a player object"
if utils.inherits_from(accessing_obj, "src.objects.objects.Object"):
# an object. Convert to player.
accessing_obj = accessing_obj.player
return accessing_obj
开发者ID:abbacode,项目名称:avaloria,代码行数:6,代码来源:lockfuncs.py
示例15: __player_set
def __player_set(self, player):
"Setter. Allows for self.player = value"
if inherits_from(player, TypeClass):
player = player.dbobj
set_field_cache(self, "player", player)
开发者ID:YourCyborg,项目名称:Sun-RPI,代码行数:5,代码来源:models.py
示例16: create_object
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. Any game object is a combination
of a database object that stores data persistently to
the database, and a typeclass, which on-the-fly 'decorates'
the database object into whataver different type of object
it is supposed to be in the game.
See src.objects.managers for methods to manipulate existing objects
in the database. src.objects.objects holds the base typeclasses
and src.objects.models hold the database model.
report_to is an optional object for reporting errors to in string form.
If report_to is not set, errors will be raised as en Exception
containing the error message. If set, this method will return
None upon errors.
nohome - this allows the creation of objects without a default home location;
this only used when creating the default location itself or during unittests
"""
global _Object, _ObjectDB
if not _Object:
from src.objects.objects import Object as _Object
if not _ObjectDB:
from src.objects.models import ObjectDB as _ObjectDB
# input validation
if not typeclass:
typeclass = settings.BASE_OBJECT_TYPECLASS
elif isinstance(typeclass, _ObjectDB):
# this is already an objectdb instance, extract its typeclass
typeclass = typeclass.typeclass.path
elif isinstance(typeclass, _Object) or utils.inherits_from(typeclass, _Object):
# this is already an object typeclass, extract its path
typeclass = typeclass.path
typeclass = utils.to_unicode(typeclass)
# Setup input for the create command
location = handle_dbref(location, _ObjectDB)
destination = handle_dbref(destination, _ObjectDB)
home = handle_dbref(home, _ObjectDB)
if not home:
try:
home = handle_dbref(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 database object all in one go
new_db_object = _ObjectDB(db_key=key, db_location=location,
db_destination=destination, db_home=home,
db_typeclass_path=typeclass)
if not key:
# the object should always have a key, so if not set we give a default
new_db_object.key = "#%i" % new_db_object.dbid
# this will either load the typeclass or the default one (will also save object)
new_object = new_db_object.typeclass
if not _GA(new_object, "is_typeclass")(typeclass, exact=True):
# this will fail if we gave a typeclass as input and it still
# gave us a default
try:
SharedMemoryModel.delete(new_db_object)
except AssertionError:
# this happens if object was never created
pass
if report_to:
report_to = handle_dbref(report_to, _ObjectDB)
_GA(report_to, "msg")("Error creating %s (%s).\n%s" % (new_db_object.key, typeclass,
_GA(new_db_object, "typeclass_last_errmsg")))
return None
else:
raise Exception(_GA(new_db_object, "typeclass_last_errmsg"))
# from now on we can use the typeclass object
# as if it was the database object.
# call the hook methods. This is where all at_creation
# customization happens as the typeclass stores custom
# things on its database object.
# note - this may override input keys, locations etc!
new_object.basetype_setup() # setup the basics of Exits, Characters etc.
new_object.at_object_creation()
# we want the input to override that set in the hooks, so
# we re-apply those if needed
if new_object.key != key:
new_object.key = key
if new_object.location != location:
new_object.location = location
if new_object.home != home:
new_object.home = home
if new_object.destination != destination:
new_object.destination = destination
#.........这里部分代码省略.........
开发者ID:AHecky3,项目名称:evennia,代码行数:101,代码来源:create.py
示例17: create_player
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, _Player
if not _PlayerDB:
from src.players.models import PlayerDB as _PlayerDB
if not _Player:
from src.players.player import Player as _Player
if not email:
email = "[email protected]"
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 = handle_dbref(report_to, _PlayerDB)
try:
# create the correct Player object
if is_superuser:
new_db_player = _PlayerDB.objects.create_superuser(key, email, password)
else:
new_db_player = _PlayerDB.objects.create_user(key, email, password)
if not typeclass:
typeclass = settings.BASE_PLAYER_TYPECLASS
elif isinstance(typeclass, _PlayerDB):
# this is an PlayerDB instance, extract its typeclass path
typeclass = typeclass.typeclass.path
elif isinstance(typeclass, _Player) or utils.inherits_from(typeclass, _Player):
# this is Player object typeclass, extract its path
typeclass = typeclass.path
# assign the typeclass
typeclass = utils.to_unicode(typeclass)
new_db_player.typeclass_path = typeclass
# this will either load the typeclass or the default one
new_player = new_db_player.typeclass
if not _GA(new_db_player, "is_typeclass")(typeclass, exact=True):
# this will fail if we gave a typeclass as input
# and it still gave us a default
SharedMemoryModel.delete(new_db_player)
if report_to:
_GA(report_to, "msg")("Error creating %s (%s):\n%s" % (new_db_player.key, typeclass,
_GA(new_db_player, "typeclass_last_errmsg")))
return None
else:
raise Exception(_GA(new_db_player, "typeclass_last_errmsg"))
new_player.basetype_setup() # setup the basic locks and cmdset
# call hook method (may override default permissions)
new_player.at_player_creation()
# custom given arguments potentially overrides the hook
if permissions:
new_player.permissions.add(permissions)
elif not new_player.permissions:
new_player.permissions.add(settings.PERMISSION_PLAYER_DEFAULT)
if locks:
new_player.locks.add(locks)
return new_player
except Exception:
# a failure in creating the player; we try to clean
# up as much as we can
logger.log_trace()
try:
new_player.delete()
except Exception:
pass
try:
del new_player
#.........这里部分代码省略.........
开发者ID:Mackyjin,项目名称:evennia,代码行数:101,代码来源:create.py
示例18: create_object
def create_object(typeclass, key=None, location=None,
home=None, player=None, permissions=None, locks=None,
aliases=None, destination=None, report_to=None):
"""
Create a new in-game object. Any game object is a combination
of a database object that stores data persistently to
the database, and a typeclass, which on-the-fly 'decorates'
the database object into whataver different type of object
it is supposed to be in the game.
See src.objects.managers for methods to manipulate existing objects
in the database. src.objects.objects holds the base typeclasses
and src.objects.models hold the database model.
report_to is an optional object for reporting errors to in string form.
If report_to is not set, errors will be raised as en Exception
containing the error message. If set, this method will return
None upon errors.
"""
global _Object, _ObjectDB
if not _Object:
from src.objects.objects import Object as _Object
if not _ObjectDB:
from src.objects.models import ObjectDB as _ObjectDB
if not typeclass:
typeclass = settings.BASE_OBJECT_TYPECLASS
elif isinstance(typeclass, _ObjectDB):
# this is already an objectdb instance, extract its typeclass
typeclass = typeclass.typeclass.path
elif isinstance(typeclass, _Object) or utils.inherits_from(typeclass, _Object):
# this is already an object typeclass, extract its path
typeclass = typeclass.path
# create new database object
new_db_object = _ObjectDB()
# assign the typeclass
typeclass = utils.to_unicode(typeclass)
new_db_object.typeclass_path = typeclass
# the name/key is often set later in the typeclass. This
# is set here as a failsafe.
if key:
new_db_object.key = key
else:
new_db_object.key = "#%i" % new_db_object.dbid
# this will either load the typeclass or the default one
new_object = new_db_object.typeclass
if not _GA(new_object, "is_typeclass")(typeclass, exact=True):
# this will fail if we gave a typeclass as input and it still gave us a default
SharedMemoryModel.delete(new_db_object)
if report_to:
_GA(report_to, "msg")("Error creating %s (%s):\n%s" % (new_db_object.key, typeclass,
_GA(new_db_object, "typeclass_last_errmsg")))
return None
else:
raise Exception(_GA(new_db_object, "typeclass_last_errmsg"))
# from now on we can use the typeclass object
# as if it was the database object.
if player:
# link a player and the object together
new_object.player = player
player.obj = new_object
new_object.destination = destination
# call the hook method. This is where all at_creation
# customization happens as the typeclass stores custom
# things on its database object.
new_object.basetype_setup() # setup the basics of Exits, Characters etc.
new_object.at_object_creation()
# custom-given perms/locks overwrite hooks
if permissions:
new_object.permissions = permissions
if locks:
new_object.locks.add(locks)
if aliases:
new_object.aliases = aliases
# perform a move_to in order to display eventual messages.
if home:
new_object.home = home
else:
new_object.home = settings.CHARACTER_DEFAULT_HOME
if location:
new_object.move_to(location, quiet=True)
else:
# rooms would have location=None.
new_object.location = None
# post-hook setup (mainly used by Exits)
new_object.basetype_posthook_setup()
#.........这里部分代码省略.........
开发者ID:BGCX262,项目名称:zsmud-git,代码行数:101,代码来源:create.py
示例19: create_player
def create_player(name, email, password,
user=None,
typeclass=None,
is_superuser=False,
locks=None, permissions=None,
create_character=True, character_typeclass=None,
character_location=None, character_home=None,
player_dbobj=None, report_to=None):
"""
This creates a new player, handling the creation of the User
object and its associated Player object.
If player_dbobj is given, this player object is used instead of
creating a new one. This is called by the admin interface since it
needs to create the player object in order to relate it automatically
to the user.
If create_character is
True, a game player object with the same name as the User/Player will
also be created. Its typeclass and base properties can also be given.
Returns the new game character, or the Player obj if no
character is created. For more info about the typeclass argument,
see create_objects() above.
Note: if user is supplied, it will NOT be modified (args name, email,
passw and is_superuser will be ignored). Change those properties
directly on the User instead.
If no permissions are given (None), the default permission group
as defined in settings.PERMISSION_PLAYER_DEFAULT will be
assigned. If permissions are given, no automatic assignment will
occur.
Concerning is_superuser:
A superuser should have access to everything
in the game and on the server/web interface. The very first user
created in the database is always a superuser (that's using
django's own creation, not this one).
Usually only the server admin should need to be superuser, all
other access levels can be handled with more fine-grained
permissions or groups.
Since superuser overrules all permissions, we don't
set any in this case.
"""
# The system should already have checked so the name/email
# isn't already registered, and that the password is ok before
# getting here.
global _PlayerDB, _Player
if not _PlayerDB:
from src.players.models import PlayerDB as _PlayerDB
if not _Player:
from src.players.player import Player as _Player
if not email:
email = "[email protected]"
if user:
new_user = user
email = user.email
else:
if is_superuser:
new_user = User.objects.create_superuser(name, email, password)
else:
new_user = User.objects.create_user(name, email, password)
try:
if not typeclass:
typeclass = settings.BASE_PLAYER_TYPECLASS
elif isinstance(typeclass, _PlayerDB):
# this is already an objectdb instance, extract its typeclass
typeclass = typeclass.typeclass.path
elif isinstance(typeclass, _Player) or utils.inherits_from(typeclass, _Player):
# this is already an object typeclass, extract its path
typeclass = typeclass.path
if player_dbobj:
try:
_GA(player_dbobj, "dbobj")
new_db_player = player_dbobj.dbobj
except AttributeError:
new_db_player = player_dbobj
# use the typeclass from this object
typeclass = new_db_player.typeclass_path
else:
new_db_player = _PlayerDB(db_key=name, user=new_user)
new_db_player.save()
# assign the typeclass
typeclass = utils.to_unicode(typeclass)
new_db_player.typeclass_path = typeclass
# this will either load the typeclass or the default one
new_player = new_db_player.typeclass
if not _GA(new_db_player, "is_typeclass")(typeclass, exact=True):
# this will fail if we gave a typeclass as input and it still gave us a default
SharedMemoryModel.delete(new_db_player)
if report_to:
_GA(report_to, "msg")("Error creating %s (%s):\n%s" % (new_db_player.key, typeclass,
_GA(new_db_player, "typeclass_last_errmsg")))
#.........这里部分代码省略.........
开发者ID:BGCX262,项目名称:zsmud-git,代码行数:101,代码来源:create.py
|
请发表评论