def AddPart(self, part_id, color_id=0, quantity = 1, condition = 'A', type = 'P'): # parts (bricks ect.) - usually something with a color if (type == 'P'): key = item.item('%s__%s__%s__%s' % (type, part_id, condition, color_id)) # everything else (instructions, boxes, sets) - something without color else: key = item.item('%s__%s__%s' % (type, part_id, condition)) self._parts[key] = self._parts.get(key, 0) + quantity
def defaultitems(): ##### # ITEMS myitems = [] myitems.append(item.item("corpse")) myitems[-1].makecorpse() myitems.append(item.item("coin")) myitems[-1].addadjective("gold") myitems[-1].setdescription("Gold currency.") myitems[-1].setstackable(True) myitems.append(item.item("sign")) myitems[-1].addadjective("white") myitems[-1].addadjective("eagle") myitems[-1].makesign() myitems[-1].sign.settext(" #c3WELCOME TO THE WHITE EAGLE#cr\n") myitems[-1].setstatic(True) myitems[-1].setunlisted(True) myitems.append(item.item("rock")) myitems[-1].setdescription("Just a dirty old rock.") myitems.append(item.item("mug")) myitems[-1].setdescription("A small ceramic mug.") myitems.append(item.item("dagger")) myitems[-1].makeweapon() myitems[-1].weapon.setdamage(4) myitems[-1].setdescription("A small but lethal dagger.") myitems.append(item.item("sack")) myitems[-1].setdescription("A small leather sack used for storing things.") myitems[-1].addadjective("small") myitems[-1].addadjective("leather") myitems[-1].makecontainer() myitems.append(item.item("bread")) myitems[-1].setdescription("A piece of crusty bread.") myitems[-1].addadjective("piece of") myitems[-1].makefood() myitems.append(item.item("beer")) myitems[-1].setdescription("A mug of beer.") myitems[-1].makedrink() myitems.append(item.item("jacket")) myitems[-1].setdescription("A well oiled dark leather jacket.") myitems[-1].addadjective("leather") myitems[-1].makearmor() myitems[-1].armor.addbodypart(defs.BODYPART_LEFTARM) myitems[-1].armor.addbodypart(defs.BODYPART_RIGHTARM) myitems[-1].armor.addbodypart(defs.BODYPART_TORSO) # store all common items in common items list hub.commonitems = myitems
def AddPart(self, part_id, color_id=0, quantity=1, condition='A', type='P'): # parts (bricks ect.) - usually something with a color if (type == 'P'): key = item.item('%s__%s__%s__%s' % (type, part_id, condition, color_id)) # everything else (instructions, boxes, sets) - something without color else: key = item.item('%s__%s__%s' % (type, part_id, condition)) self._parts[key] = self._parts.get(key, 0) + quantity
def loader(self, path): """ Takes in a csv file and stores the necessary instances for the simulation object. The file path referenced should point to a file of a particular format - an example of which can be found in utils.py txt_generator(). The exact order of the file is unimportant - the three if statements will extract the needed information. :param path: File path directory to a .csv file holding the simulation information :return: """ # Load and store csv file info = defaultdict(list) print path with open(path) as info_read: for line in info_read: if not self.is_comment(line): data = line.strip().split(',') key, val = data[0], data[1:] info[key].append(val) # print(info) # Extract grid dimensions self.dim_w = int(info['grid'][0][0]) self.dim_h = int(info['grid'][0][1]) # Add items and agents to the environment i = 0 j = 0 l = 0 for k, v in info.items(): # print k # print v if 'item' in k: self.items.append(item.item(v[0][0], v[0][1], v[0][2], i)) i += 1 elif 'agent' in k: #import ipdb; ipdb.set_trace() agnt = agent.Agent(v[0][0], v[0][1], v[0][2], v[0][3], j) agnt.set_parameters(self,v[0][4], v[0][5], v[0][6]) self.agents.append(agnt) j += 1 elif 'main' in k: # x-coord, y-coord, direction, type, index self.main_agent = agent.Agent(v[0][0], v[0][1], v[0][2], 'm', -1) self.main_agent.level = v[0][2] elif 'obstacle' in k: self.obstacles.append(obstacle.Obstacle(v[0][0], v[0][1])) l += 1 # Run Checks assert len(self.items) == i, 'Incorrect Item Loading' assert len(self.agents) == j, 'Incorrect Ancillary Agent Loading' assert len(self.obstacles) == l, 'Incorrect Obstacle Loading' # Print Simulation Description print('Grid Size: {} \n{} Items Loaded\n{} Agents Loaded\n{} Obstacles Loaded'.format(self.dim_w, len(self.items), len(self.agents), len(self.obstacles))) # Update the map self.update_the_map()
def __generate_L2(self, class_int): uncover = None self.L2.clear() item_set_here = item_set(class_int) clone_item_set = item_set_here #print("begin __generate_L2 ,class_int :" + str(class_int)) for i in range(0, self.nVariables): if int(self.dataBase.numLabels(i)) > 1: for j in range(0, int(self.dataBase.numLabels(i))): item_here = item(i, j) #print(" before pass to add item , the item_here i is :" + str(i) + " , j is :"+str(j)) #print(" before pass to add item , the item_here type is :" + str(item_here)) item_set_here.add(item_here) item_set_here.calculate_supports(self.dataBase, self.train_MyDataSet) if item_set_here.get_support_class() >= self.minsup: #print(" item_set_here.size () is : " + str(item_set_here.size())) clone_item_set = item_set_here.clone_item_set() #print(" clone_item_set.size () is : " + str(clone_item_set.size())) self.L2.append(clone_item_set) #print("item_set_here is :" + str(item_set_here)) item_set_here.remove(0) #print(" after remove 0 ,clone_item_set.size () is : " + str(clone_item_set.size())) #print("self.L2 length is :" + str(len(self.L2))) #for i in range(0, len(self.L2)): #print("L2[" + str(i) + "] size is :" + str(self.L2[i].size())) self.generate_rules(self.L2, class_int)
def move_value(self, game, alpha, beta, depth, move, hash): value = 0 hash_new = self.mod_hashkey(hash, move, game) last = self.table.get(hash_new) if last is not None: if last.depth >= depth: return last.eval #if depth > self.max_q: #value = self.eval(game) if depth > self.max_depth and not game.gives_check(move) and not game.is_capture(move) and not game.is_check(): value = self.eval(game) else: game.push(move) if game.is_game_over(): if game.is_checkmate(): value = 9999 if game.turn else -9999 elif game.turn: value = self.min_val(game, alpha, beta, depth, move, hash_new) else: value = self.max_val(game, alpha, beta, depth, move, hash_new) game.pop() board = item(value, depth, self.count) self.table.add(hash_new, board) return value
def getItemsFromDb(self): conn = self.connection.connectToDb() trans = conn.begin() cursor = conn.connection.cursor( cursor_factory=(psycopg2.extras.DictCursor)) query = 'SELECT item_id,name,price,description,total_amount FROM items;' print('\nquery is: ', query, '\n') try: try: cursor.execute(query) rows = cursor.fetchall() listOfItems = [] for row in rows: if row['total_amount'] <= 0: continue tempItem = item(row['item_id'], row['name'], row['price'], row['description'], row['total_amount']) listOfItems.append(tempItem.serialize()) trans.commit() cursor.close() return json.dumps(listOfItems) except psycopg2.Error as error: try: trans.rollback() print(error.pgerror) return 'error' finally: error = None del error finally: conn.close()
def create_temp_simulator(items, agents, main_agent): local_map = [] row = [0] * 10 for i in range(10): local_map.append(list(row)) local_items = [] for i in range(len(items)): (item_x, item_y) = items[i].get_position() local_item = item.item(item_x, item_y, items[i].level, i) local_item.loaded = items[i].loaded local_items.append(local_item) if not local_item.loaded: local_map[item_y][item_x] = 1 local_agents = list() (a_agent_x, a_agent_y) = agents[0].get_position() local_map[a_agent_y][a_agent_x] = 8 local_agent = agent.Agent(a_agent_x, a_agent_y, 'l1', 0) local_agents.append(local_agent) (m_agent_x, m_agent_y) = main_agent.get_position() local_map[m_agent_y][m_agent_x] = 9 local_main_agent = agent.Agent(m_agent_x, m_agent_y, 'l1', 1) local_main_agent.set_level(main_agent.level) tmp_sim = simulator.simulator(local_map, local_items, local_agents, local_main_agent, 10, 10) return tmp_sim
def test_reset_item(self): """ Tests item resetting with every item type """ for i in range(11): ti=item.item(i+1) ti.reset() self.assertEqual(ti.name, " ") self.assertIsInstance(ti.name, str) self.assertEqual(ti.enchantlv, 0) self.assertIsInstance(ti.enchantlv, int) self.assertEqual(ti.equip, 0) self.assertIsInstance(ti.equip, int) self.assertEqual(ti.atk, 0) self.assertIsInstance(ti.atk, int) self.assertEqual(ti.defn, 0) self.assertIsInstance(ti.defn, int) self.assertEqual(ti.price, 0) self.assertIsInstance(ti.price, int) self.assertEqual(len(ti.bonuses), 7) for i in ti.bonuses: self.assertEqual(len(i), 8) self.assertIsInstance(i, str) self.assertEqual(getattr(ti,i), 0) self.assertIsInstance(getattr(ti,i), int)
def main(): try: gram = sys.argv[1] input = sys.argv[2] except IndexError: print("Please enter two files: a grammar specification file and an input file") ##find terminals, Nodes, and the token matches terminals, N, matches = token_check(gram, input) T = [] ##list we will be using to store the scan, predict, complete results n = len(matches) + 1 for i in range(0, n): T.append([]) for j in range(0, n): T[i].append(set()) ##creating the start position tmp = item("S'", sg, 0) T[0][0].add(tmp) for j in range(0, n): process_column(j, matches, N, T) ##checking if the input is is the grammar for i in T[0][-1]: if i.rhs == sg: print('yes') return print('no')
def pickthings(dungeon,player): """ Makes the player pick whatever is on the floor up and updates stats """ tile=dungeon.dungarray[player.ypos][player.xpos] pickmsg="" #Action if player has reached a money loot tile if tile=="$": monies=random.randrange(1,player.lv*5) player.pocket+=monies player.totalgld+=monies dungeon.dungarray[player.ypos][player.xpos]="." pickmsg="\nYou find %i gold\n"%monies #Action if player has reached a gear loot tile elif tile=="/": loot=item.item(random.randrange(1,12)) picked,pickmsg=player.pickobject(loot) if picked: dungeon.dungarray[player.ypos][player.xpos]="." #Action if player has reached a food tile elif tile=="o": if random.choice([0,0,0,1]): loot=item.consumable(3,0) else: loot=item.consumable(0,0) picked,pickmsg=player.pickconsumable(loot) if picked: dungeon.dungarray[player.ypos][player.xpos]="." return pickmsg
def __getslice__(self, i, j): rows = pgpass_csv.rows(pgpass.filename) result = [] for r in rows: if r and len(r) == 5 and not r[0].strip().startswith('#'): result.append(item(*r)) return result
def register_item(): # import global variable global id_count # validations print_header('Register New Item') title = input('input the item name: ') category = input('input the item\'s category: ') price = float(input('input the price of the item: ')) stock = int(input('input the items quantity in stock: ')) if len(items) == 0: id_count = 0 if len(items) > 0: id_count = len(items) new_item = item() new_item.id = id_count new_item.title = title new_item.category = category new_item.price = price new_item.stock = stock items.append(new_item) add_log('Item registered', title, id_count) save_log() print('Item Created') print(len(items))
def getItemsFromUserCart(self, userId): conn = self.connection.connectToDb() trans = conn.begin() cursor = conn.connection.cursor( cursor_factory=(psycopg2.extras.DictCursor)) query = '\n with counts as (select item,count(*) from carts, unnest(items_in_cart) as item where user_id = ' + userId + ' group by item)\n select item_id,name,price,description,total_amount,count from items,counts,carts where carts.user_id = ' + userId + ' AND counts.item = item_id\n ' print('\nquery is: ', query, '\n') try: try: cursor.execute(query) rows = cursor.fetchall() listOfItems = [] for row in rows: tempItem = item(row['item_id'], row['name'], row['price'], row['description'], row['total_amount']) for x in range(row['count']): listOfItems.append(tempItem.serialize()) trans.commit() cursor.close() return json.dumps(listOfItems) except psycopg2.Error as error: try: trans.rollback() print(error.pgerror) return 'error' finally: error = None del error finally: conn.close()
def loadcontent(self): self.map = [[ Tile(False) for y in range(self.height) ] for x in range(self.width) ] for objd in self.objs: self.batch.add(objd) self.char.roll() self.tes = room(5, 5, 30, 25) enter = self.tes.getEnter() # self.char.setLoc([enter[0] + self.tes.getX(), enter[1] + self.tes.getY() - 2]) self.rooms = [] self.rooms.append(self.tes) self.drawRoom() self.char.inventory[item(0,0,'yellow').key] = 0 self.char.inventory[item(0,0,'green').key] = 0 self.char.inventory[item(0,0,'red').key] = 0
def __init__(self): itemModifacation = [0, 0] playerModifacation = [0, 0, 0] self.items = [ item("placeholder pants", itemModifacation, playerModifacation) ] pass
def test_enchant_naming_one(self): """ Tests item enchanting name modifier. """ ti=item.item(1) ti.name="test +1" ti.enchant() self.assertIn(ti.name,["test +2"," "])
def add_item(text_input_boxes): new_thing = [] for i in text_input_boxes: new_thing.append(i.return_text()) context, level, state, color, date = new_thing new_thing = item(context, level, state, color, date) new_thing.write_file("list.txt") return new_thing
def test_enchant_level(self): """ Checks if the enchantlv attribute is raised """ for i in range(10): ti=item.item(1) ti.enchantlv=i ti.enchant() self.assertIn(ti.enchantlv,[i+1,0])
def test_enchant_atk_def(self): """ Tests item enchanting attack and bonus raises """ for i in range(10): ti=item.item(1) ti.atk=ti.defn=0 ti.enchant() self.assertGreaterEqual(ti.atk+ti.defn, 0)
def read(month, itemList=[]): file = open(month + ".txt", "r") for line in file.readlines(): name, price, date = line.split() #add item to the list itemList.append(item(price, name, date)) return
def test_enchant_pricing_nonzero(self): """ Tests item enchanting price raises from non-zero situations """ for i in range(10): ti=item.item(1) ti.price=100 ti.enchant() self.assertIn(ti.price, [200, 0])
def test_enchant_pricing_fromzero(self): """ Tests item enchanting price raises from 0 to 2 """ for i in range(10): ti=item.item(1) ti.price=0 ti.enchant() self.assertIn(ti.price, [1, 0])
def receiptDistribution(): print("receipt distriadfpoksdlfkjad") data = request.form.to_dict() print(data) data = data['pTableData'] with open('dist/jsontext.txt', 'w') as f: f.write(data) ################# data = eval(data[1:-1]) print(data) friends = list() for i in range(0, len(data)): friends.append( friend(data[i]['FirstName'], data[i]['LastName'], data[i]['Email'])) dish1 = item('1 Edamame', 9.00, 13, 12) dish2 = item('1 Kimo', 10.50, 13, 12) dish3 = item('1 A la Carte Sushi', 243.00, 13, 12) dish1.add_friend(friends) dish1.assign_prices() dish2.add_friend(friends) dish2.assign_prices() dish3.add_friend(friends) dish3.assign_prices() url = "https://mchacks6.appspot.com/v1/request-money" headers = { 'Content-Type': "application/json", 'cache-control': "no-cache", 'Postman-Token': "d09e9d2c-cd69-429d-81b0-6669b3f7402e" } response_list = list( map( lambda x: requests.request( "POST", url, data=x.interac_request(), headers=headers), friends)) list(map(lambda x: print(x.text), response_list)) return 'homepage.html'
def __init__(self): self.__req_skills = [] self.__req_items = {} self.__task_group = [] self.__performance = [] self.__final_performance = 0 #Output success self.__difficulty = 0 self.__resolution = 0 #Margin of success or failure self.__timeresolution = 5 #maximum time for this process in minutes self.__output = item()
def parse_category(self, response): # The path to website links in directory page links = response.xpath('//td[descendant::a[contains(@href, "#pagerank")]]/following-sibling::td/font') for link in links: item = item() item['name'] = link.xpath('a/text()').extract() item['url'] = link.xpath('a/@href').extract() item['description'] = link.xpath('font[2]/text()').extract() yield item
def addItem(itemList=[]): #get item information from user name = raw_input("Please enter the name of the item: ") print price = eval(raw_input("Please enter the price of the item: ")) print date = eval(raw_input("Please enter the week the item was purchased: ")) #add item to the list itemList.append(item(price, name, date))
def get_by_id(self, id): cur = self.conn.cursor() cur.execute("""SELECT i.id, i.code, i.name, i.price, i.created_on, i.created_by, array_to_string(array_agg(c.id), ',') as categories FROM items i LEFT JOIN item_categories ic on ic.item_id = i.id INNER JOIN categories c ON c.id = ic.category_id WHERE i.id=%s GROUP BY i.id, i.code, i.name, i.price, i.created_on, i.created_by""", (id,)) row = cur.fetchone() cur.close() return item.item(row[0], row[1], row[2], row[3], row[4], row[5], row[6].split(","))
def get_one_item(op, data_path): infile = open(data_path, 'rb') for idx, row in enumerate(DictReader(infile)): s_item = item(row['user_id'], row['item_id'], row['behavior_type'], row['item_category'], row['time'], row['user_geohash']) if op == 'train': yield s_item elif op == 'dict': yield row else: yield [s_item, row]
def __init__(self): """ Vendor constructor. Generates a random NPC (The shopkeeper) and generates items to be sold. """ self.keeper=npc() self.forsale=[] self.potforsale=[] for i in range(random.randrange(4,7)): self.forsale.append(item.item(random.randrange(1,12))) for i in range(random.randrange(1,4)): self.potforsale.append(item.consumable(random.choice([0,0,3,1]),0))
def parse_category(self, response): # The path to website links in directory page links = response.xpath( '//td[descendant::a[contains(@href, "#pagerank")]]/following-sibling::td/font' ) for link in links: item = item() item['name'] = link.xpath('a/text()').extract() item['url'] = link.xpath('a/@href').extract() item['description'] = link.xpath('font[2]/text()').extract() yield item
def initCompleteItemList(): data = grabPriceData() for i in range(1000000): ITEM = data.get(str(i)) if ITEM != None: name = ITEM.get('name') overallAverage = ITEM.get('sell_average') tempItem = item(name) tempItem.overallAverage = overallAverage tempItem.setChange() tempItem.priceTracker.append( (overallAverage, datetime.datetime.now())) completeItemList.append(tempItem)
def main(self): print "OMGHAI!" self.items.append(item.item("+5 Dexterity Vest", 10, 20)) self.items.append(item.item("Aged Brie", 2, 0)); self.items.append(item.item("Elixir of the Mongoose", 5, 7)); self.items.append(item.item("Sulfuras, Hand of Ragnaros", 0, 80)); self.items.append(item.item("Backstage passes to a TAFKAL80ETC concert", 15, 20)); self.items.append(item.item("Conjured Mana Cake", 3, 6)); self.update_quality()
def test_item_generation(self): """ Tests the item generation. -Creates a item in a random category -Checks the type -Runs itemtest on it Since there is random generation involved, each category is tested 100 times """ for j in range(100): for i in range(12): ti=item.item(i) self.assertEqual(ti.type, i) self.itemtest(ti)
def get_all(self): cur = self.conn.cursor() cur.execute("""SELECT i.id, i.code, i.name, i.price, i.created_on, i.created_by, array_to_string(array_agg(c.id), ',') as categories FROM items i LEFT JOIN item_categories ic on ic.item_id = i.id INNER JOIN categories c ON c.id = ic.category_id GROUP BY i.id, i.code, i.name, i.price, i.created_on, i.created_by""") rows = cur.fetchall() cur.close() items = [] for row in rows: items.append(item.item(row[0], row[1], row[2], row[3], row[4], row[5], row[6].split(","))) return items
def scan(L, i, j, matches, N, T): if L.dpos == len(L.rhs): return if j != len(T) and L.rhs[L.dpos] == matches[j]: L2 = item(L.lhs, L.rhs, L.dpos + 1) inside = False for x in T[i][j+1]: if L2.lhs == x.lhs and L2.rhs == x.rhs: inside = True break if not inside: T[i][j+1].add(L2) global flag flag = True
def quick_sort_goods_test(): goods_list = [] for i in range(0, 10): goods_list.append(item("goods"+str(i), random.randint(1,100), random.randint(1,100))) for goods in goods_list: print(goods) print("----------------------") quick_sort_goods(goods_list, "price") for goods in goods_list: print(goods) print("----------------------") quick_sort_goods(goods_list, "quantity") for goods in goods_list: print(goods)
def new_item(goods_list): while True: print("1: Enter the name of the new item") print("2: Go back to main menu") a = input("Please choose task: ") if a == "1": c = input("Please enter the name:") for i in goods_list: if i.get_name() == c: print("name already used") return 0 p = float(input("Please enter the price:")) q = int(input("please enter the quantity: ")) goods_list.append(item(c,p,q)) return 0 elif a == "2": return 0
def predict(L, i, j, matches, N, T): if L.dpos == len(L.rhs): return Q = L.rhs[L.dpos] if Q in N: for P in N[Q]: L2 = item(Q, P, 0) inside = False for x in T[j][j]: if L2.lhs == x.lhs and L2.rhs == x.rhs: inside = True break if not inside: T[j][j].add(L2) global flag flag = True
def complete(L, i, j, matches, N, T): if L.dpos != len(L.rhs): return for k in range(0, i+1): tmp2 = list(T[k][i]) for L2 in tmp2: if L2.dpos != len(L2.rhs) and L2.rhs[L2.dpos] == L.lhs: L3 = item(L2.lhs, L2.rhs, L2.dpos+1) inside = False for x in T[k][j]: if L3.lhs == x.lhs and L3.rhs == x.rhs: inside = True break if not inside: T[k][j].add(L3) global flag flag = True
def quick_sort_goods_test(): goods_list = [] for i in range(0, 10): goods_list.append( item("goods" + str(i), random.randint(1, 100), random.randint(1, 100))) for goods in goods_list: print(goods) print("----------------------") quick_sort_goods(goods_list, "price") for goods in goods_list: print(goods) print("----------------------") quick_sort_goods(goods_list, "quantity") for goods in goods_list: print(goods)
def loaditems(): fp = defs.ITEMS_COMMON createNewFile(fp) with open(fp, "r") as f: for line in f: line = line[:-1] if line == "": continue # load item newitem = item.item("unnamed", json.loads(line)) # store common item loaded into common items list hub.commonitems.append(newitem) f.close()
def get_item(dt='total', op="train"): if dt == 'total': f = open(raw_conf['user_train_path']) elif dt == 'train': f = open(raw_conf['n_tr_time']) elif dt == 'test': f = open(raw_conf['n_te_time']) #f = open('../data/w_te_rand.csv') elif dt == 'pred': f = open(raw_conf['test_set']) else: print "no such file dir." sys.exit(1) for idx, row in enumerate(DictReader(f)): s_item = item(row['user_id'], row['item_id'], row['behavior_type'], row['item_category'], row['time'], row['user_geohash']) if op == 'train': yield s_item elif op == 'dict': yield row else: yield [s_item, row]
def reset(self): """ Changes all player variables to the default values """ self.name="_" self.pocket=0 self.exp=0 self.lv=1 self.points=0 self.race="_" self.charclass="_" self.stomach=100 self.inventory=[] self.belt=[] self.equiparr=[] for i in range(11): new=item.item(0) self.equiparr.append(new) self.totalfl=0 self.prestige=0 self.prestigelv=1 self.totalfl =self.steps =self.totalatks=self.totalhits=self.totaldmg=self.totalhit=self.kills =0 self.totalgld=self.totaltrp=self.itemspck =self.itemsenc =self.itemsdst=self.totalpot=self.totalsll=0 self.totalbuy=self.totalspn=self.maxdmg =self.maxench =0 self.INT =self.DEX =self.PER =self.WIL =self.STR =self.CON =self.CHA =1 self.intboost=self.dexboost=self.perboost =self.wilboost =self.strboost=self.conboost=self.chaboost=0 self.totatk=self.totdefn=0 self.HP=self.hp2=0 self.MP=self.mp2=0 self.END=self.SPD=0 self.xpos=self.ypos=self.zpos=0
def _Parse(self, f): self._order_bricks = {} shop_re = re.compile(r'order_shop\[(.*)\]') brick_re = re.compile(r'order_brick\[(.*),(.*)\]') qty_re = re.compile(r'\A +\* +([0-9]+) +') for line in f: shop_match = shop_re.search(line) if shop_match: shop_name = GlpkSolver._TrimQuotes(shop_match.group(1)) continue brick_match = brick_re.search(line) if brick_match: brick = item.item(brick_match.group(1)) shop_name = GlpkSolver._TrimQuotes(brick_match.group(2)) continue qty_match = qty_re.match(line) if qty_match: qty = int(qty_match.group(1)) if qty: if brick: self._order_bricks.setdefault(shop_name, {})[brick] = int(qty) continue shop_name = None brick = None
def do_item(self): from item import item return item()
def loader(self, path, log_file): """ Takes in a csv file and stores the necessary instances for the simulation object. The file path referenced should point to a file of a particular format - an example of which can be found in utils.py txt_generator(). The exact order of the file is unimportant - the three if statements will extract the needed information. :param path: File path directory to a .csv file holding the simulation information :return: """ # Load and store csv file i, j, l = 0, 0, 0 info = defaultdict(list) print path with open(path) as info_read: for line in info_read: print line log_file.write(line) if not self.is_comment(line): data = line.strip().split(',') key, val = data[0], data[1:] if key == 'grid': self.dim_w = int(val[0]) self.dim_h = int(val[1]) if 'item' in key: self.items.append(item.item(val[0], val[1], val[2], i)) i += 1 elif 'agent' in key: #import ipdb; ipdb.set_trace() agnt = agent.Agent(val[1], val[2], val[3], val[4], int(val[0])) agnt.set_parameters(self, val[5], val[6], val[7]) agnt.choose_target_state = copy(self) self.agents.append(agnt) j += 1 elif 'main' in key: # x-coord, y-coord, direction, type, index self.main_agent = intelligent_agent.Agent( val[0], val[1], val[2]) self.main_agent.level = val[4] elif 'enemy' in key: self.enemy_agent = intelligent_agent.Agent( val[0], val[1], val[2], True) self.enemy_agent.level = val[4] elif 'obstacle' in key: self.obstacles.append(obstacle.Obstacle( val[0], val[1])) l += 1 # Run Checks assert len(self.items) == i, 'Incorrect Item Loading' assert len(self.agents) == j, 'Incorrect Ancillary Agent Loading' assert len(self.obstacles) == l, 'Incorrect Obstacle Loading' # Print Simulation Description print( 'Grid Size: {} \n{} Items Loaded\n{} Agents Loaded\n{} Obstacles Loaded' .format(self.dim_w, len(self.items), len(self.agents), len(self.obstacles))) # Update the map self.update_the_map()
f_r = open('./levels/level_4.txt', 'r') lvl4 = [list(line) for line in f_r] f_r.close() loot = [] return lvl4, 10, 23, loot, [[10, 22, 2], [6, 20, 4]], 9, 10, [] items = dict([]) for file in os.listdir(path="./items"): f_r = open("./items/" + file, 'r') itype = f_r.readline().split(':')[1].strip() name = f_r.readline().split(':')[1].strip() about = f_r.readline().split(':')[1].strip() strength = f_r.readline().split(':')[1].strip() image_id = f_r.readline().split(':')[1].strip() its = item(itype, name, about, strength, int(image_id)) effects = f_r.read().split('\n') for line in effects: print(line.split(':')) type_effect, effect = line.split(':') its.add_effect(type_effect, int(effect)) items[file.split('.')[0]] = its
def __init__(self): """ Initialization of the player objects. Generates a random player. Coordinate setting must be done through enter() Attribute setting for manual player creation must be done externally """ #Main characteristics self.name="_" #Name self.pocket=0 #Money self.exp=0 #EXP self.lv=1 #Level self.points=0 self.race="_" #Race self.charclass="_" #Class self.status=0 #Paralyzed, burned, bleeding, etc self.prestige=0 #Prestige points self.prestigelv=1 #Prestige level (unused) self.stomach=100 self.hungsteps=0 #Initialize stat variables self.totalfl =self.steps =self.totalatks=self.totalgld=self.totalhits=self.totaldmg=self.totalrcv=self.kills =0 self.totaltrp=self.itemspck=self.itemsdst =self.itemsenc=self.totalpot =self.totalsll=self.totalbuy=self.totalspn=0 self.maxdmg =self.maxench =0 #Initializing inventory arrays and items self.belt=[] self.equiparr=[] self.inventory=[] for i in range(6): self.belt.append(item.consumable(4)) for i in range(11): self.equiparr.append(item.item(0)) for i in range(2): self.inventory.append(item.item(random.randint(1,11))) #Set attributes to 1, set secondary attributes self.STR=self.INT=self.CON=self.WIL=self.PER=self.DEX=self.CHA=1 self.attrs=["STR", "INT", "DEX", "PER", "CON", "WIL", "CHA"] #Set attribute boosters to 0 self.strboost=self.intboost=self.conboost=self.wilboost=self.perboost=self.dexboost=self.chaboost=0 #Secondary attributes self.HP=self.hp2=0 self.MP=self.mp2=0 self.END=self.SPD=0 self.totatk=self.totdefn=1 self.secondary() self.mp2=self.MP self.hp2=self.HP # Initialize position self.ypos=0 self.xpos=0 self.zpos=0 #Random class self.charclass=random.choice(playerd.classes.classes) # Name self.name=random.choice(playerd.names.names) # Race self.race=random.choice(playerd.races.stats.keys()) self.STR+=playerd.races.stats[self.race]["STR"] self.INT+=playerd.races.stats[self.race]["INT"] self.DEX+=playerd.races.stats[self.race]["DEX"] self.PER+=playerd.races.stats[self.race]["PER"] self.CON+=playerd.races.stats[self.race]["CON"] self.WIL+=playerd.races.stats[self.race]["WIL"] self.CHA+=playerd.races.stats[self.race]["CHA"] #Random initial attributes for i in range(9): neg=any([1 if i<1 else 0 for i in [self.STR, self.INT, self.DEX, self.PER, self.CON, self.WIL, self.CHA]]) if neg: if self.STR<1: self.STR+=1 elif self.INT<1: self.INT+=1 elif self.DEX<1: self.DEX+=1 elif self.PER<1: self.PER+=1 elif self.CON<1: self.CON+=1 elif self.WIL<1: self.WIL+=1 elif self.CHA<1: self.CHA+=1 else: randstat=random.randrange(7) if randstat==0: self.STR+=1 elif randstat==1: self.INT+=1 elif randstat==2: self.DEX+=1 elif randstat==3: self.PER+=1 elif randstat==4: self.CON+=1 elif randstat==5: self.WIL+=1 elif randstat==6: self.CHA+=1
playerInv.draw(w) p.display.update() ####### main ############ m = mapp(-3600, -3700) entities.append( entity(-200, 600, -200, 600, 5, 10, 'monster', entity_type='mob')) entities.append(entity(100, 100, 100, 100, 5, 10, 'monster', entity_type='mob')) entities.append(entity(-500, 300, -500, 300, 0, 0, 'tree', entity_type='solid')) playerInv = inventory(900, SCREEN_H - 300, False, False) items.append(item(1, 'coins', 100, 100)) items.append(item(2, 'globes', 100, 100)) ogre = player(400, 300, 64, 64) ####### main ############ run = True while run: c.tick(27) for event in p.event.get(): if event.type == p.QUIT: run = False k = p.key.get_pressed()
if (LB.buttom_is_press(window, mouse)): if (check_login(UIP.return_text(), PWP.return_text(), my_ID, my_PW)): log_in = False LB.text_in_buttom(window, myfont, "Log in") pygame.display.flip() sort_buttom = buttom(pygame.Rect([1150, 530, 80, 40]), white, black) create_item_buttom = buttom(pygame.Rect([1150, 580, 80, 40]), white, black) list_buttom = buttom(pygame.Rect([1150, 630, 80, 40]), white, black) txt_file = open("list.txt", "r") things = [] list_box = [] for line in txt_file: contect, level, state, color, date = break_line(line) things.append(item(contect, level, state, color, date)) num_of_item = 0 for i in things: str_color = i.return_color()[1:-1] RGB_list = str_color.split(', ') for j in range(0, len(RGB_list)): RGB_list[j] = int(RGB_list[j]) temp_box = text_box(pygame.Rect([20, 20 + 100 * num_of_item, 510, 80]), tuple(RGB_list), textbox_active_color) temp_box.change_text(i.string_form()) list_box.append(temp_box) num_of_item += 1 while main_in: for event in pygame.event.get():
def __init__(self): self.__req_skills = [] self.__skill_performances = {} self.__req_input_items = [] self.__items = {} self.__output_item = item()
def generate_graph_from_txt(file_path): nodes = [] f = open(file_path) print(f) content = list(f) for i in range(0, len(content)): content[i] = content[i].strip() name = content[0] if (content[1].lower() == 'unidirectional'): i = 2 indexDictionary = {} while ',' not in content[i]: nodes.append(item(content[i], None)) indexDictionary[content[i]] = i - 2 i = i + 1 while (',' in content[i]): from_node = content[i][0:content[i].index(',')] to_node = content[i][content[i].index(',') + 1:len(content[i])] nodes[indexDictionary[from_node]].add_neighbor( neighbor(1, nodes[indexDictionary[to_node]])) i = i + 1 if i == len(content): break ### NEED TO FINISH THE NEIGHBOR PART OF THIS #print("Finished Theoretically") #print(nodes) elif (content[1].lower() == 'bidirectional'): i = 2 indexDictionary = {} while ',' not in content[i]: nodes.append(item(content[i], None)) indexDictionary[content[i]] = i - 2 i = i + 1 while (',' in content[i]): from_node = content[i][0:content[i].index(',')] to_node = content[i][content[i].index(',') + 1:len(content[i])] nodes[indexDictionary[from_node]].add_neighbor( neighbor(1, nodes[indexDictionary[to_node]])) nodes[indexDictionary[to_node]].add_neighbor( neighbor(1, nodes[indexDictionary[from_node]])) i = i + 1 if i == len(content): break ### NEED TO FINISH THE NEIGHBOR PART OF THIS # print("Finished Theoretically") # print(nodes) f.close() print(nodes) return graph(nodes, name)
c = input("please choose task:") if c == "1": goods_list.pop(1) return 0 if c == "2": return 0 print ("not found!") continue elif a== "2": return 0 goods_list = [] for i in range(0, 10): goods_list.append(item("goods"+str(i), random.randint(1,100), random.randint(1,100))) while True: print("1: Add a new item") print("2: Delete an existing item") print("3: Display goods information") print("4: Quit") a = input("Please choose task: ") if a == "3": display(goods_list) elif a== "1": new_item(goods_list) elif a== "2": mydelete(goods_list)
from save import save from save import load from userInterface import userInterface import threading from watchingItems import watchingItems import os clear = lambda: os.system('cls') clear() print('starting up') #watchingItems = ['Dragon hunter crossbow', "Zulrah's scales", 'Twisted bow'] watchingItemsPrice = load() if watchingItemsPrice == []: for thing in watchingItems: tempItem = item(thing) watchingItemsPrice.append(tempItem) if len(watchingItemsPrice) < len(watchingItems): for item1 in watchingItems: foundItem = False for item2 in watchingItemsPrice: if item2.name == item1: foundItem = True break if not (foundItem): watchingItemsPrice.append(item(item1)) completeItemList = [] now = datetime.datetime.now() lastMinute = now.minute - 1