Exemple #1
0
    def setUp(self):

        self.i1 = Item()
        self.i2 = Item(name='axe', weight=1000)

        self.c1 = Container()
        self.c2 = Container(name='backpack', weight=2000)
Exemple #2
0
    def setUp(self):
        from items.item import Item
        from items.item_set import ItemSet

        sword = Item("sword", "made by elves", 2)
        helmet = Item("helmet", "made by men", 1)
        potion = Item("potion", "restores health", 1)

        self._itemList = [sword, helmet, potion]
        self._items = ItemSet([sword, helmet, potion])
    def test_inventory_add(self):
        inventory = Inventory()
        cool_item_1 = Item(uid="cool_item_1", name="Very Cool Item")
        cool_item_2 = Item(uid="cool_item_2", name="Very Cool Item Too")
        inventory.add_item(cool_item_1)
        inventory.add_item(cool_item_2)

        self.assertEqual(
            inventory.get_items("cool_item_1", pop=True)[0], cool_item_1)
        self.assertGreater(len(inventory.get_items("cool_item_1")), 0)
        self.assertEqual(inventory.get_items("cool_item_2")[0], cool_item_2)
Exemple #4
0
    def testItems(self):
        from space import Space
        from items.item import Item

        #Prepare items
        blade = Item("blade", "appears to be dull", 1)
        bow = Item("bow", "long bow", 2)

        #Create space
        space = Space("shire", "Home of the Hobbits.")
        items = space.getItemSet()

        #Assert space initially empty
        errorMsg = "New space contains items; should be empty"
        self.assertEqual(items.count(), 0, errorMsg)

        errorMsg = "Space claims to contain item even though it is empty."
        self.assertFalse(space.containsItem(blade), errorMsg)
        self.assertFalse(space.containsItem(bow), errorMsg)

        #Add blade
        space.addItem(blade)
        errorMsg = "Space failed to report that it contained item known to exist."
        self.assertTrue(space.containsItem(blade), errorMsg)

        #Add bow
        space.addItem(bow)
        self.assertTrue(space.containsItem(bow), errorMsg)

        #Get room's items. Assert blade and bow exist
        items = space.getItemSet()
        self.assertEqual(items.count(), 2,
                         "Room should contain exactly two items.")
        self.assertTrue(items.containsItem(blade),
                        "Could not find blade in room's set of items.")
        self.assertTrue(items.containsItem(bow),
                        "Could not find bow in room's set of items.")

        #Remove blade
        space.removeItem(blade)
        errorMsg = "Space claims to have item that was removed."
        self.assertFalse(space.containsItem(blade), errorMsg)
        errorMsg = "Space missing item that should still exist."
        self.assertTrue(space.containsItem(bow), errorMsg)

        #Get room's items. Assert only bow exists
        items = space.getItemSet()
        self.assertEqual(items.count(), 1,
                         "Room should contain exactly one item.")
        self.assertFalse(items.containsItem(blade),
                         "Blade found in room (even though it was removed).")
        self.assertTrue(items.containsItem(bow),
                        "Could not find bow in room's set of items.")
Exemple #5
0
    def update(self, game: List[List[int]]) -> None:
        """Loop through the game list and mirror it to a list of objects such that
        the objects represent visually what is going on in the game.

        Both lists are iterated on in parallel, if the object list contains an
        item where the new game list is empty remove that item. If they are
        different change it to the new one.
        """

        wall_color = (0, 0, 255)
        player_color = (0, 255, 0)
        food_color = (255, 0, 0)

        temp_list = []

        for row in range(len(game)):
            temp_col = []

            # Create a object based on the item in the list
            for col in range(len(game[row])):
                current = game[row][col]

                # Check which item is in the spot
                if current == 0:
                    temp_col.append(None)

                # add player object
                elif current == 1:
                    item = Item((row * self.SCALE, col * self.SCALE),
                                player_color)
                    temp_col.append(item)

                # add food object
                elif current == 2:
                    item = Item((row * self.SCALE, col * self.SCALE),
                                food_color)
                    temp_col.append(item)

                # add wall object
                elif current == 3:  # add green item
                    item = Item((row * self.SCALE, col * self.SCALE),
                                wall_color)
                    temp_col.append(item)

                else:
                    temp_col.append(None)

            temp_list.append(temp_col)

        self.objects = temp_list
    def test_inventory_keybound(self):
        inventory = KeyBoundInventory()
        cool_item_1 = Item(uid="cool_item_1", name="Very Cool Item")
        cool_item_2 = Item(uid="cool_item_2", name="Very Cool Item Too")
        cool_item_1_symbol = inventory.add_item(cool_item_1)
        cool_item_2_symbol = inventory.add_item(cool_item_2)

        self.assertEqual(inventory.pop_item_from_symbol(cool_item_1_symbol),
                         cool_item_1)
        self.assertEqual(inventory.pop_item_from_symbol(cool_item_2_symbol),
                         cool_item_2)

        symbols = []
        for kek in range(0, 1000):
            symbols.append(inventory.add_item(cool_item_1))
        print(symbols)
