Example #1
0
 def at_object_receive(self, character, source_location):
     """
     This hook is called by the engine whenever the player is moved
     into this room.
     """
     if character.has_account:
         # we only run this if the entered object is indeed a player object.
         # check so our east/west exits are correctly defined.
         wexit = search_object(self.db.west_exit)
         eexit = search_object(self.db.east_exit)
         fexit = search_object(self.db.fall_exit)
         if not (wexit and eexit and fexit):
             character.msg(
                 "The bridge's exits are not properly configured. "
                 "Contact an admin. Forcing west-end placement."
             )
             character.db.tutorial_bridge_position = 0
             return
         if source_location == eexit[0]:
             # we assume we enter from the same room we will exit to
             character.db.tutorial_bridge_position = 4
         else:
             # if not from the east, then from the west!
             character.db.tutorial_bridge_position = 0
         character.execute_cmd("look")
Example #2
0
    def _spawnRooms_exits(self):
        if self.exits_created:
            print("Exits already created!")
        else:
            for vnum, room in self.rooms.items():
                for exitDir, exitData in room['exits'].items():
                    evid = "#" + str(self.room_translate[vnum])
                    try:
                        loc = search_object(evid)[0]
                    except:
                        loc = search_object(room['name'])[0]

                    try:
                        evdestid = "#" + str(
                            self.room_translate[exitData['dest']])
                        dest = search_object(evdestid)[0]
                        newexit = create_object(
                            typeclass="typeclasses.exits.LegacyExit",
                            key=exitDir,
                            location=loc,
                            destination=dest)
                        newexit.aliases.add(DIRALIAS[exitDir])
                        newexit.tags.add(room['area'], category='area')
                        newexit.db.area = room['area']
                    except:
                        print(room['area'] + ": Exit " + exitDir + " in " +
                              str(evid) + " skipped - vloc " +
                              str(exitData['dest']) + " not found.")
                        continue
            self.exits_created = True
Example #3
0
    def display(self, show_owner=False):
        if show_owner:
            owner = evennia.search_object(searchdata=self.db_owner)
        else:
            owner = []
        origin = evennia.search_object(searchdata=self.db_origin)
        if owner:
            owner = owner[0]
        if origin:
            origin = origin[0]

        return "{} | {} {} for {} | {}" \
               "".format(self.db_date_created, self.db_value, self.db_currency,
                         self.db_reason, self.db_accrued)
Example #4
0
    def do_attack(self, *args, **kwargs):
        """
        Called regularly when in attacking mode. In attacking mode
        the mob will bring its weapons to bear on any targets
        in the room.
        """
        if random.random() < 0.01 and self.db.irregular_msgs:
            self.location.msg_contents(random.choice(self.db.irregular_msgs))
        # first make sure we have a target
        target = self._find_target(self.location)
        if not target:
            # no target, start looking for one
            self.start_hunting()
            return

        # we use the same attack commands as defined in
        # tutorial_world.objects.Weapon, assuming that
        # the mob is given a Weapon to attack with.
        attack_cmd = random.choice(("thrust", "pierce", "stab", "slash", "chop"))
        self.execute_cmd("%s %s" % (attack_cmd, target))

        # analyze the current state
        if target.db.health <= 0:
            # we reduced the target to <= 0 health. Move them to the
            # defeated room
            target.msg(self.db.defeat_msg)
            self.location.msg_contents(self.db.defeat_msg_room % target.key, exclude=target)
            send_defeated_to = search_object(self.db.send_defeated_to)
            if send_defeated_to:
                target.move_to(send_defeated_to[0], quiet=True)
            else:
                logger.log_err("Mob: mob.db.send_defeated_to not found: %s" % self.db.send_defeated_to)
Example #5
0
    def func(self):
        ch = self.caller
        args = self.args.strip().split()
        obj = ch.ndb._zedit.obj
        if not args:
            attrs = self.valid_zone_attributes.copy()
            keywords = "|n\n*|c".join(attrs)
            ch.msg(
                f'You must provide one of the valid keywords.\n*|c{keywords}')
            return

        keyword = args[0].lower()
        set_str = f"{keyword} set"
        if keyword in ('name', 'reset_msg'):
            if len(args) == 1:
                ch.msg("Must supply name for zone")
                return

            joiner = " " if keyword != 'name' else "_"
            obj[keyword] = f"{joiner}".join(args[1:]).strip()
            ch.msg(set_str)
            return
        elif match_string(keyword, 'builders'):
            if len(args) == 1:
                ch.msg("Supply builder names by spaces")
                return
            builders = args[1:]
            if 'clear' in builders:
                ch.msg("clearing all builders")
                obj['builders'].clear()
                return

            for builder in builders:

                builder = evennia.search_object(
                    builder, typeclass='typeclasses.characters.Character')
                if not builder or not is_pc(builder[0]):
                    ch.msg("no one like that exists")
                    continue

                builder = builder[0]
                if not is_builder(builder):
                    ch.msg(
                        f"{builder.name.capitalize()} is not at least lvl {BUILDER_LVL}"
                    )
                    return

                if builder.name not in obj['builders']:
                    obj['builders'].append(builder.name)

                    ch.msg(f"adding `{builder.name.capitalize()}` as builder")
                else:
                    obj['builders'].remove(builder.name)
                    ch.msg(
                        f"removing `{builder.name.capitalize()}` as builder")
            return

        else:
            ch.msg("That isn't a valid keyword")
            return
