- u"""An element of the universe."""
- def __init__(self, key, universe, filename=None):
- u"""Set up a new element."""
- import data, os.path
-
- # keep track of our key name
- self.key = key
-
- # keep track of what universe it's loading into
- self.universe = universe
-
- # clone attributes if this is replacing another element
- if self.key in self.universe.contents:
- old_element = self.universe.contents[self.key]
- for attribute in vars(old_element).keys():
- exec(u"self." + attribute + u" = old_element." + attribute)
- if self.owner: self.owner.avatar = self
-
- # i guess this is a new element then
- else:
-
- # not owned by a user by default (used for avatars)
- self.owner = None
-
- # no contents in here by default
- self.contents = {}
-
- # parse out appropriate category and subkey names, add to list
- if self.key.find(u":") > 0:
- self.category, self.subkey = self.key.split(u":", 1)
- else:
- self.category = u"other"
- self.subkey = self.key
- if not self.category in self.universe.categories:
- self.category = u"other"
- self.subkey = self.key
-
- # get an appropriate filename for the origin
- if not filename:
- filename = self.universe.default_origins[self.category]
- if not os.path.isabs(filename):
- filename = os.path.abspath(filename)
-
- # add the file if it doesn't exist yet
- if not filename in self.universe.files:
- data.DataFile(filename, self.universe)
-
- # record or reset a pointer to the origin file
- self.origin = self.universe.files[filename]
-
- # add a data section to the origin if necessary
- if not self.origin.data.has_section(self.key):
- self.origin.data.add_section(self.key)
-
- # add or replace this element in the universe
- self.universe.contents[self.key] = self
- self.universe.categories[self.category][self.subkey] = self
-
- def reload(self):
- u"""Create a new element and replace this one."""
- new_element = Element(self.key, self.universe, self.origin.filename)
- del(self)
- def destroy(self):
- u"""Remove an element from the universe and destroy it."""
- self.origin.data.remove_section(self.key)
- del self.universe.categories[self.category][self.subkey]
- del self.universe.contents[self.key]
- del self
- def facets(self):
- u"""Return a list of non-inherited facets for this element."""
- if self.key in self.origin.data.sections():
- return self.origin.data.options(self.key)
- else: return []
- def has_facet(self, facet):
- u"""Return whether the non-inherited facet exists."""
- return facet in self.facets()
- def remove_facet(self, facet):
- u"""Remove a facet from the element."""
- if self.has_facet(facet):
- self.origin.data.remove_option(self.key, facet)
- self.origin.modified = True
- def ancestry(self):
- u"""Return a list of the element's inheritance lineage."""
- if self.has_facet(u"inherit"):
- ancestry = self.getlist(u"inherit")
- for parent in ancestry[:]:
- ancestors = self.universe.contents[parent].ancestry()
- for ancestor in ancestors:
- if ancestor not in ancestry: ancestry.append(ancestor)
- return ancestry
- else: return []
- def get(self, facet, default=None):
- u"""Retrieve values."""
- if default is None: default = u""
- if self.origin.data.has_option(self.key, facet):
- raw_data = self.origin.data.get(self.key, facet)
- if raw_data.startswith(u"u\"") or raw_data.startswith(u"u'"):
- raw_data = raw_data[1:]
- raw_data.strip(u"\"'")
- if type(raw_data) == str: return unicode(raw_data, "utf-8")
- else: return raw_data
- elif self.has_facet(u"inherit"):
- for ancestor in self.ancestry():
- if self.universe.contents[ancestor].has_facet(facet):
- return self.universe.contents[ancestor].get(facet)
- else: return default
- def getboolean(self, facet, default=None):
- u"""Retrieve values as boolean type."""
- if default is None: default=False
- if self.origin.data.has_option(self.key, facet):
- return self.origin.data.getboolean(self.key, facet)
- elif self.has_facet(u"inherit"):
- for ancestor in self.ancestry():
- if self.universe.contents[ancestor].has_facet(facet):
- return self.universe.contents[ancestor].getboolean(facet)
- else: return default
- def getint(self, facet, default=None):
- u"""Return values as int/long type."""
- if default is None: default = 0
- if self.origin.data.has_option(self.key, facet):
- return self.origin.data.getint(self.key, facet)
- elif self.has_facet(u"inherit"):
- for ancestor in self.ancestry():
- if self.universe.contents[ancestor].has_facet(facet):
- return self.universe.contents[ancestor].getint(facet)
- else: return default
- def getfloat(self, facet, default=None):
- u"""Return values as float type."""
- if default is None: default = 0.0
- if self.origin.data.has_option(self.key, facet):
- return self.origin.data.getfloat(self.key, facet)
- elif self.has_facet(u"inherit"):
- for ancestor in self.ancestry():
- if self.universe.contents[ancestor].has_facet(facet):
- return self.universe.contents[ancestor].getfloat(facet)
- else: return default
- def getlist(self, facet, default=None):
- u"""Return values as list type."""
- import data
- if default is None: default = []
- value = self.get(facet)
- if value: return data.makelist(value)
- else: return default
- def getdict(self, facet, default=None):
- u"""Return values as dict type."""
- import data
- if default is None: default = {}
- value = self.get(facet)
- if value: return data.makedict(value)
- else: return default
- def set(self, facet, value):
- u"""Set values."""
- if not self.has_facet(facet) or not self.get(facet) == value:
- if type(value) is long: value = unicode(value)
- elif not type(value) is unicode: value = repr(value)
- self.origin.data.set(self.key, facet, value)
- self.origin.modified = True
- def append(self, facet, value):
- u"""Append value tp a list."""
- if type(value) is long: value = unicode(value)
- elif not type(value) is unicode: value = repr(value)
- newlist = self.getlist(facet)
- newlist.append(value)
- self.set(facet, newlist)
-
- def new_event(self, action, when=None):
- u"""Create, attach and enqueue an event element."""
-
- # if when isn't specified, that means now
- if not when: when = self.universe.get_time()
-
- # events are elements themselves
- event = Element(u"event:" + self.key + u":" + counter)
-
- def send(
- self,
- message,
- eol=u"$(eol)",
- raw=False,
- flush=False,
- add_prompt=True,
- just_prompt=False,
- add_terminator=False,
- prepend_padding=True
- ):
- u"""Convenience method to pass messages to an owner."""
- if self.owner:
- self.owner.send(
- message,
- eol,
- raw,
- flush,
- add_prompt,
- just_prompt,
- add_terminator,
- prepend_padding
- )
-
- def can_run(self, command):
- u"""Check if the user can run this command object."""
-
- # has to be in the commands category
- if command not in self.universe.categories[u"command"].values():
- result = False
-
- # avatars of administrators can run any command
- elif self.owner and self.owner.account.getboolean(u"administrator"):
- result = True
-
- # everyone can run non-administrative commands
- elif not command.getboolean(u"administrative"):
- result = True
-
- # otherwise the command cannot be run by this actor
- else:
- result = False
-
- # pass back the result
- return result
-
- def update_location(self):
- u"""Make sure the location's contents contain this element."""
- location = self.get(u"location")
- if location in self.universe.contents:
- self.universe.contents[location].contents[self.key] = self
- def clean_contents(self):
- u"""Make sure the element's contents aren't bogus."""
- for element in self.contents.values():
- if element.get(u"location") != self.key:
- del self.contents[element.key]
- def go_to(self, location):
- u"""Relocate the element to a specific location."""
- current = self.get(u"location")
- if current and self.key in self.universe.contents[current].contents:
- del universe.contents[current].contents[self.key]
- if location in self.universe.contents: self.set(u"location", location)
- self.universe.contents[location].contents[self.key] = self
- self.look_at(location)
- def go_home(self):
- u"""Relocate the element to its default location."""
- self.go_to(self.get(u"default_location"))
- self.echo_to_location(
- u"You suddenly realize that " + self.get(u"name") + u" is here."
- )
- def move_direction(self, direction):
- u"""Relocate the element in a specified direction."""
- self.echo_to_location(
- self.get(
- u"name"
- ) + u" exits " + self.universe.categories[
- u"internal"
- ][
- u"directions"
- ].getdict(
- direction
- )[
- u"exit"
- ] + u"."
- )
- self.send(
- u"You exit " + self.universe.categories[
- u"internal"
- ][
- u"directions"
- ].getdict(
- direction
- )[
- u"exit"
- ] + u".",
- add_prompt=False
- )
- self.go_to(
- self.universe.contents[self.get(u"location")].link_neighbor(direction)
- )
- self.echo_to_location(
- self.get(
- u"name"
- ) + u" arrives from " + self.universe.categories[
- u"internal"
- ][
- u"directions"
- ].getdict(
- direction
- )[
- u"enter"
- ] + u"."
- )
- def look_at(self, key):
- u"""Show an element to another element."""
- if self.owner:
- element = self.universe.contents[key]
- message = u""
- name = element.get(u"name")
- if name: message += u"$(cyn)" + name + u"$(nrm)$(eol)"
- description = element.get(u"description")
- if description: message += description + u"$(eol)"
- portal_list = element.portals().keys()
- if portal_list:
- portal_list.sort()
- message += u"$(cyn)[ Exits: " + u", ".join(
- portal_list
- ) + u" ]$(nrm)$(eol)"
- for element in self.universe.contents[
- self.get(u"location")
- ].contents.values():
- if element.getboolean(u"is_actor") and element is not self:
- message += u"$(yel)" + element.get(
- u"name"
- ) + u" is here.$(nrm)$(eol)"
- elif element is not self:
- message += u"$(grn)" + element.get(
- u"impression"
- ) + u"$(nrm)$(eol)"
- self.send(message)
- def portals(self):
- u"""Map the portal directions for a room to neighbors."""
- import re
- portals = {}
- if re.match(u"""^location:-?\d+,-?\d+,-?\d+$""", self.key):
- coordinates = [(int(x)) for x in self.key.split(u":")[1].split(u",")]
- directions = self.universe.categories[u"internal"][u"directions"]
- offsets = dict(
- [
- (
- x, directions.getdict(x)[u"vector"]
- ) for x in directions.facets()
- ]
- )
- for portal in self.getlist(u"gridlinks"):
- adjacent = map(lambda c,o: c+o, coordinates, offsets[portal])
- neighbor = u"location:" + u",".join(
- [(unicode(x)) for x in adjacent]
+
+ """An element of the universe."""
+
+ def __init__(self, key, universe, filename=None):
+ """Set up a new element."""
+
+ # keep track of our key name
+ self.key = key
+
+ # keep track of what universe it's loading into
+ self.universe = universe
+
+ # clone attributes if this is replacing another element
+ if self.key in self.universe.contents:
+ old_element = self.universe.contents[self.key]
+ for attribute in vars(old_element).keys():
+ exec("self." + attribute + " = old_element." + attribute)
+ if self.owner:
+ self.owner.avatar = self
+
+ # i guess this is a new element then
+ else:
+
+ # not owned by a user by default (used for avatars)
+ self.owner = None
+
+ # no contents in here by default
+ self.contents = {}
+
+ # parse out appropriate category and subkey names, add to list
+ if self.key.find(":") > 0:
+ self.category, self.subkey = self.key.split(":", 1)
+ else:
+ self.category = "other"
+ self.subkey = self.key
+ if self.category not in self.universe.categories:
+ self.category = "other"
+ self.subkey = self.key
+
+ # get an appropriate filename for the origin
+ if not filename:
+ filename = self.universe.default_origins[self.category]
+ if not os.path.isabs(filename):
+ filename = os.path.abspath(filename)
+
+ # add the file if it doesn't exist yet
+ if filename not in self.universe.files:
+ mudpy.data.DataFile(filename, self.universe)
+
+ # record or reset a pointer to the origin file
+ self.origin = self.universe.files[filename]
+
+ # add a data section to the origin if necessary
+ # TODO(fungi): remove this indirection after the YAML transition
+ if self.origin._format == "yaml":
+ if self.key not in self.origin.data:
+ self.origin.data[self.key] = {}
+ else:
+ if not self.origin.data.has_section(self.key):
+ self.origin.data.add_section(self.key)
+
+ # add or replace this element in the universe
+ self.universe.contents[self.key] = self
+ self.universe.categories[self.category][self.subkey] = self
+
+ def reload(self):
+ """Create a new element and replace this one."""
+ Element(self.key, self.universe, self.origin.filename)
+ del(self)
+
+ def destroy(self):
+ """Remove an element from the universe and destroy it."""
+ self.origin.data.remove_section(self.key)
+ del self.universe.categories[self.category][self.subkey]
+ del self.universe.contents[self.key]
+ del self
+
+ def facets(self):
+ """Return a list of non-inherited facets for this element."""
+ # TODO(fungi): remove this indirection after the YAML transition
+ if self.origin._format == "yaml":
+ try:
+ return self.origin.data[self.key].keys()
+ except (AttributeError, KeyError):
+ return []
+ else:
+ if self.key in self.origin.data.sections():
+ return self.origin.data.options(self.key)
+ else:
+ return []
+
+ def has_facet(self, facet):
+ """Return whether the non-inherited facet exists."""
+ return facet in self.facets()
+
+ def remove_facet(self, facet):
+ """Remove a facet from the element."""
+ if self.has_facet(facet):
+ self.origin.data.remove_option(self.key, facet)
+ self.origin.modified = True
+
+ def ancestry(self):
+ """Return a list of the element's inheritance lineage."""
+ if self.has_facet("inherit"):
+ ancestry = self.getlist("inherit")
+ for parent in ancestry[:]:
+ ancestors = self.universe.contents[parent].ancestry()
+ for ancestor in ancestors:
+ if ancestor not in ancestry:
+ ancestry.append(ancestor)
+ return ancestry
+ else:
+ return []
+
+ def get(self, facet, default=None):
+ """Retrieve values."""
+ if default is None:
+ default = ""
+ # TODO(fungi): remove this indirection after the YAML transition
+ if self.origin._format == "yaml":
+ try:
+ return self.origin.data[self.key][facet]
+ except (KeyError, TypeError):
+ pass
+ if self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if self.universe.contents[ancestor].has_facet(facet):
+ return self.universe.contents[ancestor].get(facet)
+ else:
+ return default
+ else:
+ if self.origin.data.has_option(self.key, facet):
+ raw_data = self.origin.data.get(self.key, facet)
+ if raw_data.startswith("u\"") or raw_data.startswith("u'"):
+ raw_data = raw_data[1:]
+ raw_data.strip("\"'")
+ return raw_data
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if self.universe.contents[ancestor].has_facet(facet):
+ return self.universe.contents[ancestor].get(facet)
+ else:
+ return default
+
+ def getboolean(self, facet, default=None):
+ """Retrieve values as boolean type."""
+ if default is None:
+ default = False
+ # TODO(fungi): remove this indirection after the YAML transition
+ if self.origin._format == "yaml":
+ try:
+ return bool(self.origin.data[self.key][facet])
+ except KeyError:
+ pass
+ for ancestor in self.ancestry():
+ try:
+ return self.universe.contents[ancestor].getboolean(facet)
+ except KeyError:
+ pass
+ return default
+ else:
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.getboolean(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if self.universe.contents[ancestor].has_facet(facet):
+ return self.universe.contents[ancestor].getboolean(
+ facet)
+ else:
+ return default
+
+ def getint(self, facet, default=None):
+ """Return values as int type."""
+ if default is None:
+ default = 0
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.getint(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if self.universe.contents[ancestor].has_facet(facet):
+ return self.universe.contents[ancestor].getint(facet)
+ else:
+ return default
+
+ def getfloat(self, facet, default=None):
+ """Return values as float type."""
+ if default is None:
+ default = 0.0
+ if self.origin.data.has_option(self.key, facet):
+ return self.origin.data.getfloat(self.key, facet)
+ elif self.has_facet("inherit"):
+ for ancestor in self.ancestry():
+ if self.universe.contents[ancestor].has_facet(facet):
+ return self.universe.contents[ancestor].getfloat(facet)
+ else:
+ return default
+
+ def getlist(self, facet, default=None):
+ """Return values as list type."""
+ if default is None:
+ default = []
+ value = self.get(facet)
+ if value:
+ return mudpy.data.makelist(value)
+ else:
+ return default
+
+ def getdict(self, facet, default=None):
+ """Return values as dict type."""
+ if default is None:
+ default = {}
+ value = self.get(facet)
+ if value:
+ return mudpy.data.makedict(value)
+ else:
+ return default
+
+ def set(self, facet, value):
+ """Set values."""
+ if not self.has_facet(facet) or not self.get(facet) == value:
+ if not type(value) is str:
+ value = repr(value)
+ self.origin.data.set(self.key, facet, value)
+ self.origin.modified = True
+
+ def append(self, facet, value):
+ """Append value to a list."""
+ if not type(value) is str:
+ value = repr(value)
+ newlist = self.getlist(facet)
+ newlist.append(value)
+ self.set(facet, newlist)
+
+ def send(
+ self,
+ message,
+ eol="$(eol)",
+ raw=False,
+ flush=False,
+ add_prompt=True,
+ just_prompt=False,
+ add_terminator=False,
+ prepend_padding=True
+ ):
+ """Convenience method to pass messages to an owner."""
+ if self.owner:
+ self.owner.send(
+ message,
+ eol,
+ raw,
+ flush,
+ add_prompt,
+ just_prompt,
+ add_terminator,
+ prepend_padding
+ )
+
+ def can_run(self, command):
+ """Check if the user can run this command object."""
+
+ # has to be in the commands category
+ if command not in self.universe.categories["command"].values():
+ result = False
+
+ # avatars of administrators can run any command
+ elif self.owner and self.owner.account.getboolean("administrator"):
+ result = True
+
+ # everyone can run non-administrative commands
+ elif not command.getboolean("administrative"):
+ result = True
+
+ # otherwise the command cannot be run by this actor
+ else:
+ result = False
+
+ # pass back the result
+ return result
+
+ def update_location(self):
+ """Make sure the location's contents contain this element."""
+ area = self.get("location")
+ if area in self.universe.contents:
+ self.universe.contents[area].contents[self.key] = self
+
+ def clean_contents(self):
+ """Make sure the element's contents aren't bogus."""
+ for element in self.contents.values():
+ if element.get("location") != self.key:
+ del self.contents[element.key]
+
+ def go_to(self, area):
+ """Relocate the element to a specific area."""
+ current = self.get("location")
+ if current and self.key in self.universe.contents[current].contents:
+ del universe.contents[current].contents[self.key]
+ if area in self.universe.contents:
+ self.set("location", area)
+ self.universe.contents[area].contents[self.key] = self
+ self.look_at(area)
+
+ def go_home(self):
+ """Relocate the element to its default location."""
+ self.go_to(self.get("default_location"))
+ self.echo_to_location(
+ "You suddenly realize that " + self.get("name") + " is here."
+ )
+
+ def move_direction(self, direction):
+ """Relocate the element in a specified direction."""
+ self.echo_to_location(
+ self.get(
+ "name"
+ ) + " exits " + self.universe.categories[
+ "internal"
+ ][
+ "directions"
+ ].getdict(
+ direction
+ )[
+ "exit"
+ ] + "."
+ )
+ self.send(
+ "You exit " + self.universe.categories[
+ "internal"
+ ][
+ "directions"
+ ].getdict(
+ direction
+ )[
+ "exit"
+ ] + ".",
+ add_prompt=False
+ )
+ self.go_to(
+ self.universe.contents[
+ self.get("location")].link_neighbor(direction)
+ )
+ self.echo_to_location(
+ self.get(
+ "name"
+ ) + " arrives from " + self.universe.categories[
+ "internal"
+ ][
+ "directions"
+ ].getdict(
+ direction
+ )[
+ "enter"
+ ] + "."
+ )
+
+ def look_at(self, key):
+ """Show an element to another element."""
+ if self.owner:
+ element = self.universe.contents[key]
+ message = ""
+ name = element.get("name")
+ if name:
+ message += "$(cyn)" + name + "$(nrm)$(eol)"
+ description = element.get("description")
+ if description:
+ message += description + "$(eol)"
+ portal_list = list(element.portals().keys())
+ if portal_list:
+ portal_list.sort()
+ message += "$(cyn)[ Exits: " + ", ".join(
+ portal_list
+ ) + " ]$(nrm)$(eol)"
+ for element in self.universe.contents[
+ self.get("location")
+ ].contents.values():
+ if element.getboolean("is_actor") and element is not self:
+ message += "$(yel)" + element.get(
+ "name"
+ ) + " is here.$(nrm)$(eol)"
+ elif element is not self:
+ message += "$(grn)" + element.get(
+ "impression"
+ ) + "$(nrm)$(eol)"
+ self.send(message)
+
+ def portals(self):
+ """Map the portal directions for an area to neighbors."""
+ portals = {}
+ if re.match("""^area:-?\d+,-?\d+,-?\d+$""", self.key):
+ coordinates = [(int(x))
+ for x in self.key.split(":")[1].split(",")]
+ directions = self.universe.categories["internal"]["directions"]
+ offsets = dict(
+ [
+ (
+ x, directions.getdict(x)["vector"]
+ ) for x in directions.facets()
+ ]