Exemple #7
0
    def load(self):
        with open("savefile", "rb") as f:
            loaddata = pickle.load(f)
        self.all_sprites = pg.sprite.LayeredUpdates()
        self.walls = pg.sprite.Group()
        self.mobs = pg.sprite.Group()
        self.mobslist = []
        self.ghostlist = []
        self.bullets = pg.sprite.Group()
        self.items = pg.sprite.Group()
        self.itemslist = []
        self.map = TiledMap(path.join(map_folder, 'Fase1.tmx'))
        self.map_img = self.map.make_map()
        self.map.rect = self.map_img.get_rect()

        self.player = Player(self, loaddata[0][2][0], loaddata[0][2][1])
        self.player.health = loaddata[0][0]
        self.player.weapon = loaddata[0][1]
        for zombie in loaddata[1]:
            M = Mob(self, zombie[0], zombie[1])
            self.mobslist.append(M)
        for ghost in loaddata[3]:
            G = Ghost(self, ghost[0], ghost[1])
            self.ghostlist.append(G)
        for item in loaddata[2]:
            I = Item(self, item[0], item[1])
            self.itemslist.append(I)
        for tile_object in self.map.tmxdata.objects:
            if tile_object.name == 'wall':
                Obstacle(self, tile_object.x, tile_object.y, tile_object.width,
                         tile_object.height)

        self.camera = Camera(self.map.width, self.map.height)
        self.draw_debug = False
        self.paused = False
def build_item(name, item_data, actor=None, is_player=False): 
    # Build a new item and return finished item
    item = Item(name, item_data[name]['image'], item_data[name]['color_fg'],
                1, item_data[name]['stackable'], item_data[name]['targeting'],
                item_data[name]['range'])
    item.action = build_action(name, item, item_data, actor, is_player)

    return item
Exemple #9
0
    def spawn_hearts(self, quantity: int):
        image_file = "misc/heart.png"

        for _ in range(quantity):
            chosen = choice(list(self.floors))
            position = (chosen.rect.left, chosen.rect.top)

            self.hearts.add(
                Item(self.surface, position, (30, 30), image_file, 0))
Exemple #10
0
    def spawn_energy_orbs(self, quantity: int):
        image_file = "misc/energy_orb.png"

        for _ in range(quantity):
            chosen = choice(list(self.floors))
            position = (chosen.rect.left, chosen.rect.top)

            self.energy_orbs.add(
                Item(self.surface, position, (20, 20), image_file, 0))
Exemple #11
0
def convert_to_object(entity):
    item_id = entity.key.id_or_name

    return Item(item_id, entity['title'], entity['daily_price'],
                entity['weekly_price'], entity['monthly_price'],
                entity['description'], entity['retail_price'], entity['kind'],
                entity['rented'], entity['rentee'], entity['renter'],
                entity['past_rented'], entity['category'], entity['location'],
                entity['blob_url'])
Exemple #12
0
    def testItem(self):
        from items.item import Item
        name = "Generic item"
        description = "Generic description"
        weight = 9

        item = Item(name, description, weight)

        errorMsg = "Expected item name to be '%s'." % name
        self.assertEqual(item.getName(), name, errorMsg)
        errorMsg = "Expected item description to be '%s'." % description
        self.assertEqual(item.getDescription(), description, errorMsg)
        errorMsg = "Expected item weight to be '%s'." % weight
        self.assertEqual(item.getWeight(), weight, errorMsg)
