示例#1
0
文件: rooms.py 项目: Henddher/evennia
    def func(self):
        """
        Implement the command.

        This works both as a look and a search command; there is a
        random chance of eventually finding a light source.
        """
        caller = self.caller

        # count how many searches we've done
        nr_searches = caller.ndb.dark_searches
        if nr_searches is None:
            nr_searches = 0
            caller.ndb.dark_searches = nr_searches

        if nr_searches < 4 and random.random() < 0.90:
            # we don't find anything
            caller.msg(random.choice(DARK_MESSAGES))
            caller.ndb.dark_searches += 1
        else:
            # we could have found something!
            if any(obj for obj in caller.contents if utils.inherits_from(obj, LightSource)):
                #  we already carry a LightSource object.
                caller.msg(ALREADY_LIGHTSOURCE)
            else:
                # don't have a light source, create a new one.
                create_object(LightSource, key="splinter", location=caller)
                caller.msg(FOUND_LIGHTSOURCE)
示例#2
0
文件: utils.py 项目: Gazzilow/mu2ch
def locationTunnel(location1, location1_exit_name, location2, location2_exit_name): 

    exit1 = location2_exit_name if (location2_exit_name) else location2.key
    exit2 = location1_exit_name if (location1_exit_name) else location1.key
    print "Create tunnel between '%s' and '%s'" % ( exit1, exit2 ) 
    exit1 = create_object(settings.BASE_EXIT_TYPECLASS, exit1, location = location1, destination = location2)
    exit2 = create_object(settings.BASE_EXIT_TYPECLASS, exit2, location = location2, destination = location1)
    return [ exit1, exit2 ]
示例#3
0
文件: items.py 项目: evennia/ainneve
    def at_get(self, getter):
        super(Bundlable, self).at_get(getter)
        bundle_key = self.aliases.all()[0]
        others = [obj for obj in getter.contents
                  if obj.is_typeclass('typeclasses.items.Bundlable')
                  and bundle_key in obj.aliases.all()]

        if len(others) >= self.db.bundle_size \
                and self.db.prototype_name and self.aliases.all():

            # we have enough to create a bundle

            bundle = create_object(
                typeclass='typeclasses.items.Bundle',
                key='a bundle of {}s'.format(bundle_key),
                aliases=['bundle {}'.format(bundle_key)],
                location=self.location
            )
            bundle.db.desc = ("A bundle of {item}s held together "
                              "with a thin leather strap.").format(
                item=bundle_key
            )
            bundle.db.value = self.db.bundle_size * self.db.value
            bundle.db.weight = self.db.bundle_size * self.db.weight
            bundle.db.quantity = self.db.bundle_size
            bundle.db.prototype_name = self.db.prototype_name
            for obj in others[:self.db.bundle_size]:
                obj.delete()
示例#4
0
    def create_room(self, room):
        new_room = create_object('typeclasses.rooms.Box', key = room['name'])
        new_room.db.desc = room['desc']

        if (new_room.name == u'Кухня'):
            new_room.scripts.add(KitchenKnife) 

        try:
            for npc in room['npc']:
                create_object(npc['typeclass'], key = npc['name'], location = new_room)
        except KeyError:
            pass

        #locationTunnelDefault(self, new_room);
        locationTunnel(self, "Прихожка", new_room, new_room.name);
        return new_room
示例#5
0
文件: command.py 项目: Gazzilow/mu2ch
    def func(self):

        caller = self.caller

        if caller.db.hands:
            caller.msg("У тебя уже есть руки")
        else:
            caller.db.hands = create_object(settings.BASE_OBJECT_TYPECLASS, "hands")
            caller.msg("Теперь у тебя есть руки")

        if caller.db.frags:
            caller.msg("У тебя уже есть параметр фрагов")
        else:
            caller.db.frags = 0
            caller.msg("Теперь у тебя есть фраги")

        if caller.db.death_count:
            caller.msg("У тебя уже есть параметр смертей")
        else:
            caller.db.death_count = 0
            caller.msg("Теперь у тебя есть количество смертей")

        if caller.db.effects:
            caller.msg("У тебя уже есть массив с эффектами")
        else:
            caller.db.effects = []
            caller.msg("Теперь у тебя есть массив с эффектами")
示例#6
0
def spell_conjure(caster, spell_name, targets, cost, **kwargs):
    """
    Spell that creates an object.
    
    kwargs:
        obj_key (str): Key of the created object.
        obj_desc (str): Desc of the created object.
        obj_typeclass (str): Typeclass path of the object.
    
    If you want to make more use of this particular spell funciton,
    you may want to modify it to use the spawner (in evennia.utils.spawner)
    instead of creating objects directly.
    """
    
    obj_key = "a nondescript object"
    obj_desc = "A perfectly generic object."
    obj_typeclass = "evennia.objects.objects.DefaultObject"
    
    # Retrieve some variables from kwargs, if present
    if "obj_key" in kwargs:
        obj_key = kwargs["obj_key"]
    if "obj_desc" in kwargs:
        obj_desc = kwargs["obj_desc"]
    if "obj_typeclass" in kwargs:
        obj_typeclass = kwargs["obj_typeclass"]
        
    conjured_obj = create_object(obj_typeclass, key=obj_key, location=caster.location) # Create object
    conjured_obj.db.desc = obj_desc # Add object desc
    
    caster.db.mp -= cost # Deduct MP cost
    
    # Message the room to announce the creation of the object
    caster.location.msg_contents("%s casts %s, and %s appears!" % (caster, spell_name, conjured_obj))
示例#7
0
文件: npc.py 项目: brrrrain/mu2ch
	def func(self):
		caller = self.caller

		pantsu = create_object(settings.BASE_OBJECT_TYPECLASS, "Детские трусики", caller, home=caller)
		talking_to = caller.search(caller.db.last_talk_with, location=caller.location)
		pantsu.db.desc = "Трусики принадлежат: %s!" % talking_to.key
		self.menutree.goto("END")
示例#8
0
文件: tests.py 项目: remy-r/evennia
 def test_lightsource(self):
     light = create_object(tutobjects.LightSource, key="torch", location=self.room1)
     self.call(tutobjects.CmdLight(), "", "You light torch.", obj=light)
     light._burnout()
     if hasattr(light, "deferred"):
         light.deferred.cancel()
     self.assertFalse(light.pk)
示例#9
0
文件: tests.py 项目: remy-r/evennia
 def test_mob(self):
     mobobj = create_object(mob.Mob, key="mob")
     self.assertEqual(mobobj.db.is_dead, True)
     mobobj.set_alive()
     self.assertEqual(mobobj.db.is_dead, False)
     mobobj.set_dead()
     self.assertEqual(mobobj.db.is_dead, True)
     mobobj._set_ticker(0, "foo", stop=True)
