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
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)
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
def new_inventory(args): inventory = Inventory() inventory.name = args['name'] inventory.description = args['description'] print current_user.user current_user.user.inventories.append(inventory) db_add(inventory) db_add(current_user.user) return index()
def get_inventory_byUID(cls, uid: str, db: Session): """"get an inventory that matches the uid""" if not Inventory.fetch_inventory_byUID(uid=uid, db=db): raise HTTPException(status_code=400, detail="the inventory does not exists") send_log_to_queue(f'Inventory Fetched with UID {uid}') return Inventory.fetch_inventory_byUID(uid=uid, db=db)
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)
def _inventlist(self, request, user): check_invent=Inventory.query(Inventory.name== \ request.user_name).get() if check_invent: check_invent.key.delete() invent=Inventory(name=user.name, user=user.key, \ flint=items.get("flint"), grass=items.get("grass"), \ boulder=items.get("boulder"), hay=items.get("hay"), \ tree=items.get("tree"), sapling=items.get("sapling")) invent.put()
def test_fulfill_order_multi_items(self): order = {"apple": 5, "banana": 5, "orange": 5} inventory_info = [{ "name": "owd", "inventory": { "apple": 5, "orange": 10 } }, { "name": "dm", "inventory": { "banana": 5, "orange": 10 } }] inventory = Inventory.load_inventory_data(inventory_info) final_shipment = inventory.fulfill_order(order) expected_shipment = [{ 'dm': { 'banana': 5 } }, { 'owd': { 'apple': 5, 'orange': 5 } }] self.assertEqual(final_shipment, expected_shipment)
def move_all_scrolls_to_basic(user, from_inventory): basic_inventory = Inventory.objects(owner=user.id, is_basic=True).first() sii_ls = ScrollInInventory.objects(inventory=from_inventory.id) for sii in sii_ls: sii.inventory = basic_inventory.to_dbref() sii.save()
def shop_buy(data: dict, user: str): products: Dict[str, int] = data["products"] wallet_uuid: str = data["wallet_uuid"] key: str = data["key"] for product in products: if product not in game_info["items"]: return item_not_found if not exists_wallet(wallet_uuid): return wallet_not_found bought_products: List[dict] = [] price: int = 0 for product, quantity in products.items(): price += game_info["items"][product]["price"] * quantity if price > 0: response: dict = pay_shop(wallet_uuid, key, price, products) if "error" in response: return response for product, quantity in products.items(): for _ in range(quantity): item: Inventory = Inventory.create( product, user, game_info["items"][product]["related_ms"]) bought_products.append(item.serialize) return {"bought_products": bought_products}
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
def get_post_inventory(user): if request.method == 'GET': return Inventory.objects(owner=user.id).to_json() if request.method == 'POST': name = request.json.get('name') res = for_inventory.create_inventory(user,name) return json.dumps(res)
def create(data: dict, microservice: str) -> dict: name: str = data["item_name"] if name not in game_info["items"]: return item_not_found item: Inventory = Inventory.create(name, data["owner"], data["related_ms"]) return item.serialize
def compute_quanity(inventoryID: int): # find an inventory that matches the id inv = Inventory.get_inventory_byID(id=inventoryID) if inv is not None: # get the the stock quanity total_stock = list(map(lambda obj: obj.quantity, inv.stock)) total_sales = list(map(lambda obj: obj.quantity, inv.Sales)) return sum(total_stock) - sum(total_sales)
def test_fulfill_order_one_warehouse(self): order = {"apple": 1} inventory_info = [{"name": "owd", "inventory": {"apple": 1}}] inventory = Inventory.load_inventory_data(inventory_info) final_shipment = inventory.fulfill_order(order) expected_shipment = [{"owd": {"apple": 1}}] self.assertEqual(final_shipment, expected_shipment)
def put_scroll_to_another_inventory(user,from_inv_id, scroll_id,to_inv_id): from_inv = Inventory.objects(owner=user.id, id=from_inv_id).first() to_inv = Inventory.objects(owner=user.id, id=to_inv_id).first() scroll = Scroll.objects(owner=user.id, id=scroll_id).first() if from_inv and to_inv and scroll: sii= for_inventory.move_scroll_between_inventories(scroll, from_inv,to_inv) if sii: return "", 202 else: return "", 404 else: return "", 404
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
def main(): order_json_path = os.path.join(".", "data", "order.json") order = Utils.json_file_to_dict(order_json_path) inventory_json_path = os.path.join(".", "data", "inventory.json") inventory_info = Utils.json_file_to_dict(inventory_json_path) inventory = Inventory.load_inventory_data(inventory_info["warehouses"]) final_shipment = inventory.fulfill_order(order) print(final_shipment)
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'))
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
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')
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)
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
def make_inventory(): verify_args = { 'password': fields.Str(validate=password_length_validator, required=True, use=lambda val: val.lower()), 'username': fields.Str(required=True) } args = parser.parse(verify_args, request) print args user = verify_user(args['username'], args['password']) if user is False: return make_response(jsonify({'success': False, 'error': 'Password incorrect'}), 401) username = args['username'] request_args = { 'name': fields.Str(required=True), 'description': fields.Str() } args = parser.parse(request_args, request) inventory = Inventory() inventory.name = args['name'] inventory.description = args['description'] inventory.updated = datetime.datetime.utcnow() user.inventories.append(inventory) if db_add(inventory) is True: if db_add(user) is True: return response_success(inventory_schema_simple(inventory), 201) db_delete(inventory) return make_response( jsonify({'success': False, 'error': 'Inventory was not added to user {}'.format(username)})) return make_response(jsonify({'success': False, 'error': 'Inventory {} was not created'.format(args['name'])}), 400)
def delete_inventory(user, inv): errors = [] success = False inv = Inventory.objects(owner=user.id, id=id).first() if inv: if inv.is_basic: errors.append('You can not delete this inventory') else: move_all_scrolls_to_basic(user, inv) inv.delete() success = True else: errors.append("This inventory is not yours") return {'success': success, 'errors': errors}
def delete_inventory(user, inv): errors = [] success = False inv = Inventory.objects(owner=user.id, id = id).first() if inv: if inv.is_basic: errors.append('You can not delete this inventory') else: move_all_scrolls_to_basic(user,inv) inv.delete() success = True else: errors.append("This inventory is not yours") return {'success':success, 'errors':errors}
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
def edit_inventory(inv_id): if request.method == 'POST': name:str = request.form['name'] itype:str = request.form['category'] bp = request.form['bp'] sp = request.form['sp'] u = Inventory.edit_inventory( inv_id=inv_id, name=name, itype=itype, bp=bp, sp=sp ) flash("Inventory record successfully updated", "success") return redirect(url_for('inventories'))
def get_scrolls_from_inventory(user,inventory_id): inv = Inventory.objects(id=inventory_id, owner=user).first() if inv: sii_ls = ScrollInInventory.objects(inventory=inv.id) scrolls = [] for sii in sii_ls: scroll_obj = Scroll.objects(id=sii.scroll.id).first() scroll = {'id': str(scroll_obj.id), 'is_finished': scroll_obj.is_finished, 'description': scroll_obj.description, 'name': scroll_obj.name} scrolls.append(scroll) return json.dumps(scrolls) else: return "", 404
def checkInventory(self, request, user): """Used to pull inventory on a item""" if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') chklist=Inventory.query( Inventory.user==user.key).get() if not chklist: raise endpoints.NotFoundException( 'This user does not have any Inventory') if user.key==chklist.user: if items.has_key(request.item_name)== False: raise endpoints.NotFoundException('Invalid item name') itemname=request.item_name value=getattr( chklist, itemname) return StringMessage1(message='You have {} {} '.format \ (value, itemname))
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}')
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"])
def check_for_finished_scrolls(): for scroll in Scroll.objects(is_finished=False): current_time = datetime.now() if scroll.end <= current_time: print('Scroll name ' + scroll.name) scroll.is_finished = True scroll.save() inv = Inventory.objects(owner=scroll.owner.id, is_basic=True).first() sii = ScrollInInventory() sii.scroll = scroll.to_dbref() sii.inventory = inv.to_dbref() sii.save() #inform user with node.js payload = { 'user_id': str(scroll.owner.id), 'scroll_name': scroll.name } requests.post(settings.WEBSOCKET_IP + '/scrolls/ready', data=payload)
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))
def update_inventory(cls, inventory_id: int, payload: inventory.InventoryPut, db: Session): """update an inventory""" inv: inventory.Inventory = Inventory.fetch_inventory_byID( inventory_id=inventory_id, db=db) if payload.title is not None: inv.title = payload.title if payload.isbn_no is not None: inv.isbn_no = payload.isbn_no if payload.buying_price is not None: inv.buying_price = payload.buying_price if payload.selling_price is not None: inv.selling_price = payload.selling_price if payload.status is not None: inv.status = payload.status inv.updated_at = date.today() db.commit() db.refresh(inv) return inv
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')
def create_inventory(user, name): inv = Inventory() inv.owner = user.to_dbref() inv.name = name return inv.save_me()
def craftItemNew(self, request, user): """Craft an item""" if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') ingamecheck=Game.query(Game.user==user.key).filter \ (Game.game_over == False).get() if not ingamecheck: raise endpoints.NotFoundException \ ('User is not in a game. Please create a new game for this user.') #Check for if out of time if ingamecheck.timeout == True: setattr(ingamecheck, "game_over", True) ingamecheck.put() raise endpoints.ConflictException\ ('Player has run out of time and did not survive! Start a new game.') #Starts the game timer if ingamecheck.game_started == False: t1=int(time.time()) gamediff=getattr(ingamecheck, "difficulty") setattr(ingamecheck, "timer", t1) setattr(ingamecheck, "game_started", True) ingamecheck.put() #Calls gamecheck for game timer if ingamecheck.game_started == True: if ingamecheck.difficulty > 1: gamecheck(ingamecheck) # Make a dict of inventory from ndb inventory_items=Inventory.query( Inventory.user==user.key)\ .get() # Create a dict of what is needed to craft the item takesToCraft=craft.get(request.itemcraft) if takesToCraft == None: raise endpoints.NotFoundException('Invalid item name.') # Make a copy of takesToCraft to re-populate with ndb values. copycraft=takesToCraft.copy() #Calls a function to populate copycraft invenOfCraft(copycraft, inventory_items) #return of invenOfCraft function. inven_ndb=copycraft #Compares what is needed to craft an item to what exist in inventory. #Determines if required items are present in inventory #Flags canbeMade T or F #Tells player if not enough resources to craft item canBeMade=True for i in craft[request.itemcraft]: if craft[request.itemcraft] [i]>inven_ndb[i]: canBeMade=False return StringMessage1 \ (message='Sorry, item can not be crafted. Takes {}, you only have {}' \ .format(takesToCraft, inven_ndb)) if canBeMade==True: # Adds 1 to the quantity of a crafted item in datastore. increment=1+getattr(inventory_items, request.itemcraft) setattr(inventory_items, request.itemcraft, increment) #Decrement inventory items used to craft a new item neededForCraft= takesToCraft.copy() for w in neededForCraft: if hasattr(inventory_items, w)==True: setattr(inventory_items, w, getattr \ (inventory_items, w)-neededForCraft[w]) inventory_items.put() ingamecheck.history.append(request.itemcraft) ingamecheck.put() #Checks to see if you have survived and won the game if inventory_items.tent >= 1 and inventory_items.firepit >= 1: setattr(ingamecheck, "survived", True) setattr(ingamecheck, "game_over", True) setattr(user, "wins", 1 + getattr(user, "wins")) setattr(user, "total_played", 1 + getattr \ (user, "total_played")) setattr(user, "score", 20 * ingamecheck.difficulty+ \ user.score) ingamecheck.put() user.put() return StringMessage1(message='Congrats {}, you survived! Game over.' \ .format(inventory_items.name)) else: return StringMessage1(message='{} Can be crafted! {}, You have {}' \ .format(request.itemcraft, takesToCraft, inven_ndb))