Exemple #13
0
    def create_player(self, name, address=None):
        players = self.players
        for plr in players:
            if plr.name == name:
                return None

        room1 = self.rooms[0]

        name = str(name)
        id_player = len(players) + 1
        new_player = Player(id_player, name, address=address)
        new_player.inventory.append(Item('Map', command='map'))

        self.add_to_room(new_player, room1)
        players.append(new_player)
        return id_player
def build_leather_hood():
    _item = Item(
        uid="hood",
        name="hood",
        description="A leather hood.",
        display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"),
    )
    _item.register_component(data.python_templates.material.Leather.copy())
    _item.register_component(Stats(health=10, size=Size.Medium, weight=2))
    _item.register_component(
        Armor(base_armor_class=2,
              armor_category=item_enums.ArmorCategory.Medium,
              wearable_body_parts_uid=["humanoid_head"],
              worn_layer=item_enums.WornLayer.Outer))

    return _item
def build_boot():
    _boot = Item(
        uid="boot",
        name="Boot",
        description="An iron boot",
        display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"),
    )
    _boot.register_component(data.python_templates.material.Iron.copy())
    _boot.register_component(Stats(health=10, size=Size.Medium, weight=0.5))
    _boot.register_component(
        Armor(base_armor_class=0.5,
              armor_category=item_enums.ArmorCategory.Medium,
              wearable_body_parts_uid=["humanoid_foot"],
              worn_layer=item_enums.WornLayer.Outer,
              maximum_dexterity_bonus=2))

    return _boot
def build_long_sword():
    _long_sword = Item(
        uid="long_sword",
        name="Longsword",
        description="A longsword.",
        display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"),
    )
    _long_sword.register_component(data.python_templates.material.Iron.copy())
    _long_sword.register_component(Stats(health=1, size=Size.Medium))
    _long_sword.register_component(
        Weapon(weapon_category=item_enums.WeaponCategory.Martial,
               weapon_type=item_enums.WeaponType.Melee,
               size=Size.Medium,
               melee_damage_type=DamageType.Slash,
               damage_dice=DiceStack(1, Dice(8))))

    return _long_sword
def build_leather_pants():
    # TODO Some items need to take two slots rather than one.
    item = Item(
        uid="pants",
        name="pants",
        description="Leather pants",
        display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"),
    )
    item.register_component(data.python_templates.material.Leather.copy())
    item.register_component(Stats(health=10, size=Size.Medium, weight=0.5))
    item.register_component(
        Armor(base_armor_class=1,
              armor_category=item_enums.ArmorCategory.Medium,
              wearable_body_parts_uid=["humanoid_leg"],
              worn_layer=item_enums.WornLayer.Outer,
              maximum_dexterity_bonus=2))

    return item
Exemple #18
0
    def testAddRemoveContainsItems(self):
        from items.item import Item
        antidote = Item("antidote", "cures poison", 1)

        #Verify item not included in collection
        errorMsg = "ItemSet.containsItem() claimed to contain item not present."
        self.assertFalse(self._items.containsItem(antidote), errorMsg)

        #Add item
        self._items.addItem(antidote)

        errorMsg = "ItemSet.containsItem() failed to identify existing item."
        self.assertTrue(self._items.containsItem(antidote), errorMsg)

        #Remove item
        self._items.removeItem(antidote)

        errorMsg = "ItemSet.containsItem() claimed to contain item not present."
        self.assertFalse(self._items.containsItem(antidote), errorMsg)