Example #6
0
    def _reparse(self):
        """Check args and parse a little more tightly"""
        if self.args:
            if self.lhs:
                self.lhs_target, self.lhs_text = self._parse_left()
                self.action = self.lhs_text
                self.bucket_name = self.lhs_target

            if self.rhs:
                self.rhs_target, self.rhs_text = self._parse_right()
                self.character = self.rhs_target
            else:
                self.character = self.lhs_target

        else:
            self.bucket_name = False
            self.action = False

        # set our bucket instance
        if self.bucket_name:
            self._assign_bucket(self.bucket_name)

        # validate our character object
        try:
            char_obj = ev.search_object(self.character).first()
            if ju.ischaracter(char_obj):
                self.character = char_obj
        except AttributeError:
            pass

        # Don't do multiple switch operations - this will get confusing
        if self.switches:
            self.switch = self.switches[0].lower()
        else:
            self.switch = False
Example #7
0
    def at_after_move(self, source_location):
        #        super().at_after_move(source_location)

        # Bring bound characters with you on move
        possessions = self.contents

        ligature = False
        # Make sure that caller is holding a ligature
        for p in possessions:
            if p.db.tenētur and p.typename == 'Ligātūra':
                ligature = p

        if ligature:
            if ligature.db.ligāns:
                #                bound_entity = Persōna.objects.get(id=ligature.db.ligāns[1:])
                #                bound_entity = Persōna.objects.get(id=ligature.db.ligāns[1:])
                bound_entity = search_object(ligature.db.ligāns)[0]
                if bound_entity != self:
                    bound_entity.move_to(self.location)

        if self.db.ligāta:
            loose_ligature = None
            stuff = source_location.contents
            for s in stuff:
                if s.dbref == self.db.ligāta:
                    loose_ligature = s

            if loose_ligature:
                loose_ligature.move_to(self.location)

        if self.db.pv:
            prompt = f"|wVīta: {self.db.pv['nunc']}/{self.db.pv['max']}"
Example #8
0
 def at_object_receive(self, character, source_location):
     """
     This hook is called by the engine whenever the player is moved into
     this room.
     """
     if not character.has_player:
         # only act on player characters.
         return
     # determine if the puzzle is a success or not
     is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value)
     teleport_to = self.db.success_teleport_to if is_success else self.db.failure_teleport_to
     # note that this returns a list
     results = search_object(teleport_to)
     if not results or len(results) > 1:
         # we cannot move anywhere since no valid target was found.
         character.msg("no valid teleport target for %s was found." % teleport_to)
         return
     if character.is_superuser:
         # superusers don't get teleported
         character.msg("Superuser block: You would have been teleported to %s." % results[0])
         return
     # perform the teleport
     if is_success:
         character.msg(self.db.success_teleport_msg)
     else:
         character.msg(self.db.failure_teleport_msg)
     # teleport quietly to the new place
     character.move_to(results[0], quiet=True, move_hooks=False)
     # we have to call this manually since we turn off move_hooks
     # - this is necessary to make the target dark room aware of an
     # already carried light.
     results[0].at_object_receive(character, self)
Example #9
0
    def do_attack(self, *args, **kwargs):
        """
        Called regularly when in attacking mode. In attacking mode
        the mob will bring its weapons to bear on any targets
        in the room.
        """
        if random.random() < 0.01 and self.db.irregular_msgs:
            self.location.msg_contents(random.choice(self.db.irregular_msgs))
        # first make sure we have a target
        target = self._find_target(self.location)
        if not target:
            # no target, start looking for one
            self.start_hunting()
            return

        # we use the same attack commands as defined in
        # tutorial_world.objects.Weapon, assuming that
        # the mob is given a Weapon to attack with.
        attack_cmd = random.choice(
            ("thrust", "pierce", "stab", "slash", "chop"))
        self.execute_cmd("%s %s" % (attack_cmd, target))

        # analyze the current state
        if target.db.health <= 0:
            # we reduced the target to <= 0 health. Move them to the
            # defeated room
            target.msg(self.db.defeat_msg)
            self.location.msg_contents(self.db.defeat_msg_room % target.key,
                                       exclude=target)
            send_defeated_to = search_object(self.db.send_defeated_to)
            if send_defeated_to:
                target.move_to(send_defeated_to[0], quiet=True)
            else:
                logger.log_err("Mob: mob.db.send_defeated_to not found: %s" %
                               self.db.send_defeated_to)