示例#10
0
    def _create_room(self, coordinates, report_to):
        """
        Gets a new WildernessRoom to be used for the provided coordinates.

        It first tries to retrieve a room out of storage. If there are no rooms
        left a new one will be created.

        Args:
            coordinates (tuple): coordinate tuple of (x, y)
            report_to (object): the obj to return error messages to
        """
        if self.db.unused_rooms:
            # There is still unused rooms stored in storage, let's get one of
            # those
            room = self.db.unused_rooms.pop()
        else:
            # No more unused rooms...time to make a new one.

            # First, create the room
            room = create_object(typeclass=self.mapprovider.room_typeclass,
                                 key="Wilderness",
                                 report_to=report_to)

            # Then the exits
            exits = [("north", "n"),
                     ("northeast", "ne"),
                     ("east", "e"),
                     ("southeast", "se"),
                     ("south", "s"),
                     ("southwest", "sw"),
                     ("west", "w"),
                     ("northwest", "nw")]
            for key, alias in exits:
                create_object(typeclass=self.mapprovider.exit_typeclass,
                              key=key,
                              aliases=[alias],
                              location=room,
                              destination=room,
                              report_to=report_to)

        room.ndb.active_coordinates = coordinates
        room.ndb.wildernessscript = self
        self.db.rooms[coordinates] = room

        return room
示例#11
0
文件: weapons.py 项目: Gazzilow/mu2ch
 def at_object_creation(self):
     #добавляем прочность нашему оружию(int)
     self.db.durability = 50
     self.db.is_weapon = True
     #добавим часть тела, куда одевается предмет
     #self.db.placing = "RightHand"
     self.db.desc = "Пистолет ТТ."
     mag = create_object(settings.BASE_OBJECT_TYPECLASS, "Магазин на 12 патронов", self, home=self)
     mag.db.desc = "Магазин на 12 патронов"
示例#12
0
文件: tests.py 项目: remy-r/evennia
 def test_cmdtutorial(self):
     room = create_object(tutrooms.TutorialRoom, key="tutroom")
     self.char1.location = room
     self.call(tutrooms.CmdTutorial(), "", "Sorry, there is no tutorial help available here.")
     self.call(tutrooms.CmdTutorialSetDetail(), "detail;foo;foo2 = A detail", "Detail set: 'detail;foo;foo2': 'A detail'", obj=room)
     self.call(tutrooms.CmdTutorialLook(), "", "tutroom(", obj=room)
     self.call(tutrooms.CmdTutorialLook(), "detail", "A detail", obj=room)
     self.call(tutrooms.CmdTutorialLook(), "foo", "A detail", obj=room)
     room.delete()
示例#13
0
文件: tests.py 项目: remy-r/evennia
 def test_bridgeroom(self):
     room = create_object(tutrooms.BridgeRoom, key="bridgeroom")
     room.update_weather()
     self.char1.move_to(room)
     self.call(tutrooms.CmdBridgeHelp(), "", "You are trying hard not to fall off the bridge ...", obj=room)
     self.call(tutrooms.CmdLookBridge(), "", "bridgeroom\nYou are standing very close to the the bridge's western foundation.", obj=room)
     room.at_object_leave(self.char1, self.room1)
     tutrooms.TICKER_HANDLER.remove(interval=room.db.interval, callback=room.update_weather, idstring="tutorial")
     room.delete()
示例#14
0
    def func(self):
        "creates the object and names it"
        caller = self.caller
        if not self.args:
            caller.msg("Usage: +createNPC <name>")
            return
        if not caller.location:
            # may not create npc when OOC
            caller.msg("You must have a location to create an npc.")
            return
        # make name always start with capital letter
        name = self.args.capitalize()
        # create npc in caller's location
        npc = create_object("characters.Character", 
                      key=name, 
                      location=caller.location,
                      locks="edit:id(%i) and perm(Builders)" % caller.id)
        # announce 
        message = "%s created the NPC '%s'.\n"
        caller.msg(message % ("You", name)) 
        caller.location.msg_contents(message % (caller.key, name), 
                                                exclude=caller)       

       #Let's set the initial stats for the NPC  --SG

        hitpoints = random.randint(5,10)
        npc.db.hitpoints = hitpoints
        caller.msg("Your current hitpoints was set to %i." % hitpoints)

        manapoints = random.randint(5,10)
        npc.db.manapoints = manapoints
        caller.msg("Your current manapoints was set to %i." % manapoints)
       
        strength = random.randint(1, 18)
        npc.db.strength = strength
        message = "%s's Strength was set to %i."
        caller.msg(message % (name, strength))

        dexterity = random.randint(1, 18)
        npc.db.dexterity = dexterity
        message = "%s's Dexterity was set to %i."
        caller.msg(message % (name, dexterity))

        charisma = random.randint(1, 18)
        npc.db.charisma = charisma
        message = "%s's Charisma was set to %i."
        caller.msg(message % (name, charisma))

        intelligence = random.randint(1, 18)
        npc.db.intelligence = intelligence
        message = "%s's Intelligence was set to %i."
        caller.msg(message % (name, intelligence))

        stamina = random.randint(1, 18)
        npc.db.stamina = stamina
        message = "%s's Stamina was set to %i.\n"
        caller.msg(message % (name, stamina))
示例#15
0
def example2_build_verticle_exit(x, y, **kwargs):
    """Creates two exits to and from the two rooms north and south."""
    # If on the first iteration - Do nothing.
    if kwargs["iteration"] == 0:
        return

    north_room = kwargs["room_dict"][(x, y-1)]
    south_room = kwargs["room_dict"][(x, y+1)]

    north = create_object(exits.Exit, key="south",
                          aliases=["s"], location=north_room,
                          destination=south_room)

    south = create_object(exits.Exit, key="north",
                          aliases=["n"], location=south_room,
                          destination=north_room)

    kwargs["caller"].msg("Connected: " + north_room.key +
                         " & " + south_room.key)
示例#16
0
def example2_build_horizontal_exit(x, y, **kwargs):
    """Creates two exits to and from the two rooms east and west."""
    # If on the first iteration - Do nothing.
    if kwargs["iteration"] == 0:
        return

    west_room = kwargs["room_dict"][(x-1, y)]
    east_room = kwargs["room_dict"][(x+1, y)]

    create_object(exits.Exit, key="east",
                         aliases=["e"], location=west_room,
                         destination=east_room)

    create_object(exits.Exit, key="west",
                         aliases=["w"], location=east_room,
                         destination=west_room)

    kwargs["caller"].msg("Connected: " + west_room.key +
                         " & " + east_room.key)