Exemple #19
0
    def testExecute(self):
        from player import Player
        from space import Space
        from items.item import Item
        from items.weapon import Weapon
        from commands.unequip_command import UnequipCommand

        #Attempting to unequip item not currently equipped
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        unequipCmd = UnequipCommand("unequip",
                                    "Unequips currently equipped item", player)

        item = Item("Charm", "Unknown effects", 1)
        weapon = Weapon("Dagger", "A trusty blade", 2, 2)

        rawInputMock = MagicMock(return_value="Dagger")
        with patch('commands.unequip_command.raw_input',
                   create=True,
                   new=rawInputMock):
            unequipCmd.execute()

        ###TODO: FIND SOME WAY TO MAKE SURE THAT PRINT STATEMENT PRINTED

        #Attempting to unequip item that may be unequipped
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        unequipCmd = UnequipCommand("unequip",
                                    "Unequips currently equipped item", player)

        weapon = Weapon("Dagger", "A trusty blade", 2, 2)

        player.equip(weapon)

        rawInputMock = MagicMock(return_value="Dagger")
        with patch('commands.unequip_command.raw_input',
                   create=True,
                   new=rawInputMock):
            unequipCmd.execute()

        equipped = player.getInventory()
        self.assertFalse(equipped.containsItem(weapon),
                         "Failed to unequip item that it should have.")
Exemple #20
0
    def testExecute(self):
        from space import Space
        from player import Player
        from items.item import Item
        from commands.pick_up_command import PickUpCommand

        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        item = Item("Dagger", "A trusty blade", 2)
        pickUpCmd = PickUpCommand("pick up", "Picks up an object", player)

        space.addItem(item)

        #Assert item in space but not in inventory and not in equipment
        self.assertTrue(space.containsItem(item),
                        "Space should have item but does not.")

        inventory = player.getInventory()
        self.assertFalse(inventory.containsItem(item),
                         "Player should not have item but does in inventory.")

        equipped = player.getEquipped()
        self.assertFalse(equipped.containsItem(item),
                         "Player should not have item but does in equipment.")

        #Assert item in player inventory but not in space and not in equipment
        rawInputMock = MagicMock(return_value="Dagger")

        with patch('commands.pick_up_command.raw_input',
                   create=True,
                   new=rawInputMock):
            pickUpCmd.execute()

        self.assertFalse(space.containsItem(item),
                         "Space should not have item but does.")

        equipped = player.getEquipped()
        self.assertFalse(equipped.containsItem(item),
                         "Player should not have item in equipment.")

        inventory = player.getInventory()
        self.assertTrue(inventory.containsItem(item),
                        "Player should have item but does not.")
Exemple #21
0
    def new(self):
        # Criando grupos de sprites

        self.all_sprites = pg.sprite.Group()
        self.walls = pg.sprite.Group()
        self.mobs = pg.sprite.Group()
        self.mobslist = []
        self.ghostlist = []
        self.bullets = pg.sprite.Group()
        self.items = pg.sprite.Group()
        self.itemslist = []

        # Usando a biblioteca Pytween para criar um mapa em tiles, usando o editor de mapas
        self.map = TiledMap(
            path.join(path.join(path.dirname(__file__), 'maps'), 'fase1.tmx'))
        self.map_img = self.map.make_map()
        self.map.rect = self.map_img.get_rect()

        # loop que lê os objetos posicionados no editor de mapas e cria eles
        for tile_object in self.map.tmxdata.objects:
            obj_center = vec(tile_object.x + tile_object.width / 2,
                             tile_object.y + tile_object.height / 2)

            if tile_object.name == 'player':
                self.player = Player(self, obj_center.x, obj_center.y)
            if tile_object.name == 'zombie':
                M = Mob(self, obj_center.x, obj_center.y)
                self.mobslist.append(M)
            if tile_object.name == 'ghost':
                G = Ghost(self, obj_center.x, obj_center.y)
                self.ghostlist.append(G)
            if tile_object.name == 'wall':
                Obstacle(self, tile_object.x, tile_object.y, tile_object.width,
                         tile_object.height)
            if tile_object.name in ['health', 'shotgun', 'staff']:
                I = Item(self, obj_center, tile_object.name)
                self.itemslist.append(I)

        self.camera = Camera(self.map.width, self.map.height)
        self.paused = False