Example #10
0
 def func(self):
     roles = [
         "Artificial Intelligence",
         "Chef",
         "Chemist",
         "Doctor",
         "Engineer",
         "Horticulturist",
         "Port Manager"
     ]
     enabled_roles = [
         False,
         False,
         False,
         False,
         False,
         True,
         False
     ]
     # try:
     index = int(self.args.strip()) - 1
     if index >= 0:
         if enabled_roles[index]:
             role = " the " + roles[index]
             self.caller.db.role = role
             self.caller.msg("You have become a {}!".format(roles[index].lower()))
             if index == 5:
                 hydro_room = search_object("Hydroponics")
                 self.caller.move_to(hydro_room[0])
         else:
             self.caller.msg("That class is still in development and can't be played yet.")
     else:
         self.caller.msg("That's not a valid number!")
Example #11
0
    def func(self):
        "Looking around, including a chance to fall."
        caller = self.caller
        bridge_position = self.caller.db.tutorial_bridge_position
        # this command is defined on the room, so we get it through self.obj
        location = self.obj
        # randomize the look-echo
        message = "{c%s{n\n%s\n%s" % (location.key,
                                      BRIDGE_POS_MESSAGES[bridge_position],
                                      random.choice(BRIDGE_MOODS))

        chars = [obj for obj in self.obj.contents_get(exclude=caller) if obj.has_player]
        if chars:
            # we create the You see: message manually here
            message += "\n You see: %s" % ", ".join("{c%s{n" % char.key for char in chars)
        self.caller.msg(message)

        # there is a chance that we fall if we are on the western or central
        # part of the bridge.
        if bridge_position < 3 and random.random() < 0.05 and not self.caller.is_superuser:
            # we fall 5% of time.
            fall_exit = search_object(self.obj.db.fall_exit)
            if fall_exit:
                self.caller.msg("{r%s{n" % FALL_MESSAGE)
                self.caller.move_to(fall_exit[0], quiet=True)
                # inform others on the bridge
                self.obj.msg_contents("A plank gives way under %s's feet and " \
                                      "they fall from the bridge!" % self.caller.key)
Example #12
0
    def do_patrol(self, *args, **kwargs):
        """
        Called repeatedly during patrolling mode.  In this mode, the
        mob scans its surroundings and randomly chooses a viable exit.
        One should lock exits with the traverse:has_player() lock in
        order to block the mob from moving outside its area while
        allowing player-controlled characters to move normally.
        """
        if random.random() < 0.01 and self.db.irregular_msgs:
            self.location.msg_contents(random.choice(self.db.irregular_msgs))
        if self.db.aggressive:
            # first check if there are any targets in the room.
            target = self._find_target(self.location)
            if target:
                self.start_attacking()
                return
        # no target found, look for an exit.
        #exits = [exi for exi in self.location.exits
        #         if exi.access(self, "traverse")]
        exitnames = ["Sudikoff Hall","Kemeny Hall","Robinson Hall"]            # allowed rooms to exit to/enter
        exitname = random.choice(exitnames)                                    # randomly pick an exit
        exits = search_object(exitname, typeclass='typeclasses.rooms.Room')[0] # find room with exitname

        if exits:
            # move there.
            self.move_to(exits)
        else:
            # no exits! teleport to home to get away.
            self.move_to(self.home)
Example #13
0
    def func(self):
        ch = self.caller
        cur_room = ch.location
        exit = cur_room.db.exits[self.key]
        if exit < 0:
            ch.msg(_ERR_MOVEMENT)
            return

        # double check to make sure destination room actually exists
        room = search_object(str(exit), typeclass=Room)
        if not room:
            logger.log_errmsg(
                "Attempting to move to a valid exit vnum, but room doesn't exist"
            )
            ch.msg(_ERR_MOVEMENT)
            return
        room = room[0]

        # special condition if ch is in redit
        if ch.ndb._redit:
            ch.ndb._redit.__init__(ch, exit)

        # announce to the contents in rooms
        act(f"$n leaves {self.key}", True, True, ch, None, None,
            Announce.ToRoom)
        # valid, lets move
        ch.move_to(room)
        act(f"$n arrives", True, True, ch, None, None, Announce.ToRoom)
