Example #1
0
    def create_item(
        self,
        item_template: ItemTemplate,
        count: int = 1,
    ) -> Tuple[Item, List[Item]]:
        try:
            return self.globals_repository.item_preset(
                item_template).get_items()
        except NotFoundError:
            pass

        item = Item(
            id=generate_item_id(),
            tpl=item_template.id,
        )
        if isinstance(item_template.props, AmmoBoxProps):
            ammo_template_id: TemplateId = item_template.props.StackSlots[0][
                "_props"]["filters"][0]["Filter"][0]
            ammo_template = self.templates_repository.get_template(
                ammo_template_id)
            ammo, _ = self.create_item(ammo_template, 1)
            ammo.upd.StackObjectsCount = count
            ammo.parent_id = item.id
            ammo.slot_id = "cartridges"

            return item, [ammo]

        if count > item_template.props.StackMaxSize:
            raise ValueError(
                f"Trying to create item with template id {item_template} with stack size "
                f"of {count} but maximum stack size is {item_template.props.StackMaxSize}"
            )

        if count > 1:
            item.upd.StackObjectsCount = count

        #  Item is either medkit or a painkiller
        if isinstance(item_template.props, MedsProps):
            medkit_max_hp = item_template.props.MaxHpResource

            item.upd.MedKit = ItemUpdMedKit(HpResource=medkit_max_hp)

        if isinstance(item_template.props, FuelProps):
            item.upd.Resource = ItemUpdResource(
                Value=item_template.props.MaxResource)

        item.parent_id = None
        return item, []
Example #2
0
 def _make_random_meds(self) -> Item:
     template = random.choices(
         population=self._meds_templates,
         weights=[tpl.props.SpawnChance for tpl in self._meds_templates],
         k=1,
     )[0]
     return Item(tpl=template.id)
Example #3
0
 def place_item(
     self,
     item: Item,
     **kwargs: Any,
 ) -> None:
     super().place_item(item, **kwargs)
     item.slot_id = "main"
Example #4
0
    def __generate_mod(self, slot: str, template_ids: List[TemplateId],
                       parent: Item) -> None:
        try:
            if not random.uniform(0, 100) <= self.preset.chances["mods"][slot]:
                return
        except KeyError:
            return

        template_ids = list(
            filter(self.__filter_conflicting_items, template_ids))
        if not template_ids:
            return

        random_template = self.templates_repository.get_template(
            random.choice(template_ids))
        # Ammo generation will be handler later via BotMagazineGenerator class
        if slot == "cartridges":
            return

        item = Item(
            id=generate_item_id(),
            tpl=random_template.id,
            slot_id=slot,
            parent_id=parent.id,
        )
        self.bot_inventory.add_item(item)
Example #5
0
    def __sell_to_trader(self, action: SellToTrader) -> None:
        trader_id = action.tid
        items_to_sell = action.items
        trader = self.__trader_manager.get_trader(TraderType(trader_id))
        trader_view = trader.view(self.profile)

        items = list(self.inventory.get(i.id) for i in items_to_sell)
        price_sum: int = sum(
            trader.get_sell_price(self.inventory.get(i.id), children_items=[]).amount
            for i in items_to_sell
        )
        # price_sum: int = sum(trader.get_sell_price(item, children_items=[]).amount for item in items)

        self.response.items.del_.extend(items)
        self.inventory.remove_items(items)

        currency_item = Item(
            id=generate_item_id(),
            tpl=TemplateId(CurrencyEnum[trader_view.base.currency].value),
        )
        currency_item.upd.StackObjectsCount = price_sum

        currency_items = self.inventory.split_into_stacks(currency_item)

        for item in currency_items:
            self.inventory.place_item(item)
        self.response.items.new.extend(currency_items)
Example #6
0
 def make_ammo(ammo_template: ItemTemplate, parent: Item, count: int) -> Item:
     return Item(
         tpl=ammo_template.id,
         parent_id=parent.id,
         slot_id="cartridges",
         location=ItemAmmoStackPosition(0),
         upd=ItemUpd(StackObjectsCount=count, SpawnedInSession=True),
     )
def test_can_insure_item(
    insurance_service: IInsuranceService,
    profile: Profile,
    item,
):
    item = Item(id="Item Id", tpl="Template Id", slot_id=None)
    profile.add_insurance(item=item, trader=TraderType.Prapor)
    assert insurance_service.is_item_insured(item=item, profile=profile)