Exemple #22
0
    def testEquipUnequip(self):
        from player import Player
        from space import Space
        from items.item import Item
        from items.weapon import Weapon
        from items.armor import Armor

        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)

        newItem = Item("Chainik Reakettle", "Makes good tea", 1)
        newWeapon = Weapon("Gun of Hurlocker", "Oppressive, but friendly", 2,
                           3)
        newArmor = Armor("Cookies of Miles", "Defends against sadness", 2, 4)

        player.addToInventory(newItem)
        player.addToInventory(newWeapon)
        player.addToInventory(newArmor)

        #Attempt to equip new items
        player.equip(newItem)
        self.assertFalse(newItem in player.getEquipped(),
                         "Equipped %s and should not have." % newItem)
        player.equip(newWeapon)
        self.assertTrue(newWeapon in player.getEquipped(),
                        "Failed to equip %s" % newWeapon)
        player.equip(newArmor)
        self.assertTrue(newArmor in player.getEquipped(),
                        "Failed to equip %s" % newArmor)

        #Attempt to unequip items
        player.unequip(newWeapon)
        self.assertFalse(newWeapon in player.getEquipped(),
                         "Failed to unequip %s" % newWeapon)
        player.unequip(newArmor)
        self.assertFalse(newArmor in player.getEquipped(),
                         "Failed to unequip %s" % newArmor)
Exemple #23
0
    def testItemsWeight(self):
        from items.item import Item

        errorMsg = "Initial weight of ItemSet object incorrect."
        expectedWeight = ItemSetTest.INITIAL_WEIGHT
        actualWeight = self._items.weight()
        self.assertEqual(expectedWeight, actualWeight, errorMsg)

        heavyRock = Item("heavy rock", "weighs a ton", 2000)

        #Add item
        self._items.addItem(heavyRock)

        errorMsg = "ItemSet.weight() reported incorrect weight."
        expectedWeight += 2000
        actualWeight = self._items.weight()
        self.assertEqual(expectedWeight, actualWeight, errorMsg)

        #Remove item
        self._items.removeItem(heavyRock)

        expectedWeight -= 2000
        actualWeight = self._items.weight()
        self.assertEqual(expectedWeight, actualWeight, errorMsg)
Exemple #24
0
    Room(
        "Narrow Passage",
        "The narrow passage bends here from west to north. The smell of gold permeates the air.",
    ),
    "treasure":
    Room(
        "Treasure Chamber",
        "You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.",
    ),
}

# Link rooms together

room["outside"].set_exits({"n": room["foyer"]})
room["outside"].set_loot([
    Item("Potato", "It's... Just a potato."),
])

room["foyer"].set_exits({
    "n": room["overlook"],
    "s": room["outside"],
    "e": room["narrow"]
})

room["foyer"].set_loot([Lantern()])

room["overlook"].set_exits({"s": room["foyer"]})
room["narrow"].set_exits({"n": room["treasure"], "w": room["foyer"]})
room["treasure"].set_exits({"s": room["narrow"]})