示例#17
0
文件: players.py 项目: Gazzilow/mu2ch
    def at_post_login(self, sessid = None):
        super(Player, self).at_post_login(sessid)

        
        try:
            if (settings.TEST_SERVER):
                self.permissions.add('Builders') 
        except AttributeError:
            pass

        character = self.character
        
        # Вероятно, этот код нужно убрать в at_first_login хук
        try:
            homeLocation = character.search(u"1-Общий дворик", global_search = True, quiet = True)[0] 
        except IndexError:
            # сервер после вайпа, нужно выполнить инцилизацию локаций вручную
            # bathccommand mu2ch_init
            # пока заглушка
            return 

        if (homeLocation and character.home != homeLocation):
            character.home = character.location = homeLocation
            character.move_to(homeLocation)
        
    
        apartment = None

        if (character.db.flat):
            return 

        i = 1
        while (apartment is None):
            try:
                building = character.search(u"1-Дом%d" % i, global_search = True, quiet = True)[0] 
            except IndexError:
                try:
                    building_home = character.search(u"Преддомовая территория", global_search = True, quiet = True)[0]
                except IndexError:
                    # что то пошло не так
                    return

                building = create_object('typeclasses.building.Hrushevka', key = u"Дом%d" % i) 
                locationTunnel(building, u"Дом%d" % i , building_home, u"Улица")
                if (not building):
                    print "Что-то пошло не так"
                    # never happend
                    break

            # db.flat - локация хаты персонажа
            apartment = building.assignCharacter(character) 
            if (apartment): 
                character.msg("Тебя заселили по адресу: %s" % repr(apartment)) 

            i = i + 1
示例#18
0
def example2_build_forest(x, y, **kwargs):
    """A basic room"""
    # If on anything other than the first iteration - Do nothing.
    if kwargs["iteration"] > 0:
        return None

    room = create_object(rooms.Room, key="forest" + str(x) + str(y))
    room.db.desc = "Basic forest room."

    kwargs["caller"].msg(room.key + " " + room.dbref)

    return room
示例#19
0
文件: tests.py 项目: remy-r/evennia
 def test_clothingcommands(self):
     wearer = create_object(clothing.ClothedCharacter, key="Wearer")
     friend = create_object(clothing.ClothedCharacter, key="Friend")
     room = create_object(DefaultRoom, key="room")
     wearer.location = room
     friend.location = room
     # Make a test hat
     test_hat = create_object(clothing.Clothing, key="test hat")
     test_hat.db.clothing_type = 'hat'
     test_hat.location = wearer
     # Make a test scarf
     test_scarf = create_object(clothing.Clothing, key="test scarf")
     test_scarf.db.clothing_type = 'accessory'
     test_scarf.location = wearer
     # Test wear command
     self.call(clothing.CmdWear(), "", "Usage: wear <obj> [wear style]", caller=wearer)
     self.call(clothing.CmdWear(), "hat", "Wearer puts on test hat.", caller=wearer)
     self.call(clothing.CmdWear(), "scarf stylishly", "Wearer wears test scarf stylishly.", caller=wearer)
     # Test cover command.
     self.call(clothing.CmdCover(), "", "Usage: cover <worn clothing> [with] <clothing object>", caller=wearer)
     self.call(clothing.CmdCover(), "hat with scarf", "Wearer covers test hat with test scarf.", caller=wearer)
     # Test remove command.
     self.call(clothing.CmdRemove(), "", "Could not find ''.", caller=wearer)
     self.call(clothing.CmdRemove(), "hat", "You have to take off test scarf first.", caller=wearer)
     self.call(clothing.CmdRemove(), "scarf", "Wearer removes test scarf, revealing test hat.", caller=wearer)
     # Test uncover command.
     test_scarf.wear(wearer, True)
     test_hat.db.covered_by = test_scarf
     self.call(clothing.CmdUncover(), "", "Usage: uncover <worn clothing object>", caller=wearer)
     self.call(clothing.CmdUncover(), "hat", "Wearer uncovers test hat.", caller=wearer)
     # Test drop command.
     test_hat.db.covered_by = test_scarf
     self.call(clothing.CmdDrop(), "", "Drop what?", caller=wearer)
     self.call(clothing.CmdDrop(), "hat", "You can't drop that because it's covered by test scarf.", caller=wearer)
     self.call(clothing.CmdDrop(), "scarf", "You drop test scarf.", caller=wearer)
     # Test give command.
     self.call(clothing.CmdGive(), "", "Usage: give <inventory object> = <target>", caller=wearer)
     self.call(clothing.CmdGive(), "hat = Friend", "Wearer removes test hat.|You give test hat to Friend.", caller=wearer)
     # Test inventory command.
     self.call(clothing.CmdInventory(), "", "You are not carrying or wearing anything.", caller=wearer)
示例#20
0
def example1_build_mountains(x, y, **kwargs):
    """A room that is a little more advanced"""

    # Create the room.
    room = create_object(rooms.Room, key="mountains" + str(x) + str(y))

    # Generate a description by randomly selecting an entry from a list.
    room_desc = ["Mountains as far as the eye can see",
                 "Your path is surrounded by sheer cliffs",
                 "Haven't you seen that rock before?"]
    room.db.desc = random.choice(room_desc)

    # Create a random number of objects to populate the room.
    for i in xrange(randint(0, 3)):
        rock = create_object(key="Rock", location=room)
        rock.db.desc = "An ordinary rock."

    # Send a message to the player
    kwargs["caller"].msg(room.key + " " + room.dbref)

    # This is generally mandatory.
    return room
示例#21
0
def example1_build_forest(x, y, **kwargs):
    """A basic example of build instructions. Make sure to include **kwargs
    in the arguments and return an instance of the room for exit generation."""

    # Create a room and provide a basic description.
    room = create_object(rooms.Room, key="forest" + str(x) + str(y))
    room.db.desc = "Basic forest room."

    # Send a message to the player
    kwargs["caller"].msg(room.key + " " + room.dbref)

    # This is generally mandatory.
    return room
示例#22
0
    def build(self):
        i = 0
        prev_floor = None
        for i in xrange(1, self.db.floor_n):  
            new_floor = create_object('floor.BuildingFloor', key = u"%d Этаж" % i) 
            new_floor.build(self, i) 

            new_floor.move_to(self, quiet = True, move_hooks = False) 
                
            locationTunnel(self, self.db.desc, new_floor, None)
            if (prev_floor):
                locationTunnelDefault(prev_floor, new_floor)
            prev_floor = new_floor
示例#23
0
    def at_die(self):
        """
        Хук смерти игрока. Создает труп, скидывает в него вещи, деньги, переносит игрока в лимб.
        """
        # создаем труп
        corpse = create_object(Corpse, self.key, location=self.location)
        # денюшки
        if self.db.money:
            corpse.db.money = self.db.money
            self.db.money = 0
        # corpse.key = "Труп %s" % self.key
        descriptions = [
            "Изуродованный труп %s" % self.key,
            "Бренное тело %s" % self.key,
            "Останки %s" % self.key,
            "Все, что оcталось от %s" % self.key,
        ]
        corpse.db.desc = random.choice(descriptions)
        # скидываем внего вещи
        items = self.contents
        if items:
            for item in items:
                item.move_to(corpse, quiet=True)
        if self.db.hands:
            in_hands = self.db.hands.contents
            if in_hands:
                item = in_hands[0]
                item.move_to(corpse, quiet=True)
        # сбарсываем пати, если ты умер, или умер лидер
        leader = self.db.party_leader
        party = self.db.party

        if party:
            for member in party:
                player = self.search(member, global_search=True, nofound_string="Сопартиец %s не найден!" % member)
                if not player:
                    return
                player.db.party_leader = None
                player.msg("Ваш лидер погиб и ваша группа распалась.")
            self.db.party = []
            self.msg("Твоя группа распалась.")

        if leader:
            your_leader = self.search(leader, global_search=True, nofound_string="Лидер %s не найден!" % leader)
            your_leader.db.party.remove(self.key)
            your_leader.msg("%s погиб и вышел и твой группы." % self.key)
            self.db.party_leader = None
            self.msg("Ты покинул группу %s" % your_leader.key)

        # задрежка
        delay(5, callback=self.TelToLimb)
