def __init__(self, username, password, list_name, debug=False, verbose=False, fake=False): Shop.__init__(self, debug=debug, verbose=verbose, fake=fake) # Credentials to access to the shop self.username = username self.password = password # Name of the product's list to be parsed as named in the server self.list_name = list_name
def buy(request, item): context = RequestContext(request) item_level = item[0] item_type = item[1] if item_type == 'R': new_item = getRod(item_level) elif item_type == 'B': new_item = getBoat(item_level) elif item_type == 'b': new_item = getBait(item_level) else: print "error" user = request.user new_shop = Shop() new_shop.buyItem(new_item, user) user_profile = get_userProfile(user) rod_list = get_rodList(user) boat_list = get_boatList(user) bait_list = get_baitList(user) context_dict = {'rods': rod_list, 'boats': boat_list, 'bait': bait_list, 'user_profile': user_profile} if get_balance_status(user) is False: return render_to_response('balance_error.html', context) else: return render_to_response('shop.html', context_dict, context)
def __init__(self, screen, interface, ticker, iH, menu): Shop.__init__(self, screen, interface, 'townhall', ticker, iH, menu) self.storeScreen = pygame.Surface( (300,300) ) self.inventory = [] self.images = range(2) self.images[0], r = load_image.load_image( os.path.join('MENU', "cursor.png" ), -1) self.images[1], r = load_image.load_image( os.path.join('INT', 'inn.bmp')) self.storeScreen.fill( colors.black ) self.storeScreen.blit( self.images[1], (0,0) ) self.menuBox = pygame.Surface( ( int(ceil(124*const.scaleFactor)), int(ceil(99*const.scaleFactor)) ) ) self.name = 'townhall'
def get_city_shop_info(shopId, cityId, proxy, headers): shop = Shop(shopId) shop.get(proxy=proxy, headers=headers) if not shop._fetched: return data = { # '地址': shop.address, 'reviews': shop.reviews, # 点评数 'review_tags': shop.review_tags, # 点评标签 'phoneNumber': get_full_phone(shop.phone, cityId), # 电话 'comment_kinds': shop.comment_kinds, # 点评类别 'scores': shop.scores # 评分 } return data, shop.proxy, shop.headers
def __init__(self, token, memory_filename, ban_filename, lootcrate_filename, promotion_access_filename, promotion_rating): logging.info('Initializing bot...') self.updater = Updater(token=token) logging.info('Updater initialized') self.memory_filename = memory_filename self.ban_filename = ban_filename self.memory = self.load_memory() self.lootCrates = LootCrates(lootcrate_filename) self.myshop = Shop(promotion_access_filename, helpers, self.lootCrates, self.add_cheat_winner, promotion_rating) logging.info('Memory loaded') self.today = None # self.echo_mode = False handlers = [ CommandHandler('start', self.start), CommandHandler('pidorules', self.start), CommandHandler('shrug', self.shrug), CommandHandler('pidoreg', self.reg), CommandHandler('pidunreg', self.unreg), CommandHandler('pidor', self.choose_winner), CommandHandler('pidostats', self.stats), CommandHandler('rollBan', self.rollBan), # CommandHandler('test', self.test), # CommandHandler('test2', self.test2), CommandHandler('test3', self.test3), CommandHandler('shop', self.shop), CommandHandler('pidostats_lifetime', self.get_top_winners_all), CommandHandler('listlootcrates', self.list_lootcrates), CommandHandler('openlootcrate', self.openlootcrate), CommandHandler('rmBan', self.rmBan), CommandHandler('grantLegend', self.grantLegend), CommandHandler('promotop', self.promotop), CallbackQueryHandler(self.myshop.promoInfo, pattern="promo"), CallbackQueryHandler(self.myshop.buyLegend, pattern="buy_legend"), CallbackQueryHandler(self.myshop.buyPromoAccess, pattern="aclo_access") # CommandHandler('echo', self.echo), # MessageHandler(filters.Filters.all, self.echo_msg) ] for handler in handlers: self.updater.dispatcher.add_handler(handler) self.updater.dispatcher.add_error_handler(self.error_handler) logging.info('Handlers added')
def __init__(self, screen, interface, ticker, iH, menu): Shop.__init__(self, screen, interface, 'townhall', ticker, iH, menu) self.storeScreen = pygame.Surface((300, 300)) self.inventory = [] self.images = range(2) self.images[0], r = load_image.load_image( os.path.join('MENU', "cursor.png"), -1) self.images[1], r = load_image.load_image( os.path.join('INT', 'inn.bmp')) self.storeScreen.fill(colors.black) self.storeScreen.blit(self.images[1], (0, 0)) self.menuBox = pygame.Surface((int(ceil(124 * const.scaleFactor)), int(ceil(99 * const.scaleFactor)))) self.name = 'townhall'
def get_city_shop_info(shopId, cityId, proxy, headers): shop = Shop(shopId) shop.get(proxy=proxy, headers=headers) if not shop._fetched: return data = { '地址': shop.address, '点评数': shop.reviews, '点评标签': shop.review_tags, '电话': get_full_phone(shop.phone, cityId), '点评类别': shop.comment_kinds, '评分': shop.scores } return data, shop.proxy, shop.headers
def main_loop(self): while 1: #set fps self.clock.tick(60) #if the desired mode is changed, then change the program to that mode. if self.selected_mode != str(self.current_mode): if self.selected_mode == 'Start' or self.selected_mode == 'Continue': if self.save == None: self.save = Game(self.screen) self.current_mode = self.save elif self.selected_mode == 'Menu': if self.save == None: self.current_mode = Menu(['Start', 'Quit'], self.screen) else: self.current_mode = Menu(['Continue', 'Quit'], self.screen) elif self.selected_mode == 'Shop': temp = Shop(self.screen, self.save.player) self.current_mode = temp self.save.player = temp.player elif self.selected_mode == 'Quit': raise SystemExit #if the current_mode exist, run its loop if self.current_mode != None: #the loop usually returns a str(self), so when it is not the case, the mode changes self.selected_mode = self.current_mode.loop( pygame.event.get(), self.screen) pygame.display.flip()
def __init__(self): self.create_logger() try: self.debug("Initializing pygame") pygame.init() except Exception as e: self.debug("Init Error: "+str(e)) self.music = None self.bg_vol = 0.4 self.name = None self.entities = None self.map_layer = None self.collisions = [] self.transport_rects = {} try: self.shop = Shop(self) self.manager = LevelManager(self) self.rsc = resources.ResourceManager(self) self.scenes = CutScenes(self) except Exception as e: self.debug("Manager Error: "+str(e))
def __init__(self, config): self.app = Flask(__name__) self.api_authenticator = APIAutheticate(dict(config.items( "ADMIN_ENGINE"))) self.api_port = config.getint("ADMIN_ENGINE", 'port') self.api_host = config.get("ADMIN_ENGINE", 'host') self.shop = Shop(config)
def buy(self, ashop=Shop(), bike=Bicycle): if bike.mname in self.canbuy(ashop): self.fund -= ashop.get_prices()[bike.mname] print("%s buy %s bike at %s, and have $%d remaining." % (self.cname, bike.mname, ashop.sname, self.fund)) else: print("too expensive to buy")
class CommentTest(unittest.TestCase): def setUp(self): self.wc = Shop() def test_ads(self): ret = self.wc.ads('1001') print ret
def __init__(self, root): with open('users_pwd.pkl','rb') as f: self.pwd = pickle.load(f) self.p = Shop() self.l1 = tk.Label(root, text="Account Number") self.l1.grid(row=0, column=0) self.l2 = tk.Label(root, text="Password") self.l2.grid(row=1, column=0) self.v1 = tk.StringVar() self.v2 = tk.StringVar() self.e1 = tk.Entry(root, textvariable=self.v1) self.e1.grid(row=0, column=1, padx=10, pady=5) self.e2 = tk.Entry(root, textvariable=self.v2, show="*") self.e2.grid(row=1, column=1, padx=10, pady=5) self.b1 = tk.Button(root, text="Login", width=10, command=self.home_page) self.b1.grid(row=2, column=0, sticky=tk.W, padx=10, pady=5) self.b2 = tk.Button(root, text="Sign up", width=10, command=self.sign_up) self.b2.grid(row=2, column=1, sticky=tk.E, padx=10, pady=5)
def init(): global grave_digger grave_digger = Shop("grave digger", [], False) global druid druid = Shop("druid", [item for item in game.items if not item.passive_effect], False) global blacksmith blacksmith = Shop("blacksmith", [item for item in game.items if item.passive_effect], False) global merchant merchant = Shop("merchant", game.player.inventory, True) if game.bonus_tasks: text.VILLAGE_OPTIONS.insert(text.VILLAGE_OPTIONS.index(text.OPTION_SAVE), text.OPTION_TREASURE_CHEST) text.VILLAGE_OPTIONS.insert(text.VILLAGE_OPTIONS.index(text.OPTION_SAVE), text.OPTION_GRAVE_DIGGER) update_actions()
def init(self): self.user = User(self.username, self.password) self.user.login() self.attacker = Attacker(self.user, log=self.log) self.box = Box(self.user, self.openBoxType) self.equip = Equip(self.user, self.smeltEquipType) self.item = Item(self.user, self.useItemType, self.sellItemType) self.shop = Shop(self.user) self.growup = Growup(self.user) self.card = Card(self.user)
def create_shop(): address = "piazza Calamatta" open_at = 9 close_at = 19 min_price_euro = 10 max_price_euro = 30 walk_in_start_time = 17 walk_in_length_time = 2 return Shop(address, open_at, close_at, min_price_euro, max_price_euro, walk_in_start_time, walk_in_length_time)
def dump_details(): try: details_dict = {} if os.path.exists(DUMP_FILE_SHOP_DETAILS): with open(DUMP_FILE_SHOP_DETAILS, 'r') as f: doc_details = f.read() for shop_details in decode_json_stacked(doc_details): idx = shop_idx(shop_details) details_dict[idx] = shop_details with open(DUMP_FILE_SHOPS, 'r') as f: doc_shops = f.read() shop_data_list = list(decode_json_stacked(doc_shops)) progress_bar = tqdm(range(len(shop_data_list)), unit='shop', position=0, dynamic_ncols=True) with open(DUMP_FILE_SHOP_DETAILS, 'a') as f: for cur in progress_bar: shop_data = shop_data_list[cur] idx = shop_data['店铺ID'] if details_dict.get(idx) is not None: continue shop = Shop(shop_idx(shop_data)) headers = inject_cookie(HEADERS) try_http_request( lambda: shop.get(headers=headers), lambda cookies: inject_cookie(headers, cookies)) shop.get(headers=inject_cookie(HEADERS)) to_extend = { 'comment_kinds': shop.comment_kinds, 'review_tags': parse_review_tags(shop.review_tags), 'scores': shop.scores, } shop_data.update(to_extend) f.write(encode_json(shop_data)) f.flush() progress_bar.close() finally: logger.info(f'Data dumped to {DUMP_FILE_SHOP_DETAILS}')
def parse_product_list_page(self, html_page): """Parse the HTML page which has the product list and populate the product_dict""" html_tree = lxml.html.fromstring(html_page, parser=lxml.html.HTMLParser(encoding='utf-8')) product_list = html_tree.xpath("//table[@class='tablaproductos']/tbody/tr") #print len(product_list) for product_item in product_list: # Check whether the product is available if len(product_item.xpath("./td[1]/img[@alt='PRODUCTOS NO DISPONIBLES']")) > 0: continue product_id = product_item.xpath("./td[4]/input/@value")[0].partition(';')[0] product_name = product_item.xpath("./td[1]//label")[0].text.replace(' ***LE RECOMENDAMOS***', '') product_name = product_name.encode('utf-8') product_price = float(product_item.xpath("./td[2]/span")[0].text.partition(' ')[0].replace(',', '.')) product_unitary_price = product_item.xpath("./td[2]/span[contains(" "concat(' ', normalize-space(@class), ' '), ' precio_ud ')]") if len(product_unitary_price) > 0: product_unitary_price = product_unitary_price[0].text.partition(': ') product_unit = product_unitary_price[0] product_unitary_price = float(product_unitary_price[2].partition(' ')[0].replace(',', '.')) # The following are fixings to normalize shop "bugs" if product_id == '43401': product_unitary_price = product_price product_unit = '1 UNIDAD' elif product_id == '40805': amount = re.search(r'(\d+) LAVADOS', product_name).group(1) product_unitary_price = round(round(product_price / float(amount), 4), 2) product_unit = '1 LAVADO' product_unitary_price, product_unit = self.normalize_unitary_price(product_unitary_price, product_unit) else: product_unitary_price, product_unit = self.get_unitary_price(product_price, product_name) Shop.add_product(self, Product(product_id, product_name, product_price, product_unitary_price, product_unit))
class City: def __init__(self, player, world): self.player = player self.shop = Shop() self.world = world self.arena_fights = 0 def print_city_menu(self): print( "Your Turn! Choose what you want to do!\n[1]To fight in the Arena!\n[2]To enter the Shop\n[3]To show your " "Inventory\n[4]To venture in to the World!\n[X]To quit the Game!") def arena_fight(self): self.arena_fights += 1 if 5 <= self.arena_fights < 10: return Fight(self.player, Enemy(20, 2, 5, 3)).fight() elif self.arena_fights >= 10: return Fight(self.player, Enemy(25, 4, 8, 7)).fight() return Fight(self.player, Enemy(15, 1, 3, 1)).fight() def enter_shop(self): in_shop = True while in_shop: in_shop = self.shop.show_shop_prompt(self.player) def enter_city(self): player_alive = True while player_alive: self.print_city_menu() player_input = str(input("What do you Choose?")).lower() if player_input == "1": player_alive = self.arena_fight() elif player_input == "2": self.enter_shop() elif player_input == "3": self.player.go_to_inventory(self.player) elif player_input == "4": player_alive = self.world.run_world() elif player_input == "x": return False return False
def parse_product_list_page(self, html_page): """Parse the HTML page which has the product list and populate the product_dict""" html_tree = lxml.html.fromstring(html_page, parser=lxml.html.HTMLParser(encoding='utf-8')) product_list = html_tree.xpath("//table[@id='conte']/form/tr[starts-with(@id, 'prod_') or " "starts-with(@id, 'categ_')]") #print len(product_list) for product_item in product_list: # Get product category product_id = product_item.attrib['id'] if product_id.startswith('categ_'): if not product_id.endswith('_2'): product_category = product_item.xpath("./td/table/tr/td[2]/p")[0].text.strip(' >') #print product_category continue base_xpath = "./td/table/tr/td/table/tr/td[3]/table" # Check whether the product is available if len(product_item.xpath(base_xpath + "/tr[3]/td/table/tr/td[@class='sub_menu_11']/a/" "strong[text()='Busca Sustituto']")) > 0: continue product_id = product_id.partition('_')[2] product_name = product_item.xpath(base_xpath + "/tr/td/table/tr/td[@class='menu_sup11']")[0].\ text_content().strip() product_name = product_name.encode('utf-8') product_price = float(product_item.xpath(base_xpath + "/tr[3]/td/table/tr/td[@class='menu_12_rojo_sin']/strong")[0].\ text.partition(' ')[0].replace(',', '.')) # The following are fixings to normalize shop "bugs" if product_id == '900782_2058535': product_name = product_name.replace('3x80', '3x60') product_unitary_price, product_unit = self.get_unitary_price(product_price, product_name, product_category) Shop.add_product(self, Product(product_id, product_name, product_price, product_unitary_price, product_unit))
def parse_product_list_page(self, html_page): """Parse the HTML page which has the product list and populate the product_dict""" html_tree = lxml.html.fromstring(html_page, parser=lxml.html.HTMLParser(encoding='utf-8')) product_list = html_tree.xpath("//table[@id='shopping-cart-table']/tbody/tr[not(@class)]") #print len(product_list) for product_item in product_list: # Check whether the product is available if len(product_item.xpath("./td[3]/span[text()='Producto no disponible']")) > 0: continue product_id = product_item.xpath(".//div[@class='cart_product_img']//img/@src")[0].split('/') product_id = product_id[len(product_id) - 2] product_name = product_item.xpath(".//div[@class='cart_product_txt']/h3/a/span")[0].text product_name = product_name.encode('utf-8') product_price = float(product_item.xpath(".//p[@class='ahora']/span")[0].text.strip().\ partition(' ')[0].replace(',', '.')) product_unitary_price = product_item.xpath(".//div[contains(concat(' ', normalize-space(@class), ' '), " "' precio_kg ')]") if len(product_unitary_price) > 0: product_unitary_price = product_unitary_price[0].text.strip(' ()').partition(' / ') product_unit = product_unitary_price[2] product_unitary_price = float(product_unitary_price[0].partition(' ')[0].replace(',', '.')) # The following are fixings to normalize shop "bugs" if product_id == '0201030800187': product_unitary_price *= 2 product_unitary_price, product_unit = self.normalize_unitary_price(product_unitary_price, product_unit) else: product_unitary_price, product_unit = self.get_unitary_price(product_price, product_name) Shop.add_product(self, Product(product_id, product_name, product_price, product_unitary_price, product_unit))
def __init__(self): self.menu = Menu() self.window_w = 1100 self.window_h = 700 self.wave = 0 self.player_gold = 100 self.bg = pygame.image.load("img/bg.png") self.bg = pygame.transform.scale(self.bg, (self.window_w, self.window_h)) self.run = True self.shop = Shop() self.shop_upgrades = [self.shop.dmg_rect, self.shop.def_rect, self.shop.spd_rect] self.interface = Interface() self.crossbow = Crossbow() self.enemies = [] self.window = pygame.display.set_mode((self.window_w, self.window_h)) self.hp = 1500 self.defense = 0 self.game_status = "menu" # running / shop / menu self.wave_button = pygame.image.load("img/button.png") self.wave_button = pygame.transform.scale(self.wave_button, (200, 60)) self.wave_button_pos = 30, 530 self.wave_button_rect = self.wave_button.get_rect(topleft=self.wave_button_pos)
def parse_elements(self, element): soup = BeautifulSoup(element, 'lxml') name = self.get_name(soup) full_discount = self.get_full_discount(soup) discount = self.get_discount(full_discount) label = self.get_label(full_discount) image = self.get_image(soup) url = self.get_url(soup) if name is not None and discount is not None and label is not None and image is not None and url is not None: return Shop(name=name, discount=discount, label=label, image=image, url=url)
def make_shop(gauntletNum): if gauntletNum <= 5: itemLevel = 5 else: itemLevel = gauntletNum + 1 shopItems = [] shopItems.append(Potion(itemLevel, randint(2, 5))) shopItems.append(Ether(itemLevel, randint(2, 5))) shopItems.append(Spear(itemLevel, randint(1, 6))) shop = Shop(shopItems) return shop
def draw(self): while True: self.clock.tick(30) # リストボックスの描画 self.option_listbox.draw(False) self.file_listbox.draw() self.Select_Stage(self.file_id) #ステージ選択処理 self.messagebox.draw() pygame.display.update() for event in pygame.event.get(): # リストボックスに入力 file_id = self.file_listbox.process(event) option_num = self.option_listbox.process(event) if event.type == KEYDOWN: self.Key_Event(event) #押されたキーによって異なる処理 if event.key == K_RETURN and self.select_num == 1 and self.file_id != None: return self.Return_Stage(self.stage_path[self.stage_num]) if event.type == QUIT: return EXIT, None if file_id != None: # ファイルが選択されたとき self.file_id = file_id self.stage_path = glob(self.path[self.file_id] + '/*') self.stage_text = self.stage_path self.stage_said_text = [] for i, _ in enumerate(self.stage_text): self.stage_said_text.append("Stage" + str(i+1)) self.select_num += 1 # file_listboxからターゲットを外す self.file_listbox.process(event) self.stage_num = 0 if option_num != None: # オプションが選択されたとき if option_num == 0: return None, '0' elif option_num == 1: Shop(self.screen, self.data).do() break elif option_num == 2: if Equipment(self.screen, self.data).do() == EXIT: return EXIT, None break self.screen.fill((0,0,0))
def main(): # clear terminal or console # os.system('cls') # User login user = log_in() # Interface initialization initialization() # Initialize shop rental_shop = Shop(INVENTORY_DATA_PATH) # Start to operate related instructions user.run(rental_shop)
def setUp(self) -> None: """ Before testing the method of the class, create the instance of the class. """ if not os.path.exists(CUSTOMERS_DIRECTORY): os.makedirs(CUSTOMERS_DIRECTORY) self.data_path = CUSTOMERS_DIRECTORY + "/test.json" if os.path.exists(self.data_path): with open(self.data_path, 'r') as load_f: rented_cars = json.load(load_f) self.user = Customer(self.data_path, rented_cars) else: self.user = Customer(self.data_path) rental_shop = Shop(INVENTORY_DATA_PATH) self.user.rental_shop = rental_shop
class CommentTest(unittest.TestCase): def setUp(self): self.wc = Shop() def test_search(self): #ret = self.wc.search('大衣 男', '1', '0', '0', '1', '1', '', '', '') #print ret print 1 def test_detail(self): #ret = self.wc.detail('10218381', '') #print ret print 2 def test_itemcats(self): ret = self.wc.itemcats('20') print ret
def initial_game(screen): pygame.mixer.music.stop() pygame.mixer.music.load(const.MUSIC_DIR + "home.ogg") pygame.mixer.music.set_volume(const.BGM_VOL) player = Hero('resources/images/Actor/Actor1.png', 0, 0) # load_tasks(player) player.controller = "main" dialog = Dialog(player, screen) scroll_map = ScrollMap(const.TMX_DIR + "home.tmx", screen, const.MUSIC_DIR + "home.ogg") pygame.mixer.music.play(loops=-1) icon = Icon(scroll_map, player, dialog, screen) shop = Shop(player, icon, screen) scroll_map.add(player) for start_point in scroll_map.start_points: if start_point.properties['__name__'] == 'start_point': player.rect.center = (start_point.rect.left, start_point.rect.top) break scroll_map.center(player.rect.center) return player, scroll_map, dialog, icon, shop
def load_game(screen): pygame.mixer.music.stop() screen.fill((0, 0, 0)) pygame.display.flip() own_list = pet_list("resources\\save\\own_list.json") battle_list = [] with open("resources\\save\\battle_list.json", "r") as ob: load_battle_list = json.load(ob) for i in range(len(load_battle_list)): battle_list.append(own_list[load_battle_list[i]]) with open("resources\\save\\hero.json", "r") as ob: load_hero = json.load(ob) player = Hero(load_hero[0], load_hero[1], load_hero[2]) player.load(load_hero) player.own_list = own_list player.battle_list = battle_list load_tasks(player) with open("resources\\save\\scroll_map.json", "r") as ob: load_scroll_map = json.load(ob) scroll_map = ScrollMap(load_scroll_map[0], screen, load_scroll_map[1]) scroll_map.add(player) scroll_map.center(player.rect.center) dialog = Dialog(player, screen) icon = Icon(scroll_map, player, dialog, screen) shop = Shop(player, icon, screen) pygame.mixer.music.load(scroll_map.music) pygame.mixer.music.set_volume(const.BGM_VOL) pygame.mixer.music.play(loops=-1) const.LOAD = 0 return player, scroll_map, dialog, icon, shop
def printMenu(): shopName = input("What is the name of the shop?") shopLocation = input("What is the location of the shop") s1 = Shop(shopName, shopLocation) while True: print("-" * 40) print("1. Add Product ") print("2. Sell Product ") print("3. Show Products ") print("4. Exit ") userInput = int(input("Choose a menu option.")) if userInput == 1: s1.inventory.addProduct() elif userInput == 2: s1.inventory.sellProduct() elif userInput == 3: s1.inventory.showInventory() elif userInput == 4: quit() else: pass
def __init__(self): """The main running function""" #initialize window stuff self.windowx = 680 self.windowy = 800 pygame.init() self.clock = pygame.time.Clock() self.initialize_screen() self.frametime = 0.0 self.no_exit = True self.distance = 0 self.lives = 3 self.immortal = 2000 self.last_death = -2000 self.player_killed = False self.in_level = False self.money = 0 self.font32 = pygame.font.Font("img/SVBasicManual.ttf", 20) self.addons = [pygame.image.load("img/chip.png"), pygame.image.load("img/lightning.png"), pygame.image.load("img/eraser.png"), pygame.image.load("img/cube.png")] self.player = player(self) self.key_bindings = key_bindings() self.enemies = [] self.myshop = Shop(self.windowx, self.windowy) self.shopactive = True #images 'n' such self.background = pygame.image.load("img/floor2.png")#.convert() self.deaddraw = True self.deaddrawnum = 0 #makes player flicker when respawning self.levelactive = False self.oldflag = self.levelactive self.frame = 0 self.run(False)
def setUp(self): self.wc = Shop()
from product import Product from shop import Shop from stock import Stock from controller import Controller from model import * from view import * from controller import Stock_Controller # create products bread = Product("bread", 0.80, 10) milk = Product("milk", 0.50, 50) wine = Product("wine", 5.60, 5) # create shop and add products to shop shop = Controller(Model_shop(Shop()), View()) #shop.addItem("bread", 0.80, 10) #shop.addItem("milk", 0.50, 50) #shop.addItem("wine", 5.60, 5) # show items #shop.showItems() # show item #shop.showItem("wine") #shop.updateItem("milk", 1, 10) #shop.deleteItem("milk") #shop.deleteAllItems()
def markAllAsOld(): conn = getConnection(); c = conn.cursor(); c.execute("update " + ShopTable.TABLE_NAME + " set " + ShopTable.COL_NEW + " = 0"); conn.commit(); c.close(); def getNewItemCount(): conn = getConnection(); c = conn.cursor(); c.execute("select * from " + ShopTable.TABLE_NAME + " where " + ShopTable.COL_NEW + " == 1") conn.commit(); count = len(c.fetchall()); c.close(); return count; if __name__ == '__main__': #createDb(); s = Shop(); s.city = "adfa"; s.name = "lkj"; s.province = "iiii"; s.address = "j88j8j"; success = insertShop(s); if success: print("inserted"); else: print("duplicated"); util.printTable();
def runMarketMenu(): print ("You can buy many things at the market!") Shop.buyPrompt(currentPlayer)
def __init__(self, CHANNEL_ACCESS_TOKEN, CHANNEL_SECRET, mongodb): self.CHANNEL_ACCESS_TOKEN = CHANNEL_ACCESS_TOKEN self.CHANNEL_SECRET = CHANNEL_SECRET self.mongodb = mongodb self.shop = Shop()
class SpaceshipCommand(cmd.Cmd): intro = 'Welcome to Spaceship Build' prompt = '> ' def __init__(self): self.bus = Bus('root') self.inventory = Inventory() self.shop = Shop() super().__init__() def do_exit(self, _): '''Exits the game''' print(random.choice([ 'So long!', 'Toodles!', 'Sayonara!', 'Bye', 'Farewell', 'Take care', 'Goodbye', 'Till next time', 'Later', 'Best of luck!', 'Peace Out!', 'Adios', 'Ciao!', 'Au revoir', "Don't leave!"])) return True def do_EOF(self, arg): '''Handles Ctrl+D''' return self.do_exit(arg) #----Spaceship Commands def do_broadcast(self, arg): '''Broadcast message from terminal to attached Buses: > broadcast guns.all fire! > broadcast system.report 'Everything nominal' ''' topic, message, *_ = shlex.split(arg) self.bus.broadcast(topic, message) def do_buy(self, type_name): '''This purchases an item from the shop and puts it into the player's inventory > buy raygun Raygun-001 purchased and added to inventory. ''' item = self.shop.buy(type_name) if item is None: print("Can't buy {!r} there's nothing like that." .format(type_name)) else: self.inventory.store(item) print(item, "purchased and added to inventory.") def do_subscribe(self, topic_key=''): '''Subscribe to message using the topic key, they will be visible in the console. If no argument given, all topics are subscribed to. > subscribe damage.report > subscribe guns > subscribe ''' self.bus.subscribe(topic_key, spaceship.basic_subscriber) def do_inv(self, verbose): ''' Prints full inventory''' if verbose == '-v': print(self.inventory.contents()) else: print(self.inventory.summary_contents())
def main(): """ The main function """ # Create two manufacturers and add models of bike pinarello = Manufacturer("Pinarello", 0.3) pinarello.add_model("TimeAttack", CarbonFrame, TimeTrialWheel) pinarello.add_model("RoadWarrior", AluminiumFrame, RoadWheel) pinarello.add_model("SanRemo", CarbonFrame, RoadWheel) trek = Manufacturer("Trek", 0.3) trek.add_model("MountainHawg", SteelFrame, MountainBikeWheel) trek.add_model("Rodeo", SteelFrame, RoadWheel) trek.add_model("Everest", CarbonFrame, MountainBikeWheel) # Create a shop which stocks products from both manufacturers bobs_cycles = Shop("Bob's Cycles", 0.2) bobs_cycles.add_manufacturer(pinarello) bobs_cycles.add_manufacturer(trek) # Buy 5 of each bike as stock for i in xrange(5): bobs_cycles.buy("Pinarello", "TimeAttack") bobs_cycles.buy("Pinarello", "RoadWarrior") bobs_cycles.buy("Pinarello", "SanRemo") bobs_cycles.buy("Trek", "MountainHawg") bobs_cycles.buy("Trek", "Rodeo") bobs_cycles.buy("Trek", "Everest") # Create three customers with different budgets alice = Customer("Alice", 200) dan = Customer("Dan", 500) carol = Customer("Carol", 1000) customers = (alice, dan, carol) # Print the weight of the bikes sold by Bob's Cycles print "Bicycle weights:" print "" for bike_specification in bobs_cycles.product_range(): print "{:40} {}kg".format(bike_specification.full_name(), bike_specification.weight) print "" # Print the bikes which each customer can afford print "Customers:" print "" for customer in customers: print "{} can afford the following bikes:".format(customer.name) print "" for bike_specification in bobs_cycles.product_range(): price = bobs_cycles.price(bike_specification.manufacturer_name, bike_specification.name) if price > customer.money: continue print bike_specification.full_name() print "" # Print the current stock levels at Bob's Cycles print "Inventory of Bob's Cycles: " print "" for bike_specification in bobs_cycles.product_range(): stock = bobs_cycles.stock(bike_specification.manufacturer_name, bike_specification.name) print "{:40} {} in stock".format(bike_specification.full_name(), stock) # Buy a bike for each customer alice.buy(bobs_cycles, "Trek", "MountainHawg") dan.buy(bobs_cycles, "Trek", "MountainHawg") carol.buy(bobs_cycles, "Pinarello", "SanRemo") print "" # Print the customer's purchases, and remaining money for customer in customers: print "{} now owns a {}".format(customer.name, customer.bike.full_name()) print "{} has ${:.2f} remaining".format(customer.name, customer.money) print "" # Print the updates stock levels print "Updated inventory of Bob's Cycles: " print "" for bike_specification in bobs_cycles.product_range(): stock = bobs_cycles.stock(bike_specification.manufacturer_name, bike_specification.name) print "{:40} {} in stock".format(bike_specification.full_name(), stock) print "" # Print the amount of profit Bob has made print "Profit for Bob's Cycles: ${}".format(bobs_cycles.profit)
gf.create_fleet_enemy(background, enemy_group, stats.level) gf.create_fleet(width_background, height_background, wall_group_up, wall_group_down, ground_group, ladder_group, door_group, end_group, traider_group, Wall(False).rect.h) for sprite in wall_group_up: nn = sprite.rect.y break player = Player(screen, screen_rect.centerx, nn) player_group.add(player) play_button = Button(screen, "Play", screen_rect.centerx - 100, screen_rect.centery, (100, 150, 50)) game_over_button = Button(screen, "New", screen_rect.centerx - 100, screen_rect.centery, (100, 150, 50)) quit_button = Button(screen, "quit", screen_rect.centerx - 100, screen_rect.centery + 70, (100, 150, 50)) return_intro_button = Button(screen, "return intro", screen_rect.centerx - 100, screen_rect.centery + 130, (100, 150, 50)) camera = Camera() intro = Intro(screen, stats) shop = Shop(screen, stats) help_image = gf.load_image('help.png') while stats.game_active: # действия с квавиатуры и мыши gf.key_evens(screen, player, bullets, ladder_group, door_group, play_button, game_over_button, camera, stats, intro, background, end_group, enemy_group, wall_group_down, wall_group_up, ground_group, quit_button, return_intro_button, traider_group, shop) if stats.game_intro: # интро игры intro.blit() else: if stats.game_return: # переход через интро gf.new_fleet(screen, background, end_group, enemy_group, wall_group_down, wall_group_up, ladder_group, ground_group, door_group, stats, player, camera, traider_group) stats.game_return = False
def __init__(self): global cs print("Hotel init") spa = Spa() cs = CoffeeShop() shop = Shop()
from player import Player from shop import Shop from help import Help """colour text""" def red(text): print("\033[91m {}\033[00m" .format(text)), def purple(text): print("\033[95m {}\033[00m" .format(text)), def yellow(text): print("\033[93m {}\033[00m" .format(text)), print(chr(27) + "[2J") player_name = input('What is your name?\n') player = Player(player_name) game = Game(player) fight = Fight(player, game) help = Help() shop = Shop(player, game) print(chr(27) + "[2J") red("\nWelcome, %s" % player_name) while True: game.info() choice = input() print() print(chr(27) + "[2J") print() if choice == '1': if (player.walk() == 1): fight.encounter() elif choice == '2': player.rest() elif choice == '3':
class Game: WIDTH = 720 HEIGHT = WIDTH/12*9 SIZE = (WIDTH, HEIGHT) MAP_WIDTH = 1980 MAP_HEIGHT = 1080 MAP_SIZE = (MAP_WIDTH, MAP_HEIGHT) FPS = 60 LOG_FILE = "gamelog.log" SAVE_FILE = "save.json" HAS_MAP = False HAS_HEALTH = True MAX_SCALES = 100 def __init__(self): self.create_logger() try: self.debug("Initializing pygame") pygame.init() except Exception as e: self.debug("Init Error: "+str(e)) self.music = None self.bg_vol = 0.4 self.name = None self.entities = None self.map_layer = None self.collisions = [] self.transport_rects = {} try: self.shop = Shop(self) self.manager = LevelManager(self) self.rsc = resources.ResourceManager(self) self.scenes = CutScenes(self) except Exception as e: self.debug("Manager Error: "+str(e)) def init(self, classname="Crystal"): # Create window os.environ['SDL_VIDEO_CENTERED'] = '1' # center screen self.screen = pygame.display.set_mode(self.SIZE) pygame.display.set_caption("Dragon TakeOver") # Load levels try: self.debug("Loading levels...") self.manager.load_all_levels() except Exception as e: self.debug("Level.All Error: " + str(e)) # Add icon ico_path = os.path.join("resources","images","icon.png") ico_surf = self.rsc.load_image(ico_path,(32,32),colors.WHITE) pygame.display.set_icon(ico_surf) # create camera, fps, and game var self.clock = pygame.time.Clock() self.running = True self.game_dead = False self.camera = Camera(self.SIZE, self.MAP_SIZE) self.name = str(classname).lower() # load game try: self.debug("loading resources") font = pygame.font.Font(None, 48) self.load_text = font.render("Loading...",1,colors.WHITE) self.load_rect = self.load_text.get_rect() self.load_rect.centerx = self.screen.get_rect().centerx self.load_rect.centery = self.screen.get_rect().centery self.IS_LOADING = True load_thread = self.create_thread(self.loading_screen) self.rsc.load_resources() self.IS_LOADING = False self.debug("waiting for loading thread to stop...") load_thread.join() self.debug("loading thread killed") except Exception as e: self.debug("Resource error: " + str(e)) try: self.debug("loading shop resources") self.shop.init() except Exception as e: self.debug("Shop.init Error: " + str(e)) self.create_sprites() self.load_save() ### Load Game Save file def load_save(self): save_data = None try: self.debug("loading save data") if os.path.exists(self.SAVE_FILE): with open(self.SAVE_FILE, 'r') as f: save_data = json.loads(f.read()) self.name = save_data['player'] self.scenes.reset_scenes() self.create_player() if os.path.exists(self.SAVE_FILE): self.manager.load_level(save_data['level']) self.load_player_info(save_data) except Exception as e: self.debug("Save data Error: " + str(e)) ### Create/Overwrite Game save file def write_save(self): self.debug("writing save") save = {} save['level'] = self.manager.level save['player'] = self.name save['max_hp'] = self.player.MAX_HP save['max_ap'] = self.player.MAX_AP save['attack'] = self.player.attack save['scales'] = self.player.scales save['boss_scales']= self.player.boss_scales save['party_hp'] = self.player.party_health save['party_atk'] = self.player.party_attack with open(self.SAVE_FILE, 'w') as f: f.write(json.dumps(save, indent=4, sort_keys=True)) ### Create Debug/Game log def create_logger(self): # delete existing log file if os.path.exists(self.LOG_FILE): os.remove(self.LOG_FILE) # create logger logging.basicConfig(filename=self.LOG_FILE, level=logging.DEBUG) ### Create game sprites def create_sprites(self): self.debug("creating sprites") self.background = Block(self.MAP_SIZE) self.background.block_id = "bg" self.entities = pygame.sprite.Group() self.entities.add( self.background ) def create_player(self): self.tests = [] try: self.debug("Creating party..") # spawn player self.player = Player(self, self.name) self.player.block_id = "player" self.entities.add( self.player ) # choose ally bots bot_options = ["crystal","nathan","jack"] bot_options.remove(self.name.lower()) # spawn bots self.bots = [] for bot_name in bot_options: self.debug("Creating bot: "+bot_name) if bot_name == "crystal": bot = CrystalBot(self, bot_name) elif bot_name == "jack": bot = JackBot(self, bot_name) else: bot = NathanBot(self, bot_name) bot.rect.x = self.player.rect.x + 50 bot.rect.y = self.player.rect.y - 50 self.bots.append( bot ) self.entities.add( bot ) except Exception as e: self.debug("Party Creation Error: " + str(e)) ### Load player info from save file def load_player_info(self, info): self.player.MAX_HP = info['max_hp'] self.player.MAX_AP = info['max_ap'] self.player.attack = info['attack'] self.player.scales = info['scales'] self.player.boss_scales = info['boss_scales'] self.player.party_attack = info['party_atk'] self.player.party_health = info['party_hp'] """ EVENT LOOP FUNCTIONS """ def draw(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.player.update_stop(event) self.clock.tick(self.FPS) self.screen.fill(colors.BLACK) self.draw_sprites() self.draw_player_info() self.entities.update() pygame.display.flip() def draw_sprites(self, isScene=False): self.camera.update(self.player) for e in self.entities.sprites(): if e.block_id not in ["player","bot"]: self.screen.blit(e.image, self.camera.apply(e.rect)) # prioritize drawing of player and bots for bot in self.bots: self.screen.blit(bot.image, self.camera.apply(bot.rect)) self.screen.blit(self.player.image, self.camera.apply(self.player.rect)) # do collision for sprite in self.entities.sprites(): if sprite.block_id in ["player","bot"]: if sprite.rect.collidelist(self.collisions) > -1: sprite.move_back() # check transport if not isScene: for name in self.transport_rects: rect = self.transport_rects[name] if self.player.rect.colliderect(rect): print str(name) if name == "void": if self.player.boss_scales < 3: self.player.rect.y -= 30 self.player.h_decel, self.player.v_decel = True, True self.scenes.load_scene(3) spawn = self.manager.levels["village"]["spawn"] self.player.set_pos(spawn[0], spawn[1]) break else: self.manager.load_level(name) break else: pass for x in self.tests: self.screen.blit(x[1], self.camera.apply(x[0])) def draw_bars(self, sprite): _mid = (sprite.MAX_HP*60/100) _low = (sprite.MAX_HP*30/100) bar_width = sprite.bar_width # get length of health percent_left = (sprite.HP * bar_width) / (sprite.MAX_HP * 1.0) percent_lost = ((sprite.MAX_HP - sprite.HP) * bar_width) / (sprite.MAX_HP * 1.0) # get length of ap ap_left = (sprite.AP * bar_width) / (sprite.MAX_AP * 1.0) ap_lost = ((sprite.MAX_AP - sprite.AP) * bar_width) / (sprite.MAX_AP * 1.0) # calculate color if sprite.HP > _mid: color = colors.H_GREEN elif sprite.HP > _low: color = colors.H_YELLOW else: color = colors.H_RED # draw player health if sprite.block_id == "player": bar_x, bar_y = 40, 10 bar_height = 15 # draw HP left = (bar_x+3,bar_y+3, percent_left, bar_height) lost = (bar_x+percent_left+3, bar_y+3, percent_lost, bar_height) pygame.draw.rect(self.screen, color, left) pygame.draw.rect(self.screen, (10, 10, 10), lost) # draw ap left = (bar_x + 3, bar_y + 30, ap_left, bar_height) lost = (bar_x + ap_left+3, bar_y + 30, ap_lost, bar_height) pygame.draw.rect(self.screen, colors.AP_COLOR, left) pygame.draw.rect(self.screen, (10, 10, 10), lost) # draw boss health elif sprite.block_id == "boss": pass # draw mob health else: hp_rect = self.camera.apply(sprite.rect) x, y = hp_rect.x, hp_rect.y start_x = x + (sprite.WIDTH/2) start_y = y - sprite.hp_evel bar_height = 5 left = (start_x, start_y, percent_left, bar_height) lost = (start_x+percent_left, start_y, percent_lost, bar_height) pygame.draw.rect(self.screen, color, left) pygame.draw.rect(self.screen, (10,10,10), lost) def draw_player_info(self): # draw face face = self.player.face self.screen.blit(face, (5,5)) # draw scales scale_text = self.rsc.scale_nums[str(self.player.scales)] boss_text = self.rsc.scale_nums[str(self.player.boss_scales)] self.screen.blit(self.rsc.scale, (5, 65)) self.screen.blit(self.rsc.boss_scale, (105, 65)) self.screen.blit(scale_text, (35, 65)) self.screen.blit(boss_text, (135, 65)) # draw all entity health bars for e in self.entities.sprites(): if e.IS_ALIVE: self.draw_bars(e) #### Other def draw_loading(self): self.clock.tick(self.FPS) self.screen.fill(colors.BLACK) self.screen.blit(self.load_text, self.load_rect) pygame.display.flip() def run(self): while self.running: self.draw() self.exit() def exit(self): self.write_save() pygame.quit() sys.exit() def loading_screen(self): while self.IS_LOADING: self.draw_loading() def create_thread(self, func, *args): t = threading.Thread(target=func, args=args) t.daemon = True t.start() return t def debug(self, text, debug=True): _log = text starter = "> " if not isinstance(text, basestring): _log = repr(text) if debug: logging.debug(starter + _log) else: logging.info(starter + _log) print _log
class game(): def __init__(self): """The main running function""" #initialize window stuff self.windowx = 680 self.windowy = 800 pygame.init() self.clock = pygame.time.Clock() self.initialize_screen() self.frametime = 0.0 self.no_exit = True self.distance = 0 self.lives = 3 self.immortal = 2000 self.last_death = -2000 self.player_killed = False self.in_level = False self.money = 0 self.font32 = pygame.font.Font("img/SVBasicManual.ttf", 20) self.addons = [pygame.image.load("img/chip.png"), pygame.image.load("img/lightning.png"), pygame.image.load("img/eraser.png"), pygame.image.load("img/cube.png")] self.player = player(self) self.key_bindings = key_bindings() self.enemies = [] self.myshop = Shop(self.windowx, self.windowy) self.shopactive = True #images 'n' such self.background = pygame.image.load("img/floor2.png")#.convert() self.deaddraw = True self.deaddrawnum = 0 #makes player flicker when respawning self.levelactive = False self.oldflag = self.levelactive self.frame = 0 self.run(False) def initialize_screen(self): """Initialize the window""" self.screen = pygame.display.set_mode((self.windowx, self.windowy)) pygame.display.set_caption("Proxy Name") pygame.mouse.set_visible(0) def draw(self): """Draw everything on screen""" #Draw background backrect = self.background.get_rect() ydisp = (self.distance/2)%backrect.height ydisp2 = (self.distance/4)%backrect.height self.screen.blit(self.background, pygame.Rect(0, ydisp, self.windowx, self.windowy)) self.screen.blit(self.background, pygame.Rect(0, ydisp - backrect.height,self.windowx, self.windowy)) #Draw player if self.distance > self.last_death + self.immortal or self.deaddraw: self.player.draw(self.screen) for i, flag in enumerate(self.myshop.my_inventory): if flag == True: self.screen.blit(self.addons[i], self.player.rect) self.deaddrawnum += 1 if self.deaddrawnum > 10: self.deaddrawnum = 0 self.deaddraw = not(self.deaddraw) #Draw enemies for anenome in self.enemies: anenome.draw(self.screen) #Draw HUD txtsurf = self.font32.render("Money: "+ str(self.myshop.money + self.money), 1, (255,255,255)) txtrect = txtsurf.get_rect() txtrect.center = (100, 100) self.screen.blit(txtsurf, txtrect) def update(self): """Update every frame""" #update player self.distance += self.frametime self.player.update(self.frametime) projectiles = [] if self.lives > 0: projectiles = self.player.update(self.frametime) else: txtsurf = self.font32.render("GAME OVER", 1, (255,255,255)) txtrect = txtsurf.get_rect() txtrect.center = (300, self.windowy/2) self.screen.blit(txtsurf, txtrect) pygame.display.flip() pygame.time.wait(2000) self.exit_game() if self.player_killed == True: if self.distance > self.last_death + self.immortal: self.last_death = self.distance self.lives -= 1 self.player_killed = False else: self.player_killed = False #update enemies for i, anenome in enumerate(self.enemies): if not anenome.update(self.frametime): self.enemies.pop(i) #handle collision self.handle_collision(projectiles) def handle_collision(self, projectiles): """handle all collision""" #do projectiles to enemies for projectile in projectiles: for i, anenome in enumerate(self.enemies): if projectile.rect.colliderect(anenome.imgrect): anenome.health -= 1 if anenome.health == 0: self.enemies.pop(i) projectile.hit = True self.money += 5 for i, anenome in enumerate(self.enemies): if self.player.rect.colliderect(anenome.imgrect): self.enemies.pop(i) self.lives -= 1 #do player collision def handle_events(self): """Handle events (key presses, etc.)""" #print "handling events..." for event in pygame.event.get(): if event.type == pygame.QUIT: self.exit_game() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.exit_game() #movement if event.key in self.key_bindings.up: #print "up" self.player.moving[0] = True if event.key in self.key_bindings.down: #print "down" self.player.moving[1] = True if event.key in self.key_bindings.left: #print "left" self.player.moving[2] = True if event.key in self.key_bindings.right: #print "right" self.player.moving[3] = True #abilities if event.key in self.key_bindings.shoot: self.player.shoot = True if event.type == pygame.KEYUP: #cancelling movement if event.key in self.key_bindings.up: self.player.moving[0] = False if event.key in self.key_bindings.down: self.player.moving[1] = False if event.key in self.key_bindings.left: self.player.moving[2] = False if event.key in self.key_bindings.right: self.player.moving[3] = False #cancelling abilities if event.key in self.key_bindings.shoot: self.player.shoot = False def run(self, already_run): """Begin running the game""" if (not already_run): pass self.clock.tick() while self.no_exit: #print "updating..." self.frame += 1 probability = 50+(self.myshop.sharkconvo.debt/1000) if probability < 1: probability = 1 print "probability is ", probability if self.frame%probability==0: self.enemies.append(enemy()) if self.frame >= 900: self.levelactive = False self.frame = 0 if (self.levelactive): self.handle_events() self.update() self.draw() pygame.display.flip() else: self.myshop.activate(self.screen, self.money + 2500) self.money = 0 self.levelactive = True self.frametime = float(self.clock.tick(60)) def exit_game(self): """Exit the game""" pygame.quit() sys.exit()
class AdminApi: def __init__(self, config): self.app = Flask(__name__) self.api_authenticator = APIAutheticate(dict(config.items( "ADMIN_ENGINE"))) self.api_port = config.getint("ADMIN_ENGINE", 'port') self.api_host = config.get("ADMIN_ENGINE", 'host') self.shop = Shop(config) def run(self): def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): if not self.api_authenticator.authenticate(request.headers): return self.unauthorized() return f(*args, **kwargs) return decorated def shop_not_found(): return make_response(jsonify({'message': 'Not found'}), 404) @self.app.route('/v1/shop/<string:shop_id>', methods=['POST']) @requires_auth def insert_shop(shop_id): print 'Shop id ', shop_id shop_details = request.data if len(shop_details) == 0: return make_response( jsonify({'message': 'No shop info provided'}), 400) try: shop_info = json.loads(shop_details) print shop_info self.shop.insert_shop(shop_info) except Exception as e: print e return make_response( jsonify({'message': 'shop info cannot be decoded'}), 400) print 'Here' ret = {'Message': 'OK'} return jsonify(ret) @self.app.route('/v1/services/shop/<string:shop_id>', methods=['POST']) @requires_auth def insert_services(shop_id): print 'Shop id ', shop_id services_data = request.data if len(services_data) == 0: return make_response( jsonify({'message': 'No Service details provided'}), 400) try: services_list = json.loads(services_data) print services_list self.shop.insert_services(shop_id, services_list) except Exception as e: print e return make_response( jsonify({'message': 'Service info cannot be decoded'}), 400) ret = {'Message': 'OK'} return jsonify(ret) self.app.run(host=self.api_host, port=self.api_port) @staticmethod def unauthorized(): return make_response(jsonify({'error': 'Unauthorized access'}), 401)
def main(): s = Shop() chosenStore = s.getStore() chosenStore.main()
from challengeInfo import ChallengeInfo from challengeCreate import ChallengeCreate from shop import Shop from accept import Accept from profile import Profile # Routes app.add_url_rule('/logout', view_func=Logout.as_view('logout'), methods=['GET']) app.add_url_rule('/', view_func=Login.as_view('login'), methods=['GET', 'POST']) app.add_url_rule('/profile', view_func=Profile.as_view('profile'), methods=['GET', 'POST']) app.add_url_rule('/feed', view_func=Feed.as_view('feed'), methods=['GET', 'POST']) app.add_url_rule('/challengeInfo/<int:challengeId>', view_func=ChallengeInfo.as_view('challengeInfo'), methods=['GET', 'POST']) app.add_url_rule('/challengeCreate', view_func=ChallengeCreate.as_view('challengeCreate'), methods=['GET', 'POST']) app.add_url_rule('/shop', view_func=Shop.as_view('shop'), methods=['GET', 'POST']) app.add_url_rule('/accepted/<int:id>', view_func=Accept.as_view('accept'), methods=['GET', 'POST'])
def runVendorMenu(): print("You can open a stall to sell goods here.") Shop.sellPrompt(currentPlayer)
import tkinter as tk from shop import Shop, Customer # Root window root = tk.Tk() # Option List optionList = ['Hourly', 'Daily', 'Weekly'] # Shop and Customer variables customer = Customer() shop = Shop(stock=10) global when_rented # Switch-like method for getting OptionMenu index def get_list_index(argument): switcher = { 'Hourly': 1, "Daily": 2, "Weekly": 3, } return switcher.get(argument) # return_bike functionality def rent_bike(): global when_rented if bike_entry.get() == "": set_status("Cannot be empty!", "red") # In empty, show status
class Handler: shop = Shop() def __init__(self, CHANNEL_ACCESS_TOKEN, CHANNEL_SECRET, mongodb): self.CHANNEL_ACCESS_TOKEN = CHANNEL_ACCESS_TOKEN self.CHANNEL_SECRET = CHANNEL_SECRET self.mongodb = mongodb self.shop = Shop() def callback(self, signature, body): parser = WebhookParser(self.CHANNEL_SECRET) try: events = parser.parse(body, signature) self.__handle_message(events[0]) except InvalidSignatureError as e: print(e) def __handle_message(self, event): line_bot_api = LineBotApi(self.CHANNEL_ACCESS_TOKEN) if event.type == 'message': if event.message.type == 'location': self.__handle_location_message(event, line_bot_api) elif event.message.text == 'search': self.__handle_quick_reply_action(event, line_bot_api) elif event.message.text == 'topics': print(event) elif event.message.text == 'favorites': self.__handle_favorites_message(event, line_bot_api) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="對不起,我不了解您的問題")) else: # postback actions action = event.postback.data.split('_')[0] if action == 'favorite': self.__handle_favorites_postback_action(event, line_bot_api) elif action == 'deleteshop': self.__handle_delete_shop_postback_action(event, line_bot_api) elif action == 'topics': self.__handle_topics_postback_action(event, line_bot_api) else: result = self.shop.delete_favorite_shop(event, self.mongodb) if result: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="已移除!")) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="找不到結果")) def __handle_location_message(self, event, line_bot_api): nearby_shops = self.shop.get_nearby_shops_by_location( event, self.mongodb) if nearby_shops: with open('./templates/flexmessage.json') as file: flex_message_template = json.load(file) flex_messages = { "type": "carousel", "contents": [ deepcopy( self.__insert_flex_message(nearby_shop, flex_message_template)) for nearby_shop in nearby_shops ] } line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text='店家資訊', contents=flex_messages)) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="尚未探索這區~")) def __handle_favorites_message(self, event, line_bot_api): favorite_shops = self.shop.get_favorites(event, self.mongodb) if favorite_shops: with open('./templates/favorites.json') as file: favorites_template = json.load(file) line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text='最愛清單', contents=self.__insert_favorites_flex_message( favorite_shops, favorites_template))) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="尚未加入我的最愛")) def __handle_favorites_postback_action(self, event, line_bot_api): favorite_shops = self.shop.get_favorites(event, self.mongodb) if len(favorite_shops) > 9: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="最愛店家已達十筆,請先刪除店家再進行新增!")) return None result = self.shop.add_into_my_favorites(event, self.mongodb) if result: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="加入成功")) else: line_bot_api.reply_message(event.reply_token, TextSendMessage(text="已加入")) def __handle_delete_shop_postback_action(self, event, line_bot_api): favorite_shops = self.shop.get_favorites(event, self.mongodb) with open('./templates/favoritesComfirmMessage.json') as file: favorites_confirm_message_template = json.load(file) favorites_confirm_messages = { "type": "carousel", "contents": [ deepcopy( self.__insert_favorites_confirm_flex_message( favorite_shop, favorites_confirm_message_template)) for favorite_shop in favorite_shops ] } line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text='確認刪除清單', contents=favorites_confirm_messages)) def __handle_quick_reply_action(self, event, line_bot_api): quick_reply_messages = [ QuickReplyButton( action=LocationAction(label='地點查詢', type='location')), QuickReplyButton( action=PostbackAction(label='小幫手愛店', display_text='小幫手愛店', data='topics_kensfavorites')), QuickReplyButton(action=PostbackAction( label='深夜咖啡館', display_text='深夜咖啡館', data='topics_nightcafe')), QuickReplyButton(action=PostbackAction(label='早鳥咖啡館', display_text='早鳥咖啡館', data='topics_morningcafe')), QuickReplyButton(action=PostbackAction(label='寬敞聚會咖啡廳', display_text='寬敞聚會咖啡廳', data='topics_spacious')) ] line_bot_api.reply_message( event.reply_token, TextSendMessage( text='選擇地點查詢開啟google map, 或是選擇其他主題分類', quick_reply=QuickReply(items=quick_reply_messages))) def __handle_topics_postback_action(self, event, line_bot_api): shops = self.shop.get_shops_by_topics(event, self.mongodb) with open('./templates/flexmessage.json') as file: flex_message_template = json.load(file) flex_messages = { "type": "carousel", "contents": [ deepcopy( self.__insert_flex_message(shop, flex_message_template)) for shop in shops ] } line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text='店家資訊', contents=flex_messages)) def __insert_flex_message(self, nearby_shop, flex_message_template): flex_message_template['body']['contents'][0]['text'] = nearby_shop[ 'shop_name'] flex_message_template['body']['contents'][1]['contents'][0][ 'contents'][1]['text'] = nearby_shop['address'] flex_message_template['body']['contents'][1]['contents'][1][ 'contents'][1]['text'] = nearby_shop['open_hour'] flex_message_template['body']['contents'][1]['contents'][2][ 'contents'][1]['text'] = nearby_shop['close_date'] flex_message_template['body']['contents'][1]['contents'][3][ 'contents'][1]['text'] = nearby_shop['style'] flex_message_template['body']['contents'][1]['contents'][4][ 'contents'][1]['text'] = nearby_shop['plug_number'] flex_message_template['body']['contents'][1]['contents'][5][ 'contents'][1]['text'] = nearby_shop['space'] flex_message_template['body']['contents'][1]['contents'][6][ 'contents'][1]['text'] = nearby_shop['comment'] flex_message_template['footer']['contents'][0]['action'][ 'uri'] = nearby_shop['map_url'] flex_message_template['footer']['contents'][1]['action'][ 'uri'] = nearby_shop['facebook'] flex_message_template['footer']['contents'][2]['action']['data'] = 'favorite' + \ '_' + nearby_shop['shop_name'] + '_' + str(nearby_shop['_id']) return flex_message_template def __insert_favorites_flex_message(self, favorite_shops, favorites_template): for favorite_shop in favorite_shops: flex_message = { "type": "box", "layout": "vertical", "contents": [{ "type": "text", "text": favorite_shop['shop_name'], "weight": "regular", "size": "sm", "contents": [] }] } favorites_template['body']['contents'].append(flex_message) favorites_template['footer']['contents'][0]['action'][ 'data'] = 'deleteshop' return favorites_template def __insert_favorites_confirm_flex_message( self, favorite_shop, favorites_confirm_message_template): favorites_confirm_message_template['body']['contents'][0][ 'text'] = favorite_shop['shop_name'] favorites_confirm_message_template['footer']['contents'][0]['action'][ 'data'] = str(favorite_shop['_id']) return favorites_confirm_message_template
class Discount(Shop): def __init__(self, shop_name, store_type, discount_products): super().__init__( shop_name, store_type, ) self.discount_products = discount_products def get_discounts_products(self): print(self.discount_products) if __name__ == '__main__': # a print('a task') store = Shop('Golden Car', 'used cars trade in') print(store.shop_name) print(store.store_type) store.describe_shop() store.open_shop() # b створіть три різні екзепляри, викличіть метод describe_shop для кожного print('b task') store1 = Shop('shop1', 'trading1') store2 = Shop('shop2', 'trading2') store3 = Shop('shop3', 'trading3') for st in store1, store2, store3: st.describe_shop() # c print('c task')
from shop import Shop if __name__ == "__main__": # customer = Customer("Paul", datetime.datetime(1951, 4, 13), "*****@*****.**", "555-555-5555", "email") # sale = Sale() # sale_amount = 1000 # discount = sale.send_discount_message(customer) # print(f"{customer.name} received R{discount*sale_amount} discount on their purchase of R{sale_amount} ") shop = Shop("customers.csv") shop.issue_discounts()
def __init__(self): self.bus = Bus('root') self.inventory = Inventory() self.shop = Shop() super().__init__()