コード例 #1
0
 def __init__(self,
              id=0,
              name="",
              description="",
              max_health=100,
              max_mana=150,
              mana_regen=5,
              abilities={},
              inventory=Inventory(),
              armor=Armor(),
              weapon=Weapon(),
              position=[0, 0],
              coin=0,
              character_type="mob"):
     self.id = id
     self.name = name
     self.description = description
     self.max_health = max_health
     self.health = max_health
     self.max_mana = max_mana
     self.mana = max_mana
     self.mana_regen = mana_regen
     self.abilities = abilities
     self.inventory = inventory
     self.armor = armor
     self.base_def = armor.base_power
     self.weapon = weapon
     self.base_atk = weapon.base_power
     self.position = position
     self.inventory.coin = coin
     self.character_type = character_type
コード例 #2
0
    def inventories(cls):
        # get all inventories
        all_inventories = Inventory.fetch_all()

        if request.method == 'POST':
            name: str = request.form['name']
            itype: str = request.form['category']
            bp = request.form['bp']
            sp = request.form['sp']

            # check if the inventory name exists
            inv = Inventory.check_inventory_exists(name)

            if inv is not None:
                flash('Inventory name already exists', 'danger')
                return redirect(url_for('inventories'))
            else:
                record = Inventory(name=name.title(),
                                   itype=itype.title(),
                                   bp=bp,
                                   sp=sp)
                record.create_record()
                flash('Successfully added', 'success')
                return redirect(url_for('inventories'))

        return render_template('/admin/inventories.html',
                               inventories=all_inventories)
コード例 #3
0
ファイル: product.py プロジェクト: jdht1992/cargamos
    def post(self):
        product_data = ProductSchema().load(request.json)
        quantity = product_data.pop("quantity", None)
        shop_id = product_data.pop("shop_id", None)
        product = Product(**product_data)

        try:
            product.save()
        except:
            return {"message": ERROR_INSERTING_PRODUCT}, 500

        inventory_data = {
            "product_id": product.id,
            "quantity": quantity,
            "shop_id": shop_id
        }

        inventory = Inventory(**inventory_data)

        try:
            inventory.save()
        except:
            return {"message": ERROR_INSERTING_INVENTORY}, 500

        return {"id": str(product.id)}, 201
コード例 #4
0
 def post(self):
     product = Product()
     product.from_json(request.json)
     product_repository.add_product(product, current_user.id)
     inventory = Inventory()
     inventory.product_id = product.id
     inventory_repository.add_inventory(inventory)
コード例 #5
0
def fetch_player(id=-1, name=""):
    command = f"SELECT * FROM players WHERE id = {id} OR name = '{name}'"
    cursor.execute(command)
    record = cursor.fetchone()
    if record:
        abilities = {}
        inventory = Inventory()
        armor = fetch_item(id=record[7])
        weapon = fetch_item(id=record[8])
        abilities_ids = record[9].split(",")
        for ability_id in abilities_ids:
            ability_id = int(ability_id)
            ability = fetch_ability(id=ability_id)
            abilities[ability.name] = ability
        items_id = record[10].split(",")
        for item_id in items_id:
            if item_id != "":
                item_id = int(item_id)
                inventory.add(fetch_item(id=item_id), {})
        player = Character(id=record[0],
                           name=record[1],
                           description=record[2],
                           max_health=record[3],
                           max_mana=record[5],
                           abilities=abilities,
                           inventory=inventory,
                           armor=armor,
                           weapon=weapon,
                           coin=record[13],
                           position=[record[11], record[12]],
                           character_type="player")
        player.health = record[4]
        player.mana = record[6]
        return player
    return record
コード例 #6
0
ファイル: player.py プロジェクト: naylrush/MazeGame
 def __init__(self, start_position=Position()):
     global total_ids
     self.id = total_ids
     total_ids += 1
     self.inventory = Inventory()
     self.sleep_inventories = []
     self.stun = 0
     self.sleep_times = []
     self.field_id = [0]
     self.start_position = start_position