示例#24
0
文件: floor.py 项目: Gazzilow/mu2ch
    def build(self, building, n):
        self.db.n = n
        self.db.key = self.db.desc = u"%d этаж" % n
        self.db.building = building
        per_floor = building.db.apartment_per_floor
        i = 1
        for i in xrange(1, per_floor + 1):
            room_n = ((n - 1) * per_floor) + i 
            roomEntryLocation = create_object('apartment.BuildingApartmentUnused', key = u"Кв-%d" % room_n)
            roomEntryLocation.build(self, room_n) 
            roomEntryLocation.move_to(self, quiet = True, move_hooks = False)
            locationTunnel(roomEntryLocation, roomEntryLocation.key, self, u"Лестничная площадка")

        return self
示例#25
0
文件: tests.py 项目: remy-r/evennia
    def test_clothingfunctions(self):
        wearer = create_object(clothing.ClothedCharacter, key="Wearer")
        room = create_object(DefaultRoom, key="room")
        wearer.location = room
        # Make a test hat
        test_hat = create_object(clothing.Clothing, key="test hat")
        test_hat.db.clothing_type = 'hat'
        test_hat.location = wearer
        # Make a test shirt
        test_shirt = create_object(clothing.Clothing, key="test shirt")
        test_shirt.db.clothing_type = 'top'
        test_shirt.location = wearer
        # Make a test pants
        test_pants = create_object(clothing.Clothing, key="test pants")
        test_pants.db.clothing_type = 'bottom'
        test_pants.location = wearer

        test_hat.wear(wearer, 'on the head')
        self.assertEqual(test_hat.db.worn, 'on the head')

        test_hat.remove(wearer)
        self.assertEqual(test_hat.db.worn, False)

        test_hat.worn = True
        test_hat.at_get(wearer)
        self.assertEqual(test_hat.db.worn, False)

        clothes_list = [test_shirt, test_hat, test_pants]
        self.assertEqual(clothing.order_clothes_list(clothes_list), [test_hat, test_shirt, test_pants])

        test_hat.wear(wearer, True)
        test_pants.wear(wearer, True)
        self.assertEqual(clothing.get_worn_clothes(wearer), [test_hat, test_pants])

        self.assertEqual(clothing.clothing_type_count(clothes_list), {'hat':1, 'top':1, 'bottom':1})

        self.assertEqual(clothing.single_type_count(clothes_list, 'hat'), 1)
示例#26
0
    def assignApartmentToCharacter(self, apartment_location, character): 
        # TODO проверяеть тип локации который нам дают
        floor = apartment_location.db.floor

        # Уничтожаем пустую квартиру
        room_n = apartment_location.db.n
        db_key = apartment_location.name
        apartment_location.delete() 
        
        # Создаем кваритру с комнатами
        new_apartment = create_object('apartment.BuildingApartmentUsed', key = db_key)
        new_apartment.build(floor, room_n) 
        new_apartment.db.assign_to = character
        exits = locationTunnel(new_apartment, new_apartment.name, floor, u"Лестничная площадка")
        exits[1].locks.add("traverse: id(%d) or perm(Wizard)" % character.id)
        new_apartment.move_to(floor, quiet = True, move_hooks = False)
        return new_apartment
示例#27
0
文件: command.py 项目: Gazzilow/mu2ch
    def func(self):

        caller = self.caller

        if not self.args:
            caller.msg("Использование (без <>): алхимия <ингредиент 1>+<ингредиент 2>+<ингредиент 3>+...")
            return

        componets = self.args.strip().split("+")

        if not componets:
            caller.msg("Не верно указаны ингредиенты.")
            return
        
        avaible_components,to_delete = [],[]
        for componet in componets:
            avaible = caller.search(componet, location=caller, nofound_string="У тебя нет компонента: %s" % componet)
            if not avaible:
                continue
            avaible_components.append(avaible.key)
            to_delete.append(avaible)

        if len(componets) != len(avaible_components):
            caller.msg("У тебя не хватает компонентов!")
            return
        
        recipes = Alchemy().recipes.values()
        created= False

        for recipe in recipes:
            if self.comp(list1=avaible_components, list2=recipe["components"]):
                result = create_object(recipe["typeclass"], recipe["name"], caller, home=caller)
                created = True

        if not created:
            caller.msg("Нет такого рецепта!")
            return

        string = "Ты потратил: "
        for item in to_delete:
            string += "%s, " % item.key
            item.delete()
        string+="и нахимичил %s" % result.key
        caller.msg(string)
示例#28
0
文件: npc.py 项目: brrrrain/mu2ch
    def at_tick(self):

        tickerhandler.remove(self, self.db.last_ticker_deley_value)
        self.db.last_ticker_deley_value = random.randint(15, 120) 
        tickerhandler.add(self, self.db.last_ticker_deley_value)

        if not self.goods:
            return

        goods_to_create = self.goods.values()

        for good in goods_to_create:
            good_in_inv = self.search(good["name"], location=self, nofound_string="")
            if not good_in_inv:
                new_good = create_object(good["typeclass"], good["name"], self, home=self)
                if not new_good.db.desc:
                    if good["desc"]:
                        new_good.db.desc = good["desc"]
                new_good.db.coast = good["coast"]
示例#29
0
    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, "evennia.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 = managers.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_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)
示例#30
0
 def at_object_creation(self):
     #прикручиваем руку
     self.db.hands = create_object(settings.BASE_OBJECT_TYPECLASS, "hands")
     #прикручиваем фраги
     self.db.frags = 0
     #прикручиваем количество смертей
     self.db.death_count = 0
     #прикручиваем хеш ээфектов
     self.db.effects = {} 
     #ассоциация с хатой.
     self.db.flat = None
     #прикручивам группу
     self.db.party = []
     #прикручиваем лидера группы
     self.db.party_leader = None
     #прикручиваем деньги
     self.db.money = 3
     #прикручиваем религию
     self.db.religion = "атеист"
     #прикручиваем предыдущую локацию
     self.db.last_location = None
示例#31
0
def example1_build_temple(x, y, **kwargs):
    """A unique room that does not need to be as general"""

    # Create the room.
    room = create_object(rooms.Room, key="temple" + str(x) + str(y))

    # Set the description.
    room.db.desc = ("In what, from the outside, appeared to be a grand and "
                    "ancient temple you've somehow found yourself in the the "
                    "Evennia Inn! It consists of one large room filled with "
                    "tables. The bardisk extends along the east wall, where "
                    "multiple barrels and bottles line the shelves. The "
                    "barkeep seems busy handing out ale and chatting with "
                    "the patrons, which are a rowdy and cheerful lot, "
                    "keeping the sound level only just below thunderous. "
                    "This is a rare spot of mirth on this dread moor.")

    # Send a message to the player
    kwargs["caller"].msg(room.key + " " + room.dbref)

    # This is generally mandatory.
    return room
