def handle_product_details(self, entries={}): """For a selected product, this function displays the name, nutriscore, url link to the openfoodfacts's website, the store(s) where it can be bought. """ menu = Menu('Description détaillée', title="Description détaillée", prompt="") product_manager = ProductManager(self.db) store_manager = StoreManager(self.db) substitute_code = entries['Substituts'].data['code'] substitute = product_manager.find_product_description(substitute_code) print("\n--- Description détaillée ---\n") for sub in substitute: stores = store_manager.find_stores_by_product_code(substitute_code) stores = [store['name'] for store in stores] stores = ", ".join(stores) print("Nom du produit : "+str(sub['product_name'])) print("Code du produit : "+str(sub['code'])) print("Marque du produit : "+sub['brand']) print("Lien Openfoodfacts : "+sub['url_link']) print("Note nutritionnelle : "+sub['nutrition_grade_fr']) print("Magasin(s) où l'acheter : "+str(stores)) menu = Menu('Description détaillée', prompt="Que souhaitez-vous faire ? ") menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal.", self.handle_start_menu, 'm') menu.add("Revenir en arrière.", self.handle_substitute_selected_menu, 'b') menu.manager.ask(entries)
def append(self, menu): '''Add a menu to this app's menu bar. @param menu: The menu to add (L{Menu}). @note: The first menu item of the bar menu is provided by default. ''' isinstanceOf(menu, Menu, name='menu') if self._menubar is None: # create the menu bar, once b = MenuBar(app=self) m = Menu(title=self.title) m.append( # note key modifier cmd=True is the default Item('Full ' + 'Screen', key='f', ctrl=True), # Ctrl-Cmd-F, Esc to exit ItemSeparator(), Item('Hide ' + self.title, self.menuHide_, key='h'), # Cmd-H Item('Hide Others', self.menuOther_, key='h', alt=True), # Alt-Cmd-H ItemSeparator(), Item('Quit ' + self.title, self.menuTerminate_, key='q'), # Cmd-Q ) b.append(m) b.main(app=self) self._menubar = b self._menubar.append(menu)
def __init__(self, db: Database) -> None: """Initialize database and get user information.""" self.db = db # Upper is used for user-facing print strings # Lower is used for variables and arguments self.user1_upper = self.db.get_user(1) self.user1 = self.user1_upper.lower() self.user2_upper = self.db.get_user(2) self.user2 = self.user2_upper.lower() self.menus = Menu(self, db)
def run_direct(cmd): from menus import Menu try: log("addon: start script.pulseequalizer.gui addon") m = Menu() m.sel_menu(cmd) log("addon: end script.pulseequalizer.gui addon") except Exception as e: handle(e)
def handle_favorite_details(self, entries={}): """Handler in charge of displaying all the favorite'details : the name, product code, brand, url link, nutrition grade and of course the retail(s) where to find the product. """ print("\n--- Détails du favori ---\n") product_manager = ProductManager(self.db) store_manager = StoreManager(self.db) favorite_code = entries['Favoris'].data['code'] favorite = product_manager.find_product_description(favorite_code) for fav in favorite: stores = store_manager.find_stores_by_product_code(favorite_code) stores = [store['name'] for store in stores] stores = ", ".join(stores) print("Nom du produit : "+str(fav['product_name'])) print("Code du produit : "+str(fav['code'])) print("Marque du produit : "+fav['brand']) print("Lien Openfoodfacts : "+fav['url_link']) print("Note nutritionnelle : "+fav['nutrition_grade_fr']) print("Magasin(s) où l'acheter : "+str(stores)) menu = Menu('Détails du favori', prompt="Que souhaitez-vous faire ? ") menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal.", self.handle_start_menu, 'm') menu.add("Revenir en arrière.", self.handle_selected_favorite_menu, 'b') menu.manager.ask(entries)
def update_menu(update_number, meal_number, name, description, ingredients, price): for item in menus: if item.meal == update_number: item_index = menus.index(item) temp = Menu(meal_number, name, description, ingredients, price) menus[item_index] = temp
def choose_background(rand: bool=False): index = 1 options = {} for back in Backgrounds: options[index] = back().name.capitalize() index += 1 if rand: choice = randint(1, len(options.keys())) else: choice = 1 menu = Menu("Backgrounds", options) while choice not in options.keys(): menu.display() choice = int(input("Choose an option: ")) return options[choice]
def handle_substitute_selected_menu(self, entries={}): """Handler method for the selected substitute menu. It gives the possibilities of seeing the specific details of a product, saving it into the favorites, going back to the main menu, going back to the previous menu or quit. """ prompt = "Pour ce produit de substitution, que souhaitez-vous faire ? " menu = Menu('Description', title="Gestion du substitut :", prompt=prompt) print("\nSubstitut sélectionné = "+entries['Substituts'].label) menu.add("Consulter la description détaillée du substitut.", self.handle_product_details, 'c') menu.add("Enregister le produit dans les favoris.", self.handle_record_substitute, 'e') menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal", self.handle_start_menu, 'm') menu.add("Revenir en arrière.", self.handle_substitutes_menu, 'b') menu.manager.ask(entries)
def choose_ancestry(rand: bool=False): options = { 1: "Dwarf", 2: "Elf", 3: "Gnome", 4: "Goblin", 5: "Halfling", 6: "Human", } if rand: choice = randint(1, 6) else: choice = 2 menu = Menu("Ancestry", options) while choice not in options.keys(): menu.display() choice = int(input("Choose an option: ")) return options[choice]
def handle_products_menu(self, entries={}): """Handler method for the products menu. 1. Creates the menu. 2. Adds numeric menu entries for the (bad nutriscore') products selected from the category. 2. Adds keyword menu entries to quit, return to the main menu or return to the previous menu. 3. Displays the menu to the user. """ menu = Menu('Produits', title="Les produits à remplacer :", prompt='Sélectionnez le produit en entrant son numéro : ') product_manager = ProductManager(self.db) for prod in product_manager.find_n_unhealthy_products_by_category( c.CATEGORIES_TO_RECOVER[entries['Catégories'].label]): menu.add(prod['product_name'], self.handle_substitutes_menu, data=prod) menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal.", self.handle_start_menu, 'm') menu.add("Revenir en arrière.", self.handle_categories_menu, 'b') menu.manager.ask(entries)
def handle_start_menu(self, entries={}): """Handler method for the main menu. 1. Creates the menu. 2. Adds menu entries. 3. Displays the menu to the user. """ menu = Menu('Démarrage', title='------ Menu ------', prompt='Veuillez choisir une option et appuyez sur Entrée : ') menu.add('Quel aliment souhaitez-vous remplacer ?', self.handle_categories_menu, '1') menu.add('Retrouver mes substituts favoris.', self.handle_favorites_menu, '2') menu.add("Quitter l'application.", self.handle_quit, 'q') menu.manager.ask(entries)
def __init__(self): ''' Enables the logger if logging_bool is set to True. ''' if self.logging_bool: logging.basicConfig(filename='work_log.log', filemode = 'w', level = logging.DEBUG ) logging.debug("In function: {} {},".format( WorkLog.__name__,"__init__")) from menus import Menu menu = Menu()
def handle_categories_menu(self, entries={}): """Handler method for the categories menu. 1. Creates the menu. 2. Adds numeric menu entries from the categories stored in the config.py module. 2. Adds keyword menu entries to quit the app and to return to the previous menu. 3. Displays the menu to the user. """ menu = Menu('Catégories', title="Les catégories de produits :", prompt='Sélectionnez la catégorie en entrant son numéro : ') for cat in c.CATEGORIES_TO_RECOVER.keys(): menu.add(cat, self.handle_products_menu) menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal.", self.handle_start_menu, 'm') menu.manager.ask(entries)
def handle_substitutes_menu(self, entries={}): """Handler method for the substitutes menu. 1. Creates the menu. 2. Adds numeric menu entries for the (good nutriscore') products selected from the category 2. Adds keyword menu entries to quit, return to the main menu or return to the previous menu. 3. Displays the menu to the user. """ prompt = ( "Nous vous proposons ces produits de substitution, " "lequel choisissez-vous ? " ) menu = Menu('Substituts', title="Les substituts :", prompt=prompt) product_manager = ProductManager(self.db) for sub in product_manager.find_n_healthy_products_by_category( entries['Catégories'].label): menu.add((sub['product_name']+" (Note nutitionnelle = " + sub['nutrition_grade_fr']+")"), self.handle_substitute_selected_menu, data=sub) menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal.", self.handle_start_menu, 'm') menu.add("Revenir en arrière.", self.handle_products_menu, 'b') menu.manager.ask(entries)
def register_menu_event_types(self): ## Button Events Menu.register_event_type('exit_game') Menu.register_event_type('go_back') Menu.register_event_type('enter_submenu') LevelSelectMenu.register_event_type('load_new_level') OptionsMenu.register_event_type('toggle_skyboxes') OptionsMenu.register_event_type('toggle_wireframe') OptionsMenu.register_event_type('toggle_textures') OptionsMenu.register_event_type('toggle_fps') ## Slider Events OptionsMenu.register_event_type('set_fov') OptionsMenu.register_event_type('set_mouse_sensitivity')
def handle_favorites_menu(self, entries={}): """Handler method for the favorites menu.The user has the possibility of exploring all the saved substitutes products. 1. Creates the menu. 2. Adds numeric menu entries for the favorites. 2. Adds keyword menu entries to quit, return to the main menu. 3. Displays the menu to the user. """ prompt = "Sélectionnez un favori en entrant son numéro : " menu = Menu('Favoris', prompt=prompt) favorite_manager = FavoriteManager(self.db) favorite_list = favorite_manager.find_favorite_list() print('\n--- Favoris enregistrés : ---\n') if not favorite_list: print("Il n'y a pas encore de favoris sauvegardés.\n") for fav in favorite_list: menu.add((fav['origin_prod_name']+" (remplace le produit : '" +fav['sub_prod_name']+"')"), self.handle_selected_favorite_menu, data=fav) menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal.", self.handle_start_menu, 'm') menu.manager.ask(entries)
def __init__(self): ShowBase.__init__(self) self.camera.setPosHpr(0, -12, 8, 0, -35, 0) self.disableMouse() self.tourBlanc = True self.Plateau = Plateau(self.render, self.loader) self.IA = bloc_IA(self.Plateau) self.son = AudioManager(self.loader) self.menu = Menu(self.loader, self.Plateau, self.son, self.IA) #mise en place des raccourcis self.accept('1', lambda: self.Plateau.jouerMouvement(0)) self.accept('2', lambda: self.Plateau.jouerMouvement(1)) self.accept('3', lambda: self.Plateau.jouerMouvement(2)) self.accept('4', lambda: self.Plateau.jouerMouvement(3)) self.accept('5', lambda: self.Plateau.jouerMouvement(4)) self.accept('6', lambda: self.Plateau.jouerMouvement(5)) self.accept('7', lambda: self.Plateau.jouerMouvement(6)) self.accept('8', lambda: self.Plateau.jouerMouvement(7)) self.accept('9', lambda: self.Plateau.jouerMouvement(8)) self.accept('r', self.Plateau.reset) self.accept('a', self.Plateau.annulerMouvement) self.accept('d', self.Plateau.dechargerGraphismes) self.accept('c', self.Plateau.chargerGraphismes) self.accept('t', self.test)
def add_menus(meal_number, name, description, ingredients, price): m = Menu(meal_number, name, description, ingredients, price) menus.append(m)
def main(stdscr): # locale.setlocale(locale.LC_ALL, '') curses.nonl() # constants related to rooms room_max_size = 15 room_min_size = 5 max_rooms = 15 # constants related to padding size # either height/width has to be larger than their counterparts of map # becuase writing on the bottom right corner of the padding causes an error height = 151 width = 150 # constants related to map size map_height = 150 map_width = 150 # get size of the screen for positioning # FIXME: as of now, we are going to assume that stdscr size doesn't change # stdscr is automatically init by wrapper() base_height, base_width = stdscr.getmaxyx() # constants related to view size # TODO: change view size in relation to screen size view_width = 100 view_height = 24 # default setups init_colors() curses.curs_set(0) # hide cursor # win has to be a pad, so that scrolling is easily supported win = curses.newpad(height, width) win.keypad(True) win.bkgd(' ') # msgwin msg_win = curses.newpad(10, 100) msgbox = MsgBox(msg_win, view_width, view_height, base_width, base_height) # bars bar_width = 33 bar_height = 1 bar_win = curses.newwin(bar_height, bar_width, 1, 1) # bar_win.border() combat_module = Combat(hp=30, defense=2, power=5) inventory = Inventory(26) player = Player(combat_module, inventory) entities = [player] game_map = maps.GameMap(map_width, map_height) maps.generate_map(game_map, max_rooms, room_min_size, room_max_size, player, entities) game_state = GameStates.PLAYERS_TURN previous_game_state = game_state # initial compute of fov game_map.compute_fov(player) inventory_menu = Menu(win, "INVENTORY", 30, base_width, base_height) while True: rendering.render_all(win, entities, game_map, view_width, view_height, player, base_width, base_height, msgbox, bar_win, inventory_menu, game_state) action = input_handler.handle_input(win, game_state) mv = action.get('move') pickup = action.get('pickup') show_inventory = action.get('show_inventory') hide_inventory = action.get('hide_inventory') item_at_cursor = action.get('item_at_cursor') inventory_index = action.get('inventory_index') move_cursor = action.get('move_cursor') move_page = action.get('move_page') exit = action.get('exit') inventory_shown = False player_turn_results = [] if mv: dx, dy = mv dest_x = player.x + dx dest_y = player.y + dy if game_map.walkable[dest_x, dest_y]: target = blocking_entity_at_position(entities, dest_x, dest_y) if target: atk_results = player.combat.attack(target) player_turn_results.extend(atk_results) else: move_results = {'move': mv} player_turn_results.append(move_results) elif pickup: for e in entities: if e.item and e.x == player.x and e.y == player.y: pickup_results = player.inventory.add_item(e) player_turn_results.extend(pickup_results) # only acquire one item at one turn break else: msgbox.add("no_item") # Toggle Inventory screen elif show_inventory: msgbox.add("open inven") previous_game_state = game_state game_state = GameStates.SHOW_INVENTORY # FIXME: cursor, page should have a value limit # and it probably should be handled by menus, not here elif exit: # quit game # break pass if GameStates.SHOW_INVENTORY: if move_cursor: inventory_menu.next_item(move_cursor) elif move_page: inventory_menu.next_page(move_page) elif hide_inventory: game_state = previous_game_state elif item_at_cursor: item = inventory_menu.item_at_cursor() if item: # TEMP FIX: check validity of choice at menu? use_results = player.inventory.use_item(item) player_turn_results.extend(use_results) elif inventory_index is not None: # unlike other inputs, inventory_index can be 0, # so compare it with "None" # check will cause input 0 to be ignored item = inventory_menu.item_at(inventory_index) if item: use_results = player.inventory.use_item(item) player_turn_results.extend(use_results) # evaluate results of player turn for result in player_turn_results: movement = result.get('move') dead_entity = result.get('dead') item_added = result.get('item_added') msg = result.get('msg') item_used = result.get('item_used') if movement: dx, dy = movement player.move(dx, dy) game_map.compute_fov(player) if item_added: entities.remove(item_added) if msg: msgbox.add(msg) if dead_entity == player: game_state = GameStates.PLAYER_DEAD if item_used: inventory_shown = True # toggle state only when something is done in PLAYERS_TURN game_state = GameStates.ENEMY_TURN if game_state == GameStates.ENEMY_TURN: # move those with ai modules enemies = (e for e in entities if e.ai) for e in enemies: e_turn_results = e.ai.take_turn(player, game_map, entities) # still a bit WET! for result in e_turn_results: msg = result.get('msg') dead_entity = result.get('dead') if msg: msgbox.add(msg) if dead_entity == player: game_state = GameStates.PLAYER_DEAD # check whether to return to beginning of loop if game_state == GameStates.PLAYER_DEAD: break elif game_state == GameStates.SHOW_INVENTORY: pass #if item was used at screen, keep the inventory opened elif inventory_shown: game_state = GameStates.SHOW_INVENTORY else: game_state = GameStates.PLAYERS_TURN
def draw(self,events): Menu.draw(self,events) for event in events: if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.return_to_main()
class Application: """Class for getting input from user and printing text to terminal.""" def __init__(self, db: Database) -> None: """Initialize database and get user information.""" self.db = db # Upper is used for user-facing print strings # Lower is used for variables and arguments self.user1_upper = self.db.get_user(1) self.user1 = self.user1_upper.lower() self.user2_upper = self.db.get_user(2) self.user2 = self.user2_upper.lower() self.menus = Menu(self, db) def utilities(self) -> list: """Get a list of present utilities from the database.""" utilities = [] for tupl in self.db.get_utilities(): utilities.append(tupl[0]) return utilities def user_owes(self, user: int) -> float: """Get total owed by a given user.""" if user == 1: return self.db.get_total_owed(self.user1) else: return self.db.get_total_owed(self.user2) def final_owed(self) -> str: """Amount to pay and to who.""" amount = self.user_owes(1) - self.user_owes(2) if amount == 0: return "Neither user owes the other anything at this time." if amount > 0: more_owed_user = self.user1_upper less_owed_user = self.user2_upper elif amount < 0: more_owed_user = self.user2_upper less_owed_user = self.user1_upper amount = abs(amount) return f"{more_owed_user} owes {less_owed_user} {round(amount)} yen." def start(self) -> None: """Display information on initial launch of application.""" os.system("cls") print( f"\nWelcome to {self.user1_upper}" f" and {self.user2_upper}'s utility calculator.\n" f"Today is {formatted_today()}" ) self.main_menu() def quit_program(self) -> None: """Close database connection and exit program.""" self.db.conn.close() sys.exit("Closing program...") def main_menu(self) -> None: """Display main menu.""" self.menus.update_main_options() if self.db.debug is True: print( "****************************\n" "------DEBUGGING MODE!------" ) print( "****************************\n" f"{self.user1_upper} currently owes " f"{self.user_owes(1)} yen " f"and {self.user2_upper} currently owes " f"{self.user_owes(2)} yen.\n" f"{self.final_owed()}\n" "You can examine a particular utility " f"or either {self.user1_upper}" f"or {self.user2_upper}'s payment history.\n" ) self.menus.print_main_menu() acceptable_inputs = set(self.menus.main_options.keys()) intent = input_handler( self, prompt=( "\nYou can return to this page " "by entering 'main' at any point." "\nYou can also quit this program at any point " "by entering 'quit'." ), acceptable_inputs=acceptable_inputs, ) option = self.menus.main_options.get(intent, {}) option_func = option.get("func") if TYPE_CHECKING: assert callable(option_func) try: # Handle menu requests which require an argument option_func(option.get("arg")) except TypeError: # Handle menu requests which do not require an argument option_func() def user_page(self, user: str) -> None: """Display total owed and unpaid bills and return to main menu.""" print( f"{user[0].upper() + user[1:]} owes", self.db.get_total_owed(user) ) print("Here are their unpaid bills:") for entry in self.db.get_bills_owed(user): print(entry) self.main_menu() def utility_menu(self, utility: str, display=True) -> None: """Display utility menu options.""" if display: self.check_record(utility) print(f"What would you like to do with {utility}?\n") for key in self.menus.utility_options.keys(): option = self.menus.utility_options.get(key, {}) print(f"{option.get('name')} - {option.get('description')}") acceptable_inputs = set(self.menus.utility_options.keys()) intent = input_handler( self, destination=Destinations.UTILITY_MENU, acceptable_inputs=acceptable_inputs, utility=utility, display=False, ) option_func = self.menus.utility_options.get(intent, {}).get("func") if TYPE_CHECKING: assert callable(option_func) option_func(utility) def add_utility(self) -> None: """Add a new utility to the database.""" intent = input_handler( self, prompt="What is the name of your new utility?" ) self.add_bill(intent) def remove_utility(self) -> None: """Remove a utility and all associated bills.""" print("What utility would you like to remove?") for utility in self.utilities(): print(f"{utility[0].upper() + utility[1:]}") intent = input_handler( self, prompt=( "WARNING: removing a utility " "will also remove all bills associated with that utility!" ), ) removal_intent = input_handler( self, prompt=f"Are you sure you want to remove {intent}?", boolean=True, ) if removal_intent: self.db.remove_utility(intent) redirect(self, message=f"{intent} has been removed.") else: redirect(self, message=None) def add_bill(self, utility: str) -> None: """Add a bill to the database.""" amount_intent = input_handler( self, prompt="\nHow much is the bill for?\nEnter the amount in yen:", destination=Destinations.BILL_ADDITION, integer=True, utility=utility, ) print( "What month(s) is this bill for?\n" "Enter the bill date like the following:" " '04-21' for April 9th.\n" "In the event that there is more than one month listed," " please list with a ',' between the dates." ) date_intent = input_handler(self) moreinfo_intent = input_handler( self, prompt="If you want to add more information, type 'yes'. " " Otherwise, press any key to continue.", ) if moreinfo_intent == "yes": user1_intent = input_handler( self, prompt=f"Has {self.user1_upper} paid?", destination=Destinations.BILL_ADDITION, utility=utility, boolean=True, ) user2_intent = input_handler( self, prompt=f"Has {self.user2_upper} paid?", destination=Destinations.BILL_ADDITION, utility=utility, boolean=True, ) print( "Do you have any notes you'd like to make about this bill? " "(Press enter to skip)" ) note_intent = input() print("*****") print("Creating bill...") if user1_intent == "yes": user1_intent = True else: user1_intent = False if user2_intent == "yes": user2_intent = True else: user2_intent = False if user1_intent is True and user2_intent is True: paid_intent = True else: paid_intent = False bill = Bill( utility, date_intent, amount_intent, user1_paid=user1_intent, user2_paid=user2_intent, paid=paid_intent, note=note_intent, ) else: print("Creating bill...") bill = Bill(utility, date_intent, amount_intent) self.db.add_bill(bill) print( "Bill has been successfully created " f"and added to the {bill.utility} bill record!\n" "Returning to main menu..." ) self.main_menu() def remove_bill(self, utility: str) -> None: """Remove a bill from the database.""" records = self.db.get_utility_record(utility) if not records: redirect( self, message=f"There are no bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) for record in records: print(record) intent = input_handler( self, prompt=("Which bill would you like to remove?\n" "Input bill ID:"), destination=Destinations.BILL_REMOVAL, integer=True, utility=utility, ) for entry in records: if entry.id == intent: print(entry) intent = input_handler( self, prompt=f"Will you remove this bill?", destination=Destinations.BILL_REMOVAL, boolean=True, utility=utility, ) if intent == "yes": self.db.remove_bill(entry) redirect(self, message=None) else: redirect(self, message="Returning to main menu.") redirect( self, message="The input bill ID could not be found.", destination=Destinations.BILL_REMOVAL, utility=utility, ) def check_record(self, utility: str) -> None: """Print all bills under a given utility.""" for record in self.db.get_utility_record(utility): print(record) def check_unpaid_bills(self, utility: str) -> None: """Print all unpaid bills under a given utility.""" records = self.db.get_utility_record(utility) if not records: redirect( self, message=f"There are no bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) checker = False for entry in records: if not entry.paid: checker = True print(entry) if not checker: redirect( self, message=f"You have no unpaid bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) self.utility_menu(utility, display=False) def pay_bill(self, utility: str) -> None: """Pay a bill.""" def payment(bill: Bill, user: str) -> None: """Write information to bill object and send it to the database.""" if user == self.user1: bill.user1_paid = True bill.note += ( f"\n{self.user1_upper} paid {bill.owed_amount} " f"for bill (ID {bill.id}) " f"on {formatted_today()}, " "paying off their portion of the bill." ) else: bill.user2_paid = True bill.note += ( f"\n{self.user2_upper} paid {bill.owed_amount} " f"for bill (ID {bill.id}) " f"on {formatted_today()}, " "paying off their portion of the bill." ) if bill.user1_paid is True and bill.user2_paid is True: bill.paid = True self.db.pay_bill(bill) print(f"Bill ID {bill.id} has been completely paid off!") else: self.db.pay_bill(bill) print("You successfully paid your bill!") records = self.db.get_utility_record(utility) if not records: redirect( self, message=f"There are no bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) identity = input_handler( self, prompt=( "Who are you?\n" f"Enter '{self.user1_upper}' or '{self.user2_upper}'." ), destination=Destinations.BILL_PAYMENT, acceptable_inputs={self.user1, self.user2}, utility=utility, ) if identity == self.user1: collector = [] for entry in records: if not entry.user1_paid: collector.append(entry) if len(collector) == 0: print("You don't have any bills to pay.") redirect(self, message=None) for entry in collector: print(entry) else: collector = [] for entry in records: if not entry.user2_paid: collector.append(entry) if len(collector) == 0: print("You don't have any bills to pay.") redirect(self, message=None) for entry in collector: print(entry) intent = input_handler( self, prompt=( "Which bill would you like to pay?\n" "You can pay multiple bills at once " "by entering multiple IDs separated by a space.\n" "Enter the ID:" ), destination=Destinations.BILL_PAYMENT, utility=utility, ) intent_list = intent.split(" ") # Paying by a single ID if len(intent_list) == 1: for entry in records: if entry.id == int(intent): intent = input_handler( self, prompt=( f"{entry}\nYou owe {entry.owed_amount} yen\n" "Will you pay your bill?" ), destination=Destinations.BILL_PAYMENT, utility=utility, boolean=True, ) match intent: case "yes": payment(entry, identity) redirect(self, message=None) case "no": redirect(self, message=None) case _: redirect( self, destination=Destinations.BILL_PAYMENT, utility=utility ) redirect( self, message="The inputted bill ID could not be found.", destination=Destinations.BILL_PAYMENT, utility=utility, ) # Paying by multiple IDs elif len(intent_list) > 1: for id_intent in intent_list: for entry in records: if int(id_intent) == entry.id: payment(entry, identity) redirect(self, message=None) else: redirect(self, destination=Destinations.BILL_PAYMENT, utility=utility)
def main(): character = None choice = "" main_menu = Menu("Main Menu", options={ "N": "Create new character", "D": "Display character", "L": "Load character", "A": "Auto create", "q": "Quit" }) while choice.lower() != "q": main_menu.display() choice = input("Please choose an option: ") if choice not in main_menu.options.keys(): print("Invalid option, please choose again") continue elif choice in ["q", "Q"]: continue if choice in ["N", "n"]: """ 1. choose ancestry size, speed, hit points, languages, ability score boosts and flaws select ancestry feat """ character = Character("TEST") choice = choose_ancestry() character.assign_ancestry(choice.upper()) """ 2. choose background boosts to 2 abilities, skill training, background skill feat """ choice = choose_background() character.assign_background(choice.upper()) """ 3. choose class boost to key ability """ choice = choose_class() character.assign_class(choice.upper()) """ 4. ability scores base score of 10, boost +2, flaw -2 ancestry gives free boost, humans gain 2 background gives 2 free boosts (1 predetermined, 1 chosen) class boost 4 free boosts """ character.assign_ability_scores() """ 5. calculate hit points ancestry, class, CON mod 6. Assign proficiency levels U: level -2, T: level, E: level + 1 7. choose skills ranks from class + INT mod assign signature skills 8. assign class features and feats 9. buy gear 150 SP to start """ elif choice in ["L", "l"]: print("That option not implemented, please try again.") time.sleep(1) elif choice in ["d", "D"]: character.display() elif choice in ["a", "A"]: # Choose ancestry """ choose ancestry randomly set character ancestry to Enum by choice for every bonus in ancestry.bonuses add to list in bonuses["ancestry"] for every flaw in ancestry.flaws add to list in bonuses["flaws"] set maxHP to ancestry HP value set character.size to ancestry.size set speed to ancestry.speed set languages to ancestry.languages for every ability in ancestry.special_abilities apply ability to character choose random ancestry feat """ character = Character("auto") choice = choose_ancestry(rand=True) character.assign_ancestry(choice.upper()) # Choose background """ choose background randomly, weighted by ancestry set character background to Enum by choice for every bonus in background.bonuses add to list in bonuses["background"] add background.skill_feat to list of character feats add background.lore to dict of character skills set proficiency of skills[background.lore] to TRAINED """ choice = choose_background(rand=True) character.assign_background(choice.upper()) # Choose class """ choose class randomly, weighted by ancestry + background set character class to Enum by choice set level to 1 add class.bonus to list in bonuses["class"] """ # Finalize Ability Scores """ create named tuple of stats set all ability scores to 10 for every flaw in bonuses["flaws"] apply flaw to ability score for every bonus in bonuses["ancestry"] remove bonus from stat list add bonus to ability score if bonus is free choose appropriate ability from remaining stats apply bonus to ability for bonus in bonuses["background"] choose bonus from options remove bonus from remaining ability add bonus to ability score if bonus is free choose ability from remaining stats apply bonus to ability for i in range(1, 5): choose ability from remaining stats apply bonus to ability remove ability from remaining stats apply class bonus to ability set ability scores to temp values """ # Apply class to character """ assign key ability score classDC = 10 + key ability mod + level add class HP + CON mod to HP total for proficiency in class.proficiencies assign proficiency to character for skill in signature skills assign skill as signature for i in range (1, class skills + 1) choose skill training """ # skill modifier = ability mod + proficiency + other mods + feat + item # Buy Equipment """ set starting money to 150 sp purchase weapon purchase armor purchase adventuring gear for purchase in purchases if melee, then assign strike elif ranged, then assign strike elif armor, then assign armor else, assign item to inventory set current money to remaining coins """ # Fill in finishing details """ set Armor Class set Touch Armor Class set maxBulk and encumbered values calculate current Bulk if current Bulk >= encumbered then assign encumbered condition assign melee and ranged strikes assign Perception modifier set Resonance Points total to CHA mod + level set current RP to maxRP value assign modifier for saving throws """ ...
def main(): """ Master menu that allows users to select which function they'd like to run """ menu_instance = Menu(main_menu) user_input = input(main_menu) while user_input != 'q'.lower(): if user_input == 'L'.lower(): menu_instance.login() elif user_input == 'T'.lower(): menu_instance.transfer_student() elif user_input == 'H'.lower(): menu_instance.navigate_to_home() elif user_input == 'E'.lower(): menu_instance.log_out() elif user_input == 'R'.lower(): menu_instance.reprint_i20() elif user_input == 'S'.lower(): menu_instance.shorten_program() elif user_input == 'C'.lower(): menu_instance.cpt_employment() elif user_input == 'O'.lower(): menu_instance.opt_employment() print('\n') menu_again = input('Would you like to see the menu again? (Y/N): ') if menu_again == 'Y'.lower(): user_input = input(main_menu) elif menu_again == 'N'.lower(): break else: print('Unknown command.') user_input = input(main_menu)
def __init__(self): Menu.__init__(self,LevelMenu.levelentries[0:GlobalObjects.unlockedWorlds+1])
from stats import stat from menus import Menu from game import Game current_stats = stat() men = Menu(current_stats) gam = Game(current_stats) print("Welcome to Bravery and Malice.") print("Please choose a option.") print("Also please type the number beside the option not the name.") select_nation = False game_ended = False while not select_nation: men.print_menu() men.select() select_nation = men.check_options(gam.options) while not game_ended: gam.print_situation() game_ended = gam.take_turn()
def __init__(self, name): self.menu = Menu() self.pname = "{}.{}".format(name, os.getppid()) self.ppath = path_pipe + self.pname self.exit_str = "sfdaoekga"
def handle_selected_favorite_menu(self, entries={}): """The user has a view of all the favorites, he can choose to check their details with the favorite details menu, and of course he can delete a substitute if needed. """ favorite_manager = FavoriteManager(self.db) product_code = entries['Favoris'].label menu = Menu('Gestion', title="Gestion du favori :", prompt="Pour ce favori, que souhaitez-vous faire ? ") menu.add("""Consulter les détails du favori.""", self.handle_favorite_details, 'c') menu.add("Supprimer le favori.", self.handle_delete_favorite, 's') menu.add("Quitter l'application.", self.handle_quit, 'q') menu.add("Revenir au menu principal", self.handle_start_menu, 'm') menu.add("Revenir en arrière.", self.handle_favorites_menu, 'b') menu.manager.ask(entries)
class Launcher(): def __init__(self, name): self.menu = Menu() self.pname = "{}.{}".format(name, os.getppid()) self.ppath = path_pipe + self.pname self.exit_str = "sfdaoekga" def wait_user_action(self): try: log("launcher: wait for user action") with open(self.ppath) as f: result = f.read() return result except OSError as e: handle(e) return self.exit_str def loop(self): log("launcher: start {}".format(self.ppath)) try: os.makedirs(path_pipe) except OSError: pass try: os.mkfifo(self.ppath) except OSError: pass lock = path_pipe + "lock" while True: try: result = self.wait_user_action() if result == self.exit_str: break log("launcher: start menu {}".format(result)) self.menu.sel_menu(result) except Exception as e: handle(e) try: os.remove(lock) except OSError: pass try: os.remove(self.ppath) except OSError: pass log("launcher: stop") def stop(self): try: with open(self.ppath, "w") as f: f.write(self.exit_str) except OSError: pass def start(self): try: os.remove(path_pipe + "lock") except OSError: pass threading.Thread(target=self.loop).start()
def main(): c = Controller(View(), UserInterface(), GameSession(), Menu(), HumanPlayer(), Player()) c.play_game()