コード例 #7
0
    def test_successful_inventory(self):
        address_data = {
            "street": "primera",
            "city": "segunda",
            "state": "tercero",
            "country": "cuarto",
            "name_code": "123abc"
        }
        address = Address(**address_data)
        address.save()

        shop_data = {"name": "un ejemplo mas", "address_id": address.id}
        shop = Shop(**shop_data)
        shop.save()

        catalog_data = {"name": "primavera verano", "shop_id": shop.id}
        catalog = Catalog(**catalog_data)
        catalog.save()

        product_data = {
            "title": "p2",
            "description": "un articulo de ropa",
            "price": 2.2,
            "is_featured": True,
            "sku": "abc12345678",
            "catalog_id": catalog.id,
        }

        product = Product(**product_data)
        product.save()

        inventory_data = {
            "product_id": product.id,
            "quantity": 10,
            "shop_id": shop.id
        }
        inventory = Inventory(**inventory_data)
        inventory.save()

        # Given
        payload = json.dumps({
            "sku": "abc12345678",
            "quantity": 10,
            "shop_id": shop.id
        })

        # When
        response = self.app.post('/api/v1/inventory/',
                                 headers={"Content-Type": "application/json"},
                                 data=payload)

        # Then
        self.assertEqual(dict, type(response.json))
        self.assertEqual(200, response.status_code)
コード例 #8
0
 def __init__(self,
              id=0,
              name="shop",
              description="this a shop",
              commission=5,
              inventory=Inventory()):
     self.id = id
     self.name = name
     self.description = description
     self.commission = commission
     self.inventory = inventory
コード例 #9
0
def shop_gen(name="shop",
             description="this a shop",
             commission=5,
             shop_type="All",
             abilities=None):
    if shop_type == "Merlin":
        name = "Merlin Shop"
        # description = "Merlin sells scrolls of knowledge that you can learn new abilities from them or you can sell scroll to him."
        description = "Merlin buy and sell everything, even souls of mortals"
        commission = 2
        shop = Shop(
            0, name, description, commission,
            Inventory(scroll_list=create_scrolls(abilities),
                      armor_list=epic_armors,
                      weapon_list=epic_weapons,
                      potion_list=epic_potions,
                      misc_list=[],
                      coin=10000000))
    elif shop_type == "Blacksmith":
        name = "Vulcan Blacksmith"
        description = "Vulcan epic weapons and armors"
        commission = 10
        shop = Shop(
            0, name, description, commission,
            Inventory(armor_list=epic_armors, weapon_list=epic_weapons))
    elif shop_type == "Apothecary":
        shop = Shop(0, name, description, commission,
                    Inventory(potion_list=epic_potions))
    else:
        name = "Mercury shop"
        description = "Mercury buy and sell everything, even souls of mortals"
        commission = 20
        shop = Shop(
            0, name, description, commission,
            Inventory(armor_list=epic_armors,
                      weapon_list=epic_weapons,
                      potion_list=epic_potions))
    return shop
コード例 #10
0
def register(email, username, password):
    user = User()
    user.email = email
    user.username = username
    user.password = password
    errors = user.validate_me()
    if errors:
        print(errors)
        return {'errors': errors}
    else:
        res = user.save_me()
        if 'id' in res.keys():
            user = User.objects(id=res['id']).first()
            Inventory(owner=user.to_dbref(), name='Basic',
                      is_basic=True).save()
        return res
コード例 #11
0
    def add_inventory(cls):
        if request.method == 'POST':
            name = request.form['name']
            itype = request.form['category']
            bp = request.form['bp']
            sp = request.form['sp']

            #Check if the Inventory name exist
            if Inventory.check_inventory_exists(inventory_name=name):
                flash('Inventory name already exists!', 'danger')
                return redirect(url_for('inventories'))
            else:
                record = Inventory(name=name.title(),
                                   itype=itype.title(),
                                   bp=bp,
                                   sp=sp)
                record.create_record()
                flash('Inventory successfully added!', 'success')
                return redirect(url_for('inventories'))
コード例 #12
0
    def add_inventory(cls, payload: inventory.InventoryPost, db: Session):
        """create a new inventory"""
        # check inventory title exists

        # if Inventory.check_title_exists(title=payload.title, db=db):
        #     raise HTTPException(status_code=409, detail="the inventory already exists")

        try:
            # add the inventory
            record = Inventory(public_id=str(uuid.uuid4()),
                               title=payload.title.strip().title(),
                               isbn_no=payload.isbn_no,
                               buying_price=payload.buying_price,
                               selling_price=payload.selling_price,
                               uid=payload.uid)
            created_record = record.create(db=db)
            send_log_to_queue('Successfully Save Inventory Record')
            return created_record
        except Exception as e:
            send_log_to_queue('Failed Save Inventory')
            raise HTTPException(status_code=500, detail='Server Error')