示例#32
0
文件: command.py 项目: j3b4/Mutiny
 def func(self):
     "creates the object and names it"
     caller = self.caller
     if not self.args:
         caller.msg("Usage: +createNPC <name>")
         return
     if not caller.location:
         # may not create npc when OOC
         caller.msg("You must have a location to create an NPC.")
         return
     # make name always start with a capital letter
     name = self.args.strip().capitalize()
     # create npc in caller's location
     npc = create_object("characters.Character",
                         key=name, location=caller.location,
                         locks="edit:id(%i) and perm(Builders)"
                         % caller.id)
     # announce
     message = "%s created the NPC '%s'."
     caller.msg(message % ("You", name))
     caller.location.msg_contents(message % (caller.key, npc.key),
                                  exclude=caller)
示例#33
0
 def test_crumblingwall(self):
     wall = create_object(tutobjects.CrumblingWall,
                          key="wall",
                          location=self.room1)
     self.assertFalse(wall.db.button_exposed)
     self.assertFalse(wall.db.exit_open)
     wall.db.root_pos = {"yellow": 0, "green": 0, "red": 0, "blue": 0}
     self.call(
         tutobjects.CmdShiftRoot(),
         "blue root right",
         "You shove the root adorned with small blue flowers to the right.",
         obj=wall)
     self.call(tutobjects.CmdShiftRoot(),
               "red root left",
               "You shift the reddish root to the left.",
               obj=wall)
     self.call(
         tutobjects.CmdShiftRoot(),
         "yellow root down",
         "You shove the root adorned with small yellow flowers downwards.",
         obj=wall)
     self.call(
         tutobjects.CmdShiftRoot(),
         "green root up",
         "You shift the weedy green root upwards.|Holding aside the root you think you notice something behind it ...",
         obj=wall)
     self.call(
         tutobjects.CmdPressButton(),
         "",
         "You move your fingers over the suspicious depression, then gives it a decisive push. First",
         obj=wall)
     self.assertTrue(wall.db.button_exposed)
     self.assertTrue(wall.db.exit_open)
     wall.reset()
     if hasattr(wall, "deferred"):
         wall.deferred.cancel()
     wall.delete()
示例#34
0
文件: wiz.py 项目: ChrisLR/scrolls
    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])
示例#35
0
def spell_conjure(caster, spell_name, targets, cost, **kwargs):
    """
    Spell that creates an object.

    kwargs:
        obj_key (str): Key of the created object.
        obj_desc (str): Desc of the created object.
        obj_typeclass (str): Typeclass path of the object.

    If you want to make more use of this particular spell funciton,
    you may want to modify it to use the spawner (in evennia.utils.spawner)
    instead of creating objects directly.
    """

    obj_key = "a nondescript object"
    obj_desc = "A perfectly generic object."
    obj_typeclass = "evennia.objects.objects.DefaultObject"

    # Retrieve some variables from kwargs, if present
    if "obj_key" in kwargs:
        obj_key = kwargs["obj_key"]
    if "obj_desc" in kwargs:
        obj_desc = kwargs["obj_desc"]
    if "obj_typeclass" in kwargs:
        obj_typeclass = kwargs["obj_typeclass"]

    conjured_obj = create_object(
        obj_typeclass, key=obj_key, location=caster.location
    )  # Create object
    conjured_obj.db.desc = obj_desc  # Add object desc

    caster.db.mp -= cost  # Deduct MP cost

    # Message the room to announce the creation of the object
    caster.location.msg_contents(
        "%s casts %s, and %s appears!" % (caster, spell_name, conjured_obj)
    )
示例#36
0
 def spawnRooms(self):
     if self.rooms_created:
         print("Rooms already created!")
     else:
         firstRoom = True
         for vnum, room in self.rooms.items():
             if (self.last_area != room['area']):
                 self.last_area = room['area']
                 firstRoom = True
             newroom = create_object(
                 typeclass="typeclasses.rooms.LegacyRoom", key=room['name'])
             newroom.db.desc = room['desc']
             newroom.tags.add(room['area'], category='area')
             newroom.db.area = room['area']
             self.room_translate[vnum] = newroom.id
             if self.verbose:
                 print("Area: %s Room: %s Vnum: %s Evid: %s" %
                       (room['area'], room['name'], vnum, newroom.id))
             if (firstRoom):
                 print(room['area'] + ': ' + str(newroom.id) + " = " +
                       room['name'])
                 firstRoom = False
         self.rooms_created = True
         self._spawnRooms_exits()
示例#37
0
文件: wiz.py 项目: ChrisLR/scrolls
    def func(self):
        ch = self.caller
        args = self.args.strip().split()

        if not args:
            ch.msg(f"{self.__doc__}")
            return
        if len(args) == 1:
            ch.msg("must supply valid vnum number")
            return
        # <obj/mob> <vnum>
        obj_type, vnum = args
        if obj_type.lower() not in ('obj', 'mob'):
            ch.msg("must supply either `obj` or `mob`")
            return

        try:
            vnum = int(vnum)
        except ValueError:
            ch.msg("invalid vnum number")
            return

        # check to see if vnum exists
        if vnum not in GLOBAL_SCRIPTS.objdb.vnum.keys():
            ch.msg(f"that {obj_type}:{vnum} does not exist")
            return
        obj_bp = GLOBAL_SCRIPTS.objdb.vnum[vnum]
        # create instance of object and either put in room
        obj_type = CUSTOM_OBJS[obj_bp['type']]
        obj = create_object(obj_type, key=vnum)
        obj.move_to(ch.location)
        act_msg = "$n motions $s hands around and $e creates"\
            f" |G{obj.db.sdesc}|n"
        act(act_msg, False, False, ch, None, None, Announce.ToRoom)
        act(f"You create |G{obj.db.sdesc}|n", False, False, ch, None, None,
            Announce.ToChar)
示例#38
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))
示例#39
0
    def func(self):
        errmsg = "Usage: createnpc <name>"
        "create the object and name it"
        caller = self.caller
        # Error handling
        if not self.args:
            caller.msg(errmsg)
            return
        if not caller.location:
            # May not create npc when OOC
            caller.msg("|430You must be in a location to build an npc.|n")
            return

        # make name always start with capital letter
        name = self.args.strip().capitalize()
        # create npc in caller's location
        npc = create_object(
            "characters.Character",
            key=name,
            location=caller.location,
            locks="edit:id(%i) and perm(Builders);call:false()" % caller.id)
        # announce
        message = "%s created the NPC '%s'."
        caller.msg(message % ("You", name))