room["treasure"].set_loot([Coin(13)])
    def parseItems(self):

        print "parseItems"

        while 1:

            source_url = redisdb.rpop("SmzdmfxUrls")
            print source_url

            selector = loadHtmlSelector(source_url, method="GET")

            if selector is None: return

            lists = selector.findAll("li", {"class": "list"})
            #             print divs
            item_list = []
            for list in lists:

                item = Item()
                #                 item.categoryid = source['item_id']      #分类ID

                #条目ID
                item.itemid = int(list.attrs['articleid'].split("_")[-1])
                #                 clr.print_blue_text(item.itemid)
                print item.itemid

                #更新,直接跳到下�?个分�?
                #                 num = mongodbItem.find({"itemid":item.itemid}).count()
                #                 if num != 0 : return
                #                 if num != 0 :
                #                     clr.print_yellow_text("item exits")
                #                     continue  #暂停,继续爬�?

                #时间
                item.updatetime = int(list.attrs['timesort'])
                updatetime = time.asctime(time.localtime(item.updatetime))
                article_time = datetime.datetime.strptime(
                    updatetime,
                    "%a %b %d %H:%M:%S %Y").strftime("%Y-%m-%d %H:%M:%S %A")
                print item.updatetime
                print article_time

                #条目名称
                item.name = list.find("h2", {
                    "class": "itemName"
                }).find("span", {
                    "class": "black"
                }).get_text().strip()
                #                 print item.name

                if "优惠券".decode('utf-8') in item.name: continue  #过滤非商品条目
                if "活动".decode('utf-8') in item.name: continue
                if "专享".decode('utf-8') in item.name: continue

                #商品图片
                item.image = list.find("img", alt=True)
                if item.image:
                    item.image = item.image.attrs['src']
                    print item.image
                else:
                    item.image = ""

                    continue
                #价格
                item.price = list.find("h2", {
                    "class": "itemName"
                }).find("span", {
                    "class": "red"
                }).get_text()
                #                 if item.price == '' : continue
                if "促销".decode('utf-8') in item.price: continue
                if "红包".decode('utf-8') in item.price: continue  #过滤非商品条�?
                if item.price != '' and not re.search(r'\d', item.price):
                    continue  #过滤价格中没有数字的条目
                #                 print item.price

                #购买链接
                item.href = list.find("div", {
                    "class": "item_buy_mall"
                }).find("a", {
                    "class": "directLink"
                }).attrs['href']
                #                 clr.print_blue_text(item.href)
                #                 print item.href

                #推荐�?
                goodcount = list.find("div", {
                    "class": "zan_fav_com"
                }).find("a", {
                    "class": "zan"
                }).find("em").get_text()  #“�?��?�数
                goodcountnum = int(goodcount)
                print "goodcountnum is %d" % goodcountnum

                #评论�?
                commentcount = list.find("div", {
                    "class": "zan_fav_com"
                }).find("a", {
                    "class": "comment"
                }).get_text()
                commentcountnum = int(commentcount)
                print "commentcountnum is %d" % commentcountnum

                #文章链接
                article_url = list.find("h2", {
                    "class": "itemName"
                }).find("a").attrs['href']
                #                 print article_url
                #                 clr.print_blue_text(article_url)

                article_selector = loadHtmlSelector(article_url, headers=None)

                #商城
                originmall = article_selector.find("div", {
                    "class": "article-meta-box"
                }).find("a", {"onclick": None})
                if originmall:
                    originmall = originmall.get_text()
                else:
                    originmall = ""
#                 print originmall

#                 content_item = article_selector.find("article", {"class":"article-details"}).find("div", {"class":"item-box"})
#                 if content_item :
#优惠力度
                youhui_content = article_selector.find(
                    "div", {"class": "item-box item-preferential"})
                if youhui_content:
                    youhui_content = youhui_content.find(
                        "div", {"class": "inner-block"})
                    if youhui_content:
                        youhui_content = youhui_content.find(
                            "p").get_text().replace("\t", "").replace(
                                "\n", "").replace("\r", "").strip()
                    else:
                        youhui_content = ""
                    #爆料原文
                    baoliao_content = article_selector.find(
                        "div", {
                            "class": "item-box item-preferential"
                        }).find("div", {"class": "baoliao-block"})
                    if baoliao_content:
                        baoliao_content = baoliao_content.find(
                            "p").get_text().replace("\t", "").replace(
                                "\n", "").replace("\r", "").strip()
                    else:
                        baoliao_content = ""
                else:
                    youhui_content = article_selector.find(
                        "article", {
                            "class": "article-details"
                        }).find("div", {
                            "class": "inner-block"
                        }).get_text().replace("\t",
                                              "").replace("\n", "").replace(
                                                  "\r", "").strip()
                    baoliao_content = ""
#                 print youhui_content
#                 print baoliao_content

#商品介绍
                item_description = ""
                item_descriptions = article_selector.findAll(
                    "div", {"class": "item-box"})
                if item_descriptions:
                    description_count = 1
                    for description in item_descriptions:
                        if description_count == 2:
                            item_description = description.find(
                                "div", {"class": "inner-block"})
                            if item_description:
                                item_description = item_description.find("p")
                                if item_description:
                                    item_description = item_description.get_text(
                                    ).replace("\t",
                                              "").replace("\n", "").replace(
                                                  "\r", "").strip()
                                else:
                                    item_description = ""
                            else:
                                item_description = ""
                        description_count += 1