Example #8
0
 def place_item(
     self,
     item: Item,
     *,
     child_items: List[Item] = None,
     location: AnyItemLocation = None,
 ) -> None:
     super().place_item(item, child_items=child_items, location=location)
     item.slot_id = self._slot_id
Example #9
0
    def put_items_in_area_slots(
        self,
        area_type: HideoutAreaType,
        slot_id: int,
        item: Item,
    ) -> None:
        area = self.get_area(area_type)

        item.location = None
        item.parent_id = None
        item.slot_id = None

        area_slots = area["slots"]
        diff = slot_id + 1 - len(area_slots)
        if diff > 0:
            area_slots.extend([{"item": None} for _ in range(diff)])

        area_slots[slot_id]["item"] = [item.dict()]
Example #10
0
    def generate_magazines_for_weapon(self, weapon: Item) -> None:
        # Magazine template to generate for a bot
        magazine_template: ItemTemplate
        # Magazine that is currently in the weapon
        magazine_in_weapon: Item

        for item in self.bot_inventory.items.values():
            item_template = self.templates_repository.get_template(item.tpl)
            if (
                isinstance(item_template.props, MagazineProps)
                and item.parent_id == weapon.id
            ):
                magazine_template = item_template
                magazine_in_weapon = item
                break
        else:
            raise ValueError("Magazine wasn't found")

        assert isinstance(magazine_template.props, MagazineProps)
        cartridges = random.choice(magazine_template.props.Cartridges)
        ammo_types: List[TemplateId] = self.preset.inventory["mods"][
            magazine_template.id
        ]["cartridges"]
        ammo_type = self.templates_repository.get_template(random.choice(ammo_types))

        # Generate ammo for current magazine
        self.bot_inventory.add_item(
            self.make_ammo(ammo_type, magazine_in_weapon, cartridges.max_count)
        )

        reload_type = MagazineReloadType(magazine_template.props.ReloadMagType)

        # Generate additional magazines if magazine is external
        if reload_type == MagazineReloadType.ExternalMagazine:
            for _ in range(
                random.randint(self.config.magazines.min, self.config.magazines.max)
            ):
                for _ in range(self.ATTEMPTS_TO_PLACE):
                    container = self.inventory_containers.random_container(
                        include=["Pockets", "TacticalVest"]
                    )

                    try:
                        mag = Item(tpl=magazine_template.id)
                        container.place_randomly(item=mag)
                        self.bot_inventory.add_item(
                            self.make_ammo(ammo_type, mag, cartridges.max_count)
                        )
                        break
                    except NoSpaceError:
                        pass
Example #11
0
    def generate_equipment(self) -> None:
        """
        Generates equipment items (Weapons, Backpack, Rig, etc)
        """

        # A set with equipment slots that should be generated
        equipment_slots_to_generate: Set[str] = {
            slot
            for slot, template_ids in
            self.preset.inventory["equipment"].items() if (
                # If slot isn't present in the _chances then it should be always generated
                slot not in self.preset.chances["equipment"]
                # Else we check if it should spawn
                or random.uniform(0, 100) <= self.preset.chances["equipment"]
                [slot]) and template_ids
        }
        # Force pistol to generate if primary weapon wasn't generated
        weapon_slots = "FirstPrimaryWeapon", "SecondPrimaryWeapon"
        if not any(slot in equipment_slots_to_generate
                   for slot in weapon_slots):
            equipment_slots_to_generate.add("Holster")

        assert any(i in weapon_slots
                   for i in ("FirstPrimaryWeapon", "SecondPrimaryWeapon",
                             "Holster"))
        for equipment_slot in equipment_slots_to_generate:
            template_ids = self.preset.inventory["equipment"][equipment_slot]
            template_ids = [
                i for i in template_ids if self.__filter_conflicting_items(
                    i, equipment_slots_to_generate)
            ]

            random_template_id = random.choice(template_ids)
            self.bot_inventory.add_item(
                Item(
                    id=generate_item_id(),
                    tpl=random_template_id,
                    slot_id=equipment_slot,
                    parent_id=self.bot_inventory.inventory.equipment,
                ))
Example #12
0
def item() -> Item:
    return Item(id="Item Id", tpl="Template Id", slot_id=None)