Example #14
0
    def func(self):
        "Looking around, including a chance to fall."
        caller = self.caller
        bridge_position = self.caller.db.tutorial_bridge_position
        # this command is defined on the room, so we get it through self.obj
        location = self.obj
        # randomize the look-echo
        message = "{c%s{n\n%s\n%s" % (location.key,
                                      BRIDGE_POS_MESSAGES[bridge_position],
                                      random.choice(BRIDGE_MOODS))

        chars = [
            obj for obj in self.obj.contents_get(exclude=caller)
            if obj.has_player
        ]
        if chars:
            # we create the You see: message manually here
            message += "\n You see: %s" % ", ".join("{c%s{n" % char.key
                                                    for char in chars)
        self.caller.msg(message)

        # there is a chance that we fall if we are on the western or central
        # part of the bridge.
        if bridge_position < 3 and random.random(
        ) < 0.05 and not self.caller.is_superuser:
            # we fall 5% of time.
            fall_exit = search_object(self.obj.db.fall_exit)
            if fall_exit:
                self.caller.msg("{r%s{n" % FALL_MESSAGE)
                self.caller.move_to(fall_exit[0], quiet=True)
                # inform others on the bridge
                self.obj.msg_contents("A plank gives way under %s's feet and " \
                                      "they fall from the bridge!" % self.caller.key)
Example #15
0
    def func(self):
        ch = self.caller
        if not self.args:
            char = ch
        else:
            self.args = self.args.strip().split(' ')

            char_name = self.args[0]
            char = search_object(char_name)
            if not char:
                ch.msg(f"There is no such character as {char_name}")
                return
            char = char[0]

            if not char.has_account:
                ch.msg("You cannot do a chargen with that object.")
                return

            if not char.is_connected:
                ch.msg(f"{char.name} is not online")
                return

        EvMenu(char,
               "world.chargen.gen",
               startnode="pick_race",
               cmdset_mergetype='Replace',
               cmdset_priority=1,
               auto_quit=True)
Example #16
0
 def at_object_receive(self, character, source_location):
     """
     This hook is called by the engine whenever the player is moved into
     this room.
     """
     if not character.has_player:
         # only act on player characters.
         return
     # determine if the puzzle is a success or not
     is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value)
     teleport_to = self.db.success_teleport_to if is_success else self.db.failure_teleport_to
     # note that this returns a list
     results = search_object(teleport_to)
     if not results or len(results) > 1:
         # we cannot move anywhere since no valid target was found.
         print "no valid teleport target for %s was found." % teleport_to
         return
     if character.is_superuser:
         # superusers don't get teleported
         character.msg(
             "Superuser block: You would have been teleported to %s." %
             results[0])
         return
     # perform the teleport
     if is_success:
         character.msg(self.db.success_teleport_msg)
     else:
         character.msg(self.db.failure_teleport_msg)
     # teleport quietly to the new place
     character.move_to(results[0], quiet=True, move_hooks=False)
Example #17
0
    def func(self):
        caller = self.caller
        if self.args:
            target = self.args
        elif self.args:
            return caller.msg("I can't find a player by that name.")
        else:
            target = caller

        if target.cg:
            target = target.cg
            mode = "chargen"
        else:
            mode = "normal"

        tag = "|Rsr5 > |n"

        if not target.db.karma:
            caller.msg(tag + "That target doesn't seem to have a nuyen log.")

        if not self.switches:
            caller.msg(target.db.nuyen)
        elif "log" in self.switches:
            table = evtable.EvTable("Date", "Transaction", "Origin")
            log_list = target.db.nuyen.log()
            for date, owner, value, currency, reason, origin in log_list:
                # Origin comes in as a dbref and we need it to be a name.
                origin = evennia.search_object(searchdata=origin)[0].name
                table.add_row(date.strftime("%c"),
                              "{} {}: {}".format(value, currency,
                                                 reason), origin)

            caller.msg(table)
        else:
            return False
Example #18
0
    def do_hunting(self, *args, **kwargs):
        """
        Called regularly when in hunting mode. In hunting mode the mob
        scans adjacent rooms for enemies and moves towards them to
        attack if possible.
        """
        if random.random() < 0.01 and self.db.irregular_msgs:
            self.location.msg_contents(random.choice(self.db.irregular_msgs))
        if self.db.aggressive:
            # first check if there are any targets in the room.
            target = self._find_target(self.location)
            if target:
                self.start_attacking()
                return
        # no targets found, scan surrounding rooms
        #exits = [exi for exi in self.location.exits
        #         if exi.access(self, "traverse")]

        exitnames = ["Sudikoff Hall","Kemeny Hall","Robinson Hall"]         # allowed rooms to exit to/enter
        exits = [search_object(exitname, typeclass='typeclasses.rooms.Room')[0] for exitname in exitnames]  # find rooms with exitnames

        if exits:
            # scan the exits destination for targets
            for exit in exits:
                target = self._find_target(exit)
                if target:
                    # a target found. Move there.
                    self.move_to(exit)
                    return
            # if we get to this point we lost our
            # prey. Resume patrolling.
            self.start_patrolling()
        else:
            # no exits! teleport to home to get away.
            self.move_to(self.home)