#                 print item_description
#                 else :
#                     baoliao_content = article_selector.find("article", {"class":"article-details"}).find("div", {"class":"inner-block"}).find("p", {"itemprop":"description"}).get_text().replace("\t","").replace("\n", "").replace("\r", "").strip()
#                     youhui_content = ""
#                     item_description = ""

#不推荐数
                badcount = article_selector.find("div", {
                    "class": "score_rate"
                }).find("span", {
                    "id": "rating_unworthy_num"
                }).get_text().strip()
                badcountnum = int(badcount)
                print "badcountnum is %d" % badcountnum

                #收藏�?
                favcount = article_selector.find("div", {
                    "class": "operate_box"
                }).find("div", {
                    "class": "operate_icon"
                }).find("a", {
                    "class": "fav"
                }).find("em").get_text()
                favcountnum = int(favcount)
                print favcountnum

                item_dict = item.createItemdic({
                    "originmall": originmall,
                    "baoliao_content": baoliao_content,
                    "youhui_content": youhui_content,
                    "item_description": item_description,
                    "bad_count": badcountnum,
                    "fav_count": favcountnum,
                    "article_url": article_url,
                    "article_time": article_time,
                    "good_count": goodcountnum,
                    "comment_count": commentcountnum
                })
                print item_dict

                item_list.append(item_dict)

            sendCrawlItemsToQueue(self.database, self.item_collection_name,
                                  item_list)
Exemple #26
0
import unittest
from items.container import Container, Backpack
from items.item import Item

ITEM = Item(name='pot', weight=500)

CUSTOM_ITEMS = [
    Item(name='rope', weight=2500),
    Item(name='knife', weight=100),
    Item(name='bottle', weight=1000)
]

CUSTOM_ITEMS_2 = [
    Item(name='rope', weight=2500),
    Item(name='knife', weight=100),
    Item(name='bottle', weight=1000)
]

CUSTOM_ITEMS_3 = [
    Item('gem', weight=10),
    Item('staff', weight=1000),
]

CUSTOM_ITEMS_4 = [
    Item(name='gem', weight=10),
    Item(name='flask', weight=50),
    Item(name='button', weight=2),
    Item(name='book', weight=150),
    Item(name='stone', weight=1000)
]
Exemple #27
0
    def testExecute(self):
        from player import Player
        from space import Space
        from items.item import Item
        from items.weapon import Weapon
        from commands.equip_command import EquipCommand

        #Tests default states
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)

        #Trying to equip item not in inventory
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        equipCmd = EquipCommand("Equip", "Equips item in inventory to player",
                                player)

        item = Item("Charm", "Unknown effects", 1)
        weapon = Weapon("Dagger", "A trusty blade", 2, 2)

        rawInputMock = MagicMock(return_value="Dagger")
        with patch('commands.equip_command.raw_input',
                   create=True,
                   new=rawInputMock):
            equipCmd.execute()

        equipped = player.getEquipped()
        self.assertFalse(equipped.containsItem(weapon),
                         "Player equipped item not in inventory.")

        #Trying to equip item that cannot be equipped (e.g. item is not instance of Armor or Weapon)
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        equipCmd = EquipCommand("Equip", "Equips item in inventory to player",
                                player)

        item = Item("Charm", "Unknown effects", 1)

        inventory = player.getInventory()
        inventory.addItem(item)

        rawInputMock = MagicMock(return_value="Charm")
        with patch('commands.equip_command.raw_input',
                   create=True,
                   new=rawInputMock):
            equipCmd.execute()

        equipped = player.getEquipped()
        self.assertFalse(equipped.containsItem(item),
                         "Player equipped item of Item class.")

        #Equipping item that can be equipped
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        equipCmd = EquipCommand("Equip", "Equips item in inventory to player",
                                player)

        weapon = Weapon("Dagger", "A trusty blade", 2, 2)

        inventory = player.getInventory()
        inventory.addItem(weapon)

        rawInputMock = MagicMock(return_value="Dagger")
        with patch('commands.equip_command.raw_input',
                   create=True,
                   new=rawInputMock):
            equipCmd.execute()

        equipped = player.getEquipped()

        self.assertTrue(equipped.containsItem(weapon),
                        "Player failed to equip equipable item.")

        #Equipping an item that is already equipped
        space = Space("Shire", "Home of the Hobbits.")
        player = Player("Frodo", space)
        equipCmd = EquipCommand("Equip", "Equips item in inventory to player",
                                player)

        weapon = Weapon("Dagger", "A trusty blade", 2, 2)

        inventory = player.getInventory()
        inventory.addItem(weapon)

        equipped = player.getEquipped()
        equipped.addItem(weapon)

        rawInputMock = MagicMock(return_value="Dagger")
        with patch('commands.equip_command.raw_input',
                   create=True,
                   new=rawInputMock):
            equipCmd.execute()

        numberInInventory = 0
        numberInEquipped = 0
        for item in inventory._items:
            if item == weapon:
                numberInInventory += 1
        for item in equipped._items:
            if item == weapon:
                numberInEquipped += 1

        self.assertEqual(
            inventory.count(), 1,
            "Equipping an item that is already equipped failed -- inventory problem."
        )
        self.assertEqual(
            equipped.count(), 1,
            "Equipping an item that is already equipped failed -- equipment problem."
        )