示例#40
0
def connect_all_areas():
    CARDINAL_DIRS = {
        "north": "south",
        "south": "north",
        "east": "west",
        "west": "east",
        "northeast": "southwest",
        "southwest": "northeast",
        "southeast": "northwest",
        "northwest": "southeast"
    }

    EXIT_OPPOSITE = {
        "north": "south",
        "south": "north",
        "east": "west",
        "west": "east",
        "northeast": "southwest",
        "southwest": "northeast",
        "southeast": "northwest",
        "northwest": "southeast"
    }

    def is_cardinal_direction(mech_exit):
        return mech_exit.name in CARDINAL_DIRS

    # Gets the exit of of the opposite direction from destRoom (i.e.
    # if mech_exit is North, it will return the Exit object of South
    # from destRoom.
    # If opposite exit is not found, it will return None.
    def get_opposite_exit(mech_exit, destRoom):
        for exit in destRoom.exits:
            if EXIT_OPPOSITE[exit.name] == mech_exit.name:
                return exit

        return None

    # Get all the rooms that match the <area> tag
    connector_from_rooms = evennia.utils.search.search_object_by_tag(
        key="connector_from", category="map_builder")
    connector_to_rooms = evennia.utils.search.search_object_by_tag(
        key="connector_to", category="map_builder")

    for from_room in connector_from_rooms:
        # get the connector dict
        connectorDict = from_room.db.map_builder_connector_dict

        if not connectorDict:
            raise Exception(
                "No connector dictionary assigned to connector from_room "
                "%s/#%d in zone %s" % (from_room.name, int(
                    from_room.id), from_room.tags.get(category="zone")))

        zoneDest = connectorDict["zoneDestination"]
        connectorName = connectorDict["connectorName"]

        for rooms in connector_to_rooms:
            print "TEST"
            print "zoneDest: " + zoneDest
            print "connectorname: " + connectorName
            print rooms.tags.all(return_key_and_category=True)
            print rooms.ndb.connector_name
            print "connectorname == rooms.ndb.connector_name" + \
            str(str(connectorName) == str(rooms.ndb.connector_name))

        # Search the to rooms for the one with a tag with zoneDest as zone
        # TROUBLE HERE.  connector_name == connectorName doesn't seem to work.
        to_room = [to_room for to_room in connector_to_rooms if \
                   to_room.tags.get(zoneDest, category="zone") and \
                   (str(to_room.ndb.connector_name) == str(connectorName))]

        # Do we have multiple to rooms?
        if len(to_room) > 1:
            exMsg = "Multiple to_room for connector to zone %s:%s" % (
                zoneDest, connectorName)
            raise Exception(exMsg)

        if len(to_room) == 0:
            exMsg = "No to_room matching %s:%s" % (zoneDest, connectorName)
            raise Exception(exMsg)

        if to_room == None:
            exMsg = "No to_room for connector to zone %s:%s" % (zoneDest,
                                                                connectorName)
            raise Exception(exMsg)

        to_room = to_room[0]

        # Gather exits leading into this room.
        # Check to make sure to_room doesn't already have these exits.
        # Follow the exit to exit's distination, and then set the cardinal
        # direction exit to the to_room instead
        # Then delete the from_room connector.

        #Gather exits
        from_room_exits = from_room.exits
        to_room_exits = to_room.exits

        # Gather exits in "from_room", and move them to "to_room"
        for from_exit in from_room_exits:
            exit_in_to_room = False
            create_exit_name = from_exit.name

            if (is_cardinal_direction(from_exit)):
                for to_exit in to_room_exits:
                    if to_exit.name == create_exit_name:
                        exit_in_to_room = True
                if exit_in_to_room:
                    raise Exception("Can't connect connector room exit.  There"
                                    "is already an exit named %s in room #%s" %
                                    (create_exit_name, to_room.id))

            # Create the exit in the to_room, same as exit in from_room
            evennia.create_object(typeclass="exits.Exit",
                                  key=create_exit_name,
                                  location=to_room,
                                  destination=from_exit.destination,
                                  aliases=from_exit.aliases.all())

            # Now iterate over all the rooms with exits to the "from_room", and
            # set their destination to the to room.
            for currExit in Exit.objects.all_family():
                if currExit.destination == from_room:
                    currExit.destination = to_room
示例#41
0
文件: apartment.py 项目: op-hui/mu2ch
 def at_repeat(self): 
     knife = self.obj.search(u"Картонный нож", quiet = True)
     if (not knife):
         create_object('typeclasses.weapons.Knife', u"Картонный нож", self.obj)
示例#42
0
 def setUp(self):
     super(TestWilderness, self).setUp()
     self.char1 = create_object(DefaultCharacter, key="char1")
     self.char2 = create_object(DefaultCharacter, key="char2")
示例#43
0
 def setUp(self):
     super(TestRPSystem, self).setUp()
     self.room = create_object(rpsystem.ContribRPRoom, key="Location")
     self.speaker = create_object(rpsystem.ContribRPCharacter, key="Sender", location=self.room)
     self.receiver1 = create_object(rpsystem.ContribRPCharacter, key="Receiver1", location=self.room)
     self.receiver2 = create_object(rpsystem.ContribRPCharacter, key="Receiver2", location=self.room)
示例#44
0
 def test_tutorialobj(self):
     obj1 = create_object(tutobjects.TutorialObject, key="tutobj")
     obj1.reset()
     self.assertEqual(obj1.location, obj1.home)
示例#45
0
Batchcode for Balamb Garden.