Example #19
0
    def attempt_repair(self, caller):
        if self.db.required_repairs <= 0:
            return

        score, sit = caller.get_skill_score("Repair")


        self.db.required_repairs = max(self.db.required_repairs - 1, 0)

        if self.db.required_repairs <= 0:
            caller.msg("Repairs are now complete.")
            if self.db.success_teleport_to != "":
                # find the telport target
                teleport_targets = search_object(self.db.success_teleport_to)
                if not teleport_targets:
                    print "no valid teleport target for %s was found." % self.db.success_teleport_to
                    return
                elif len(teleport_targets) > 1:
                    print "found more than one teleport target, aborting."
                    return
                teleport_target = teleport_targets[0]

                # do the teleport of all contents
                for con in (x for x in self.location.contents if not x.destination and x != self):
                    con.msg(self.db.success_teleport_msg)
                    con.move_to(teleport_target, quiet=True, move_hooks=False)

                # reset the puzzle
                self.db.required_repairs = self.db.reset_repairs
Example #20
0
 def _character_validate(self):
     """validates character objects"""
     char_obj = ev.search_object(self.character).first()
     if ju.ischaracter(char_obj):
         self.character = char_obj
         return True
     else:
         return False
Example #21
0
 def getObject(commandTest, objKeyStr):
     # A helper function to get a spawned object and
     # check that it exists in the process.
     query = search_object(objKeyStr)
     commandTest.assertIsNotNone(query)
     obj = query[0]
     commandTest.assertIsNotNone(obj)
     return obj
Example #22
0
 def on_parse(self, args_line):
     args = args_line.split()
     a_info = {}
     if len(args) > 0:
         targets = search_object(args[0])
         if targets:
             a_info['target'] = targets[0]
     return a_info
Example #23
0
 def getObject(commandTest, objKeyStr):
     # A helper function to get a spawned object and
     # check that it exists in the process.
     query = search_object(objKeyStr)
     commandTest.assertIsNotNone(query)
     obj = query[0]
     commandTest.assertIsNotNone(obj)
     return obj
Example #24
0
    def display(self):
        owner = evennia.search_object(searchdata=self.db_owner)
        if owner:
            owner = owner[0]

        return "{}'s {} Ledger:\n" \
               "{} / {}".format(str(owner).title(), self.db_currency,
                                self.db_value, self.db_accrued)
Example #25
0
    def func(self):
        caller = self.caller

        if not caller.db.icloc:
            caller.msg("You have not used +ooc yet!")
        else:
            if caller.db.icstat:
                caller.msg("You are already IC!")
            else:
                caller.db.icstat = True
                caller.move_to(search_object(caller.db.icloc)[0])
Example #26
0
 def set_dead(self):
     self.db.is_dead = True
     self.ndb.is_attacking = False
     self.ndb.is_immortal = True
     send_defeated_to = search_object(self.db.send_defeated_to)
     if send_defeated_to:
         self.move_to(send_defeated_to[0], quiet=True)
     else:
         self.msg(send_defeated_to + " 未找到")
         logger.log_err("Mob: mob.db.send_defeated_to not found: %s" %
                        self.db.send_defeated_to)
     self.set_alive()
Example #27
0
 def at_object_receive(self, character, source_location):
     """
     This hook is called by the engine whenever the player is moved
     into this room.
     """
     if character.has_player:
         # we only run this if the entered object is indeed a player object.
         # check so our east/west exits are correctly defined.
         wexit = search_object(self.db.west_exit)
         eexit = search_object(self.db.east_exit)
         fexit = search_object(self.db.fall_exit)
         if not (wexit and eexit and fexit):
             character.msg("The bridge's exits are not properly configured. "\
                           "Contact an admin. Forcing west-end placement.")
             character.db.tutorial_bridge_position = 0
             return
         if source_location == eexit[0]:
             # we assume we enter from the same room we will exit to
             character.db.tutorial_bridge_position = 4
         else:
             # if not from the east, then from the west!
             character.db.tutorial_bridge_position = 0
Example #28
0
    def func(self):
        caller = self.caller

        if not caller.db.icloc:
            caller.db.icloc = None
            caller.db.icstat = True

        if caller.db.icstat:
            caller.db.icstat = False
            caller.db.icloc = caller.location
            caller.move_to(search_object(ooc_root)[0])
        else:
            caller.msg("You are already OOC!")