Exemple #28
0
    def create_items(self):
        rooms = self.rooms
        items = self.items

        # Room 1:
        blue_key = Key(description="A blue key")
        blue_key.color = 'blue'
        blue_key.id_door = 0
        blue_key.command = 'blue key'
        rooms[0].items.append(blue_key)
        items['blue key'] = blue_key

        torch = Item("An unlit torch",
                     "unlit",
                     key_item=True,
                     position="On the wall")
        rooms[0].items.append(torch)
        items['torch'] = torch
        torch.command = 'torch'

        # Room 2:
        red_key = Key(description="A red key")
        red_key.color = 'red'
        red_key.id_door = 2
        red_key.command = 'red key'
        rooms[1].items.append(red_key)
        items['red key'] = red_key

        # Room 3:
        green_key = Key(description="A green key")
        green_key.color = 'green'
        green_key.id_door = 1
        green_key.command = 'green key'
        rooms[2].items.append(green_key)
        items['green key'] = green_key

        book = Item("A weird book. There seems to be something inside.",
                    "unopened",
                    position='',
                    collectable=False)
        rooms[2].items.append(book)
        items['book'] = book
        book.command = 'book'

        # Room 4:
        yellow_key = Key(description="A yellow key")
        yellow_key.color = 'yellow'
        yellow_key.id_door = 3
        yellow_key.command = 'yellow key'
        rooms[3].items.append(yellow_key)
        items['yellow key'] = yellow_key

        safe = Item(
            'The safe has 3 buttons, each with a number: 11, 12 and 13.\nWritten in a piece of paper near the safe is the sequence \"0,1,1,2,3,5,8...\"',
            'closed')
        rooms[3].items.append(safe)
        items['safe'] = safe
        safe.command = 'safe'

        # Room 5:
        panel = Item(
            'The panel has 4 buttons having a single letter each : R, Y, G, B.'
        )
        rooms[4].items.append(panel)
        items['panel'] = panel
        panel.command = 'panel'
Exemple #29
0
    def spawn_portal(self):
        image_file = 'misc/portal.png'

        self.portal = Item(self.surface, self.spawn_point, (32, 64),
                           image_file, 0)
Exemple #30
0
FULLSCREEN = pygame.FULLSCREEN
MEM_BOMB = []

pygame.init()
pygame.display.init()
pygame.mixer.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

pygame.mixer.music.load(os.path.join('sounds', 'music.mp3'))
pygame.mixer.music.set_volume(0.1)

# Instanciação de mapas
m1 = Mapa()
# Instanciaçâo de items.
item = Item()
kick_item = pygame.sprite.Group()
item.item_detection(kick_item)

group = pygame.sprite.Group()
# adiciona ao grupo sprite da instaciação de player para usar collide sprite.
gp_player = pygame.sprite.Group()

#gp_player.add()
explode_group = pygame.sprite.Group()

#gp_bomb = pygame.sprite.Group()
#gp_bomb.add(p1, p1.bomb())

# Instanciação de players.
p1 = Player(group, gp_player, explode_group, MEM_BOMB, 0, 'malandro')