def setup(self): self.player = Player() self.capitol = Capitol() self.coequipier = None self.gui = Gui(0, CONST.MAX_VOTES) self.supporters = [] self.bullets = [] self.ui_manager = UIManager() self.tweet = Tweet() self.strike_button = Strike(center_x=CONST.STRIKE_BUTTON_X, center_y=CONST.STRIKE_BUTTON_Y, normal_texture=self.button_normal, hover_texture=self.button_hovered_texture, text='') self.ui_manager.add_ui_element(self.strike_button) arcade.set_background_color(arcade.color.AMAZON) self.background = arcade.load_texture("tileset/background.png") self.music_list = ["audios/background_music.mp3"] self.current_song_index = 0 self.music = arcade.Sound(self.music_list[self.current_song_index], streaming=True) self.play_song()
def openSearch(self, params={}): get = params.get if re.match('\d+', get("url")): try: keyboard = xbmc.Keyboard( urllib.unquote_plus(get("like")), self.localize("Edit Line For Searching:")) except: keyboard = xbmc.Keyboard('', self.localize("Input Search Phrase:")) keyboard.doModal() query = keyboard.getText() if keyboard.isConfirmed() and query: url = '/search?original_id=%s&s=%s' % (re.search( "(\d+)$", get("url")).group(1), urllib.quote_plus(query)) else: return else: url = urllib.unquote_plus(get("url")) videos = self.fetchData(url) for section in Parser().search(videos): Gui().drawItem(section['title'], 'openPage', section['link'], section['image']) Gui().drawPaging(videos, 'openSearch') Gui().lockView('info_big')
def __init__(self, central): """Cria o menu com seus textos e botoes""" self.gui = Gui() self.fundo = "fundo.png" #self.mouse = RatazanaSimples(self, 0, 0) #titulo = Texto("L I X O !", tamanho=30, img_botao="botao.png") #titulo.alt_cor(128, 128, 0) #titulo.posicionar(512, 128) #self.adi(titulo) bot_iniciar = BotaoAnimado(central.comecar_jogo, texto="Iniciar!", img_botao="iniciar.png", linha=0) bot_iniciar.posicionar(400, 384) bot_iniciar.alt_cor(0, 255, 0) self.adi(bot_iniciar) #bot_aju = BotaoAnimado(central.ajuda, texto="Ajuda", # img_botao="ajuda.png", linha=1) # bot_aju.posicionar(512, 384) # bot_aju.alt_cor(0, 0, 255) # self.adi(bot_aju) bot_sair = BotaoAnimado(sys.exit, texto="Sair", img_botao="sair.png", linha=2) bot_sair.posicionar(650, 384) bot_sair.alt_cor(255, 0, 0) self.adi(bot_sair) pygame.mouse.set_visible(False)
def __init__(self): self.api_key = 'YOUR-API-KEY' self.gui = Gui() self.gui.show() self.getSymbols() self.gui.convertButton.clicked.connect(self.getComboBoxFrom) self.gui.convertButton.clicked.connect(self.getComboBoxTo) self.gui.convertButton.clicked.connect(self.getValueBefore) self.gui.convertButton.clicked.connect(self.convertVal)
def displayPlot(self, path): Gui.displayPlot(self, path) w = QPushButton('Save scores as PNG') w.clicked.connect(self.saveScoresPng) self.layout().addWidget(w, 2, 0) w = QPushButton('Save scores as text file') w.clicked.connect(self.saveScoresText) self.layout().addWidget(w, 2, 1)
def quit(self): """Shuts down the World.""" # setting exists tells other threads that the world is gone self.exists = False # destroy closes the window self.destroy() # quit terminates mainloop (but since mainloop can get called # recursively, quitting once might not be enough!) Gui.quit(self)
def main(self): self.gui = Gui() self.Intervals = [ '1 Minute', '5 Minutes', '15 Minutes', '30 Minutes', '60 Minutes', '1 Day', '1 Week', '1 Month' ] previous_ticker = '' while True: event, values = self.gui.data() self.getMonths(values) if values['Ticker'] != previous_ticker: self.gui.updateTickers() previous_ticker = values['Ticker'] elif values['Ticker'] in ['Ticker', '']: self.gui.window.FindElement('Ticker').Update( values=self.gui.allTickers, value=values['Ticker'], size=(10, 10)) if event in [PySimpleGUI.WIN_CLOSED, 'Exit']: exit() elif event == 'Run': toEnter = [ values['Ticker'], self.Intervals.index(values['Interval']), values['StartMonth'], values['EndMonth'], ] self.gui.update('SD', "Calculating...") self.gui.update('SMVI', "Calculating...") self.gui.update('Terminal', 'Calculating...') if values['Handle'] in ['', 'Handle']: PySimpleGUI.popup( 'Error, please enter a valid Twitter handle') continue stock = Stock(toEnter[0], toEnter[1], toEnter[2], toEnter[3], self.gui.Months, False) if stock.hasErrors: error_message = 'An error occured' self.gui.update('Terminal', error_message) self.gui.update('SD', error_message) self.gui.update('SMVI', error_message) continue else: SDToDisplay = str(stock.SDToDisplay)[0:8] self.gui.update('SD', SDToDisplay) self.gui.update('Terminal', 'Calculating baseline...') DIA = Stock('DIA', toEnter[1], toEnter[2], toEnter[3], self.gui.Months, True) self.gui.update('Terminal', 'Calculating SVMI') cor = Correlation(stock, DIA, self.parseHandles(values['Handle'])) self.gui.update('SMVI', str(cor.SMVI * float(SDToDisplay))[0:8]) self.gui.update('Terminal', 'Done!')
class Controleur(): def __init__(self): #TODO self.modele = Modele() + inititalisation du modèle self.gui = Gui(self.gameLoop) #TODO self.gui.rafraichir(self.modele.anneCourante, self.modele.planetes, # len(self.modele.getPlanetesHumains), # len(self.modele.getPlanetesGubru), # len(self.modele.getPlanetesCzins) #) def gameLoop(self, userAction, coordinates=None): """ the coordiantes should be tuples """ if userAction == UserActions.VALIDER_DEPLACEMENT: self.validationDeplacement() elif userAction == UserActions.VALIDER_TOUR: self.finTour() elif userAction == UserActions.SELECT_PLANETE: self.gestionSelectionPlanete() elif userAction == UserActions.FLOTTE_CHANGEMEMT: self.gestionChangementFlotte() def gestionSelectionPlanete(self): pass #TODO Gestion Selection Planete # afficher les informations de la planète sélectionnée selon niveau connaissances # Si planete == Humain ==> Si on a pas déjà une flotte dans le modèle ==> faire une nouvelle flotte #self.gui.getNbVaisseaux() #self.gui.inspecterPlanete(planete.nom, planete.capacite, nbVaisseaux) pass # Check coordinates (tuples) def validationDeplacement(self): pass #TODO validation Deplacement def finTour(self): pass #TODO Fin d'un tour def gestionChangementFlotte(self): # TODO mettre flotte même nombre que vaisseaux GUI #print(self.gui.getNbVaisseaux()) pass def executer(self): self.gui.run()
def main(): """Entry point. Gets user input, runs GUI or task manager depending on the input""" user_input = UserInput() if user_input.gui_flag: g = Gui(user_input.get_file(), user_input.get_docid(), user_input.get_userid()) g.run() else: manager = TaskManager(user_input.get_file(), user_input.get_docid(), user_input.get_userid()) task = user_input.task manager.run(task)
def main(): """ Creates the GUI and runs the pipeline. """ gui = Gui(key_handler=key_handler) gui.state["model"] = load_model() widget_camera = Widget("Camera", do_camera, show_window=True, show_controls=False) gui.widgets.append(widget_camera) widget_greyscale = Widget("Greyscale", do_greyscale, show_window=False, show_controls=False) gui.widgets.append(widget_greyscale) # widget_denoising = Widget("Denoising", do_denoising) # widget_denoising.params.append(Param(P_DENOISE_KERNEL, 1, 20, 1)) # gui.widgets.append(widget_denoising) widget_threshold = Widget("Threshold", do_threshold, show_controls=False) widget_threshold.params.append(Param(P_THRESHOLD_BLOCK_SIZE, 0, 50, 5)) widget_threshold.params.append(Param(P_THRESHOLD_MAX_VAL, 0, 255, 160)) widget_threshold.params.append(Param(P_THRESHOLD_CONSTANT, -20, 20, 0)) gui.widgets.append(widget_threshold) widget_blur = Widget("Blur", do_blur, show_controls=False) widget_blur.params.append(Param(P_BLUR_KERNEL, 0, 20, 2)) gui.widgets.append(widget_blur) widget_edges_canny = Widget("Canny Edge Detection", do_edges_canny, display_function=do_display_edges, show_controls=False) widget_edges_canny.params.append(Param(P_CANNY_THRESHOLD_1, 1, 600, 110)) widget_edges_canny.params.append(Param(P_CANNY_THRESHOLD_2, 1, 600, 320)) gui.widgets.append(widget_edges_canny) # widget_edges_hough = Widget("Hough Line Detection", do_edges_hough, show_image=False) # widget_edges_hough.params.append(Param(P_HOUGH_RHO, 1, 10, 1)) # widget_edges_hough.params.append(Param(P_HOUGH_THRESHOLD, 1, 500, 100)) # widget_edges_hough.params.append( # Param(P_HOUGH_MIN_LINE_LENGTH, 1, 300, 10)) # widget_edges_hough.params.append(Param(P_HOUGH_MAX_LINE_GAP, 1, 300, 10)) # gui.widgets.append(widget_edges_hough) widget_annotate = Widget("Annotated Camera Frame", do_annotation) gui.widgets.append(widget_annotate) gui.show()
def __init__(self, delay=0.5, *args, **kwds): Gui.__init__(self, *args, **kwds) self.delay = delay self.title('World') # keep track of the most recent world World.current_world = self # set to False when the user presses quit. self.exists = True # list of animals that live in this world. self.animals = []
def __init__(self, filename=None): Gui.__init__(self) #self.geometry('1260x800+74+32') self.filename = filename self.views = {} self.w = self self.threads = [] self.running = False self.delay = 0.2 self.setup() self.run_init() for col in self.cols: col.create_thread()
def main(): """ opening through GUI or Terminal """ args = parse_arguments() labyrinth = Maze("grid.txt") if args.gui is True: gui = Gui(labyrinth) gui.start() else: print(maze_title) print(game_intro) game_manager = GameManager(labyrinth) game_manager.play_or_quit()
def __init__(self, debug=False, pedantic=False): """Initializes Lumpy. Args: debug: boolean that makes the outlines of the frames visible. pedantic: boolean whether to show aliasing for simple values. If pedantic is false, simple values are replicated, rather than, for example, having all references to 1 refer to the same int object. """ Gui.__init__(self, debug) self.pedantic = pedantic self.withdraw() # initially there is no object diagram, no class diagram # and no representation of the stack. self.od = None self.cd = None self.stack = None # instance_vars maps from classes to the instance vars # that are drawn for that class; for opaque classes, it # is an empty list. # an instance of an opaque class is shown with a small empty box; # the contents are not shown. self.instance_vars = {} # the following classes are opaque by default self.opaque_class(Lumpy) self.opaque_class(object) self.opaque_class(type(make_thing)) # function self.opaque_class(Exception) self.opaque_class(set) # I don't remember why # any object that belongs to a class in the Tkinter module # is opaque (the name of the module depends on the Python version) self.opaque_module(TKINTER_MODULE) # by default, class objects and module objects are opaque classobjtype = type(Lumpy) self.opaque_class(classobjtype) modtype = type(inspect) self.opaque_class(modtype) # the __class__ of a new-style object is a type object. # when type objects are drawn, show only the __name__ self.opaque_class(type) self.make_reference()
def __init__(self, ast): self.gui = Gui() self.ast = ast self.form_name = ast.name self.values = [] self.trueExpressions = {} self.submitButtonShown = False self.labels = {} self.textBoxes = {} self.yesNoButtons = {} self.yesNoButtonsValues = {} self.parseStatements(ast)
def appProcess(inputQueeuChannel, outputQueeuChannel, eventLoop, clipboard): appState = AppState() put(outputQueeuChannel, appState.requestAddr()) windowState = Gui() # waitingD terminate = False itera = 0 step = time.time() # temporal solution while not (terminate): # print itera itera += 1 # for debuging windowState.updateWindowsAndDraw(appState) eventLoop.processEvents( QtCore.QEventLoop.WaitForMoreEvents ) # trigger the all the gui changes and blocks waiting for input, therefore, it is CRITICAL, # that whenever a new set of elements are added to the queeu, a void event is feeded into the # event loop, just to awake the thread. # For safety reasons, only a QThread can concurrently feed the event loop, therefore, the thread # adding element to the Queue shall be a QThread instead of a normal Thread if windowState.copy_to_clipboard: clipboard.setText(appState.lastAddr) windowState.copy_to_clipboard = False guiValue, terminate = windowState.getValues() if not guiValue is None: print guiValue commtValue = non_blocking_get(inputQueeuChannel) appState.updateAppState(commtValue) output = appState.getValues(guiValue) if terminate is True: put(outputQueeuChannel, None) else: if output != None: # we pass a None as termination signal put(outputQueeuChannel, output) if (time.time() - step >= 15) or ( not (windowState.payment is None) ): # While not async updates we have to poll :( step = time.time() # TODO: "Delete this and refactoorrrr" put(outputQueeuChannel, appState.getValues(("RE_SCAN", None)))
def run(): l = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) gobject.threads_init() gtk.gdk.threads_init() if hildonize.IS_FREMANTLE_SUPPORTED: hildonize.set_application_name("FMRadio") else: hildonize.set_application_name(constants.__pretty_app_name__) gui = Gui() controller = Player(ui = gui) gui.controller = controller gui.load_settings() gtk.main()
def main(): Input_box_lambda print("lamGen= %d" % globcfg.lamGen) print("lamRW= %d" % globcfg.lamRW) Button print("Priority: %s" % globcfg.priority) book = Book.Book() g = Gui() generator = SystemControl.Generator(book, g) scheduler = SystemControl.Scheduler() generator.start() scheduler.start() # start Gui g.animation(50, 50, 5)
def __init__(self, delay=0.5, *args, **kwds): Gui.__init__(self, *args, **kwds) self.delay = delay self.title('World') # keep track of the most recent world World.current_world = self # set to False when the user presses quit. self.exists = True # list of animals that live in this world. self.animals = [] # if the user closes the window, shut down cleanly self.protocol("WM_DELETE_WINDOW", self.quit)
def main(): """ The condition will defined if you want start in terminal, with the module GameManager or with in graphic version with the module Gui. To allow you to choose the version in shell, a argument "-g" is adding for the graphic version. """ laby = Labyrinth('labyrinth.txt') if args.gui: gui = Gui(laby) gui.launch_game() else: gamer = GameManager(laby) gamer.launch_game()
def search(self, moves, game_state, player_order): self.tree = [] self.init_game_state = game_state self.init_moves = moves self.player_order = player_order state = self.init_game_state parent = None f_move = None act_id = self.id moves_dict = self.get_pre_prob(state, self.init_moves, self.id, self.player_order) i_r = Instant_reward() root_node = Node(state, parent, f_move, moves_dict, act_id, i_r, self.tree) self.root_node = root_node self.time_monitor = defaultdict(float) start = time.time() n = 0 # while n<= 4: # while True: nodes_len = 5 * (2**(len(moves)**(1 / 2))) while n < nodes_len: #a = input('input') n += 1 self.one_search(root_node) print('searched times', n) print('nodes:', len(self.tree)) print('MCTS search finished') print('seach duration', time.time() - start) print('distribute', self.time_monitor) print() # for m,(c, p) in root_node.moves.items(): # print(m[1], m[2], p, (c.value, get_max_difference(c.value, self.id)) if c is not None else ()) dict = {} for m, (c, p) in root_node.moves.items(): Q = get_max_difference(c.value, self.id) if c is not None else -1000 dict[m] = Q move = randomMax(dict) track = self.get_predict_track(root_node, move) # print('track:') # for t in track: # print(t) # for i, plr in enumerate(state.players): # row_score, column_score, set_score, left_score = eval(self.agent.using_reward)(state, i, # self.player_order).get_round_expection() # print(row_score, column_score, set_score, left_score) if USING_GUI: Gui(self.tree) return move
class MenuPrincipal(): """Menu principal de jogo""" def __init__(self, central): """Cria o menu com seus textos e botoes""" self.gui = Gui() self.fundo = "fundo.png" #self.mouse = RatazanaSimples(self, 0, 0) #titulo = Texto("L I X O !", tamanho=30, img_botao="botao.png") #titulo.alt_cor(128, 128, 0) #titulo.posicionar(512, 128) #self.adi(titulo) bot_iniciar = BotaoAnimado(central.comecar_jogo, texto="Iniciar!", img_botao="iniciar.png", linha=0) bot_iniciar.posicionar(400, 384) bot_iniciar.alt_cor(0, 255, 0) self.adi(bot_iniciar) #bot_aju = BotaoAnimado(central.ajuda, texto="Ajuda", # img_botao="ajuda.png", linha=1) # bot_aju.posicionar(512, 384) # bot_aju.alt_cor(0, 0, 255) # self.adi(bot_aju) bot_sair = BotaoAnimado(sys.exit, texto="Sair", img_botao="sair.png", linha=2) bot_sair.posicionar(650, 384) bot_sair.alt_cor(255, 0, 0) self.adi(bot_sair) pygame.mouse.set_visible(False) def comecar(self, janela): """Faz a janela mostrar esse menu""" janela.alt_mundo(self) janela.alt_fundo(self.fundo) def adi(self, coisa): """Adiciona alguma coisa na Gui""" self.gui.adi(coisa) def rem(self, coisa): """Remove algo da Gui""" self.gui.rem(coisa) def atualizar(self, m_pos, clique, m_pressi): """Atualiza menu verificando posicao e clique do mouse""" self.gui.atualizar(m_pos, clique) #self.mouse.atualizar(m_pos, clique, m_pressi) def desenhar(self, superf): """Desenha menu e mouse""" self.gui.desenhar(superf)
def __init__(self, args=['']): Gui.__init__(self) self.parse_args(args) self.namer = Namer() self.locals = sim_locals self.globals = sim_globals self.views = {} self.w = self self.threads = [] self.running = False self.delay = 0.2 self.setup() self.run_init() for col in self.cols: col.create_thread()
def sectionMenu(self): for section in Parser().sections( self.fetchData("/%s/video" % (self.LANGUAGE))): Gui().drawItem(section['title'], 'openSection', section['link'], section['image']) Gui().drawItem(self.localize('< Search Everywhere >'), 'searchAll', image=self.ROOT + '/resources/media/icons/search.png') Gui().drawItem(self.localize('< Search User Page >'), 'searchUser', image=self.ROOT + '/resources/media/icons/search_user.png') if self.__settings__.getSetting("auth"): Gui().drawItem(self.localize('< User Bookmarks >'), 'openSearch', '/buffer', self.ROOT + '/resources/media/icons/bookmarks.png') Gui().drawItem(self.localize('< User Logout >'), 'logoutUser', image=self.ROOT + '/resources/media/icons/logout.png') else: Gui().drawItem(self.localize('< User Login >'), 'loginUser', image=self.ROOT + '/resources/media/icons/login.png') Gui().lockView('info')
def plot_graph(self) -> None: """ Plots the graph. If the nodes have a position, the nodes will be placed there. Otherwise, they will be placed in a random but elegant manner. :param self: getting the self of this class :return: None """ Gui(self.graph)
def __init__(self, ql_ast, qls_ast=None): self.gui = Gui() self.ql_ast = ql_ast self.qls_ast = qls_ast self.frame_order = [] self.rendered_frame_order = [] self.frame_counter = 0 self.done_rendering = False self.parseQLAST(ql_ast) if qls_ast: self.QLSBuilder = QLSGuiBuilder(self.gui, qls_ast) self.frame_order = self.QLSBuilder.parseQLSAST(self.frame_order) self.renderWidgets() self.rendered_frame_order = self.frame_order self.frame_order = []
def __init__(self, filename=None): Gui.__init__(self) #self.geometry('1260x800+74+32') self.filename = filename self.namer = Namer() self.locals = sim_locals self.globals = sim_globals self.views = {} self.w = self self.threads = [] self.running = False self.delay = 0.2 self.setup() self.run_init() for col in self.cols: col.create_thread()
class Converter(): def __init__(self): self.api_key = 'YOUR-API-KEY' self.gui = Gui() self.gui.show() self.getSymbols() self.gui.convertButton.clicked.connect(self.getComboBoxFrom) self.gui.convertButton.clicked.connect(self.getComboBoxTo) self.gui.convertButton.clicked.connect(self.getValueBefore) self.gui.convertButton.clicked.connect(self.convertVal) # Getting currency symbols from API def getSymbols(self): url = fr'https://free.currconv.com/api/v7/currencies?apiKey={self.api_key}' request = requests.get(url) result = request.json() resultList = list(result.items()) resultDict = resultList[0][1] listOfSymbols = [] for key in resultDict.keys(): listOfSymbols.append(key) self.gui.fromCurrency.addItems(listOfSymbols) self.gui.toCurrency.addItems(listOfSymbols) def getComboBoxFrom(self): return self.gui.fromCurrency.currentText() def getComboBoxTo(self): return self.gui.toCurrency.currentText() def getValueBefore(self): return self.gui.valueBefore.text() def convertVal(self): cur1 = self.getComboBoxFrom() cur2 = self.getComboBoxTo() val = self.getValueBefore() url = fr'https://free.currconv.com/api/v7/convert?apiKey={self.api_key}&q={cur1}_{cur2}&compact=y' request = requests.get(url) result = request.json() resultList = list(result.items()) resultDict = resultList[0][1].get('val') calculatedVal = float(val) * resultDict self.gui.valueAfter.setText(str(calculatedVal))
def __init__(self, args=['']): Gui.__init__(self) self.parse_args(args) self.namer = Namer() self.locals = SIM_LOCALS self.globals = SIM_GLOBALS # views is a map from a variable name to the row that # should be updated when the variable changes self.views = {} self.w = self self.threads = [] self.running = False self.delay = 0.2 self.setup() self.run_init() for col in self.cols: col.create_thread()
def __init__(self): self.my_db = Database('ega.db','user.db') self.c = {} root = Tk() root.geometry("800x300+100+100") self.my_gui = Gui(self, root) root.mainloop()
def openPage(self, params={}): get = params.get content = self.fetchData(urllib.unquote_plus(get("url"))) self.__settings__.setSetting("lastContent", content) artistMenu = re.compile( "<div class=\"pg_menu\">.*?<a.+?</a>.*?<a(.+?)>.+?</div>", re.DOTALL).search(content) if artistMenu: if re.compile("class=\"active\"").search(artistMenu.group(1)): pass else: anchor = re.compile("href=\"(/view/\d+)\"").search( artistMenu.group(1)) if anchor.group(1): params.update({'url': urllib.quote_plus(anchor.group(1))}) return self.openPage(params) fileId = Parser().fileId(content) details = Parser().details(content) if details and fileId: if Parser().flv(content): Gui().drawItem(self.localize('FLV Playlist'), 'playFLV', '', self.ROOT + '/resources/media/icons/flash.png', False) if Parser().m3u(content): Gui().drawItem(self.localize('M3U Playlist'), 'playM3U', '', self.ROOT + '/resources/media/icons/video.png', False) comments = re.compile( "<a href='(/view_comments/\d+).+?(\d+)</a>").search(content) if comments: Gui().drawDetails( details, Parser().comments(self.fetchData(comments.group(1))), comments.group(2)) else: Gui().drawDetails(details, {}, 0) if self.__settings__.getSetting("auth"): Gui().drawItem( self.localize('Leave\nComment'), 'leaveComment', fileId, self.ROOT + '/resources/media/icons/comment.png', False) Gui().drawItem( self.localize('To My\nPage'), 'toMyPage', fileId, self.ROOT + '/resources/media/icons/add_to_user_page.png', False) Gui().drawItem( self.localize('To My\nBookmarks'), 'toBookmarks', fileId, self.ROOT + '/resources/media/icons/add_bookmark.png', False) Gui().lockView('icons') else: params.update({'contentReady': True}) self.openSection(params)
def run(self): self.write2csv([f"Session started: {datetime.now()}" ]) #timestamping session self.write2csv(self.metadata) # writing headers while True: gui = Gui(self.apiKey, self.metadata, self.debugOn) if gui.data['Quit'] == True: # checking to see if Quit thing works break else: row = self.constructRow(gui.data) self.write2csv(row)
def __init__(self): #Boiler Plate Loading and setting of Variables self.__location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) self.fcat = os.path.join(self.__location__, 'images/sprites/catmandoRight.png') self.fcatleft = os.path.join(self.__location__, 'images/sprites/catmandoLeft.png') self.fman = os.path.join(self.__location__, 'images/sprites/kramer_sprites.png') self.fmanleft = os.path.join(self.__location__, 'images/sprites/kramer_sprites_left.png') self.fwiz = os.path.join(self.__location__, 'images/sprites/wizzardRight.png') self.fwizleft = os.path.join(self.__location__, 'images/sprites/wizzardLeft.png') self.lives = os.path.join(self.__location__, 'images/lives.png') self.error = os.path.join(self.__location__, 'images/sprites/error.png') self.load = os.path.join(self.__location__, 'images/loading.png') self.loading = simplegui._load_local_image(self.load) self.back = os.path.join(self.__location__, 'images/1280x720GameBackground.png') self.background = simplegui._load_local_image(self.back) self.level = 0 self.player = Player(self.fcat, self.fcatleft, 16, 16) self.keyboard = KeyBoard() self.enemies = [] self.gui = Gui(self.lives, self.lives, 1, 1, self.player) self.counter = 0 self.gameOver = False # Load from correct directories to work on all systems. __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) soundeffect = os.path.join(__location__, 'Sounds/bensound-jazzyfrenchy.ogg') self.music1 = simplegui._load_local_sound(soundeffect) soundeffect = os.path.join(__location__, 'Sounds/bensound-theelevatorbossanova.ogg') self.music2 = simplegui._load_local_sound(soundeffect) soundeffect = os.path.join( __location__, 'Sounds/Captive_Portal_-_03_-_An_Example_For.ogg') self.music3 = simplegui._load_local_sound(soundeffect) self.interaction = Interaction(self.player, self.keyboard, self.enemies, self.gui) self.frame = simplegui.create_frame("Catmando", WIDTH, HEIGHT) self.frame.set_draw_handler(self.draw) self.frame.set_keydown_handler(self.keyboard.keyDown) self.frame.set_keyup_handler(self.keyboard.keyUp)
class Facade: def __init__(self): self.analisis = Analisis() self.generarDatos = FuenteDatos() self.vistaControlador = VistaControlador(self.generarDatos) self.mainWindow = Gui(self.vistaControlador) def iniciarBot(self): seniales = self.analisis.analisisMediasMoviles( [("AAPL", self.generarDatos.apple), ("MSFT", self.generarDatos.microsoft), ("GOOG", self.generarDatos.google), ("FB", self.generarDatos.facebook), ("TWTR", self.generarDatos.twitter), ("NFLX", self.generarDatos.netflix), ("AMZN", self.generarDatos.amazon), ("YHOO", self.generarDatos.yahoo), ("GE", self.generarDatos.ge), ("QCOM", self.generarDatos.qualcomm), ("IBM", self.generarDatos.ibm), ("HPQ", self.generarDatos.hp)], fast=20, slow=50) bk = self.analisis.backtest(seniales, 1000000) self.mainWindow.setDatosGrilla(bk) self.mainWindow.setGraficaPortafolio(bk) #self.mainWindow.setResultados(bk) self.mainWindow.iniciar()
def openSection(self, params={}): get = params.get url = urllib.unquote_plus(get("url")) if 'True' == get("contentReady"): videos = self.__settings__.getSetting("lastContent") if 0 == len(Parser().sections(videos)): videos = self.fetchData(url) else: videos = self.fetchData(url) originalId = Parser().originalId(videos) if originalId: Gui().drawItem(self.localize('< Search >'), 'openSearch', originalId, self.ROOT + '/resources/media/icons/search.png') else: Gui().drawItem(self.localize('< Search >'), 'openSearch', re.search("(\d+)$", url).group(1), self.ROOT + '/resources/media/icons/search.png') for section in Parser().sections(videos): contextMenu = [( self.localize('Search Like That'), 'XBMC.Container.Update(%s)' % ('%s?action=%s&url=%s&like=%s' % (sys.argv[0], 'openSearch', re.search("(\d+)$", url).group(1), urllib.quote_plus(section['title']))))] xbmc.log('%s: url %s' % (sys.argv[0], section['link']), xbmc.LOGNOTICE) description = self.openPage2(section['link']) Gui().drawItem(section['title'], 'openPage', section['link'], section['image'], contextMenu=contextMenu, fanart=True, description=description) Gui().drawPaging(videos, 'openSection') xbmcplugin.setContent(int(sys.argv[1]), 'movies') Gui().lockView('info_big')
def __init__(self): super(MainWindow, self).__init__() self.media_object = None self.current_time = 0 self.totalTime = "00:00:00" self.audioOutput = Phonon.AudioOutput(Phonon.VideoCategory, self) self.media_object = Phonon.MediaObject(self) self.videoUI = QtGui.QWidget() self.videoWidget = Phonon.VideoWidget(self.videoUI) Phonon.createPath(self.media_object, self.videoWidget)#link media source with video output self.media_object.setTickInterval(1000) #1 milliseconds self.setWindowTitle("A^2_Player") self.setMinimumSize(500, 500) Phonon.createPath(self.media_object, self.audioOutput)#link media source with audio output self.media_object.stateChanged.connect(self.stateChanged) self.media_object.currentSourceChanged.connect(self.sourceChanged) self.media_object.finished.connect(self.finished) self.media_object.tick.connect(self.tick) self.setupActions() self.setupMenus() gui=Gui(self); window=gui.setupUi() self.setCentralWidget(window) self.sources = []
def initGui(self): self.gui = Gui(self.gameLoop) self.gui.activerValiderDeplacement(False) self.gui.activerBarreAugmentation(False) data = {} data["anneeCourante"] = self.modele.anneeCourante data["listePlanetes"] = self.modele.planetes data["nbPlanetesHumain"] = self.modele.getNbPlanetesRace(Races.HUMAIN) data["nbPlanetesGubru"] = self.modele.getNbPlanetesRace(Races.GUBRU) data["nbPlanetesCzin"] = self.modele.getNbPlanetesRace(Races.CZIN) data["selection1"] = None data["selection2"] = None data["flottesHumaines"] = None data["flottes"] = self.modele.flottes self.gui.rafraichir(data)
class Widok(object): def __init__(self, root, kolejka_zdarzen): self._kolejka_zdarzen = kolejka_zdarzen self.root = root self._gui = Gui(self, root) self._gui.pack(side='top', fill='both', expand=True) def wez_makiete(self, makieta): self._gui.update(makieta) def wez_inicjalizujaca_makiete(self, makieta): self._gui.pierwsze_update(makieta) def _obsluz_zamkniecie_gui(self): self._kolejka_zdarzen.put(ZdarzenieKoniec()) self.root.destroy() def obsluz_zdarzenie_oblicz(self): materialA = self._gui._comboBox.get() materialB = self._gui._comboBox2.get() self._kolejka_zdarzen.put(ZdarzenieOblicz(materialA, materialB))
def process_line(self, cols): """ process a line and either produce standard output or accumulate a subtotal to be printed at the end of the report """ # talley credits and debits amount = Decimal(cols[self.amt]) if amount > 0: self.file_credit += amount else: self.file_debit += amount # pull out the date, description and (optional) account date = cols[self.date] desc = cols[self.desc] if self.acct > 0 and cols[self.acct] != "": self.tagged += 1 acct = cols[self.acct] else: acct = None entry = Entry(date, amount, acct, desc) # see if we use rules to produce account/description confirm = False if acct is None and self.rules is not None: (new_entry, confirm) = self.rules.match(date, desc, amount) if new_entry is not None: self.matched += 1 entry.account = new_entry.account entry.description = new_entry.description # maybe we can throw up a GUI and ask the user if self.interactive and (confirm or entry.account is None): gui = Gui(self, entry) new_entry = gui.mainloop() if new_entry is None: # delete this entry return entry.account = new_entry.account entry.description = new_entry.description if entry.account is None: self.unmatched += 1 else: # see if this result should be aggregated key = entry.account if entry.description != "": key += "-" + entry.description if key in self.aggregations: new_entry = self.aggregations[key] entry.amount += new_entry.amount if new_entry.date < entry.date: entry.date = new_entry.date self.aggregations[key] = entry return # check for commas in the description (scare some parsers) if "," in entry.description: sys.stderr.write("WARNING: comma in description (%s: %s)\n" % (entry.date, entry.description)) # see if we need to accumulate output for sorting if self.sort: self.buffered.append(entry) else: self.output.write(entry.str() + "\n")
def displayEndGame(self): self.getTable().hideButtons() Gui.displayEndGame(self)
def updateGrid(self): self.getGrid().buttonClicked.disconnect() Gui.updateGrid(self) self.getGrid().buttonClicked.connect(self.game.selectQuestion)
class Engine: def __init__(self): self.my_db = Database('ega.db','user.db') self.c = {} root = Tk() root.geometry("800x300+100+100") self.my_gui = Gui(self, root) root.mainloop() def doRandom(self): self.i = self.right = self.total = 0 self.wrong_questions = [] self.questions = [x[0] for x in self.my_db.getRandomQuestions()] self.nextQuestion() def doWorstRated(self): self.i = self.right = self.total = 0 self.wrong_questions = [] self.questions = [x[0] for x in self.my_db.getWorstRated()] self.nextQuestion() def doType(self, id_type): self.i = self.right = self.total = 0 self.wrong_questions = [] self.questions = [x[0] for x in self.my_db.getFullType(id_type)] self.nextQuestion() def doExam(self, id_exam): self.i = self.right = self.total = 0 self.wrong_questions = [] self.questions = [x[0] for x in self.my_db.getFullExam(id_exam)] self.nextQuestion() def nextQuestion(self): if self.i < len(self.questions): id_question = self.questions[self.i] question = self.my_db.getSingleQuestion(id_question) self.c["id_question"] = id_question self.c["id_exam"] = question[9] self.c["solution"] = question[6] self.i += 1 self.my_gui.setQuestion(question) else: if self.total == 10: self.my_db.insertScore(self.right) self.my_gui.launchPopup(self.doWrong) def doWrong(self): self.questions = list(set(self.wrong_questions)) self.i = self.right = self.total = 0 self.my_gui.setStatusBar(str(self.right) + " / " + str(self.total)) self.wrong_questions = [] self.nextQuestion() def questionCallback(self, sel_option): c = self.c if not c["id_question"] in self.wrong_questions: self.total += 1 if c["solution"] == sel_option: self.right += 1 else: self.wrong_questions.append(c["id_question"]) self.my_gui.setStatusBar(str(self.right) + " / " + str(self.total)) self.my_db.updateQuestion(c["id_question"], c["id_exam"], (c["solution"] == sel_option)) if c["solution"] == sel_option: self.nextQuestion()
class MainWindow(QtGui.QMainWindow): #Flags flag_b=False loop_flag =False bookmark_flag =True video_name = 'xyz' visible=True time =0 current_time=0 playing = False; name_dict={} download=1 #Constructor def __init__(self): super(MainWindow, self).__init__() #Child Class To Handle Toolbar class Widget1(Phonon.VideoWidget): outer_self= self tempWidget = QtGui.QWidget() def __init__(self): super(Widget1,self).__init__() def resizeEvent(self, event): self.tempWidget.setParent(self) self.tempWidget.setGeometry(0,self.height()-50,self.width(),50) def mouseMoveEvent(self,event): if(self.tempWidget.isHidden()): self.tempWidget.show() QtCore.QTimer.singleShot(10000,self.tempWidget.hide) def mouseDoubleClickEvent(self,event): if self.isFullScreen(): self.setFullScreen(False) self.outer_self.show() self.outer_self.gui.btn_fscr.setIcon(QtGui.QIcon.fromTheme("view-fullscreen")) self.tempWidget.show() else: self.setFullScreen(True) self.outer_self.hide() self.outer_self.gui.btn_fscr.setIcon(QtGui.QIcon.fromTheme("view-restore")) self.tempWidget.hide() #Intiazling Variables self.media_object = None self.current_time = 0 self.totalTime =QtCore.QTime((int(00 / 3600000) % 24), int((00 / 60000) % 60), int((00 / 1000) % 60)) #Adding Audio to phonon self.audioOutput = Phonon.AudioOutput(Phonon.VideoCategory, self) self.media_object = Phonon.MediaObject(self) self.videoWidget = Widget1() Phonon.createPath(self.media_object, self.videoWidget) self.media_object.setTickInterval(1000) #1 milliseconds self.setWindowTitle("A^2_Player") self.setMinimumSize(500, 500) Phonon.createPath(self.media_object, self.audioOutput)#link media source with audio output #Connecting Method for various Action self.media_object.stateChanged.connect(self.stateChanged) self.media_object.currentSourceChanged.connect(self.sourceChanged) self.media_object.finished.connect(self.finished) self.media_object.tick.connect(self.tick) #setting up Gui self.setupActions() self.setupMenus() self.gui=Gui(self); window=self.gui.setupUi() self.setCentralWidget(window) self.sources = [] #Fired after every one sec to update the label def tick(self, time): displayTime = QtCore.QTime((time / 3600000) % 24, (time / 60000) % 60, (time / 1000) % 60) self.timeLabel.setText(displayTime.toString("HH:mm:ss")+"/"+self.totalTime.toString("HH:mm:ss")) if not self.flag_b: self.current_time = time #Fired Whenever State is Changed def stateChanged(self, newState, oldState): if newState == Phonon.ErrorState: if self.media_object.errorType() == Phonon.FatalError: QtGui.QMessageBox.warning(self, "Fatal Error", self.media_object.errorString()) else: QtGui.QMessageBox.warning(self, "Error", self.media_object.errorString()) elif newState == Phonon.PlayingState: self.playAction.setEnabled(False) self.pauseAction.setEnabled(True) self.stopAction.setEnabled(True) self.computeAction.setEnabled(True) self.fullScrAction.setEnabled(True) self.seek_backward.setEnabled(True) self.seek_forward.setEnabled(True) self.totalTime = QtCore.QTime((int(self.media_object.totalTime() / 3600000) % 24), int((self.media_object.totalTime() / 60000) % 60), int((self.media_object.totalTime() / 1000) % 60)) displayTime = QtCore.QTime((self.current_time / 3600000) % 24, (self.current_time / 60000) % 60, (self.current_time / 1000) % 60) self.timeLabel.setText(displayTime.toString("HH:mm:ss")+"/"+self.totalTime.toString("HH:mm:ss")) self.playing = True print ("playing") self.media_object.seek(self.current_time) elif newState == Phonon.StoppedState: self.stopAction.setEnabled(False) self.playAction.setEnabled(True) self.gui.btn.setEnabled(True) self.gui.btn.setIcon(QtGui.QIcon.fromTheme("media-playback-pause")) self.pauseAction.setEnabled(False) self.playing=False print("stopping") if not self.flag_b: self.current_time = 0 self.computeAction.setEnabled(False) self.fullScrAction.setEnabled(True) self.flag_b=False elif newState == Phonon.PausedState: self.pauseAction.setEnabled(False) self.stopAction.setEnabled(True) self.playAction.setEnabled(True) self.computeAction.setEnabled(True) self.fullScrAction.setEnabled(True) self.playing=False print ("pausing") def sourceChanged(self, source): print("yes") #Playlist Clicked Action def tableClicked(self, item_x,col): self.media_object.stop() self.media_object.clearQueue() self.video_name=item_x.text(col) if item_x.parent() != None: father = item_x.parent() else: father = item_x print(self.videoTable.indexOfTopLevelItem(father)) self.media_object.setCurrentSource(self.sources[self.videoTable.indexOfTopLevelItem(father)]) self.media_object.play() self.videoTable.setCurrentItem(item_x) self.timeLabel.setText("00:00:00/00:00:00") self.current_time = 0 self.time=0 #if playing currently, continue playing the click one if item_x.parent() != None: child_idx = item_x.parent().indexOfChild(item_x) bmark_file = open(self.name_dict[item_x.parent().text(0)]+".txt","r") idx =0; for line in bmark_file: if idx == child_idx: ##print "Yes" self.name = str(line) break idx = idx+1 idx = 0; while(self.name[idx] != '('): idx = idx+1 self.current_time = int(self.name[(idx+1):-2]) self.flag_b=True #Setting Up Action def setupActions(self): self.playAction = QtGui.QAction( self.style().standardIcon(QtGui.QStyle.SP_MediaPlay), "Play", self, shortcut="Space", enabled = True, triggered = self.media_object.play) self.playAction.toggle() self.pauseAction = QtGui.QAction( self.style().standardIcon(QtGui.QStyle.SP_MediaPause), "Pause", self, shortcut="Space", enabled=False, triggered = self.media_object.pause) self.stopAction = QtGui.QAction( self.style().standardIcon(QtGui.QStyle.SP_MediaStop), "Stop", self, shortcut="Ctrl+S", enabled=False, triggered = self.media_object.stop) self.computeAction = QtGui.QAction( self.style().standardIcon(44), "Stop", self.videoWidget, shortcut="Esc", enabled=False, triggered=self.compute) self.loopAction = QtGui.QAction("Loop", self,shortcut = "Ctrl+R",enabled = True, triggered = self.loop ) self.bookmarkAction = QtGui.QAction("bookmark", self,shortcut="Ctrl+B", enabled=True, triggered=self.bookmark_function) self.downloadAction = QtGui.QAction("download", self,shortcut="Ctrl+D", enabled=True, triggered=self.download_function) self.downloadAction.setCheckable(True) self.downloadAction.setChecked(True) self.loopAction.setCheckable(True) self.loopAction.setChecked(False) self.speedAction = QtGui.QAction( self.style().standardIcon(45),"Speed", self,shortcut='[',enabled = True, triggered = self.speed_fun) self.playlistAction = QtGui.QAction("Playlist", self,shortcut='Ctrl+P',enabled = True, triggered = self.playlist_fun) self.fullScrAction = QtGui.QAction("FullScreen", self,shortcut="F11", enabled=False, triggered=self.compute) self.seek_forward= QtGui.QAction( self.style().standardIcon(QtGui.QStyle.SP_ToolBarVerticalExtensionButton), "Forward", self, enabled=False, triggered=self.forward) self.seek_backward = QtGui.QAction( self.style().standardIcon(QtGui.QStyle.SP_ToolBarVerticalExtensionButton), "Backward", self, enabled=False, triggered=self.backward) self.seek_forward.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Right)) self.seek_backward.setShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Left)) self.addFilesAction = QtGui.QAction("Open", self, shortcut = "Ctrl+F", triggered = self.magic) self.exitAction = QtGui.QAction("Exit", self, shortcut="Ctrl+X", triggered = self.close) self.aboutAction = QtGui.QAction("About", self, shortcut = "Ctrl+i", triggered = self.about) #Returning File Name def get_file_name(self, file_path): slash = file_path.rfind('/') file_name = file_path[slash +1 : ] return file_name #Seeking Forward def forward(self): self.current_time = (self.current_time+10000)%self.media_object.totalTime() self.media_object.seek(self.current_time) #Seeking Backward def backward(self): self.current_time = self.current_time-10000 if(self.current_time<0): self.current_time=0 self.media_object.seek(self.current_time) #Handling Download Option def download_function(self): if self.downloadAction.isChecked(): self.download=1 self.downloadAction.setChecked(True) else: self.download=0 self.downloadAction.setChecked(False) #Bookmarking def bookmark_function(self): self.bstart_time=self.current_time self.cur_item = self.videoTable.currentItem() if self.cur_item.parent() !=None: self.cur_item = self.cur_item.parent() b = open(str(self.name_dict[self.cur_item.text(0)]+".txt"),"a+") if self.cur_item.parent() !=None: self.cur_item = self.cur_item.parent() text,ok = QtGui.QInputDialog.getText(self, 'Bookmark Dialog', 'Enter name of bookmark:') if not ok: return self.cur_child = QtGui.QTreeWidgetItem() b.write(text+"("+str(self.bstart_time)+")"+"\n") self.cur_child.setText(0,text) self.cur_item.addChild(self.cur_child) def playlist_fun(self): w = self.gui.splitter.width() if self.visible: self.gui.splitter.setSizes([0,w]) self.visible=False else: self.gui.splitter.setSizes([w/4,3*w/4]) self.visible=True def speed_fun(self): list_of_backend_audio_effects = Phonon.BackendCapabilities.availableAudioEffects() list_of_effect_names = [str(elem.name()) for elem in list_of_backend_audio_effects] speed_effect = Phonon.Effect(list_of_backend_audio_effects[5]) speed_effect.setParameterValue(speed_effect.parameters()[0],QtCore.QVariant(str(2))) self.path.insertEffect(speed_effect) #Handling Play And Pause def play_and_pause(self): if not self.playing: self.media_object.play() self.gui.btn.setIcon(QtGui.QIcon.fromTheme("media-playback-pause")) self.playing = True else: self.media_object.pause() self.gui.btn.setIcon(QtGui.QIcon.fromTheme("media-playback-start")) self.playing = False #Setting Loop Flag def loop(self): if self.loop_flag ==False: self.loop_flag=True else: self.loop_flag=False #Converting File name def convert_file_path(self, file_path): #convert back_slah to slash #self.media_object.currentSouce().fileName() using slash return file_path.replace("\\", "/") #Add files def magic(self): self.files = QtGui.QFileDialog.getOpenFileNames(self,"open", QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MoviesLocation), "Video(*.avi *.mkv *.mp4 *.flv *.wmv);; Audio(*.mp3)") self.addFiles() return #Call Downloading for added files def addFiles(self): files=self.files index = len(self.sources) #Checking For Download option if(self.download): print("downloading") app = QtGui.QWidget() app.show() getSubtitle(files) app.hide() else: print("Not downloading") files_is_empty = True durationItem = None for string in files: self.subtitle_string=string string = self.convert_file_path(string) files_is_empty = False self.sources.append(Phonon.MediaSource(string)) currentRow = self.videoTable.topLevelItemCount() self.media_object.setCurrentSource(self.sources[currentRow]) name = string title = self.get_file_name(name) self.name_dict[title]=string titleItem = QtGui.QTreeWidgetItem() titleItem.setText(0,title) #Setting Up Bookmark File if(os.path.isfile(name+".txt")): bmark_file = open(name+".txt","r") for line in bmark_file: child = QtGui.QTreeWidgetItem() idx = 0 while(line[idx] != '('): idx = idx+1 child.setText(0,line[:idx]) titleItem.addChild(child) self.videoTable.addTopLevelItem(titleItem) if files_is_empty: return if self.sources: print(index) self.media_object.setCurrentSource(self.sources[index]) all_src = self.videoTable.findItems(self.get_file_name(self.sources[index].fileName()),QtCore.Qt.MatchExactly) print (all_src[0].text(0)) self.videoTable.setCurrentItem(all_src[0]) self.timeLabel.setText("00:00:00") self.current_time = 0 self.time=0 self.media_object.play() #About the Devloper def about(self): QtGui.QMessageBox.information(self, "About", "Created By A^2 Team") #Check Looping and set source accordingly def finished(self): if self.loop_flag == False: index = self.videoTable.indexOfTopLevelItem(self.videoTable.currentItem())+1 else: index = self.videoTable.indexOfTopLevelItem(self.videoTable.currentItem()) if index >= len(self.sources): index=0 self.media_object.setCurrentSource(self.sources[index]) all_src = self.videoTable.findItems(self.get_file_name(self.sources[index].fileName()),QtCore.Qt.MatchExactly) self.videoTable.setCurrentItem(all_src[0]) print ("call from finished") self.media_object.play() print ("call returned") #Setting Up MenuBar def setupMenus(self): fileMenu = self.menuBar().addMenu("Menu") fileMenu.addAction(self.addFilesAction) fileMenu.addSeparator() fileMenu.addAction(self.exitAction) optionMenu = self.menuBar().addMenu("Options") optionMenu.addAction(self.fullScrAction) optionMenu.addSeparator() optionMenu.addAction(self.loopAction) optionMenu.addSeparator() optionMenu.addAction(self.bookmarkAction) optionMenu.addSeparator() optionMenu.addAction(self.playlistAction) optionMenu.addSeparator() optionMenu.addAction(self.downloadAction) aboutMenu = self.menuBar().addMenu("Help") aboutMenu.addAction(self.aboutAction) #Handling Fullscreen Feature def compute(self): if self.videoWidget.isFullScreen(): self.videoWidget.setFullScreen(False) self.show() self.gui.btn_fscr.setIcon(QtGui.QIcon.fromTheme("view-fullscreen")) self.videoWidget.tempWidget.show() else: self.videoWidget.setFullScreen(True) self.hide() self.gui.btn_fscr.setIcon(QtGui.QIcon.fromTheme("view-restore")) self.videoWidget.tempWidget.hide() #For Rezing the window def resizing(self): self.gui.tempWidget.setGeometry(0,self.videoWidget.height,600,50)
def destroy(self): """Closes the top window.""" self.running = False Gui.destroy(self)
def __init__(self): Gui.__init__(self) self.title('GraphWorld') self.setup()
def __init__(self, root, kolejka_zdarzen): self._kolejka_zdarzen = kolejka_zdarzen self.root = root self._gui = Gui(self, root) self._gui.pack(side='top', fill='both', expand=True)
class Controleur(): def __init__(self): self.modele = None self.gui = None nbCol = 25 nbLignes = 20 nbPlanete = 35 self.initModele(nbCol, nbLignes, nbPlanete) self.initGui() def initGui(self): self.gui = Gui(self.gameLoop) self.gui.activerValiderDeplacement(False) self.gui.activerBarreAugmentation(False) data = {} data["anneeCourante"] = self.modele.anneeCourante data["listePlanetes"] = self.modele.planetes data["nbPlanetesHumain"] = self.modele.getNbPlanetesRace(Races.HUMAIN) data["nbPlanetesGubru"] = self.modele.getNbPlanetesRace(Races.GUBRU) data["nbPlanetesCzin"] = self.modele.getNbPlanetesRace(Races.CZIN) data["selection1"] = None data["selection2"] = None data["flottesHumaines"] = None data["flottes"] = self.modele.flottes self.gui.rafraichir(data) def initModele(self, nbCols, nbLignes, nbPlanetes): self.modele = Modele(nbCols, nbLignes, nbPlanetes) self.modele.creerPlanetes() def executer(self): """ permet de lancer le GUI """ self.gui.run() def gameLoop(self, userAction, coordinates=None): """ the coordiantes should be tuples """ if userAction == UserActions.VALIDER_DEPLACEMENT: self.validationDeplacement() elif userAction == UserActions.VALIDER_TOUR: self.finTour() elif userAction is UserActions.SELECT_PLANETE or userAction is UserActions.SELECT_PLANETE_2: self.gestionSelectionPlanete(coordinates, userAction) elif userAction == UserActions.FLOTTE_CHANGEMEMT: self.gestionChangementFlotte() # MÉTHODES DE CONTRÔLES PRINCIPALES # def gestionSelectionPlanete(self, coordonnee, userAction): """ Méthode gérant le cas de la sélection d'une planète """ planete = self.modele.getPlaneteAt(coordonnee[0], coordonnee[1]) if not planete: # Si on clique dans le vide if userAction is UserActions.SELECT_PLANETE: self.modele.planeteSelectionnee = None self.gui.resetNombreVaisseaux() self.gui.activerBarreAugmentation(False) self.gui.activerValiderDeplacement(False) else: self.modele.planeteSelectionnee2 = None else: self.inspecterPlanete(planete) if userAction is UserActions.SELECT_PLANETE: self.gestionSelection1(planete) else: self.gestionSelection2(planete) self.rafraichirFlotte() self.rafraichirGui() def gestionSelection1(self, planete): self.modele.planeteSelectionnee = planete if self.modele.planeteSelectionnee.civilisation == Races.HUMAIN: self.gui.nbVaisseauxWidget.configure(to_=planete.nbVaisseaux) activation = True else: activation = False self.gui.resetNombreVaisseaux() self.gui.activerBarreAugmentation(activation) def gestionSelection2(self, planete): self.modele.planeteSelectionnee2 = planete if self.modele.planeteSelectionnee: if self.modele.planeteSelectionnee.civilisation == Races.HUMAIN: self.gui.nbVaisseauxWidget.configure(to_=self.modele.planeteSelectionnee.nbVaisseaux) activation = True else: activation = False self.gui.resetNombreVaisseaux() self.gui.activerBarreAugmentation(activation) def gestionChangementFlotte(self): """ Méthode gérant le cas du changement du nombre de vaisseaux d'une flotte """ if self.gui.getNbVaisseaux() <= 0 or not self.modele.planeteSelectionnee2: activation = False else: activation = True self.gui.activerValiderDeplacement(activation) def rafraichirFlotte(self): depart = self.modele.planeteSelectionnee arrivee = self.modele.planeteSelectionnee2 data = {"planeteDepart": depart, "planeteArrivee": arrivee} if depart and arrivee: data["distance"] = self.modele.calculerDistance(depart, arrivee) else: data["distance"] = None self.gui.rafraichirFlotte(data) def inspecterPlanete(self, planete): """ Inspecte une la planete selon le niveau de connaissance """ if planete.civilisation == Races.HUMAIN: self.gui.inspecterPlanete(planete.nom, planete.posX, planete.posY, planete.nbManufactures, planete.nbVaisseaux) return if planete.nbVisites == 0: self.gui.inspecterPlanete(planete.nom, planete.posX, planete.posY) if planete.nbVisites == 1: self.gui.inspecterPlanete(planete.nom, planete.posX, planete.posY, planete.nbManufactures) if planete.nbVisites == 2: self.gui.inspecterPlanete(planete.nom, planete.posX, planete.posY, planete.nbManufactures) if planete.nbVisites >= 3: self.gui.inspecterPlanete(planete.nom, planete.posX, planete.posY, planete.nbManufactures, planete.nbVaisseaux) def validationDeplacement(self): """ Méthode gérant le cas de la validation d'un déplacement """ # Rafraîchissement du GUI self.rafraichirGui() planeteDepart = self.modele.planeteSelectionnee planeteArrive = self.modele.planeteSelectionnee2 nbVaisseaux = self.gui.getNbVaisseaux() self.modele.ajouterFlotte(planeteDepart, planeteArrive, Races.HUMAIN, nbVaisseaux) self.gui.resetNombreVaisseaux() self.gui.activerBarreAugmentation(False) self.gui.activerValiderDeplacement(False) self.rafraichirGui() def finTour(self): """ Méthode gérant le cas de la fin d'un tour""" self.modele.avancerTemps() self.gestionNotifications() self.rafraichirGui() def rafraichirGui(self): data = {} data["anneeCourante"] = self.modele.anneeCourante data["listePlanetes"] = self.modele.planetes data["nbPlanetesHumain"] = self.modele.getNbPlanetesRace(Races.HUMAIN) data["nbPlanetesGubru"] = self.modele.getNbPlanetesRace(Races.GUBRU) data["nbPlanetesCzin"] = self.modele.getNbPlanetesRace(Races.CZIN) data["selection1"] = self.modele.planeteSelectionnee data["selection2"] = self.modele.planeteSelectionnee2 data["flottes"] = self.modele.flottes self.gui.rafraichir(data) def gestionNotifications(self): """ Permet de gérer les notifications """ notifications = self.modele.notifications for notif in notifications: if isinstance(notif, Affrontement): self.gestionNotifAffrontement(notif) elif isinstance(notif, Annihilation): self.gestionNotifAnnihilation(notif) self.modele.notifications = [] # On vide les notifications def gestionNotifAnnihilation(self, notif): """ Gestion notifications d'annihilation """ self.gui.consoleHumains.annihilation(notif.annee, notif.race) self.gui.consoleEnnemis.annihilation(notif.annee, notif.race) def gestionNotifAffrontement(self, notif): """ Gestion notifications d'affrontement """ isHumainConcernes = False if notif.attaquant is Races.HUMAIN or notif.defenseur is Races.HUMAIN: isHumainConcernes = True # il y eu affrontement if isHumainConcernes: self.gui.consoleHumains.affrontementPlanete(notif.annee, notif.attaquant, notif.defenseur, notif.planete) self.gui.consoleEnnemis.affrontementPlanete(notif.annee, notif.attaquant, notif.defenseur, notif.planete) if notif.isDefenseReussie: # Défense réussie if isHumainConcernes: self.gui.consoleHumains.defensePlanete(notif.annee, notif.defenseur, notif.attaquant, notif.planete) self.gui.consoleEnnemis.defensePlanete(notif.annee, notif.defenseur, notif.attaquant, notif.planete) else: # Défense ratée, perte planète gain pour autre if isHumainConcernes: self.gui.consoleHumains.victoirePlanete(notif.annee, notif.attaquant, notif.planete) self.gui.consoleHumains.pertePlanete(notif.annee, notif.defenseur, notif.attaquant, notif.planete) self.gui.consoleEnnemis.pertePlanete(notif.annee, notif.defenseur, notif.attaquant, notif.planete) self.gui.consoleEnnemis.victoirePlanete(notif.annee, notif.attaquant, notif.planete)
def __init__(self): super(MainWindow, self).__init__() #Child Class To Handle Toolbar class Widget1(Phonon.VideoWidget): outer_self= self tempWidget = QtGui.QWidget() def __init__(self): super(Widget1,self).__init__() def resizeEvent(self, event): self.tempWidget.setParent(self) self.tempWidget.setGeometry(0,self.height()-50,self.width(),50) def mouseMoveEvent(self,event): if(self.tempWidget.isHidden()): self.tempWidget.show() QtCore.QTimer.singleShot(10000,self.tempWidget.hide) def mouseDoubleClickEvent(self,event): if self.isFullScreen(): self.setFullScreen(False) self.outer_self.show() self.outer_self.gui.btn_fscr.setIcon(QtGui.QIcon.fromTheme("view-fullscreen")) self.tempWidget.show() else: self.setFullScreen(True) self.outer_self.hide() self.outer_self.gui.btn_fscr.setIcon(QtGui.QIcon.fromTheme("view-restore")) self.tempWidget.hide() #Intiazling Variables self.media_object = None self.current_time = 0 self.totalTime =QtCore.QTime((int(00 / 3600000) % 24), int((00 / 60000) % 60), int((00 / 1000) % 60)) #Adding Audio to phonon self.audioOutput = Phonon.AudioOutput(Phonon.VideoCategory, self) self.media_object = Phonon.MediaObject(self) self.videoWidget = Widget1() Phonon.createPath(self.media_object, self.videoWidget) self.media_object.setTickInterval(1000) #1 milliseconds self.setWindowTitle("A^2_Player") self.setMinimumSize(500, 500) Phonon.createPath(self.media_object, self.audioOutput)#link media source with audio output #Connecting Method for various Action self.media_object.stateChanged.connect(self.stateChanged) self.media_object.currentSourceChanged.connect(self.sourceChanged) self.media_object.finished.connect(self.finished) self.media_object.tick.connect(self.tick) #setting up Gui self.setupActions() self.setupMenus() self.gui=Gui(self); window=self.gui.setupUi() self.setCentralWidget(window) self.sources = []
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Gerrit Wyen <*****@*****.**>" __license__ = "GNU General Public License v2 or later (GPLv2+)" from Gui import Gui from helper import loadSettings if __name__=="__main__": settings = loadSettings() camgui = Gui(settings) camgui.runMainLoop()
def displayAnswer(self): Gui.displayAnswer(self) self.displayNextQuestionButton()
def __init__(self, title='GraphWorld',width=400,height=400,scaleFactor=20): Gui.__init__(self) self.title(title) self.setup(width,height,scaleFactor)
def __init__(self): Gui.__init__(self) self.title("GraphWorld") self.setup()
def displayQuestion(self, i): Gui.displayQuestion(self, i) Gui.displayAnswer(self) self.displayShowAnswerButton()