Example #29
0
    def func(self):
        ch = self.caller

        if not self.args:
            ch.msg("supply a rvnum to goto")
            return

        vnum = self.args.strip()
        try:
            vnum = int(vnum)
        except:
            ch.msg("That is not a valid vnum")
            return

        # handle special case of void here
        if vnum == 1:
            void = search_object('#2')[0]
            ch.move_to(void)
            ch.execute_cmd('look')
            return

        # try to find vnum in database
        room = search_object(str(vnum),
                             typeclass='typeclasses.rooms.rooms.Room')
        roomdb = GLOBAL_SCRIPTS.roomdb

        if not room:
            # make sure a blueprint of room exists
            try:
                _ = roomdb.vnum[vnum]
            except KeyError:
                ch.msg("That room does not exist")
                return
            room = create_object('typeclasses.rooms.rooms.Room', key=vnum)
            ch.move_to(room)
        else:
            ch.move_to(room[0])
Example #30
0
    def func(self):
        ch = self.caller
        args = self.args.strip().split()
        if not args:
            zone = ch.db.assigned_zone
            zone = "none" if zone is None else zone
            zonemsg = f"You are assigned zone: |m{zone.replace('_', ' ')}|n"
            ch.msg(zonemsg)
            return

        action, player, zonename = args
        player = search_object(player,
                               typeclass='typeclasses.characters.Character')[0]
        if not player or not player.has_account:
            ch.msg("There is no one like that online")
            return

        if action in ('set'):
            if not is_wiz(ch):
                ch.msg("You are not permitted to do that.")
                return

            if zonename == 'clear':
                player.attributes.remove('assigned_zone')
                ch.msg(f"Zone cleared for {player.name.capitalize()}")
                return
            # set a valid zone to player
            zones = [x['name'] for x in GLOBAL_SCRIPTS.zonedb.vnum.values()]
            if zonename not in zones:
                ch.msg("That is not a valid zone")
                return
            if player.attributes.has(
                    'assigned_zone') and player.attributes.get(
                        'assigned_zone') == zonename:
                player.attributes.remove('assigned_zone')
                ch.msg(
                    f"You unassigned zone {zonename} to {player.name.capitalize()}"
                )
                player.msg(
                    f"{ch.name.capitalize()} unassigned zone {zonename} from you."
                )
            else:
                player.attributes.add('assigned_zone', zonename)
                ch.msg(
                    f"You set zone {zonename} to {player.name.capitalize()}")
                player.msg(
                    f"{ch.name.capitalize()} assigned zone {zonename} to you.")
            return
Example #31
0
def create_evscaperoom_object(typeclass=None,
                              key="testobj",
                              location=None,
                              delete_duplicates=True,
                              **kwargs):
    """
    This is a convenience-wrapper for quickly building EvscapeRoom objects. This
    is called from the helper-method create_object on states, but is also useful
    for the object-create admin command.

    Note that for the purpose of the Evscaperoom, we only allow one instance
    of each *name*, deleting the old version if it already exists.

    Kwargs:
        typeclass (str): This can take just the class-name in the evscaperoom's
            objects.py module. Otherwise, a full path is needed.
        key (str): Name of object.
        location (Object): The location to create new object.
        delete_duplicates (bool): Delete old object with same key.
        kwargs (any): Will be passed into create_object.
    Returns:
        new_obj (Object): The newly created object, if any.


    """
    if not (callable(typeclass) or typeclass.startswith("evennia")
            or typeclass.startswith("typeclasses")
            or typeclass.startswith("evscaperoom")):
        # unless we specify a full typeclass path or the class itself,
        # auto-complete it
        typeclass = _BASE_TYPECLASS_PATH + typeclass

    if delete_duplicates:
        old_objs = [
            obj for obj in search_object(key) if
            not inherits_from(obj, "evennia.objects.objects.DefaultCharacter")
        ]
        if location:
            # delete only matching objects in the given location
            [obj.delete() for obj in old_objs if obj.location == location]
        else:
            [obj.delete() for obj in old_objs]

    new_obj = create_object(typeclass=typeclass,
                            key=key,
                            location=location,
                            **kwargs)
    return new_obj
Example #32
0
 def goto_next_room(self):
     currentroom = self.location.dbref
     #print(currentroom)
     #print(self.db.rooms)
     idx = self.db.rooms.index(currentroom) + self.db.direction
     
     if idx < 0 or idx >= len(self.db.rooms):
         #We reached the end of our path
         self.stop_driving()
         #Reverse the direction of the train
         self.db.direction *= -1
     else:
         roomref = self.db.rooms[idx]
         room = search_object(roomref)[0]
         self.move_to(room)
         self.msg_contents("The train is moving forward to %s." % (room.name, ))
Example #33
0
    def func(self):
        "move one step westwards"
        caller = self.caller

        bridge_step = max(-1, caller.db.tutorial_bridge_position - 1)

        if bridge_step < 0:
            # we have reached the far west end of the bridge.
            # Move to the west room.
            wexit = search_object(self.obj.db.west_exit)
            if wexit:
                caller.move_to(wexit[0])
            else:
                caller.msg("No west exit was found for this room. Contact an admin.")
            return
        caller.db.tutorial_bridge_position = bridge_step
        # since we are really in one room, we have to notify others
        # in the room when we move.
        caller.location.msg_contents("%s steps westwards across the bridge." % caller.name, exclude=caller)
        caller.execute_cmd("look")
