def doBuyArmor(self, Player): """Initializes armor buy dialogue with player""" # Generate shop inventory menu ShopWaresMenu = UI.MenuClass() ShopWaresMenu.Title = "Armor" while not ShopWaresMenu.Returned: # Fill with with items & information and trade-in value ShopWaresMenu.clear() for ShopItem in self.ArmorList: Name = ShopItem.descString() ShopWaresMenu.addItem(Name) ShopWaresMenu.CustomText = ( "You have " + str(Player.Gold) + " gp\nYour armor: " + Player.Equipment["Armor"].Base.descString() ) Index = ShopWaresMenu.doMenu() if ShopWaresMenu.Returned: break ShopItem = self.ArmorList[Index] if Player.Gold < ShopItem.Value: print("You cannot afford that!") UI.waitForKey() continue # Secure the transaction self.ArmorList.remove(ShopItem) Player.Gold -= ShopItem.Value Player.addItem(ShopItem) print(ShopItem.Name, "bought") UI.waitForKey()
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) sys.stdout=StdoutRedirector(self.ui.console) #### 1: ROADMAP #### UI.setRoadmapGUI(self) self.ui.roadmap_widget.hide() self.ui.roadmap_Run.clicked.connect(self.start_roadmap) self.createTable("roadmap") self.ui.roadmap_table.hide() self.ui.roadmap_Options.clicked.connect(self.ui.roadmap_table.show) self.ui.roadmap_Options.clicked.connect(self.ui.roadmap_save_button.show) self.ui.roadmap_save_button.clicked.connect(self.saveOptions) #### 2: POLYGONS #### UI.setPolygonsGUI(self) self.ui.polygons_widget.hide() self.ui.polygons_Run.clicked.connect(self.start_polygons) #### 3: BUILDING_GENERATION #### self.ui.building_generation_Run.clicked.connect(UI.building_generation) #### 4: VISUALIZATION #### self.ui.visualization_Run.clicked.connect(UI.visualization)
def breed(self, mate): if not mate.breedable(): return for partner in self.crew: # no sterile or pregnant partners if not partner.breedable(): continue if partner.sex == mate.sex: continue # no fathers or mothers if partner.crew_id == mate.mom.crew_id or partner.crew_id == mate.dad.crew_id: continue if mate.crew_id == partner.mom.crew_id or mate.crew_id == partner.dad.crew_id: continue prob = .006 # half siblings and full siblings if mate.dad.crew_id == partner.dad.crew_id: prob *= .01 if mate.mom.crew_id == partner.mom.crew_id: prob *= .01 if random.random() < prob: baby = Crewmate() mate.breeding = True partner.breeding = True if mate.sex == Sex.Male: baby.be_born(mate, partner) else: baby.be_born(partner, mate) self.crew.append(baby) print UI.inline_print(baby)+" has been born." print "Their parents are "+mate.name+" and "+partner.name return
def doBuyWeapon(self, Player): ShopWaresMenu = UI.MenuClass() ShopWaresMenu.Title = "Weapons" # Do bying menu while not ShopWaresMenu.Returned: # Fill with with items & information and trade-in value ShopWaresMenu.clear() for ShopItem in self.WeaponList: Name = ShopItem.descString() ShopWaresMenu.addItem(Name) ShopWaresMenu.CustomText = ( "You have " + str(Player.Gold) + " gp\nYour weapon: " + Player.Equipment["Weapon"].Base.descString() ) Index = ShopWaresMenu.doMenu() if ShopWaresMenu.Returned: break ShopItem = self.WeaponList[Index] if Player.Gold < ShopItem.Value: print("You cannot afford that!") UI.waitForKey() continue # Secure the transaction self.WeaponList.remove(ShopItem) Player.addItem(ShopItem) Player.Gold -= ShopItem.Value print(ShopItem.Name, "bought") UI.waitForKey()
def main(): # The topLevelObjects is a list to store objects at the top level to listen for events. # A typical use should only have the navigationViewController inside it as the subclasses manage events global topLevelObjects # Allow for the topLevelObjects list to be used elsewhere topLevelObjects = [] # Initialise screen and pyGame pygame.init() screen = pygame.display.set_mode((800, 600)) # Set the window title pygame.display.set_caption('Squares') # initialisation of the navigation controller. navigationViewController = NWPi.navigationController(screen) # Create a navigation view controller. Will parent all the Viewcontrollers topLevelObjects.append(navigationViewController) # This will now be added to topLevelObjects so it can recieve events # draw each viewController to the navigation controller home = UI.homeViewController(navigationViewController) # Create a ViewController, from subclass homeViewController where all elements are already defined navigationViewController.addSubView("HOMEVIEWCONTROLLER", home) # Add the ViewController to the navigation Controller. Do the same with the rest. secondView = UI.instructionsViewController(navigationViewController) navigationViewController.addSubView("INSTRUCTIONS", secondView) gameView = UI.mainGameViewController(navigationViewController) navigationViewController.addSubView("GAMEVIEW", gameView) # We need to set a viewController to show as the top level. Choose it here: navigationViewController.makeKeyAndVisible("INSTRUCTIONS") # Tell the navigation controller to set the view with the specified identifier to the top # We need a loop to keep the script running. Defining it here while True: loop() # Run the loop() function we defined earlier.
def doExamine(self, Player): """Starts cell object examination dialogue""" while 1: ObjectMenu = UI.MenuClass() ObjectMenu.Title = "Objects" for Object in self.Items: ObjectMenu.addItem(Object.Name) Choice = ObjectMenu.doMenu() if ObjectMenu.Returned: break Chosen = self.Items[Choice] print(Chosen.descString()) ChosenMenu = UI.MenuClass() ChosenMenu.DoCLS = 0 ChosenMenu.addItem("Take", UI.emptyCallback, "t") Choice = ChosenMenu.doMenu() if ChosenMenu.Returned: continue if Choice == 0: self.Items.remove(Chosen) Player.Inventory.addItem(Chosen) print("You take", Chosen.Name) UI.waitForKey()
def save(): """Saves user character progress, returns 0 on success, -1 on failure""" global Player FileName = UI.xInput("Enter filename to save to (default: player.dat): ", "player.dat") FileName = "".join(("saves/", FileName)) try: if os.path.exists(FileName): if input("Warning! File already exists. Type \'yes\' if you want to continue: ") != "yes": return 0 Out = open(FileName, "wb") pickle.dump(Player, Out) Out.close() except Exception: print ("Error: " + sys.exc_info()[0]) UI.waitForKey() return -1 print("Complete") UI.waitForKey() return 0
def filter_items(): """Update items based on selected tags.""" show_wip = optionWindow.SHOW_WIP.get() style_unlocked = StyleVarPane.tk_vars['UnlockDefault'].get() == 1 # any() or all() func = TAG_MODES[TAG_MODE.get()] sel_tags = [ tag for tag, enabled in TAGS.items() if enabled ] no_tags = len(sel_tags) == 0 for item in UI.pal_items: if item.needs_unlock and not style_unlocked: item.visible = False continue if item.item.is_wip and not show_wip: item.visible = False continue if no_tags: item.visible = True else: item_tags = item.item.filter_tags item.visible = func( tag in item_tags for tag in sel_tags ) UI.flow_picker()
def main(): my_persons = PersonRepository() my_activities = ActivityRepository() my_Controller = Controller(my_persons, my_activities) my_UI = UI(my_Controller) my_UI.do_menu()
def load(): global selected_game all_games.clear() for gm in config: if gm != 'DEFAULT': try: new_game = Game( gm, int(config[gm]['SteamID']), config[gm]['Dir'], ) except ValueError: pass else: all_games.append(new_game) new_game.edit_gameinfo(True) if len(all_games) == 0: # Hide the loading screen, since it appears on top loadScreen.main_loader.withdraw() # Ask the user for Portal 2's location... if not add_game(refresh_menu=False): # they cancelled, quit UI.quit_application() loadScreen.main_loader.deiconify() # Show it again selected_game = all_games[0]
def remove_game(_=None): """Remove the currently-chosen game from the game list.""" global selected_game lastgame_mess = ( "\n (BEE2 will quit, this is the last game set!)" if len(all_games) == 1 else "" ) confirm = messagebox.askyesno( title="BEE2", message='Are you sure you want to delete "' + selected_game.name + '"?' + lastgame_mess, ) if confirm: selected_game.edit_gameinfo(add_line=False) all_games.remove(selected_game) config.remove_section(selected_game.name) config.save() if not all_games: UI.quit_application() # If we have no games, nothing can be done selected_game = all_games[0] selectedGame_radio.set(0) add_menu_opts(game_menu)
def contract(_): """Shrink the filter view.""" global is_expanded is_expanded = False wid["expand_frame"].grid_remove() snd.fx("contract") UI.flow_picker()
def run() -> None: """Initializes program""" # global corpus # may want to load excel files on a case by case basis later on if load_excel_files: print("Loading excel files...") excel_setup() print("Done") UI.setup() # if corpus != None: # corpus = eval(corpus) # UI.return_data(analyze(word)) print( """ Notes: some 2 part words can be analyzed, however, the results - of the analysis of such words may be inconsistant depending on - whether the input uses a space or an underscore to seperate them entering default as an option when it is available will run the - given function using a set of predetermined common words - (see common words.txt)""" ) while True: interface_data = UI.interface() if interface_data[0] == "quit": break elif interface_data == (None, None): continue UI.output_data(collect_data(interface_data)) return
def downloadCurrentVersionUI(filename,secondary_dir,file_type,root): continue_analysis = downloadCurrentVersion(filename,secondary_dir,file_type) if continue_analysis == 'no' and 'nnot' not in filename: import UI try: root.destroy(); UI.getUserParameters('no'); sys.exit() except Exception: sys.exit() try: root.destroy() except Exception(): null=[] ### Occurs when running from command-line
def expand(_): """Expand the filter view.""" global is_expanded is_expanded = True wid["expand_frame"].grid(row=2, column=0, columnspan=2, sticky="NSEW") wid["tag_list"]["height"] = TK_ROOT.winfo_height() / 48 snd.fx("expand") UI.flow_picker()
def print_blocks_for_selected_meaning(self): """ This methods prints the block strings for the selected meaning. Example: -------- For the word '안녕', the blocks will be ['안', '녕'] """ UI.render_info('print blocks for selected meaning') UI.render_info([block.get_str() for block in self.blocks[self.selected_meaning]]) return [block.get_str() for block in self.blocks[self.selected_meaning]]
def doSell(self, Player): """Initializes sell dialogue with Player""" while 1: ChosenItem = Player.Inventory.chooseInventoryItem("Sell") if ChosenItem == None: break Player.removeItem(ChosenItem.Base) Player.Gold += ChosenItem.Base.Value print(ChosenItem.Base.Name, "sold") UI.waitForKey()
def draw(): global image clear_canvas() UI.draw() Letter.draw() update_canvas() pass
def assign_job(s): mate = UI.pick_list_crew(s.crew) if mate == -1: return colorful_jobs = map(UI.color_code, Jobs) for quest in quest_list: colorful_jobs.append(quest.description+" "+str(quest.quest_id)) job = UI.list_options(colorful_jobs, UI.inline_print(s.crew[mate])) if job < len(Jobs): s.crew[mate].job = Jobs[job] else: index = job - len(Jobs) s.crew[mate].job = quest_list[index].description+" "+str(quest_list[index].quest_id)
def initialize(): global layers, gameState layers['map_console'] = 0 layers['panel_console'] = 2 layers['UI_Back'] = 1 layers['side_panel_console'] = 2 layers['entity_console'] = 3 layers['messages'] = 4 layers['animation_console'] = 5 layers['overlay_console'] = 6 UI.load_from_xp(Constants.MAP_CONSOLE_WIDTH, 0, 'Side_panel', layers['UI_Back']) UI.load_from_xp(0, Constants.MAP_CONSOLE_HEIGHT, 'Panel', layers['UI_Back'])
def corupus_setup(file, name: str)->bool: '''sets up a new corpus to be selected from''' try: listing = open('corpora.txt', 'a') corpora = open('corpora.txt', 'r') index = int(corpora.read().splitlines()[-1].split()[0]) + 1 listing.write('\n{}\t{}\t{}'.format(index,name,file)) listing.close() corpora.close() UI.setup() except: print("Could not install new corpus...") return False return True
def expand(_): """Expand the filter view.""" global is_expanded is_expanded = True wid['expand_frame'].grid( row=2, column=0, columnspan=2, sticky='NSEW', ) wid['tag_list']['height'] = TK_ROOT.winfo_height() / 48 snd.fx('expand') UI.flow_picker()
def doShop(self, Player): """Starts the shop interface with Player""" # If player is dead or doesn't exist, exit the shop if Player.Exists == 0: print("You have to create a character first!") UI.waitForKey() UI.clrScr() return if Player.Health == 0: print("Your character is dead! Create a new one!") UI.waitForKey() UI.clrScr() return while not self.ShopMenu.Returned: Choice = self.ShopMenu.doMenu() if self.ShopMenu.Returned: self.ShopMenu.Returned = 0 break if Choice == 0: self.doBuyWeapon(Player) elif Choice == 1: self.doBuyArmor(Player) else: self.doSell(Player)
def corupus_setup(file, name: str) -> bool: """sets up a new corpus to be selected from""" try: listing = open("corpora.txt", "a") corpora = open("corpora.txt", "r") index = int(corpora.read().splitlines()[-1].split()[0]) + 1 listing.write("\n{}\t{}\t{}".format(index, name, file)) listing.close() file.close() UI.setup() # UI.corpora.append('{}\t{}\t{}'.format(index,name,file)) # UI.max_index = index except: print("Could not install new corpus...") return True
def importAgilentExpressionValues(filename,array,channel_to_extract): """ Imports Agilent Feature Extraction files for one or more channels """ print '.', red_expr_db={} green_expr_db={} parse=False fn=unique.filepath(filename) for line in open(fn,'rU').xreadlines(): data = UI.cleanUpLine(line) if parse==False: if 'ProbeName' in data: headers = string.split(data,'\t') pn = headers.index('ProbeName') try: gc = headers.index('gProcessedSignal') except Exception: pass try: rc = headers.index('rProcessedSignal') except Exception: pass parse = True else: t = string.split(data,'\t') probe_name = t[pn] try: green_channel = math.log(float(t[gc])+1,2) #min is 0 except Exception: pass try: red_channel = math.log(float(t[rc])+1,2) #min is 0 except Exception: pass if 'red' in channel_to_extract: red_expr_db[probe_name] = red_channel if 'green' in channel_to_extract: green_expr_db[probe_name] = green_channel if 'red' in channel_to_extract: red_channel_db[array] = red_expr_db if 'green' in channel_to_extract: green_channel_db[array] = green_expr_db
def downloadCurrentVersion(filename,secondary_dir,file_type): import UI file_location_defaults = UI.importDefaultFileLocations() ud = file_location_defaults['url'] ### Get the location of the download site from Config/default-files.csv url_dir = ud.Location() ### Only one entry dir = export.findParentDir(filename) dir = string.replace(dir,'hGlue','') ### Used since the hGlue data is in a sub-directory filename = export.findFilename(filename) url = url_dir+secondary_dir+'/'+filename print url file,status = download(url,dir,file_type); continue_analysis = 'yes' if 'Internet' in status and 'nnot' not in filename: ### Exclude for Affymetrix annotation files print_out = "File:\n"+url+"\ncould not be found on the server or an internet connection is unavailable." if len(sys.argv)<2: try: UI.WarningWindow(print_out,'WARNING!!!') continue_analysis = 'no' except Exception: print 'cannot be downloaded';force_error else: print 'cannot be downloaded';force_error elif status == 'remove' and ('.zip' in file or '.tar' in file or '.gz' in file): try: os.remove(file) ### Not sure why this works now and not before except Exception: status = status return continue_analysis
def importExpressionValues(filename): """ Imports tab-delimited expression values""" header = True sample_expression_db = {} fn = unique.filepath(filename) for line in open(fn, "rU").xreadlines(): data = UI.cleanUpLine(line) if header: sample_names = string.split(data, "\t") header = False else: exp_values = string.split(data, "\t") gene = exp_values[0] index = 1 for value in exp_values[1:]: sample_name = sample_names[index] if sample_name in sample_expression_db: gene_expression_db = sample_expression_db[sample_name] gene_expression_db[gene] = value else: gene_expression_db = {} gene_expression_db[gene] = value sample_expression_db[sample_name] = gene_expression_db index += 1 return sample_expression_db
def xhyper(words)->[str]: '''returns the highest order x hypernyms''' x = UI.request_x() print("\nNote: this program will use the first parallel synset if there are any") print("\nGathering data...") result = [x] hyp = lambda w: w.hypernyms() #This would pick up the deepest branch's depth -> valueAt returns None -> returns None #depth = lambda L: isinstance(L, list) and max(map(depth, L))+1 for i in range(len(words)): synsets = wordnet.synsets(words[i]) if len(synsets) > 0: for s in range(len(synsets)): hyper = wordnet.synsets(words[i])[s].tree(hyp) if (hyper[0].pos() in ['a','s','r']): result.append([words[i], 'None', 'None', [None]]) continue d = first_depth(hyper) - 1 xhyper = [] for j in range(x): xhyper.append(valueAt(d - j, hyper)) if xhyper[-1] is None: break result.append([words[i], pos_redef(hyper[0].pos()), hyper[0], xhyper]) else: result.append([words[i], 'None', 'None', [None]]) return result
def end_turn(s): for quest in quest_list: quest.apply_work(s) if quest.succeed(): quest.victory(s) quest_list.remove(quest) else: quest.failure(s) if random.random() > 0.7: new_quest = Initial.get_random_quest() new_quest.set_cost(s) UI.acknowledge() print new_quest.intro quest_list.append(new_quest) s.pass_turn() UI.acknowledge()
def euthanize(s): answer = UI.pick_list_crew(s.crew) if answer == -1: return s.crew[answer].alive = False s.crew.remove(s.crew[answer]) s.happiness_penalty += 500
def function_2(): if not MBTI.user_type.is_empty(): print("\nCurrent user MBTI type set to", MBTI.user_type) else: print("User MBTI type is not currently set.") inputted_mbti = input("Enter user MBTI type or enter {0} to quit: ".format(UI.quit)).upper() if inputted_mbti.lower() == UI.quit: print("Returning to root...") UI.ui() else: print("Checking... ") valid = MBTI.check_validity(inputted_mbti) if valid: print("Input valid. Setting user MBTI...") MBTI.user_type = MBTI.mbti(inputted_mbti[0], inputted_mbti[1], inputted_mbti[2], inputted_mbti[3]) print("User MBTI set to", MBTI.user_type) else: run_again = program_functions.return_to_root("Invalid input", True) if run_again: function_2()
def add_button_type(self, type_name, normal, hover, pressed, size): """Add a new button type. :param type_name: the button type/group name :param normal: src to normal button image (can be none) :param hover: src to hover button image (can be none) :param pressed: src to pressed button image (can be none) :param size: button size (width, height) :return: None """ self.buttons[type_name] = UI.UIButtons(hover, normal, pressed, size)
def toggle_pause_menu(self): if self.pause_menu is None: self.on_pause() width = self.screen_width / 4 height = self.screen_height / 4 x = self.screen_width / 2 - width / 2 y = self.screen_height / 2 - height / 2 self.pause_menu = UI.PauseWindow(x, y, width, height) else: self.pause_menu = None self.on_resume()
def __init__(self, data): super().__init__(data) self.fps = 30 self.replay, self.last_frame, self.next_scene = self.data self.replay_pointer = self.start_frame(self.replay, self.last_frame) self.frame = self.replay[self.replay_pointer] self.flash = (60, 120) width = pygame.display.get_surface().get_width() self.text = UI.GameText("INSTANT REPLAY", (width // 2, 40), palette.GREEN, 40, self.flash)
def change_player_name(self): enter_name = UI.Enter_Name(self.my_board.scrn_info) name = enter_name.get_name(self.my_board.screen) enter_name.kill() self.my_board.update() config = configparser.ConfigParser() config["User_Settings"] = {"Player_Name": name} with open("config.ini", "w+") as config_f: config.write(config_f) self.my_board.interface.player_name = name
def getCurrentGeneDatabaseVersion(): global gene_database_dir try: filename = 'Config/version.txt' fn = filepath(filename) for line in open(fn, 'r').readlines(): gene_database_dir, previous_date = string.split(line, '\t') except Exception: import UI gene_database_dir = '' try: for db_version in db_versions: if 'EnsMart' in db_version: gene_database_dir = db_version UI.exportDBversion(db_version) break except Exception: pass return gene_database_dir
def __init__(self): self.ui = UI.Gui(self.on_selected_category, threadingops.get_categories()) self.apps_model_search = Gtk.ListStore(str, str, str, str) self.installed_model_search = Gtk.ListStore(str, str, str, str) #------------------------------------------------------- self.choosed_page = 0 self.last_page = 0 self.actual_category = "packages" self.was_searching = False self.startup = True self.active_for_search = True #------------------------------------------------------- self.action_group = None self.refresh_system_call() #------------------------------------------------------- self.ui.pages.get_function = self.get_func self.ui.pages.installed_function = self.installed_func self.ui.search_pkg.search_function = self.search #------------------------------------------------------- self.ui.pages.basket_function = self.refresh_app_basket self.ui.install_pkgs.connect("clicked", self.on_install_pkgs) self.ui.remove_mai_button.connect("clicked", self.on_clear_basket) #------------------------------------------------------- self.ui.toolbar.back.connect("clicked", self.back_to_last_page) self.ui.toolbar.settings.connect("clicked", self.on_show_preferences) #------------------------------------------------------- self.ui.apps_all.connect("cursor-changed", self.on_selected_available) self.ui.apps_installed.connect("cursor-changed", self.on_selected_available) self.ui.apps_all.connect("row-activated", self.on_more_info_row, 0) self.ui.apps_installed.connect("row-activated", self.on_more_info_row, 1) self.ui.statusbox.combo.connect("changed", self.statusbox_combo_changed) #------------------------------------------------------- self.ui.apps_message.add_remove_button.connect( "clicked", self.on_install_or_remove, None) self.ui.installed_message.add_remove_button.connect( "clicked", self.on_install_or_remove, self.ui.apps_installed) self.ui.apps_message.details_button.connect("clicked", self.on_more_info, 0) self.ui.installed_message.details_button.connect( "clicked", self.on_more_info, 1) #------------------------------------------------------- self.ui.appsinfo.button.connect("clicked", self.on_install_or_remove, self.ui.apps_installed) self.ui.appsinfo.scrot_button.connect("button-press-event", self.maximize_screenshot) self.ui.appsinfo.check_reviews.connect("clicked", self.download_review) #------------------------------------------------------- self.ui.no_found_button.connect("clicked", self.search_in_all) #------------------------------------------------------- self.depends = []
def doWorld(self, Player): #If player's cell not defined, find player in current cell list if self.PlayerCell == None: for Cell in self.Cells: if Player in Cell.Chars: self.PlayerCell = Cell break #If no player found, bail out if self.PlayerCell == None: print("No player detected!") UI.waitForKey() return while 1: NewCell = self.PlayerCell.doCell(Player) if NewCell == None: break else: self.PlayerCell = NewCell
def on_init(self): self.gamedisplay = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) GameWorld.Gameworld.gameDisplay = self.gamedisplay pygame.display.set_caption(self.name) pygame.display.set_icon(self.img) self.clock = pygame.time.Clock() self.score = Score.Score() self.gameworld = GameWorld.Gameworld(self.score) self.UI = UI.UI(self.score, (self.display_width, self.display_height)) return True
def check_chsn(logs_chsn, y_left, p_wdth, spacing): # Height of each log in Chosen Logs and Spacing inbetween log_end = -1 for i in range(0, len(logs_chsn)): y_aftr = y_left - spacing - len(UI.parse_lines(logs_chsn[i], p_wdth)) if y_aftr < 0: log_end = i break else: y_left = y_aftr return log_end, y_left
def find_unit(self, x, y): unit_now = None for i in self.unit_list: if [x, y] == [i.unit_place[0], i.unit_place[1]]: self.unit_info = UI.Text( 'жизни: {}, урон: {}, тип: {}'.format( i.hp, i.damage, i.type), self.height * self.unit_info_y_coef, self.width * self.unit_info_x_coef) unit_now = i return unit_now
def apply_consolidation_rules(self, subset): # given a subset with component trades and rule, sends back ONE ROW with concolidated trades, doesn't do anything in master table rule = set(subset.cons_type) if len(set(subset.cons_type)) > 1: UI.error_exit( 'Something is wrong with your ' + str(list(set(subset.ticker))) + ' orders; check them and try again; exiting from `apply_consolidation_rules` line 149' ) rule = list(rule)[0] subset = subset.sort_values(by=['first_leg', 'strategy']) if rule == 'J': result = self.consolidate_order_rows(subset) result.cons_type = 'done-J' else: UI.error_exit('Something is wrong with your orders for ' + str(subset.ticker)) result.send_to_sheet = False return result
def Watch(): #Watches over all threads and outputs displays if told to. #threads in case one of them errors out print("Waiting for threads to initalize") time.sleep(1.5) #give the threads a little more time to start print("Starting...") while True: if Utilities.ProgramEnding: #but first lets check to see if the ending flag is up print("Vision man is going away now...") UI.Master_Window.destroy( ) # say goodbye to settings and output window break #stop loop is the program ending flag is up if Settings.DEVMODE: UI.UpdateUI( ) #updates the UI with updated values such as box center, contour data, etc UI.UpdateOutputImage( ) #updates the output image with the contour at the center else: #not devmode, we should print the coordinates out print("(" + str(Utilities.BoxCenterX) + ", " + str(Utilities.BoxCenterY) + ")", end='\r') Utilities.CheckThreadConditions() #send values to the RoboRIO. sendX = -1 sendY = -1 if (Utilities.BoxCenterX > -1) and (Utilities.BoxCenterY > -1): sendX = int((Utilities.BoxCenterX / 200) * 1280) #scales to 720p resolution sendY = int((Utilities.BoxCenterY / 200) * 720) UDPMessage = str(sendX) + "," + str(sendY) #our message! Utilities.MainThreadMessage = "\nSending to the RIO: " + UDPMessage Utilities.sock.sendto( UDPMessage, (Settings.UDP_IP, Settings.UDP_PORT)) #haha this is what actually sends it
def __init__(self, player, screenObj=None, world_unit=None): """Constructor""" self.world_unit = world_unit self.images = load_sprite_sheet("Witchcraft.png", 1, 22) self.image_num = 0 self.player = player self.player.con = self self.dy = 0 self.dx = 0 self.direction = 1 self.label1 = UI.Label( 300, 300, " player gold:{}".format(self.player.booty["Gold"])) if screenObj is not None: self.screen_obj = screenObj else: self.screen_obj = UI.ScreenUnit(player.current_tile.world_x, player.current_tile.world_y, self.images[0], 15, 15, False, self.controls) from UI import cam cam.center_on(self.screen_obj)
def user_list(call, lang): p = UI.Paging(Course.Course(call.data['c_id']).participants, sort_key='name') text = msgs[lang]['teacher']['management']['user_list'] + p.msg( call.data['page'], lang) markup = mkp.create_listed( lang, tbt.users(p.list(call.data['page']), call.data['c_id']), tbt.user_list, call.data['c_id'], lang, call.data['page']) botHelper.edit_mes(text, call, markup=markup)
def update_info(): global sum global xh xh = 1 print 'Successfully login in and acquire the data' get_info_2() cnt = 0 while True: time.sleep(1) cnt = cnt + 1 print '第', cnt, '次查询期末成绩数据,暂无更新' if cnt % 20 == 0: break t = get_info_2() if not sum: sum = t if t > sum: print '第', cnt, '次查询期末成绩数据,你有成绩更新了!' UI.tell_update() break UI.tell_Success(2)
def filter_items(): """Update items based on selected tags.""" style_unlocked = StyleVarPane.tk_vars['UnlockDefault'].get() == 1 # any() or all() func = TAG_MODES[TAG_MODE.get()] sel_tags = [tag for tag, enabled in TAGS.items() if enabled] no_tags = len(sel_tags) == 0 for item in UI.pal_items: if item.needs_unlock and not style_unlocked: item.visible = False continue if no_tags: item.visible = True else: item_tags = item.item.filter_tags item.visible = func(tag in item_tags for tag in sel_tags) UI.flow_picker()
def start(self): self._frame.destroy() self.mode = self._var.get() if self.mode == 1: ChineseChess = UI.app(self._window) ChineseChess.run() elif self.mode == 2: arbitaryChess = FreeMode.appArb(self._window) arbitaryChess.run() else: keynote = Keynote.Keynote(self._window)
def on_orig_changed(self, w): adep = text = w.props.text w.props.text = text.upper() if not text.isalpha() and text != "": try: w.props.text = w.previous_value except: w.props.text = "" gtk.gdk.beep() self.sb.push( 0, utf8conv("Formato incorrecto de aeródromo de origen")) return w.previous_value = text self.sb.pop(0) if adep.upper() in self.fir.local_ads[self.sector]: self.set_departure(True) else: self.set_departure(False) if w.props.max_length == len(text): UI.focus_next(w) self.fill_completion()
def AnnounceAction(self, action): if UI.AutoAllow(): return 'Allow', None for player in self.state.players: if (player == self.player or player.influence == 0): continue response = player.handler.DecideToCounterAction(action) if response != 'Allow': return response, player return response, None
def intro(): #The intro to the game print(Reset, end='') Clear.clear() with open("Globals.txt", 'r') as file: variables = json.load(file) if variables["color"] != 0: UI.necro_color() print(Green_Blackxx, end='') else: UI.necro() print("\n") WordCore.word_corex("DEVELOPER |", "78 Alpha\n") print("\n") time.sleep(0.5) WordCore.word_corex("CONTINUE |", "Start the game from previous save") print("\n") time.sleep(0.5) WordCore.word_corex("NEW |", "Create a new game") print("\n") time.sleep(0.5) WordCore.word_corex("SETTINGS |", "Change game settings") print("\n") time.sleep(0.5) WordCore.word_corex("EXIT |", "Exit the application") print("\n") time.sleep(0.5) action = input(str("What would you like to do: ")) if action == "CONTINUE": Level1.Save_Check() elif action == "NEW": load_3() Level1.Save_Check() elif action == "SETTINGS": settings() intro() elif action == "EXIT": Clear.clear() exit() else: intro()
def run(): """ entry point in the program :return: """ poemlist = [] test.testInit(poemlist) while True: try: cmd = readCommand() command = cmd[0] idP = cmd[1] params = cmd[2] if command == "add": UI.addPoemCommand(poemlist, idP, params) elif command == "haikus": UI.printHaikus(poemlist) elif command == "dada": UI.generateDadaPoem(poemlist) elif command == "print": print(poemlist) else: print("invalid command") except ValueError as ve: print(str(ve))
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) sys.stdout=StdoutRedirector(self.ui.console) #### 1: ROADMAP #### UI.setRoadmapGUI(self) self.ui.roadmap_widget.hide() self.ui.roadmap_Run.clicked.connect(self.start_roadmap) self.createTable("roadmap") self.ui.roadmap_splitter.setSizes([80,800]) self.ui.roadmap_table.hide() #### 2: POLYGONS #### UI.setPolygonsGUI(self) self.ui.polygons_widget.hide() self.ui.polygons_Run.clicked.connect(self.start_polygons) self.createTable("polygons") self.ui.polygons_splitter.setSizes([80,800]) #### 3: BUILDING_GENERATION #### UI.setBuilding_generationGUI(self) self.ui.building_generation_widget.hide() self.ui.building_generation_Run.clicked.connect(self.start_building_generation) self.createTable("building_generation") self.ui.building_generation_splitter.setSizes([80,800]) #### 4: VISUALIZATION #### self.ui.visualization_Run.clicked.connect(UI.visualization) self.createTable("visualization") self.ui.visualization_splitter.setSizes([80,800])
def __init__(self, player=None, enemy1=None, enemy2=None, enemy3=None): Globals.battle = self self.b1 = UI.Button(3, 33, None, True) self.b2 = UI.Button(3, 41, None, False) self.b3 = UI.Button(44, 33, None, False) self.b4 = UI.Button(44, 41, None, False) self.currentbutton = self.b1 self.downbox = UI.Static(0, 31, 'bottombox') self.upbox = UI.Static(0, 0, 'upperbox') self.bars = UI.Static(0, 26, 'statusbars') self.uptext = DrawableObject.Text(2, 2, '') self.downtext1 = DrawableObject.Text(3, 33, '') self.downtext2 = DrawableObject.Text(3, 41, '') self.o1 = DrawableObject.Text(13, 33, 'attack') self.o2 = DrawableObject.Text(13, 41, 'skills') self.o3 = DrawableObject.Text(54, 33, 'items') self.o4 = DrawableObject.Text(54, 41, 'status') self.enemyarrow = UI.Static(40, 10, 'enemyarrow', False) self.hpbar = UI.PixelBar(2, 30, 20) self.mpbar = UI.PixelBar(62, 30, 20) self.player = player self.enemy1 = enemy1 self.enemy2 = enemy2 self.enemy3 = enemy3 self._currenttarget = enemy1 if self.enemy1 is not None: self.enemy1.x = 34 self.enemy1.y = 13 if self.enemy2 is not None: self.enemy2.x = 9 self.enemy2.y = 13 if self.enemy3 is not None: self.enemy3.x = 59 self.enemy3.y = 13 self.turnorder = [] self.battleover = False self.c = Controller.Control() self.action = None self.orderqueue = [player, enemy1, enemy2, enemy3] self.orderqueue.sort(key=lambda x: x.current_dex(), reverse=True)
def DecideToCounterAction(self, action): UI.DisplayTable(self.state, self.player) p = action.doer.name + ' wants to ' + action.name if action.target != None: p += ' /// TARGET == ' + action.target.name responses = ['Allow'] if action.isBlockable: if not action.isTargetable or action.target == self.player: responses.append('Block') if action.isChallengeable: responses.append('Challenge') #p= 'How do you want to respond ' + self.player.name + ' ??' response = UI.DisplayOptions(p, responses, False) if response == 'Block': response = UI.DisplayOptions("Block With?", action.blockableBy, False) return response
def DecideAction(self, availableActions): # Query user for action # Display Board State UI.DisplayTable(self.state, self.player) actionKey = UI.DisplayOptions('Available Actions:', availableActions, False) action = actions[actionKey] action.doer = self.player # If the action has a target, get it if action.isTargetable: action.target = UI.DisplayOptions( 'Available Targets:', self.state.players, True, [self.player] + self.state.deadPlayers) #choose target's card to coup if actionKey == 'Coup': action.cardToCoup = UI.DisplayOptions('Cards to Coup:', game.characters, False) return action
def playMatchs(players, args): # On récupère les arguments de l'utilisateur boardSize = args.boardSize withUI = args.withUI matchs = args.matchs time = args.maxTime # On parcourt la liste des matchs for m in matchs: # On récupère les joueurs à partir de leurs noms player1 = getPlayerFromName(players, m[0]) player2 = getPlayerFromName(players, m[1]) # On vérifie que les deux joueurs sont corrects if player1 != None and player2 != None: # Match allé match = Match(player1, player2) board = UI.createBoard(boardSize) startMatch(board, match, boardSize, withUI, time) # Match retour match = Match(player2, player1) board = UI.createBoard(boardSize) startMatch(board, match, boardSize, withUI, time) else: if player1 == None: print(m[0] + " is not a valid name for a player") if player2 == None: print(m[1] + " is not a valid name for a player") if "-NB" in sys.argv: ########################################CHANGEONS CA DES QUE POSSIBLE, CA FAIT MAL AAAAAAAHHHHHHHHH################ player1 = getPlayerFromName(players, m[0]) player2 = getPlayerFromName(players, m[1]) player1.printPlayer() player2.printPlayer()
def on_fix_changed(self, w, event=None): text = w.props.text = w.props.text.upper() valid = False for f in self.route.props.text.split(" "): if f == text: w.previous_value = text self.sb.pop(0) UI.focus_next(w) return if f.startswith(text): valid = True break if not valid and text != "": try: w.props.text = w.previous_value except: w.props.text = "" gtk.gdk.beep() self.sb.push(0, utf8conv("El fijo debe pertenecer a la ruta")) return w.previous_value = text self.sb.pop(0)
def show_devices(self): UI.SystemOut("网卡列表: ") devices_keys = self.devices.keys() devices_names = [] for key in devices_keys: devices_names.append(self.devices[key]) i = 1 for name in devices_names: print("%d. " % i, end="") print(name) i += 1 return
def buildUniProtFunctAnnotations(species,force): import UI file_location_defaults = UI.importDefaultFileLocations() """Identify the appropriate download location for the UniProt database for the selected species""" uis = file_location_defaults['UniProt'] trembl_filename_url='' for ui in uis: if species in ui.Species(): uniprot_filename_url = ui.Location() species_codes = importSpeciesInfo(); species_full = species_codes[species].SpeciesName() from build_scripts import ExtractUniProtFunctAnnot; reload(ExtractUniProtFunctAnnot) ExtractUniProtFunctAnnot.runExtractUniProt(species,species_full,uniprot_filename_url,trembl_filename_url,force)