"""

from evennia import create_object
from typeclasses import rooms, exits, characters

###############################################################################
# INITIATE ROOMS
# Rooms are created first, as adding exits and details will cross refer to
# different locations which would otherwise not be instantiated yet.
###############################################################################

# BASEMENT

underground_chamber = create_object(rooms.Room, key="Underground Chamber")
garden_masters_office = create_object(rooms.Room, key="Garden Master's Office")

# FLOOR 1

front_gate = create_object(rooms.Room, key="Front Gate")
front_courtyard = create_object(rooms.Room, key="Front Courtyard")
reception = create_object(rooms.Room, key="Reception")
lobby = create_object(rooms.Room, key="Lobby")

infirmary = create_object(rooms.Room, key="Infirmary")

quad = create_object(rooms.Room, key="Quad")

cafeteria = create_object(rooms.Room, key="Cafeteria")
示例#46
0
def build_the1st_lodge():

    lodge = create_object(LodgeInstance, key='lodge01')

    hall = lodge.create_room(key='hall', position=(3, 3), size=(7, 5))

    passage_l = lodge.create_room(key='left passage',
                                  position=(2, 3),
                                  size=(1, 5))

    passage_r = lodge.create_room(key='right passage',
                                  position=(10, 0),
                                  size=(1, 8))

    passage_m = lodge.create_room(key='middle passage',
                                  position=(3, 2),
                                  size=(7, 1))

    room_1 = lodge.create_room(key='room 1',
                               aliases=['r1'],
                               position=(0, 7),
                               size=(2, 1))

    room_2 = lodge.create_room(key='room 2',
                               aliases=['r2'],
                               position=(0, 3),
                               size=(2, 4))

    room_3 = lodge.create_room(key='room 3',
                               aliases=['r3'],
                               position=(0, 0),
                               size=(3, 3))

    room_4 = lodge.create_room(key='room 4',
                               aliases=['r4'],
                               position=(3, 0),
                               size=(4, 2))

    room_5 = lodge.create_room(key='room 5',
                               aliases=['r5'],
                               position=(7, 0),
                               size=(3, 2))

    room_6 = lodge.create_room(key='room 6',
                               aliases=['r6'],
                               position=(11, 0),
                               size=(2, 8))

    hall.link_with_exit(passage_l, aliases=['left'])
    hall.link_with_exit(passage_r, aliases=['right'])
    hall.link_with_exit(passage_m, aliases=['middle', 'mid'])

    passage_l.link_with_exit(room_1, back_aliases=['out'])
    passage_l.link_with_exit(room_2, back_aliases=['out'])
    passage_l.link_with_exit(room_3, back_aliases=['out'])

    room_3.link_with_exit(room_4)
    passage_m.link_with_exit(room_4, back_aliases=['out'])
    passage_m.link_with_exit(room_5, back_aliases=['middle', 'mid'])

    passage_m.link_with_exit(passage_r,
                             aliases=['right'],
                             back_aliases=['middle', 'mid'])
    passage_r.link_with_exit(room_5, back_aliases=['right'])
    passage_r.link_with_exit(room_6, back_aliases=['out'])
示例#47
0
 def setUp(self):
     super(TestBarter, self).setUp()
     self.tradeitem1 = create_object(key="TradeItem1", location=self.char1)
     self.tradeitem2 = create_object(key="TradeItem2", location=self.char1)
     self.tradeitem3 = create_object(key="TradeItem3", location=self.char2)
示例#48
0
    def func(self):
        args = self.args.strip().split()
        if not args:
            self.caller.msg("Craft what?")
            return

        items = list()
        action = args.pop(0).lower()

        if action not in ["add", "remove", "recipe", "cancel"]:
            self.caller.msg("Invalid syntax.")
            return

        if action in ["add", "remove"]:
            args = " ".join(args).split(",")

            for item in args:
                items.append(item.strip())

           
        self.items = items
        self.action = action

        caller = self.caller
        recipe_script = search_script("recipescript", typeclass="world.recipescript.RecipeScript")

        try:
            recipe_script = recipe_script[0]
        except IndexError:
            recipe_script = create_script(key="recipescript", typeclass="world.recipescript.RecipeScript")


        if self.action == "add":
            for _item in self.items:
                item = caller.search(_item, location=caller)
                if not item:
                    continue

                if item.tags.get(category="craftable"):
                    caller.db.craft_stack.append(item)
                    caller.msg("Added '%s' to the crafting stack..." % item)

        elif self.action == "remove":
            pass
        elif self.action == "cancel":
            pass
        elif self.action == "recipe":
            inv = []
            recipe_name = self.args.strip()

            for item in caller.db.craft_stack:
                tag = item.tags.get(category="craftable")

                if type(tag) is type(""):
                    inv.append(tag.lower())

                elif type(tag) is type([]):
                    inv.extend(t.lower() for t in tag)

            found_recipe = None

            for recipe in recipe_script.recipes:
                for recipe_key in recipe.keys():
                    if recipe_key == recipe_name:
                        found_recipe = recipe
                        break
                if found_recipe:
                    break

            if not found_recipe:
                caller.msg("No such recipe.")

            recipe = found_recipe
            missing = []

            for comp in recipe["components"]:
                for needed_count in recipe["components"][comp]
                    inv_count = inv.count(comp)

                    if inv_count < needed_count:
                        # missing ingredients
                        missing.append((comp, needed_count - inv_count))
                    else:
                        # we have all we need of this ingredient
                        pass

            if len(missing) > 0:
                for row in missing:
                    caller.msg("You are missing %s %s." % row)

                return

            for component in recipe['components']:
                for c in range(recipe['components'][component]):
                    # remove component from caller
                    for item in self.caller.db.craft_stack:
                        if item.tags.get(component, category="crafting"):
                            caller.db.craft_stack.remove(item)
                            # item.delete()
                            # _item = caller.search("#%i" % item.id, use_dbref=True, quiet=True)
                            # if _item:
                                # _item.pop().delete()

            obj = create_object(key=recipe_name, typeclass=recipe['typeclass'], location=caller)
            caller.msg("You crafted %s." % obj)
示例#49
0
def _maintain_demo_room(caller, delete=False):
    """
    Handle the creation/cleanup of demo assets. We store them
    on the character and clean them when leaving the menu later.
    """
    # this is a tuple (room, obj)
    roomdata = caller.db.tutorial_world_demo_room_data

    if delete:
        if roomdata:
            # we delete directly for simplicity. We need to delete
            # in specific order to avoid deleting rooms moves
            # its contents to their default home-location
            prev_loc, room1, sign, room2, stone, door_out, door_in = roomdata
            caller.location = prev_loc
            sign.delete()
            stone.delete()
            door_out.delete()
            door_in.delete()
            room1.delete()
            room2.delete()
            del caller.db.tutorial_world_demo_room_data
    elif not roomdata:
        # create and describe the cabin and box
        room1 = create_object("evennia.objects.objects.DefaultRoom", key="A small, cozy cabin")
        room1.db.desc = _ROOM_DESC.lstrip()
        sign = create_object(
            "evennia.objects.objects.DefaultObject", key="small wooden sign", location=room1
        )
        sign.db.desc = _SIGN_DESC.strip()
        sign.locks.add("get:false()")
        sign.db.get_err_msg = "The sign is nailed to the wall. It's not budging."

        # create and describe the meadow and stone
        room2 = create_object("evennia.objects.objects.DefaultRoom", key="A lush summer meadow")
        room2.db.desc = _MEADOW_DESC.lstrip()
        stone = create_object(
            "evennia.objects.objects.DefaultObject", key="carved stone", location=room2
        )
        stone.db.desc = _STONE_DESC.strip()

        # make the linking exits
        door_out = create_object(
            "evennia.objects.objects.DefaultExit",
            key="Door",
            location=room1,
            destination=room2,
            locks=["get:false()"],
        )
        door_out.db.desc = _DOOR_DESC_OUT.strip()
        door_in = create_object(
            "evennia.objects.objects.DefaultExit",
            key="entrance to the cabin",
            aliases=["door", "in", "entrance"],
            location=room2,
            destination=room1,
            locks=["get:false()"],
        )
        door_in.db.desc = _DOOR_DESC_IN.strip()

        # store references for easy removal later
        caller.db.tutorial_world_demo_room_data = (
            caller.location,
            room1,
            sign,
            room2,
            stone,
            door_out,
            door_in,
        )
        # move caller into room
        caller.location = room1
示例#50
0
def create_room_exits_from_xml(xml_exit_node, xml_rooms_dict, mechRoomsDict):
    # Create the exits
    #TODO: ONE-WAY EXITS! This is useful for non-cardinal direction exits which
    # might have different discriptions on either side of the exit...

    # A list - First 2 entries are source and destination.
    roomsSrcDest = []

    # Get the ids. Each "dock" has ids in continous order for a single exit,
    # so store in a list.
    dockNodes = {}

    isOneWay = False
    if xml_exit_node.attrib.get("flow") == "oneWay":
        isOneWay = True

    for child in xml_exit_node:
        if (child.tag == "dock"):
            dockIndex = child.attrib.get("index")
            dockNodes[dockIndex] = child

            roomId = child.attrib.get("id")
            roomsSrcDest.append(mechRoomsDict[roomId])

    # Create exits on both rooms.
    for dockKey, dock in dockNodes.iteritems():
        print dock

        dockIndex = int(dock.attrib.get("index"))

        if isOneWay:
            print "Is one way? " + str(isOneWay)
            if dockIndex != 0:
                continue

        # Check if this is one way, and we are going the correct way.
        exitNameList = []
        if xml_exit_node.attrib.get("name"):
            if (xml_exit_node.attrib.get("name") != ""):
                # Names on exits override
                exitNameList = get_named_exit_aliases_from_line(xml_exit_node)
                print(exitNameList)

        if (len(exitNameList) == 0):
            exitNameList = get_cardinal_name_and_aliases_from_dock_node(dock)

        # TODO Tags?
        srcRoom = roomsSrcDest[dockIndex]
        dstRoom = roomsSrcDest[(dockIndex + 1) % 2]

        for exit in srcRoom.exits:
            if exit.name == exitNameList[0]:
                msg = "Trying to create an exit {0}:#{1} on room" \
                      "{2}:#{3} that already has that exit " \
                      "created!".format(exit.name, exit.id, \
                       srcRoom.name, srcRoom.id)

                print(msg)
                raise Exception(msg)

        evennia.create_object(typeclass="exits.Exit",
                              key=exitNameList[0],
                              location=srcRoom,
                              aliases=exitNameList[1:],
                              destination=dstRoom)
示例#51
0
delete_tagged(tag)


# Tag players
try:
    p1 = search_object('Foo')[0]
    p2 = search_object('Bar')[0]
except IndexError:
    assert(False), 'Please create the "Foo" and "Bar" users before running this script.'
p1.tags.add("p1", category="duo")
p1.tags.remove("p2", category="duo")
p2.tags.add("p2", category="duo")
p2.tags.remove("p1", category="duo")

blue_room = create_object(Room,
        key="Blue Room",
        aliases=["blue"])
blue_room.tags.add(tag)

red_room = create_object(Room,
        key="Red Room",
        aliases=["red"])
red_room.tags.add(tag)

caller.msg("About to link...")
links = link([blue_room, limbo])
[x.tags.add(tag) for x in links]

links = link([blue_room, red_room])
# Only one player can traverse between the red and blue room.
for link in links:
示例#52
0
 def at_object_creation(self):
     self.db.is_corpse = True
     self.db.hands = create_object(settings.BASE_OBJECT_TYPECLASS, "hands")
     #создаем таймер для трупа
     tickerhandler.add(self, 60*3)
示例#53
0
# -*- coding:utf-8 -*-

from evennia import create_object
from evennia import DefaultObject
from world import map_module

map = create_object(DefaultObject, key="Map", location=caller.location)

map.db.desc = map_module.return_map()

caller.msg("A map appears out of thin air and falls to the ground.")
示例#54
0
 def test_introroom(self):
     room = create_object(tutrooms.IntroRoom, key="introroom")
     room.at_object_receive(self.char1, self.room1)
示例#55
0
def build_map(caller, game_map, legend, iterations=1, build_exits=True):
    """
    Receives the fetched map and legend vars provided by the player.

    Args:
        caller (Object): The creator of the map.
        game_map (str): An ASCII map string.
        legend (dict): Mapping of map symbols to object types.
        iterations (int): The number of iteration passes.
        build_exits (bool): Create exits between new rooms.

    Notes:
        The map
        is iterated over character by character, comparing it to the trigger
        characters in the legend var and executing the build instructions on
        finding a match. The map is iterated over according to the `iterations`
        value and exits are optionally generated between adjacent rooms according
        to the `build_exits` value.

    """

    # Split map string to list of rows and create reference list.
    caller.msg("Creating Map...")
    caller.msg(game_map)
    game_map = _map_to_list(game_map)

    # Create a reference dictionary which be passed to build functions and
    # will store obj returned by build functions so objs can be referenced.
    room_dict = {}

    caller.msg("Creating Landmass...")
    for iteration in range(iterations):
        for y in range(len(game_map)):
            for x in range(len(game_map[y])):
                for key in legend:
                    # obs - we must use == for strings
                    if game_map[y][x] == key:
                        room = legend[key](x,
                                           y,
                                           iteration=iteration,
                                           room_dict=room_dict,
                                           caller=caller)
                        if iteration == 0:
                            room_dict[(x, y)] = room

    if build_exits:
        # Creating exits. Assumes single room object in dict entry
        caller.msg("Connecting Areas...")
        for loc_key, location in room_dict.items():
            x = loc_key[0]
            y = loc_key[1]

            # north
            if (x, y - 1) in room_dict:
                if room_dict[(x, y - 1)]:
                    create_object(
                        exits.Exit,
                        key="north",
                        aliases=["n"],
                        location=location,
                        destination=room_dict[(x, y - 1)],
                    )

            # east
            if (x + 1, y) in room_dict:
                if room_dict[(x + 1, y)]:
                    create_object(
                        exits.Exit,
                        key="east",
                        aliases=["e"],
                        location=location,
                        destination=room_dict[(x + 1, y)],
                    )

            # south
            if (x, y + 1) in room_dict:
                if room_dict[(x, y + 1)]:
                    create_object(
                        exits.Exit,
                        key="south",
                        aliases=["s"],
                        location=location,
                        destination=room_dict[(x, y + 1)],
                    )

            # west
            if (x - 1, y) in room_dict:
                if room_dict[(x - 1, y)]:
                    create_object(
                        exits.Exit,
                        key="west",
                        aliases=["w"],
                        location=location,
                        destination=room_dict[(x - 1, y)],
                    )

    caller.msg("Map Created.")
示例#56
0
 def test_darkroom(self):
     room = create_object(tutrooms.DarkRoom, key="darkroom")
     self.char1.move_to(room)
     self.call(tutrooms.CmdDarkHelp(), "", "Can't help you until")
示例#57
0
def give_starting_gold(character):
  gold = create_object("typeclasses.objects.Gold", key="gold")
  gold.add(STARTING_GOLD_AMOUNT)
  # use move_to() so we invoke StackableObject accumulation
  gold.move_to(character, quiet=True)
  character.msg(f"You now have {gold.db.amount} gold.")
示例#58
0
 def test_teleportroom(self):
     create_object(tutrooms.TeleportRoom, key="teleportroom")
示例#59
0
 def func(self):
     myObj = create_object(DefaultObject,
                           key="MyObj",
                           location=self.caller.location)
     self.caller.msg(
         "An object appears out of thin air and falls to the ground.")
示例#60
0
 def test_outroroom(self):
     create_object(tutrooms.OutroRoom, key="outroroom")