Example #34
0
def create_room(room_name, character, location, roomtype_key="Generic", roomtype_value="Generic"):
    """
    Create room(if doesn't exist) based on location metadata, 
    attach script to control room state and move player to the room
    """
    rooms = search_object(room_name, typeclass='typeclasses.rooms.Room')

    if not rooms:                                                      # If room doesn't exists
        room = create_object("typeclasses.rooms.Room", key=room_name)  # then create room
        logger.log_info("Room %s Created" % room)
    else:
        room=rooms[0]

    # set room type if changed or new room
    if room.db.roomtype_key != roomtype_key or room.db.roomtype_value != roomtype_value:
        room.db.roomtype_key = roomtype_key
        room.db.roomtype_value = roomtype_value

        if roomtype_key != 'building':  # if outdoors
            room.scripts.add("typeclasses.scripts.Weather")             # attach script to get weather
            room.scripts.add("typeclasses.scripts.Outdoors")            # and attach script to control room state
        
        if roomtype_value == 'library':  # if library
            room.scripts.add('typeclasses.scripts.Library')

        logger.log_info("Room Type Updated to %s: %s" % (room.db.roomtype_key,room.db.roomtype_value))

    if not room.db.location:
        room.db.location = location

    # teleport character to room, if not already in room
    if character.location.name != room_name:
        character.move_to(room, quiet=True)
        logger.log_info("User entered %s" % room_name)
        character.msg("You've entered %s" % room_name)
        character.db.just_entered = False

    elif character.db.just_entered:
        character.msg("You're in %s" % room_name)
        character.db.just_entered = False
Example #35
0
 def func(self):
     roles = [
         "Artificial Intelligence", "Chef", "Chemist", "Doctor", "Engineer",
         "Horticulturist", "Port Manager"
     ]
     enabled_roles = [False, False, False, False, False, True, False]
     # try:
     index = int(self.args.strip()) - 1
     if index >= 0:
         if enabled_roles[index]:
             role = " the " + roles[index]
             self.caller.db.role = role
             self.caller.msg("You have become a {}!".format(
                 roles[index].lower()))
             if index == 5:
                 hydro_room = search_object("Hydroponics")
                 self.caller.move_to(hydro_room[0])
         else:
             self.caller.msg(
                 "That class is still in development and can't be played yet."
             )
     else:
         self.caller.msg("That's not a valid number!")
Example #36
0
    def func(self):
        ch = self.caller
        cur_room = ch.location
        exit = cur_room.db.exits[self.key]
        if exit < 0:
            ch.msg(_ERR_MOVEMENT)
            return

        # double check to make sure destination room actually exists
        room = search_object(str(exit), typeclass=Room)
        ch.msg("{}{}".format(exit, room))
        if not room:
            logger.log_errmsg(
                "Attempting to move to a valid exit vnum, but room doesn't exist"
            )
            ch.msg(_ERR_MOVEMENT)
            return
        room = room[0]

        # special condition if ch is in redit
        if ch.ndb._redit:
            ch.ndb._redit.__init__(ch, exit)
        # valid, lets move
        ch.move_to(room)
Example #37
0
    def spawnObjects(self):
        if self.objects_created:
            print("Objects already created!")
        else:
            print("spawning items")
            for vnum, ob in self.objects.items():
                if vnum not in self.object_location.keys():
                    #if self.verbose: print("Object vnum not found in object_location table: %s" % vnum)
                    continue
                else:
                    evid = "#" + str(
                        self.room_translate[self.object_location[vnum]])
                    try:
                        loc = search_object(evid)[0]
                    except Exception as e:
                        print("location for object vnum %s not found: %s" %
                              (vnum, evid))
                        continue

                    try:
                        newob = create_object(
                            key=ob['name'],
                            location=loc,
                            home=loc,
                            aliases=ob['aliases'],
                            typeclass="typeclasses.objects.LegacyObject",
                            attributes=[('desc', ob['desc']),
                                        ('ext_desc', ob['ext']),
                                        ('type', ob['type']),
                                        ('area', ob['area'])])
                        print("%s created in %s - #%s" %
                              (ob['name'], loc.name, newob.id))
                    except Exception as e:
                        print("Error creating %s, vnum: %s location: %s" %
                              (ob['name'], vnum, loc.id))
                        print(str(e))
