Exemple #1
0
    async def convert(self, ctx: Context, value: str) -> Item_:
        try:
            if value.isdigit():
                return Item_.from_id(int(value))

            return Item_.from_name(value.lower().replace("-", " "))
        except UnknownObject:
            raise ConvertError(value, self, "Такой предмет не существует")
Exemple #2
0
    async def run(self, ctx: Context, args: Arguments) -> CommandResult:
        items = [i for i in Item.all_instances()]
        items.sort(key=lambda x: x.id)

        return codeblock(
            "\n".join(sorted(f"{item.id:>3} {item.name}" for item in items))
        )
Exemple #3
0
    async def add_item(self, item: Item, pool: asyncpg.Pool) -> Item:
        """
        Add item to player inventory.
        Returns added item on success.
        """

        if isinstance(item, int):
            item = Item.from_id(item)

        return await self.inventory.add(item, self, pool)
Exemple #4
0
    def __contains__(self, obj: object) -> bool:
        """Check if item is in player's inventory or equipment."""

        if isinstance(obj, int):
            item: Item = Item.from_id(obj)
        elif isinstance(obj, Item):
            item = obj
        else:
            return False

        return item in self.inventory or item in self.equipment
Exemple #5
0
    async def add(
        self, item: Union[int, Item], player: Player, pool: asyncpg.Pool
    ) -> Item:
        """Add item to player inventory. Returns added item on success."""

        if isinstance(item, int):
            item = Item.from_id(item)

        self._items.append(item)

        await pool.fetch(
            "UPDATE players SET inventory = $1 WHERE discord_id = $2",
            [i.id for i in self._items],
            player.discord_id,
        )

        return item
Exemple #6
0
    async def remove_item(self, item: Item, pool: asyncpg.Pool) -> Item:
        """
        Remove item from inventory (preferable) or equipment.
        Returns removed item on success.
        """

        if isinstance(item, int):
            item = Item.from_id(item)

        if item not in self.inventory:
            # prefer removing item from inventory
            if isinstance(item, Equippable):
                with suppress(ItemAlreadyUnequipped):
                    await self.equipment.unequip(item, self, pool)

                    # avoid adding item to inventory and removing it again
                    return item

        return await self.inventory.remove(item, self, pool)
Exemple #7
0
    def __init__(self, **kwargs: Optional[int]):
        # mypy help
        self.weapon: Weapon
        self.helmet: Armor
        self.chestplate: Armor
        self.leggings: Armor
        self.boots: Armor
        self.shield: Armor

        type_map = {
            "weapon": Weapon,
            "helmet": Armor,
            "chestplate": Armor,
            "leggings": Armor,
            "boots": Armor,
            "shield": Armor,
        }

        checked_kwargs = {}
        for name in self._slots:
            instance: Optional[Union[int, Item]] = kwargs.pop(name, None)

            if isinstance(instance, int):
                instance = Item.from_id(instance)

            # make sure include default None values
            checked_kwargs[name] = instance

            if instance is None:
                continue

            cls = type_map[name]

            if not isinstance(instance, cls):
                raise TypeError(f"{instance} is not an instance of {cls}")

        if kwargs:
            raise ValueError(
                f"Unknown argument(s) passed: {tuple(kwargs.keys())}"
            )

        for name, instance in checked_kwargs.items():
            setattr(self, name, instance)
Exemple #8
0
    async def remove(
        self, item: Union[int, Item], player: Player, pool: asyncpg.Pool
    ) -> Item:
        """
        Remove item from inventory.
        Returns removed item on success.
        """

        if isinstance(item, int):
            item = Item.from_id(item)

        if item not in self:
            raise ItemNotFound

        self._items.remove(item)

        await pool.fetch(
            "UPDATE players SET inventory = $1 WHERE discord_id = $2",
            [i.id for i in self._items],
            player.discord_id,
        )

        return item
Exemple #9
0
 def __init__(self, *, items: List[int]):
     self._items: List[Item] = list(Item.from_id(i) for i in items)
from rpg.thieves import Thief
from rpg.inventory import Inventory
from rpg.items import Item
from rpg.items import Weapon

jimmy = Thief(name="Jimmy", sneaky=False)
print(jimmy.sneaky)
print(jimmy.hide(9))

inventory = Inventory()
coin = Item('coin', 'a gold coin')
sword = Weapon('sword', 'sharp', 100)

inventory.add(coin)
inventory.add(sword)

print(inventory.__len__())
print(inventory.__contains__(sword))
for item in inventory:
    print(item.description)
    print(item.name)

print("**********************")
for item in inventory:
    if isinstance(item, Weapon):
        print(item.power)
 def used_for(self) -> List[Item]:
     return [Item.from_id(i) for i in self._used_for]