コード例 #13
0
ファイル: characters.py プロジェクト: simonbw/dndhelper
    def __init__(self, name='', max_hit_points=10, backstory='...', personality='...',
                 race='Human', character_class='Fighter', **kwargs):
        self.name = name
        self.name = name
        self.max_hitpoints = max_hit_points
        self.hitpoints = max_hit_points
        self.backstory = backstory
        self.personality = personality
        self.race = get_race(race)
        self.character_class = get_class(character_class)

        self.abilities = AbilitiesComponent()
        self.skills = SkillsComponent()
        self.inventory = Inventory()
        self.messages = MessagesComponent()

        for ability in list_abilities():
            self.abilities.set_score(ability, kwargs.get(ability.name, DEFAULT_ABILITY_SCORE))

        for skill in list_skills():
            self.skills.set_level(skill, kwargs.get(skill.name, DEFAULT_SKILL_LEVEL))
コード例 #14
0
def create_character_from_json(abilities, all_items, character_dict):
    _abilities = {}
    for ability_dict in character_dict["abilities"]:
        ability = abilities[ability_dict]
        _abilities[ability.name] = ability
    _armor = character_dict["armor"]
    _weapon = character_dict["weapon"]
    _inventory = Inventory()
    _inventory.remove_all()
    char_inventory = character_dict["inventory"]
    for item in all_items:
        if _inventory.count_all_item() >= len(char_inventory) and type(
                _armor) == Armor and type(_weapon) == Weapon:
            break
        elif item.id == _armor:
            _armor = item
            continue
        elif item.id == _weapon:
            _weapon = item
            continue
        elif item.id in char_inventory:
            for _ in range(char_inventory.count(item.id)):
                _inventory.add(item, {})
            continue

    if _inventory.count_all_item() < len(char_inventory):
        raise Exception("lost some item")
    return Character(id=character_dict["id"],
                     name=character_dict["name"],
                     description=character_dict["description"],
                     max_health=character_dict["max_health"],
                     max_mana=character_dict["max_mana"],
                     mana_regen=character_dict["mana_regen"],
                     abilities=_abilities,
                     inventory=_inventory,
                     armor=_armor,
                     weapon=_weapon,
                     position=character_dict["position"],
                     coin=character_dict["coin"],
                     character_type=character_dict["character_type"])
コード例 #15
0
def post_app():
    #print('form')
    signed_request = request.form.get('signed_request')
    data = facebook_tools.parse_signed_request(signed_request,
                                               FACEBOOK_APP_SECRET)
    print(signed_request)
    print(data)
    session['oauth_token'] = (data['oauth_token'], '')
    me = facebook.get('/me')
    username = me.data['name']
    email = me.data['email']
    user = User.objects(email=email).first()
    if user:
        session['user_id'] = str(user.id)
    else:
        user = User()
        user.email = email
        user.username = username
        user.save()
        Inventory(owner=user.to_dbref(), name='Basic', is_basic=True).save()

    return send_file('public/index.html')
コード例 #16
0
def facebook_authorized():
    resp = facebook.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'], request.args['error_description'])
    if isinstance(resp, OAuthException):
        return 'Access denied: %s' % resp.message

    session['oauth_token'] = (resp['access_token'], '')
    me = facebook.get('/me')
    username = me.data['name']
    email = me.data['email']
    user = User.objects(email=email).first()
    if user:
        session['user_id'] = str(user.id)
    else:
        user = User()
        user.email = email
        user.username = username
        user.save()
        Inventory(owner=user.to_dbref(), name='Basic', is_basic=True).save()

    return redirect('/')
コード例 #17
0
def main():
    inventory = Inventory([])
    inventory.add_guitar(
        Guitar(
            "001", 120.5,
            GuitarSpec(Builder.Toyota, "A002", GuitarType.Electric, Wood.Oak,
                       Wood.Yak)))
    inventory.add_guitar(
        Guitar(
            "002", 200,
            GuitarSpec(Builder.Toyota, "A002", GuitarType.Electric, Wood.Oak,
                       Wood.Yak)))
    inventory.add_guitar(
        Guitar(
            "003", 150,
            GuitarSpec(Builder.Toyota, "B005", GuitarType.Silver, Wood.Oak,
                       Wood.Yak)))

    results = inventory.search(
        GuitarSpec(Builder.Toyota, "A002", GuitarType.Electric, Wood.Oak,
                   Wood.Yak))

    for r in results:
        print(f'--- found guitar: {r.serial_number}, price: {r.price}')
