def init_items(self): item_list = [items.Item('stick'), items.Item('keys'), items.Item('mirror'), items.Container('chest'), items.Container('pond'), items.ContainedItem('map'), items.ContainedItem('sphere'), items.Blocker('rubble') ] return item_list
def __init__(self, filename): self.connection = DBQueue() self.filename = filename self.items = {} self.dbhistory = history.DBHistory(self.connection, self.items, self.filename) # Enable multi-threading, as the database is protected with a queue self.connection.put( FileDB(filename, check_same_thread=False, name_based=True)) qconn = self.connection.get() cursor = qconn.cursor() cursor.execute(queries.properties_select_history) softlimit = cursor.fetchone()[0] config = coreaux_api.get_configuration()('History') timelimit = config.get_int('time_limit') hardlimit = config.get_int('hard_limit') self.dbhistory.set_limits(softlimit, timelimit, hardlimit) dbitems = cursor.execute(queries.items_select_tree) self.connection.give(qconn) for item in dbitems: self.items[item['I_id']] = items.Item(self.connection, self.dbhistory, self.items, self.filename, item['I_id'])
def add_products_batch(bazaar_data): products_data = bazaar_data["products"] session = Session() item_list = [] timestamp = int(time.time() * 1000) for product_name in products_data.keys(): product = products_data[product_name] quick_status = product["quick_status"] bazaar_product = BazaarProduct( product_id=product["product_id"], sell_price=quick_status["sellPrice"], sell_volume=quick_status["sellVolume"], sell_moving_week=quick_status["sellMovingWeek"], sell_orders=quick_status["sellOrders"], buy_price=quick_status["buyPrice"], buy_volume=quick_status["buyVolume"], buy_moving_week=quick_status["buyMovingWeek"], buy_orders=quick_status["buyOrders"], timestamp=timestamp) session.add(bazaar_product) try: item_list.append(items.Item(bazaar_product)) except items.ItemNotFoundError: continue session.commit() return items.ItemBatch(item_list, timestamp)
def load_char_if_saved(): query = Query() if db is not None: var = db.search(query.name == name_to_load) if var: var = var[0] ch.name = var.get('name') ch.coins = var.get('coins') inventory = var.get('inventory') player_inventory = [] for thing in inventory: if thing.get('type') == 'item': item = items.Item(thing.get('name'), thing.get('price')) player_inventory.append(item) elif thing.get('type') == 'weapon': weap = items.Weapon(thing.get('name'), thing.get('price'), thing.get('damage')) player_inventory.append(weap) elif thing.get('type') == 'armor': armor = items.Armor(thing.get('name'), thing.get('price'), thing.get('defense')) player_inventory.append(armor) elif thing.get('type') == 'potions': potion = items.Potion(thing.get('name'), thing.get('price'), thing.get('health')) player_inventory.append(potion) ch.inventory = player_inventory
def itemFromRows(rows): items = [] for row in rows: item = itm.Item() item.fillFromVal(row) items.append(item) return items
async def dgive(ctx, *args): if len(args) == 0: return amount = 1 plant = "" try: int(args[0]) except ValueError: plant = " ".join(args).strip() else: amount = int(args[0]) plant = " ".join(args[1:]).strip() if not items.is_item(plant): await client.say(f"`{plant}` isn't a real item...") return if ctx.message.author not in play.players: play.players[ctx.message.author] = play.Player(ctx.message.author) current_player = play.players[ctx.message.author] item = items.Item(plant, amount=amount) current_player.items += item await client.say( f"Gave {item.emoji} **{item.name}** (x{item.amount}) to {current_player.player.name}" )
def drawunlocks(self,screen,mousepos): ypointer = 82 ychange = 12 #used to store the images and their positions for when the mouse hovers over text popupblit = [] for unlock in self.unlocks: #the text of the unlock is it's actual description, then a counter if that unlock is countable string = unlock["description"] if type(unlock["progress"]) == type(1): string += "("+str(unlock["progress"])+"/"+str(unlock["condition"])+")" #dull the colour and strikethrough the unlock if it has been completed if unlock["finished"]: colour = (80,80,80) text = generatetext(string,None,"small",(0,0),colour) pygame.draw.line(text,colour,(0,3),(text.get_width()-2,3)) else: text = generatetext(string,None,"small",(0,0),(192,192,192)) #draw the text to the screen in the center textrect = text.get_rect() textrect.centerx = screen.get_width()//2 textrect.y = ypointer screen.blit(text,textrect) ypointer += ychange #if the mouse touches the text if textrect.collidepoint(mousepos): #change the image and text if the item is unlocked or not if unlock["finished"]: itemname = items.Item(unlock["item"]).name itemimage = items.SURFACES[str(unlock["item"])] else: itemname = "locked" itemimage = LOCKIMAGE itemrect = itemimage.get_rect() itemrect.topleft = mousepos nameimage = generatetext(itemname,None,"small",(0,0),(192,192,192)) namerect = nameimage.get_rect() namerect.center = itemrect.center namerect.top = itemrect.bottom #put black backgrounds to the images back = pygame.Surface(nameimage.get_size()) back.blit(nameimage,(0,0)) nameimage = back back = pygame.Surface(itemimage.get_size()) back.blit(itemimage,(0,0)) itemimage = back popupblit = [[nameimage,namerect],[itemimage,itemrect]] #draw the item image and text if it exists for image in popupblit: screen.blit(image[0],image[1])
def findSubTypes(rows): itemsWithSubtypes = [] for row in rows: item = itms.Item() item.fillFromVal(row) item.subtype = itms.findSubType(item.name, item.category, item.type) itemsWithSubtypes.append([item.subtype, item.name]) dao.setSubtypesMany(itemsWithSubtypes)
def place_objects(self, items): ''' Object managing : 1- We generate a random index between 0 and the len of possible loc 2- For each item we create an instance of Item and place it in the maze at the place defined randomly ''' locations = sample(self.obj_poss_loc, len(items)) for location, item in zip(locations, items): it.Item(self, *location, type=item)
def _starting_inventory(self): ''' (None) -> None Defines amount of items and resources that players should start with ''' for player in self.session.players: for i in range(12): player.stock.append(items.Item(self.db.item(name='food'))) return None
def harvest(self): if self.crop is None: return None #now = datetime.datetime.now() #if now >= self.completeTime: if time.time() >= self.completeTime: item_name = self.crop.item itemCount = randint(self.crop.minItem,self.crop.maxItem) self.crop = None self.completeTime = None return items.Item(item_name, amount=itemCount) #return {item:itemCount} #if these return none then I will need to make item a copy. else: return None
def write_data(df, spread): """ Writes data contained in 'df' to 'spread' spreadsheet df: pandas dataframe containing data spread: a gspread object representing the entire Google Sheets spreadsheet (whereas 'sheet' is a tab on the spreadsheet) """ for d in df: item = items.Item(d['Link'][0]) dstbtr = item.get_distributor() spread.df_to_sheet(d, sheet=dstbtr, replace=True)
def createItem(self, character, itemName): """Creates a new copy of the specified item by replicating the "master" version created when the item files were loaded""" if itemName not in self.items: raise Exception, "Invalid item name" if not character.inventory or not isinstance(character.inventory, items.Inventory): raise Exception, "Must pass a valid inventory" ret = items.Item(character.inventory, self) orig = self.items[itemName] for attr in orig.__dict__.keys(): ret.__setattr__(attr, orig.__dict__[attr]) ret.inventory = character.inventory return ret
def get_all_products_batches(): session = Session() timestamps = items.timestamps batches = [] for ts in timestamps: q = session.query(BazaarProduct).filter( BazaarProduct.timestamp == ts).all() items_list = [] for i in q: try: items_list.append(items.Item(i)) except items.ItemNotFoundError: continue ib = items.ItemBatch(items_list, ts) batches.append(ib) session.commit() return batches
def _do_history_row_insert(self, filename, action, jparams, hid, type_, itemid): parent, previous, text = json.loads(jparams) qconn = self.connection.get() cursor = qconn.cursor() cursor.execute(queries.items_insert, (itemid, parent, previous, text)) self.connection.give(qconn) self.items[itemid] = items.Item(self.connection, self, self.items, self.filename, itemid) history_insert_event.signal(filename=self.filename, id_=itemid, parent=parent, previous=previous, text=text, hid=hid)
def main(): a = items.Item(name='pirouni', description='voithaei stin vrosi', value=0.01) print(a) gold = items.Currency(currency_type='Silver', amount=30) print(gold) rock = items.Rock() print(rock) dagger = items.Weapon(name='Dagger', description='A small dagger', damage='d4', value=0.2) print(dagger) another_dagger = items.Dagger() print(another_dagger) assassin_suit = items.AssassinSuit() print(assassin_suit)
def convert_to_item(self, line): stripped_line = line.strip('\n') contents = stripped_line.split(',') timestamp = datetime.datetime.strptime(contents[1], '%Y-%m-%d %H:%M:%S.%f') completion = False if contents[2] == "True": completion = True due_date = '' if contents[3] != '': due_date = datetime.datetime.strptime(contents[3], '%Y-%m-%d %H:%M:%S') return items.Item(contents[0], completion, timestamp, due_date)
def parse_and_save_html(self): while 1: #signal.SIGINT信号对应的是ctrl+c,当收到这个信号时就调用stop函数 signal.signal(signal.SIGINT, self.stop) if self.redis.lindex('html'): content = self.redis.brpop('html') text = content['html'].decode('utf-8') extracts = extract.Extract(item=items.Item(), text=text, selector=parsel.Selector) #url的格式符合正则表达式,说明对应的response需要提取结构化数据 if self.patten.search(content['url'].decode('utf-8')): extracts.item_xpath('movie_name', '//h1/span[@property="v:itemreviewed"]/text()') extracts.item_xpath('movie_year', '//span[@property="v:initialReleaseDate"]/text()') extracts.item_xpath('movie_type', '//span[@property="v:genre"]/text()') extracts.item_xpath('movie_rate', '//strong[@class="ll rating_num"]/text()') item = extracts.get_item() result_item = (content['url'], item['movie_name'], item['movie_year'], item['movie_type'], item['movie_rate'],) cmd = """insert into item (url, movie_name, movie_year,movie_type, movie_rate) values (%s, %s, %s, %s, %s)""" self.db.query(cmd, result_item) else: extracts.link_xpath('//a/@href', r'/subject/[0-9]+/$|/tag/.*') url_list = extracts.get_links() #这里需要传输url的原因,是因为网页中提取出来的可能是相对网址 #在后续操作中需要将相对网址补充为绝对网址 result = json.dumps({'url': content['url'], 'url_list': url_list}) self.redis.rpush('unbloom_url_queue', result) html = zlib.compress(content['html']) headers = json.dumps(content['response_headers']).encode('utf-8') result1 = (content['url'], content['http_code'], headers, html,) cmd = """insert into html (url, http_code, response_headers, html) values (%s, %s, %s, %s)""" self.db.query(cmd, result1) self.logger.info('Save [%s] to MySQL', content['url'].encode('utf-8'))
def _loadItems(self): "Read the itemset zip file for item zips, creating Item objects along the way." print "loading itemset: %s" % self.itemset z = ZipFile(configuration.items) itemsets = self.splitSets(z.namelist()) for itemset in itemsets[self.itemset]: item_filenames = itemsets[self.itemset][itemset] item = items.Item(None, self) for item_filename in item_filenames: if item_filename.endswith('.py'): script = z.read(item_filename) self._setItemData(item, script) elif item_filename.endswith('.png'): item.image = pygame.image.load(StringIO(z.read(item_filename))).convert_alpha() else: print 'Skipping unknown filetype "%s"' % item_filename continue print "Created item: %s" % item.name self.items[item.name] = item z.close()
def update(self): super().update() if self.lifes <= 0 and self.count > 7: heart = items.Item(levels.HEART, 'heart') heart.rect.x = self.rect.x heart.rect.bottom = self.rect.y self.level.set_of_items.add(heart) diff = self.rect.left - self.player.rect.right diff2 = self.rect.centery - self.player.rect.centery if diff < 500: if diff2 > 0: self.movement_y = -1 elif diff2 < 0: self.movement_y = 1 else: self.movement_y = 0 if self.rect.x <= self.player.rect.x: self.movement_x = 3 elif self.rect.x > self.player.rect.x: self.movement_x = -3 else: self.movement_x = 0 self.movement_y = 0
def __init__(self, file_image, sound_list): super().__init__() self.image = file_image self.rect = self.image.get_rect() self.items = set() self.items_count = 0 self.ammo = 0 self.movement_x = 0 self.movement_y = 0 self._count = 0 self.power = 0 self.lifes = 2 self.level = None self.direction_of_movement = 'right' self.actual_weapon = None self.climbing = False self.slide = False self.crouch = False self.cheering = False self.sounds = sound_list special_attack = items.Item(SPECIAL_BULLET, 'special attack') self.items.add(special_attack)
def add_item(self,item,overwrite=False): if item["Id"] in self.items and overwrite == False: raise ValueError('Item {0} already exists in configuration.'.format(item["Id"])) """ Python 2/3 compat """ try: is_string = isinstance(item["Destination"], basestring) except NameError: is_string = isinstance(item["Destination"], str) if isinstance(item["Destination"],list): for dest in item["Destination"]: if dest not in self.destinations: raise ValueError('Item references destination that does not exist') elif is_string: if item["Destination"] not in self.destinations: raise ValueError('Item references destination that does not exist') else: raise TypeError('Item destination must be a string or an array') i = items.Item(item) self.items[i.id] = i
root = tk.Tk() root.geometry("300x100+100+100") start_room = rooms.Room("The Entrance", n=True) end_room = rooms.Room("The Bee Room", s=True, n=start_room) # Initialise a map game_map = rooms.Map([[start_room], [end_room]], start_room, end_room) # String var name name = "Jordan Hay" # Create player object player = Player(name, game_map) player.inventory().add_items([ items.Item("Bees"), items.Weapon("A HIVE FULL OF BEES", 10, 300), items.Armour("Honeycomb Kneepads", 100), items.Potion("10mL Syringe full of Honey", 10) ]) # After ten seconds the name will change root.after(10000, lambda: name.set("Different name")) # Display player inventory #player.inventory().gui(root) # Display player stats player.gui(root) # Root mainloop
def getXmlBlock(row): item = items.Item() item.fillFromVal(row) return item.getXML()
# characters and items Cookie = character.Character( "Cookiezi", "This person seems to be sitting behind a desk with a computer mashing " "his keyboard\nslightly, but you could definitely hear it. On his monitor, " "he seems to be clicking circles...", None, None, None) jeff = character.Character( "jeff", "he's sitting on a chair playing a game on the left side of the room", "stop", None, 50) cookie = items.Food("Cookie", "A chocolate chip cookie. Seems delicious.") bed = items.Item("Bed", "Your average-looking bed.") ball = items.Ball("Ball", "A regular, old tennis ball.") techRoomKey = items.Item( "Key", "The key has a message engraved that says 'Tech Room Key'...") backwardsGun = items.BackwardsGun( "Gun", "It's a gun, but its barrel is pointing the opposite way.") water = items.Drink( "Water Bottle", "A water bottle that has an off-center label that says 'Fiji'.") cookieMask = items.Mask( "Mask", "A mask of a smiling man wearing glasses with slits in the eyes. Wonder what you'd use it for." ) shirt = items.Shirt("Shirt", "Just a plain white shirt.") weirdBag = items.Container("Backpack", "Just a regular backpack.", 4)
def createItemFromTypeBlock(block, mod): item = itm.Item() item.fill(block, mod) return item
def place_objects(self, rooms): for room in rooms: # maximum number of monsters per room max_monsters = self.from_dungeon_level([[2, 1], [3, 4], [5, 6]]) #chance of each monster monster_chances = {} monster_chances['orc'] = 80 #orc always shows up, even if all other monsters have 0 chance monster_chances['troll'] = self.from_dungeon_level([[15, 3], [30, 5], [60, 7]]) #choose random number of monsters num_monsters = libtcod.random_get_int(0, 0, max_monsters) for i in range(num_monsters): #choose random spot for this monster x = libtcod.random_get_int(0, room.x1 + 1, room.x2 - 1) y = libtcod.random_get_int(0, room.y1 + 1, room.y2 - 1) if not self.is_blocked(x, y): choice = self.random_choice(monster_chances) if choice == 'orc': #create an orc fighter_component = character_classes.BaseCharacterClass(hp=20, defense=0, power=4) ai_component = creatures.BasicMonster() monster = creatures.Creature(x, y, 'o', 'orc', libtcod.desaturated_green, blocks=True, character_class=fighter_component, ai=ai_component, xp=35, screen=self.screen) elif choice == 'troll': #create a troll fighter_component = character_classes.BaseCharacterClass(hp=30, defense=2, power=8) ai_component = creatures.BasicMonster() monster = creatures.Creature(x, y, 'T', 'troll', libtcod.darker_green, blocks=True, character_class=fighter_component, ai=ai_component, xp=100, screen=self.screen) monster.player = self.player self.objects.append(monster) #maximum number of items per room max_items = self.from_dungeon_level([[1, 1], [2, 4]]) #chance of each item (by default they have a chance of 0 at level 1, which then goes up) item_chances = {} item_chances['heal'] = 35 #healing potion always shows up, even if all other items have 0 chance item_chances['lightning'] = self.from_dungeon_level([[25, 4]]) item_chances['fireball'] = self.from_dungeon_level([[25, 6]]) item_chances['confuse'] = self.from_dungeon_level([[10, 2]]) item_chances['sword'] = self.from_dungeon_level([[10, 3]]) num_items = libtcod.random_get_int(0, 0, max_items) for i in range(num_items): #choose random spot for this item x = libtcod.random_get_int(0, room.x1 + 1, room.x2 - 1) y = libtcod.random_get_int(0, room.y1 + 1, room.y2 - 1) #only place it if the tiles is not blocked if not self.is_blocked(x, y): choice = self.random_choice(item_chances) item = items.Item(x, y, '?','', libtcod.white) if choice == 'heal': #create a healing potion item = items.Spell_Scroll(x, y, '!', 'healing potion', libtcod.violet, 'heal') elif choice == 'lightning': #create a lightning bolt scroll item = items.Spell_Scroll(x, y, '#', 'scroll of lightning bolt', libtcod.dark_blue, 'lightning') elif choice == 'fireball': #create a fireball scroll item = items.Spell_Scroll(x, y, '#', 'scroll of fireball', libtcod.dark_orange, 'fireball') elif choice == 'confuse': #create a confuse scroll item = items.Spell_Scroll(x, y, '#', 'scroll of confusion', libtcod.light_blue, 'confusion') elif choice == 'sword': #create a sword item = items.Equipment(x, y, '/', 'sword', libtcod.sky, slot='right hand') self.objects.append(item) item.send_to_back(self.objects) # items appear below other objects
def talk(self): colliding_npcs = pygame.sprite.spritecollide(self, self.level.set_of_npcs, False) colliding_items = pygame.sprite.spritecollide(self, self.level.set_of_items, False) # jeśli npc nazywa się Solider, to gadaj z nim # Solider rzuca broń, chyba że juz z nim gadaliśmy wcześniej for npc in colliding_npcs: if self.direction_of_movement == 'left': self.image = TALK_L elif self.direction_of_movement == 'right': self.image = TALK_R if npc.name == "Soldier": self.sounds[5].play() npc.talking = True self.level.objective = "Weź broń i oczyść miasto z potworów" if not npc.already_talked: gun = items.Item(levels.SHOTGUN, 'gun') gun.rect.x = 800 gun.rect.bottom = constants.HEIGHT - 100 self.level.set_of_items.add(gun) npc.already_talked = True if npc.name == "Sister": self.sounds[5].play() npc.talking = True self.cheering = True self.level.objective = "GRATULACJE, UKOŃCZYŁEŚ GRĘ" if not npc.already_talked: pass npc.already_talked = True # itemki for item in colliding_items: # jeżeli item to skrzynia, i masz klucz do tej skrzyni # to otwórz skrzynie i dropnij itemka if item.name == "lock box1": for check_item in self.items: if check_item.name == 'yellow key': item.kill() self.items.remove(check_item) self.cheering = True gun = items.Item(levels.LASER_GUN, 'laser gun') gun.rect.x = 85 gun.rect.bottom = constants.HEIGHT - 500 self.level.set_of_items.add(gun) break # podobnie jak wyżej if item.name == "lock box2": for check_item in self.items: if check_item.name == 'blue key': item.kill() self.items.remove(check_item) self.cheering = True ammo = items.Item(LASER_BULLET, 'laser ammo') ammo.rect.x = 120 ammo.rect.bottom = 200 self.level.set_of_items.add(ammo) power_up = items.Item(levels.POWER_UP, 'power up') power_up.rect.x = 120 power_up.rect.bottom = 200 self.level.set_of_items.add(power_up) break # obsługa przekładni if item.name == 'lever': if item.status == 'left': item.status = 'mid' elif item.status == 'mid': item.status = 'left' break # obsługa pochodnii if item.name == 'torch': if item.status == 'off': item.status = 'on' elif item.status == 'on': item.status = 'off'
CUCHILLO = Tok('CUCHILLO') PALANCA = Tok('PALANCA') CRUCIFIJO = Tok('CRUCIFIJO') nombres = Voc({ LLAVE: ['LLAVE', 'LLAVECITA'], PUERTA: ['PUERTA', 'PORTON'], CUCHILLO: ['CUCHILLO', 'NAVAJA'], PALANCA: ['PALANCA'], CRUCIFIJO: ['CRUCIFIJO', 'CRUZ'], }) # ÍTEMS cuchillo = items.Item( 'un cuchillo', CUCHILLO ) palanca = items.Item( 'una palanca', PALANCA ) crucifijo = items.Item( 'un crucifijo', CRUCIFIJO ) # LOCALIDADES vestibulo = mapeado.Localidad(
print("*"*75) print("Current prices at items tracking") item_track.GetUserItemTrackPrices(db_connection=db_connection,pd=pd,user_id=user_id, item_id="NULL") print("*"*75) ################################################################# ####Track New Item############################################## track_new_item = str(input("Would you like to track a new item(y/n)?")) item_id = 0 if track_new_item.lower() == 'y': print("Current Items supported") items.GetItems(db_connection,pd) item_listed = str(input("Is your item listed(y/n)?")) if item_listed == 'n': print("place holder for new item") new_item = items.Item(db_connection, pd) item_id = new_item.CreateItem() print(item_id) else: item_id = int(input("Please enter the item id:")) #item_track.CreateUserItemTrack(db_connection=db_connection,user_id=user_id, item_id=item_id) ########Attached Item to Store(s)##################################### #out put all stores that item is attached to store_items = store_item.StoreItem(db_connection=db_connection,pd=pd,item_id=item_id, user_id = user_id) store_items.StoreItemProfile() ##################################################################### #####Grab Current website prices################################# if item_id == 0: item_id = "NULL" #convert to null for sproc to grab all items #issue with babies r us web scrap