Example #38
0
    def at_object_receive(self, character, source_location):
        """
        This hook is called by the engine whenever the player is moved into this room.
        """

        if not character.has_account:
            # only act on player characters.
            return
        teleport_to = self.db.teleport_to
        results = search_object(teleport_to)
        character.msg(self.db.desc)
        if not results or len(results) > 1:
            character.msg("no valid teleport target for %s was found." %
                          teleport_to)
            return
        if character.is_superuser:
            # superusers don't get teleported
            character.msg(
                "Superuser block: You would have been teleported to %s." %
                results[0])
            return
        # perform the teleport
        character.move_to(results[0], quiet=True, move_hooks=False)
        results[0].at_object_receive(character, self)
Example #39
0
#

#HEADER {{{1

# This will be included in all other #CODE blocks

from evennia import create_object, search_object, search_tag
from evennia.contrib.tutorial_examples import red_button
from evennia import DefaultObject
from typeclasses.objects import Object
from typeclasses.duo import *
from typeclasses.rooms import Room
from typeclasses.exits import Exit
from django.core.exceptions import ObjectDoesNotExist

limbo = search_object('Limbo')[0]
def delete_tagged(tag):
    for obj in search_tag(tag):
        try:
            obj.delete()
        except ObjectDoesNotExist:
            pass

def link(rooms):
    if (len(rooms) > 1):
        x = rooms[0]
        xs = rooms[1:]
        result = []

        for room in xs:
            # Link these rooms both ways
Example #40
0
 def player(self):
     evennia.search_object(self._player_ref)
Example #41
0
# The following variable is automatically made available for the script:

# caller - the object executing the script
#


#HEADER

# everything in this block will be appended to the beginning of
# all other #CODE blocks when they are executed.

from evennia import create_object, search_object
from evennia.contrib.tutorial_examples import red_button
from evennia import DefaultObject

limbo = search_object('Limbo')[0]


#CODE (create red button)

# This is the first code block. Within each block, Python
# code works as normal. Note how we make use if imports and
# 'limbo' defined in the #HEADER block. This block's header
# offers no information about red_button variable, so it
# won't be able to be deleted in debug mode.

# create a red button in limbo
red_button = create_object(red_button.RedButton, key="Red button",
                                          location=limbo, aliases=["button"])

# we take a look at what we created
Example #42
0
 def at_repeat(self): 
     knife = search_object(u"Картонный нож", location = self.obj, quiet = True)[0] 
     if (not knife):
         create_object('typeclasses.weapons.Knife', u"Картонный нож", self.obj)
Example #43
0
	def at_repeat(self):
		if not self.instruction:
			return

		inst_list = self.instruction.values()

		if not inst_list:
			return

		for inst in inst_list:
			#ищем текущий предмет
			items = search_object(inst["name"])

			#если нет таких передметов
			if not items:
				#self.obj.msg_contents("не нашел %s" % inst["name"])
				for count in range(inst["world_count"]):
					self.obj.msg_contents("создаю %s" % inst["name"])
					#берем рандомную локацию из списка локаций
					location = random.choice(inst["locations"])
					self.obj.msg_contents("выбрал %s" % location)
					#ищем ее
					loc = search_object(location)
					self.obj.msg_contents("нашел %s" % loc)
					#если их много как кухонь то, из них берем рандомную
					creation_loc = random.choice(loc)
					self.obj.msg_contents("выбрал %s" % creation_loc.key)
					#создаем там объект
					obj = create_object(inst["typeclass"],inst["name"], creation_loc)
					self.obj.msg_contents("создал %s" % obj.key)
					# буду к этому вязяться когда будут предметы с одинаоквыми именами
					obj.db.respawnable = True
					#задаем описание если нет стандартного как у ножа	
					if inst["desc"]:
						if not obj.db.desc:
							obj.db.desc = inst["desc"]

			#если предметы найдены				
			else:
				#self.obj.msg_contents("нашел %s" % items)
				#если их меньше чем задано в world_count
				if len(items) < inst["world_count"]:
					self.obj.msg_contents("добвляю не достоющие %s" % inst["name"])
					#создаем не достающее количество объектов
					for count in range(inst["world_count"] - len(items)):
						#берем рандомнуб локацию из списка локаций
						location = random.choice(inst["locations"])
						self.obj.msg_contents("выбрал %s" % location)
						#ищем ее
						loc = search_object(location)
						self.obj.msg_contents("нашел %s" % loc)
						#если их много как кухонь то, из них берем рандомную
						creation_loc = random.choice(loc)
						self.obj.msg_contents("выбрал %s" % creation_loc.key)
						#создаем там объект
						obj = create_object(inst["typeclass"],inst["name"], creation_loc)
						self.obj.msg_contents("создал %s" % obj.key)
						# буду к этому вязяться когда будут предметы с одинаоквыми именами
						obj.db.respawnable = True
						#задаем описание если нет стандартного как у ножа	
						if inst["desc"]:
							if not obj.db.desc:
								obj.db.desc = inst["desc"]