コード例 #18
0
 def __init__(self):
     super().__init__()
     self.inventory = Inventory(has_key=True)
コード例 #19
0
def create_inventory(user, name):
    inv = Inventory()
    inv.owner = user.to_dbref()
    inv.name = name
    return inv.save_me()
コード例 #20
0
def character_gen(character_type="",
                  difficulty=0,
                  _name="",
                  abilities={},
                  _position=[0, 0],
                  armor=None,
                  weapon=None,
                  _inventory=None,
                  heal_abilities=[],
                  attack_abilities=[]):
    # TODO ADD Base_power_ratio list arg
    # TODO potion add to mob and boss
    # TODO use potion for mob and boss with log
    name = ""
    description = ""
    max_health = 100
    max_mana = 150
    rand_abilities = []
    _abilities = {}
    inventory = Inventory()
    inventory = inventory.remove_all()
    coin = 0
    if character_type.lower() == "mob":
        name, gender = character_names_gen(
            first_prefix=static_vars["lvl"],
            second_prefix=static_vars["outlaws"],
            second_suffix=static_vars["races"])
        description = character_description_gen(name, gender)
        max_health = math.floor((1 + random.random()) * 100)
        max_mana = math.floor((1 + random.random()) * 150)
        armor = common_armors[random.randint(0, len(common_armors) - 1)]
        weapon = common_weapons[random.randint(0, len(common_weapons) - 1)]
        name_parts = name.split(" ")
        if len(name_parts) > 3:
            lvl_index = static_vars["lvl"].index(name_parts[0])
            if lvl_index > 1:
                inventory.add(random.choice(common_potions), {})
        coin = random.randint(1, difficulty + 1) * 14
        rand_heal_abilities = random.choice(heal_abilities)
        _abilities[rand_heal_abilities] = abilities[rand_heal_abilities]
        rand_attack_abilities = random.choice(attack_abilities)
        _abilities[rand_attack_abilities] = abilities[rand_attack_abilities]
        for _ in range(random.randint(1, difficulty + 1)):
            inventory.add(
                common_miscs[random.randint(0,
                                            len(common_miscs) - 1)], {})
    elif character_type.lower() == "boss":
        name, gender = character_names_gen(first_prefix=static_vars["outlaws"],
                                           second_prefix=static_vars["races"],
                                           second_suffix=static_vars["races"])
        description = character_description_gen(name, gender)
        max_health = math.floor(((1 + random.random()) * 100) +
                                (100 * difficulty))
        max_mana = math.floor(((1 + random.random()) * 150) +
                              (100 * difficulty))
        armor = epic_armors[random.randint(0, len(epic_armors) - 1)]
        weapon = epic_weapons[random.randint(0, len(epic_weapons) - 1)]
        inventory.add(random.choice(common_potions), {})
        inventory.add(random.choice(epic_potions), {})
        coin = random.randint(difficulty, difficulty * 2) * 110
        rand_abilities = random.choices(list(abilities.keys()),
                                        k=random.randint(
                                            difficulty,
                                            len(abilities) - 1))
        rand_abilities.append(random.choice(heal_abilities))
        for key in rand_abilities:
            _abilities[key] = abilities[key]
        for _ in range(random.randint(difficulty, difficulty * 2)):
            inventory.add(
                common_miscs[random.randint(0,
                                            len(common_miscs) - 1)], {})
            inventory.add(
                common_miscs[random.randint(0,
                                            len(common_miscs) - 1)], {})
    elif character_type.lower() == "player":
        name = _name
        description = static_vars["player_desc"]
        max_health = math.floor((1 + random.random()) * 100)
        max_mana = math.floor((1 + random.random()) * 150)
        _abilities = abilities
        if _inventory:
            inventory = _inventory
        coin = 50
    return Character(name=name,
                     description=description,
                     max_health=max_health,
                     max_mana=max_mana,
                     abilities=_abilities,
                     inventory=inventory,
                     armor=armor,
                     weapon=weapon,
                     position=_position,
                     coin=coin,
                     character_type=character_type)