def main(): """ Main Routine """ print("\n[.] Initializing parameters/settings for simulator...") print("[.] Values in brackets represent reccommended/tested values.") print("[.] Using untested values may result in unstable behavior.\n") # Ask for parameters user_debug = input("[?] Enable debugging information [No]: ") debug = (user_debug == "Yes") memory_size = input("[?] Size of main memory (bytes) [100]: ") virtual_memory_size = input("[?] Size of virtual memory (bytes) [8000]: ") cache_size = input("[?] Size of cache (bytes)[40]: ") block_size = input("[?] Size of cache blocks (bytes)[4]: ") page_size = input("[?] Size of disk pages (bytes)[32]: ") table_size = input("[?] Number of TLB table entries (bytes)[10]: ") # Initialize components with bus and debug flag bus = Bus(debug) cpu = CPU(debug) cache = Cache(int(cache_size), int(block_size), debug) tlb = TLB(int(table_size), debug) memory = Memory(int(memory_size), int(virtual_memory_size), debug) disk = Disk(int(page_size), debug) # Initialize GUI menu = GUI(bus, cpu, cache, tlb, memory, disk, debug) menu.menu_loop()
def __init__(self): self.history = History() self.colors = Colors() self.gui = GUI() self.start_game() self.gui.master.bind("<Left>", self.left) self.gui.master.bind("<Right>", self.right) self.gui.master.bind("<Up>", self.up) self.gui.master.bind("<Down>", self.down) self.gui.master.bind("a", self.left) self.gui.master.bind("d", self.right) self.gui.master.bind("w", self.up) self.gui.master.bind("s", self.down) self.gui.master.bind("r", self.restart) self.gui.master.bind("q", self.quit) self.gui.master.bind("z", self.undo) self.gui.master.bind("p", self.printall) self.gui.master.bind("i", self.z) self.gui.master.bind("e", self.look) self.gui.master.bind("f", self.agent)
def main(): shnake = Env() player = Player(shnake) player.start() rt1 = RepeatedTimer((shnake.refresh_rate/1000), shnake.step) window = GUI(shnake) window.run()
def main(): gui = GUI(25, 10, 700) gui.init_checkBox() gui.init_button() gui.create_grid() gui.run()
def main(): parser = argparse.ArgumentParser(description='Othello game') parser.add_argument('-c', action='store_true', help='Run othello game in the console, if not specified, will run in GUI') args = parser.parse_args() # Size of the board size = 8 if args.c: # Run in console print("Othello: ") opt = input("Do you want to start first, 'y' or 'n': ") if opt.lower() == 'y': # Player 1 starts first player1 = Player("BLACK", Cell.B) player2 = AI_Random("AI_RANDOM", Cell.W) cs.main(size, player1, player2) elif opt.lower() == 'n': # AI starts first player1 = AI_Random("AI_RANDOM", Cell.B) player2 = Player("WHITE", Cell.W) cs.main(size, player1, player2) else: print("Wrong input, try again, exiting") else: # Run using Tkinter GUI player1 = Player("BLACK", Cell.B) player2 = Player("WHITE", Cell.W) gui = GUI(size, player1, player2) gui.run()
def __init__(self, ip='0.0.0.0', port=8220, save_dir='received\\', debug=False): """ :param ip: the ip of the master :param port: the port of the master socket :param debug: debug mode (True-on, False-off) """ # create a server self.__server = Server( ip=ip, port=port, connection_callback=self.__handle_new_connection, receiving_callback=self.__handle_receiving, disconnect_callback=self.__handle_disconnection, debug=debug) # create a gui self.__gui = GUI(send_callback=self.__handle_sending, debug=debug) # the directory to save all received files self.__save_dir = save_dir # the number of received files self.__file_counter = 0 # debug mode self.__DEBUG = debug
def main(): taso1 = Maailma(MAAILMAN_KOKO) hahmo = Hahmo() taso1.add_hahmo(hahmo) #poistamalla demomaalin kommentin voi testata maaliinpääsemistä helpommin taso1.add_maali(Sijainti(400, 26)) #oikea #taso1.add_maali(Sijainti(665,625)) #demo platform1 = taso1.add_wall(Sijainti(100, 600), 100, 25) platform2 = taso1.add_wall(Sijainti(250, 550), 75, 25) platform3 = taso1.add_wall(Sijainti(375, 500), 50, 25) platform4 = taso1.add_wall(Sijainti(300, 440), 25, 25) platform5 = taso1.add_wall(Sijainti(200, 440), 25, 25) platform6 = taso1.add_wall(Sijainti(100, 440), 25, 25) platform7 = taso1.add_wall(Sijainti(25, 350), 50, 25) platform8 = taso1.add_wall(Sijainti(100, 300), 500, 25) platform9 = taso1.add_wall(Sijainti(400, 75), 75, 25) platform10 = taso1.add_wall(Sijainti(200, 150), 25, 150) platform11 = taso1.add_wall(Sijainti(125, 200), 5, 5) platform12 = taso1.add_wall(Sijainti(525, 225), 25, 25) platform13 = taso1.add_wall(Sijainti(625, 175), 25, 25) platform14 = taso1.add_wall(Sijainti(523, 150), 25, 25) platform15 = taso1.add_wall(Sijainti(375, 25), 25, 75) platform16 = taso1.add_wall(Sijainti(225, 299), 100, 20) platform17 = taso1.add_wall(Sijainti(200, 674), 175, 20) platform16.make_ansa() platform17.make_ansa() app = QApplication(sys.argv) gui = GUI(taso1, taso1.esteet, app) gui.activate_exit() sys.exit(app.exec_())
def __init__(self): self.thread = None self.reload = False # Time variables self.time_cycle = 80 self.ideal_cycle = 80 self.iteration_counter = 0 self.frequency_message = {'brain': '', 'gui': ''} self.server = None self.client = None self.host = sys.argv[1] # Initialize the GUI, HAL and Console behind the scenes self.console = console.Console() self.hal = HAL() self.gui = GUI(self.host, self.console, self.hal) # initialize Teleoperation variables self.teop = False self.speedV = 0.3 self.speedW = 0.5 self.stop = 0 self.key = None self.flag = 0 self.pattern_V = 'HAL.motors.sendV' self.pattern_W = 'HAL.motors.sendW'
def __init__(self, datasets_root, seed): sys.excepthook = self.excepthook self.seed = seed self.datasets_root = datasets_root self.recognized_datasets = [] self.utterances = set() self.current_generated = (None, None, None, None ) # speaker_name, mel, breaks, wav self.speaker_filepathes = defaultdict(set) self.audio_ext = {'.wav', '.flac', '.mp3'} for datafolder in utils.data.get_subdirs(datasets_root): self.load_dataset_info(os.path.join(self.datasets_root, datafolder)) self.engine = None # type: VC self.current_src_utt = None self.current_tgt_utts = None self.current_tgt_spk = None self.loaded_utts = [] self.conv_utts_list = [] self.conv_utts_idlist = [] self.self_record_count = 0 self.trim_silences = True # Initialize the events and the interface self.ui = GUI() self.reset_ui(seed) self.setup_events() self.ui.start()
def main(): # Initialise screen and sound pygame.init() pygame.mixer.pre_init(22050, -16, 2, 512) # Small buffer for less sound lag screen = pygame.display.set_mode((RESOLUTION_X, RESOLUTION_Y)) pygame.display.set_caption('Switch & If') # Initialise Data structures and engine objects unit_roster = {"Players": [], "Enemies": []} maps = Maps(screen) # Enter menu screen to collect needed info to generate rest of objects menu_screen(screen)(screen, unit_roster, maps) gui = GUI(screen, unit_roster) script = Script(unit_roster, maps, screen) engine = ENGINE(screen, gui, unit_roster, maps, script) #init gui interface gui.draw(unit_roster) # Event loop while 1: for event in pygame.event.get(): if event.type == QUIT: return #Main Events engine.update_logic() engine.update_draw()
def main(): gfx = Video() inp = Input() gui = GUI() # Initialize try: gfx.initialize() inp.initialize() gui.initialize() except InitializationError as error: print(error) return 1 # Setup the interface gui.setupInterface() # Main Loop gfx.enterMainLoop() # Done # - We will never actually get here. gfx.shutdown() return 0
def StartInfoActions(infos, params): if "artistname" in params: params["artistname"] = params.get("artistname", "").split(" feat. ")[0].strip() params["artist_mbid"] = fetch_musicbrainz_id(params["artistname"]) prettyprint(params) prettyprint(infos) if "prefix" in params and (not params["prefix"].endswith('.')) and (params["prefix"] is not ""): params["prefix"] = params["prefix"] + '.' # NOTICE: compatibility for info in infos: # data = [] if info == 'venueinfo': HOME.setProperty('infodialogs.active', "true") dialog = LastFMDialog(u'script-%s-dialog.xml' % (ADDON_NAME), ADDON_PATH, venueid=params.get("id", ""), name=params.get("name", "")) dialog.doModal() HOME.clearProperty('infodialogs.active') elif info == 'eventinfo': HOME.setProperty('infodialogs.active', "true") dialog = LastFMDialog(u'script-%s-dialog.xml' % (ADDON_NAME), ADDON_PATH, eventid=params.get("id", ""), name=params.get("name", "")) dialog.doModal() HOME.clearProperty('infodialogs.active') elif info == "map": gui = GUI(u'script-%s-main.xml' % ADDON_NAME, ADDON_PATH) gui.doModal() del gui
def eventFilter(self, obj, e): """ Adds any event listeners required by the window. """ window = self._window # Sanity check. if obj is not window.control: return False if e.type() == QtCore.QEvent.Close: # Do not destroy the window during its event handler. GUI.invoke_later(window.close) if window.control is not None: e.ignore() return True if e.type() == QtCore.QEvent.WindowActivate: window.activated = window elif e.type() == QtCore.QEvent.WindowDeactivate: window.deactivated = window elif e.type() == QtCore.QEvent.Resize: # Get the new size and set the shadow trait without performing # notification. size = e.size() window._size = (size.width(), size.height()) elif e.type() == QtCore.QEvent.Move: # Get the real position and set the trait without performing # notification. Don't use event.pos(), as this excludes the window # frame geometry. pos = window.control.pos() window._position = (pos.x(), pos.y()) elif e.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = e.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = e.modifiers() window.key_pressed = KeyPressedEvent( alt_down=((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down=(( mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down=( (mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code=kcode, event=e) return False
def __init__(self): ''' Instantiates the application ''' # Open and load configuration data with Path('./config.json').open('r') as f: config = json.load(f) try: const.ADMIN_EMAIL = config['admin_email'] const.FREE_PARKING_LIMIT = config['free_parking_limit'] const.PAYMENT_LIMIT = config['payment_limit'] const.PARKING_RATE = config['parking_rate'] const.BITCOIN_ADDR = config['bitcoin_addr'] except KeyError: print("Bad config file") sys.exit(0) # Instantiate modules self.gui = GUI() self.payments = Payments() self.sensors = SensorHandler() self.parking_start_time = None self.parking_end_time = None # Initial State SV.state = State.EMPTY
def __init__(self): """Creates a GUI for the image trainer.""" GUI.__init__(self) self.__previous_time = datetime.datetime.now() self.__user = os.environ.get("USERNAME") self.__computer = os.environ.get("COMPUTERNAME") self.__database_filepath = DEFAULT_DATABASE_FILEPATH self.__application = ImageRecognition(self.__database_filepath) self.__init_assets() self.__init_config() self.__init_menu() self.__init_widgets() self.__init_shortcuts() self.load_image(self.__application.get_next_image()) # Assign Row Weights for i in range(5): if i == 2: continue else: self.grid_rowconfigure(i, weight=1) # Assign Column Weights for i in range(10): self.grid_columnconfigure(i, weight=1) self.show()
class Controller(object): def __init__(self): dispatcher.connect(self.handle_image_load_event, signal='load_image', sender=dispatcher.Any) dispatcher.connect(self.handle_filter_event, signal='apply_filter', sender=dispatcher.Any) self.image = None self.im_processor = ImageProcessor() self.user_interface = GUI() self.user_interface.run() def handle_filter_event(self, sender, args): filter_name, params = args if not self.image is None: if filter_name == 'Salt & pepper': self.image = self.im_processor.salt_and_pepper(self.image, params[0]) elif filter_name == 'Median': self.image = self.im_processor.median(self.image, int(params[0])) elif filter_name == 'Average': self.image = self.im_processor.average(self.image, int(params[0])) elif filter_name == 'Binarization': self.image = self.im_processor.binarization(self.image) elif filter_name == 'Color detection': self.image = self.im_processor.color_detection(self.image, params[0], int(params[1])) elif filter_name == 'Complement': self.image = self.im_processor.complement(self.image) elif filter_name == 'Diagonal lines': self.image = self.im_processor.diagonal(self.image, params[0]) elif filter_name == 'Difference': self.image = self.im_processor.difference(self.image, cv2.imread(params[0])) elif filter_name == 'High pass': self.image = self.im_processor.high_pass(self.image, int(params[0])) elif filter_name == 'Horizontal': self.image = self.im_processor.horizontal(self.image) elif filter_name == 'Hough': if params[0] == 'Line': self.image = self.im_processor.hough_lines(self.image) else: self.image = self.im_processor.hough_circles(self.image) elif filter_name == 'Intersection': self.image = self.im_processor.intersection(self.image, cv2.imread(params[0])) elif filter_name == 'Prewitt': self.image = self.im_processor.prewitt(self.image) elif filter_name == 'Roberts': self.image = self.im_processor.roberts(self.image) elif filter_name == 'Seam carving': self.image = self.im_processor.seam_carving(self.image, int(params[0])) elif filter_name == 'Sobel': self.image = self.im_processor.sobel(self.image) elif filter_name == 'Union': self.image = self.im_processor.union(self.image, cv2.imread(params[0])) colormap = self.im_processor.convert_bgr_to_rgb(self.image) self.user_interface.append_image(self.image, colormap, filter_name) else: print('There is no image set to apply this filter') def handle_image_load_event(self, sender, image_path): self.image = cv2.imread(image_path) print('the image was set')
def draw(self, scale=1): scaled_side = self.side * scale circumcircle_radius = scaled_side * math.sqrt((2+math.sqrt(2))/2) points = list() for i in range(8): points.append(GUI.get_rotated_point(circumcircle_radius, 0, i * 0.25 * math.pi)) GUI.draw_polygon(self, points, scale)
def draw(self, scale=1): scaled_side = self.side * scale circumcircle_radius = scaled_side * (1/math.sqrt(3 - constants.GOLDEN_RATIO)) points = list() for i in range(5): points.append(GUI.get_rotated_point(circumcircle_radius, 0, i * 0.4 * math.pi)) GUI.draw_polygon(self, points, scale)
def __init__(self, options=None, title='EmdrosApplication', DO_REF=True, DO_OUT=True, DO_LBL=True): if options is None: options = Options() kernel_cfg_name = options.get('kernel') if kernel_cfg_name is not None: kernel_cfg_name = 'emdros_application.syscfg.' + re.sub( '\.py[c]?$', '', kernel_cfg_name) else: kernel_cfg_name = syscfg.config.DEFAULT_KERNEL import importlib kernel = importlib.import_module(kernel_cfg_name) self.kernel = kernel #kernel = __import__(kernel_cfg_name) self.title = title self.DO_REF = DO_REF self.DO_OUT = DO_OUT self.DO_LBL = DO_LBL self.title = title self.spinner = Spinner() if options is None: self.options = Options( addPathAndExt('options', kernel.CFG_DIR, kernel.CFG_EXT)) else: self.options = options self.cfg = self.configure(self.options, kernel) self.modeCfgs = self.setupModeConfigurations(kernel) self.mql = MQLEngine(database=self.database, usr=self.usr, pwd=self.pwd, be=self.backend, domainfile=self.domainqueryfile, domain=self.domain, VERBOSE=self.VERBOSE, verbose=self.verbose, test=self.test, outstream=self.outstream, errstream=self.errstream, kernel=kernel) if self.DO_OUT or self.DO_REF: self.ref, self.out = self.setupOutput(kernel=kernel) if self.DO_LBL: self.lbl = self.setupLabelManagers(options.args, kernel=kernel) if self.options.get('gui'): self.gui = GUI(title=title, app=self) self.gui.mainloop() else: self.gui = None
def __init__(self, world, controller, dt=0.1, fps=60, monitor_width=1200, monitor_height=300): self.dt = dt self.fps = fps self.controller = controller self.simulator = Simulator(deepcopy(world)) self.gui = GUI(monitor_width, monitor_height)
def __init__(self): GUI.__init__(self) self.create_widgets() self.refresh_QR(imgfile='blank.png') self.protocol("WM_DELETE_WINDOW", self.on_closing)
def __init__(self): self.current = 0 self.buffers = [] self.config = config gui = GUI() state['gui'] = gui self.preferences = Preferences() try: self.recent_manager = gtk.recent_manager_get_default() except AttributeError: self.recent_manager = None self.status = gui.status self.revision_status = gui.revision_status self.window = gui.window self.window.add_accel_group(make_accel_group(self)) self.textbox = gui.textbox self.UNNAMED_FILENAME = FILE_UNNAMED self.autosave_timeout_id = '' self.autosave_elapsed = '' self.textbox.connect('key-press-event', self.key_press_event) # Autosave timer object autosave.start_autosave(self) self.window.show_all() self.window.fullscreen() # Handle multiple monitors screen = gtk.gdk.screen_get_default() root_window = screen.get_root_window() mouse_x, mouse_y, mouse_mods = root_window.get_pointer() current_monitor_number = screen.get_monitor_at_point(mouse_x, mouse_y) monitor_geometry = screen.get_monitor_geometry(current_monitor_number) self.window.move(monitor_geometry.x, monitor_geometry.y) # Defines the glade file functions for use on closing a buffer or exit gladefile = os.path.join(state['absolute_path'], "interface.glade") builder = gtk.Builder() builder.add_from_file(gladefile) self.dialog = builder.get_object("SaveBuffer") self.dialog.set_transient_for(self.window) self.quitdialog = builder.get_object("QuitSave") self.quitdialog.set_transient_for(self.window) dic = { "on_button-close_clicked": self.unsave_dialog, "on_button-cancel_clicked": self.cancel_dialog, "on_button-save_clicked": self.save_dialog, "on_button-close2_clicked": self.quit_quit, "on_button-cancel2_clicked": self.cancel_quit, "on_button-save2_clicked": self.save_quit, } builder.connect_signals(dic) self.keybindings = define_keybindings(self) # this sucks, shouldn't have to call this here, textbox should # have its background and padding color from GUI().__init__() already gui.apply_theme()
def __init__(self, root): root.wm_title("eBay Table") sizex = 800 sizey = 600 posx = 100 posy = 100 root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) GUI.__init__(self, root, "ebay")
def main(): chess = Singleton().chess root = tk.Tk() root.title("Chess") gui = GUI(root, chess) gui.pack() root.mainloop()
def main(): chess = Chess() root = tk.Tk() root.title("Chess") gui = GUI(root, chess) gui.pack() root.mainloop()
def main(): global app app = QApplication(sys.argv) gui = GUI() gui.show() sys.exit(app.exec_())
def render(self): if self.gui_object is None: self.gui_object = GUI(self.quad_properties) self.gui_object.quads['q1']['position'] = self.quad.get_position('q1') self.gui_object.quads['q1']['orientation'] = self.quad.get_orientation( 'q1') self.gui_object.update()
def __init__(self): self.gui = GUI() self.web_parser = WebParser("www.devrant.io") self.executed_commands = [] self.page = 0 self.limit = 20 self.sort = "recent" self.state = "NO_STATE"
def run_offline(): if options.gui_enabled: from gui import GUI gui = GUI(orchestra) gui.main_loop() else: play() wait_for_play_completion_or_interruption()
def eventFilter(self, obj, e): """ Adds any event listeners required by the window. """ window = self._window # Sanity check. if obj is not window.control: return False if e.type() == QtCore.QEvent.Close: # Do not destroy the window during its event handler. GUI.invoke_later(window.close) if window.control is not None: e.ignore() return True if e.type() == QtCore.QEvent.WindowActivate: window.activated = window elif e.type() == QtCore.QEvent.WindowDeactivate: window.deactivated = window elif e.type() == QtCore.QEvent.Resize: # Get the new size and set the shadow trait without performing # notification. size = e.size() window._size = (size.width(), size.height()) elif e.type() == QtCore.QEvent.Move: # Get the real position and set the trait without performing # notification. Don't use event.pos(), as this excludes the window # frame geometry. pos = window.control.pos() window._position = (pos.x(), pos.y()) elif e.type() == QtCore.QEvent.KeyPress: # Pyface doesn't seem to be Unicode aware. Only keep the key code # if it corresponds to a single Latin1 character. kstr = e.text() try: kcode = ord(str(kstr)) except: kcode = 0 mods = e.modifiers() window.key_pressed = KeyPressedEvent( alt_down = ((mods & QtCore.Qt.AltModifier) == QtCore.Qt.AltModifier), control_down = ((mods & QtCore.Qt.ControlModifier) == QtCore.Qt.ControlModifier), shift_down = ((mods & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier), key_code = kcode, event = e) return False
class Game: def __init__(self): pygame.init() self.gameDisplay = pygame.display.set_mode((config.display_width,config.display_height)) pygame.display.set_caption(config.title) self.gameDisplay.fill(config.white) self.clock = pygame.time.Clock() self.map = Map(100,50) self.gui = GUI() self.cars = pygame.sprite.Group() self.player_car = Car(self.map.size_y/2*config.tile_size,self.map.size_x/2*config.tile_size) self.cars.add(self.player_car) def run(self): breaking = 0 acceleration = 0 steering = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q: pygame.quit() quit() elif event.key == pygame.K_w: self.gui.acceleration += 1 elif event.key == pygame.K_s: self.gui.acceleration -= 1 elif event.key == pygame.K_a: self.gui.steering -= 1 elif event.key == pygame.K_d: self.gui.steering += 1 elif event.type == pygame.KEYUP: if event.key == pygame.K_q: pygame.quit() quit() elif event.key == pygame.K_w: self.gui.acceleration -= 1 elif event.key == pygame.K_s: self.gui.acceleration += 1 elif event.key == pygame.K_a: self.gui.steering += 1 elif event.key == pygame.K_d: self.gui.steering -= 1 self.cars.update(self.gui.acceleration,self.gui.steering,self.gui.breaking) self.gameDisplay.fill(config.white) self.map.draw(self.gameDisplay,self.player_car.position) self.cars.draw(self.gameDisplay) self.gui.draw(self.gameDisplay,self.clock) pygame.display.update() self.clock.tick(config.fps) pygame.quit()
def __init__(self): self.guiDisplay = GUI() self.guiDisplay.start() self.channel_mapping = {'qdac%s' % (n,):qdacChannel(qdac = self.qdacInst, number = n, gui = self.guiDisplay, name= 'qdac%s' % (n,), _qdacwrapper = self) for n in range(1,49)} self.voltage_dict = {n: 0 for n in range(1,49)} return
def start(self, screen): self.running = True self.screen = screen self.background = BackGround() self.player = Player() self.load_level() ALL_SPRITES.draw(self.screen) self.gui = GUI(self.player) pygame.display.flip()
def initComponents(self, crop=None): undistort = False self.pre = Preprocessor(self.rawSize, self.threshold, undistort, crop=crop) self.featureEx = FeatureExtraction(self.pre.cropSize) self.gui = GUI(self.world, self.pre.cropSize, self.threshold, self) self.world.setResolution(self.pre.cropSize)
def getY(self): self.yPos = None def operation(): x, y = self.win.get_position() self.yPos = y GUI.doOperation(operation) while self.yPos is None: sleep(0) return self.yPos
def start(self, gui_on=True): gui = GUI(self.SCREEN_WIDTH, self.SCREEN_HEIGHT, scaling_factor, gui_on) done = False while not done: done = gui.iteration(self) self.deleteSnakes() self.eatOrMove() pygame.quit()
def getWidth(self): self.width = None def operation(): width, height = self.win.get_size() self.width = width GUI.doOperation(operation) while self.width is None: sleep(0) return self.width
def getHeight(self): self.height = None def operation(): width, height = self.win.get_size() self.height = height GUI.doOperation(operation) while self.height is None: sleep(0) return self.height
def main(): data_loader = DataLoader() app_gui = GUI(*data_loader.get_loaded_data()) while True: if not app_gui.read(): break
def main_loop(): ### initialization ### # pygame initialization pygame.init() # initialize pygame pygame.display.set_caption('PythonTD') # window name # game fps clock game_gui = GUI() # game FPS = 60 # fps variable fpsClock = pygame.time.Clock() # update clock # load map argv = sys.argv[1:] # load argument level = "tdmap" # default if len(argv) > 0: level = argv[0] game_gui.load_level("maps/" + level + ".lvl") # load map # main game loop while 1: # user input for event in pygame.event.get(): if event.type == pygame.QUIT: # quit pygame.display.quit() sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: pygame.display.quit() sys.exit() if event.type == pygame.MOUSEBUTTONUP: game_gui.on_click(event) # render game_gui.update() # update assets game_gui.draw() # draws fpsClock.tick(FPS) # fps (default 60)
def __init__(self): xbmc.log("version %s started" % ADDON_VERSION) xbmc.executebuiltin('SetProperty(mapsbrowser_running,True,home)') # try: self._parse_argv() if self.infos: StartInfoActions(self.infos, self.params) else: gui = GUI(u'script-%s-main.xml' % ADDON_NAME, ADDON_PATH) gui.doModal() del gui xbmc.executebuiltin('ClearProperty(mapsbrowser_running,home)')
def main(): thread_events = Event() data_transfer = DataTransfer() model = BoidsModel(thread_events, data_transfer, WIDTH, HEIGHT) controller = Controller(model) app = GUI(WIDTH, HEIGHT, data_transfer, controller) model.start() app.on_execute() thread_events.set() model.join()
def main(): path_to_covers = '/home/anosov/data/hard_base/covers/case_0.dump' base, ext = os.path.splitext(path_to_covers) path_to_data = base + '__computing' + ext h = DataHandler(path_to_covers, path_to_data) gui = GUI(h) # gui.append(trivia.show_stat_rm) # gui.append(trivia.show_equal_stat) gui.append(trivia.case_0) gui.run()
def draw_tooltip(self, screen, name, description = []): font = Game.get_font(False) big_font = Game.get_font(True) mouse_pos = pygame.mouse.get_pos() name_image = GUI.render_string_array([name], big_font, 0, Game.WHITE) desc_image = GUI.render_string_array(description, font, 0, Game.WHITE) name_width = name_image.get_width() name_height = name_image.get_height() desc_width = desc_image.get_width() desc_height = desc_image.get_height() width = max(name_width, desc_width) height = name_height if desc_height > 0: height += TOOLTIP_GAP + desc_height corner = 4 * Game.SCALE edge = 2 * corner pos = (mouse_pos[0] + corner, mouse_pos[1]) #if too long, flip it to the other side of the mouse if pos[0] + width + 2 * corner > Game.SCREEN_WIDTH: pos = (max(pos[0] - width - 4 * corner, 0), pos[1]) #gap for mouse if pos[1] + height + 2 * corner > Game.SCREEN_HEIGHT: pos = (pos[0], pos[1] - height - 2 * corner) #top border screen.blit(Images.tooltip_pieces[0][0], pos) for x in range(0, width, edge): screen.blit(Images.tooltip_pieces[0][1], (pos[0] + corner + x, pos[1])) screen.blit(Images.tooltip_pieces[0][2], (pos[0] + 3 * corner + x, pos[1])) #middle slices = math.ceil(height / edge) for s in range(slices): y = height * s // slices screen.blit(Images.tooltip_pieces[1][0], (pos[0], pos[1] + corner + y)) for x in range(0, width, edge): screen.blit(Images.tooltip_centers[((x + y) // edge) % 4], (pos[0] + corner + x, pos[1] + corner + y)) screen.blit(Images.tooltip_pieces[1][2], (pos[0] + 3 * corner + x, pos[1] + corner + y)) #bottom border y = corner + height screen.blit(Images.tooltip_pieces[2][0], (pos[0], pos[1] + y)) for x in range(0, width, edge): screen.blit(Images.tooltip_pieces[2][1], (pos[0] + corner + x, pos[1] + y)) screen.blit(Images.tooltip_pieces[2][2], (pos[0] + 3 * corner + x, pos[1] + y)) #text screen.blit(name_image, (pos[0] + corner, pos[1] + corner)) screen.blit(desc_image, (pos[0] + corner, pos[1] + corner + name_height + TOOLTIP_GAP))
def guiprocess(s, q): from gui import GUI g = GUI(s,s) def f(): try: m = q.get(False) g.map = m except: pass g.schedule(f) g.display()
def main(): #--------------------------------------------------------------------------- import sys, argparse #application local from gui import GUI from application import Application #--------------------------------------------------------------------------- #parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("--skip-test", default = False, action = 'store_true', help = "skip over device tests", ) parser.add_argument("--no-detach", dest = "detach", default = True, action = 'store_false', help = "remain bound to terminal session", ) parser.add_argument("--ignore-device-errors", dest = "ignore_device_errors", default = False, action = 'store_true', help = "ignore initial device errors" ) args = parser.parse_args() #initialize the control application app = Application(skip_test = args.skip_test, ignore_device_errors = args.ignore_device_errors, ) #parse and loads the configuration objects app.load(config_filepath = OLMpstat.pkg_info.platform['config_filepath']) #initialize the controllers app.initialize() if args.detach: #detach the process from its controlling terminal from automat.system_tools.daemonize import detach app.print_comment("Process Detached.") app.print_comment("You may now close the terminal window...") detach() #start the graphical interface gui = GUI(app) #give the app the ability to print to the GUI's textbox app.setup_textbox_printer(gui.print_to_text_display) #launch the GUI gui.load() gui.launch()
def _init_window(self): try: lw.log( ["############################################################"], xbmc.LOGNOTICE ) lw.log( ["# %-50s #" % Addon.__name__], xbmc.LOGNOTICE ) lw.log( ["# %-50s #" % Addon.__id__], xbmc.LOGNOTICE ) lw.log( ["# %-50s #" % Addon.__author__], xbmc.LOGNOTICE ) lw.log( ["# %-50s #" % Addon.__version__], xbmc.LOGNOTICE ) lw.log( ["############################################################"], xbmc.LOGNOTICE ) slbWindow = GUI( "script-slbenfica.xml" , Addon.__path__, "Default") slbWindow.doModal() del slbWindow except: lw.log(['Error in script occured:', print_exc()]) xbmcgui.Window( 10000 ).setProperty( "slbenfica_addon_running", "False" )
def run(): if os.path.isfile('save.json'): try: with open('save.json') as f: save = json.load(f) except ValueError: os.remove('save.json') save = dict(username=None, password=None) else: save = dict(username=None, password=None) ucal = UCal() gui = GUI(ucal.start, ucal.clear_all, save['username'], save['password']) gui.master.title('uCal - Import your UOIT schedule to google calendar') gui.mainloop()
def __init__(self, display): GUI.__init__(self, display) self.onClose = None self.onSetLight = None self.lumWarm = 0 self.lumCold = 0 self.margin = 16 self.cellsX = 3 self.cellsY = 4 self.gridW = (self.width - self.margin * (self.cellsX + 1)) / self.cellsX self.gridH = (self.height - self.margin * (self.cellsY + 1)) / self.cellsY nextX = self.margin nextY = self.margin buttonQuit = Button(self, nextX, nextX, self.gridW, self.gridH, name="quit", label="Quit") nextX += self.gridW + self.margin buttonReboot = Button(self, nextX, nextY, self.gridW, self.gridH, name="reboot", label="Reboot") #nextX += self.gridW + self.margin #button3 = Button(self, nextX, nextY, self.gridW, self.gridH) nextX += self.gridW + self.margin buttonClose = Button(self, nextX, nextY, self.gridW, self.gridH, name="close", label="CLOSE") sliderWidth = self.gridW * self.cellsX + (self.cellsX-1) * self.margin nextX = self.margin nextY += self.gridH + self.margin sliderWarm = Slider(self, nextX, nextY, sliderWidth, self.gridH, name="warm", label="WARM") nextY += self.gridH + self.margin sliderCold = Slider(self, nextX, nextY, sliderWidth, self.gridH, name="cold", label="COLD") sliderWarm.onChange = self.changeLight sliderCold.onChange = self.changeLight buttonQuit.onClick = self.clickButton buttonReboot.onClick = self.clickButton #button3.onClick = self.clickButton buttonClose.onClick = self.clickButton self.addWidget(buttonQuit) self.addWidget(buttonReboot) #self.addWidget(button3) self.addWidget(buttonClose) self.addWidget(sliderWarm) self.addWidget(sliderCold) self.drawBG()
def play_game(self, gui = False): while(True): self.gui = gui if (gui == False): self.gui = GUI(self) menu_sel = self.gui.print_menu() if(menu_sel == 1): #start new game #set labyrinth size: width = self.gui.ask_width() height = self.gui.ask_height() #create labyrinth self.labyrinth = Labyrinth(width, height) self.labyrinth.generateMaze() #createa player self.player = Player(self.labyrinth.getStartNode()) #the game itself self.gui.game_loop() if(menu_sel == 2): #Load game from a file self.load_game() self.gui.game_loop() if(menu_sel == 3): #Exit game return self.end_game()
def __init__(self, pitch, color, our_side, video_port=0, comm_port='/dev/ttyACM0', quick=False, is_attacker=False): """ Entry point for the SDP system. Params: [int] video_port port number for the camera [string] comm_port port number for the arduino [int] pitch 0 - main pitch, 1 - secondary pitch [string] our_side the side we're on - 'left' or 'right' # """ self.controller = Controller(comm_port) if not quick: print("Waiting 10 seconds for serial to initialise") time.sleep(10) # Kick once to ensure we are in the correct position self.controller.update(CommandDict.kick()) self.pitch = pitch # Set up the vision system self.vision = VisionWrapper(pitch, color, our_side, video_port) # Set up the planner self.planner = Planner(our_side, pitch, attacker=is_attacker) # Set up GUI self.GUI = GUI(calibration=self.vision.calibration, pitch=pitch, launch=self) self.color = color self.side = our_side self.control_loop()
def execute(self): # Pre launch set-up MyrmidonGame.current_fps = 60 self.priority = PRIORITY_MAIN_GAME # Load all media self.media = Media() self.media.load_fonts() self.media.load_graphics() self.media.load_audio() # Debug display if DEBUG_SHOW_FPS: self.fps_text = MyrmidonGame.write_text(0.0, 0.0, font = self.media.fonts['basic'], text = 0) self.fps_text.colour = (1, 1, 1, 1) self.fps_text.z = -2000 # Set up starting game objects self.galaxy = Galaxy(self) self.gui = GUI(self) self.switch_game_state_to(GAME_STATE_SOLAR_SYSTEM) self.media.audio['ambient'].play(loops = -1) while True: # update debug display if DEBUG_SHOW_FPS: self.fps_text.text = "fps: " + str(MyrmidonGame.fps) yield
def __init__(self): dispatcher.connect(self.handle_image_load_event, signal='load_image', sender=dispatcher.Any) dispatcher.connect(self.handle_filter_event, signal='apply_filter', sender=dispatcher.Any) self.image = None self.im_processor = ImageProcessor() self.user_interface = GUI() self.user_interface.run()
class Adventure(GUI): # creates the Adventure # syntax: Adventure(width, height) # parameters: # width: of the window in pixels (int) # height: of the window in pixels (int) # returns: None def __init__(self, width, height): super().__init__() self.isDone = False self.cutscene = None self.__width = width self.__height = height self.__currentLevel = 0 # goes to the next level # syntax: self.win() # parameters: None # returns:None def win(self): self.__currentLevel += 1 if self.__currentLevel >= len(standardAdventure): self.isDone = True # ultimate victory # gets the game settings for the current level # syntax: self.getPlaySettings() # parameters: None # returns: None def getPlaySettings(self): return standardAdventure[self.__currentLevel]['settings'] # displays and animates a cutscene # syntax: showCutscene(window) # parameters: # window: window to draw custscene to (graphics.GraphWin) # returns: None def showCutscene(self, window): self.cutscene = GUI() background = Rectangle(Point(0, 0), Point(self.__width, self.__height)) background.setFill("blue") cutsceneText = TextArea(Point(-100, 50)) level = standardAdventure[self.__currentLevel] cutsceneText.add(level['catchphrase'], "black", 12, 0, 40) cutsceneText.add(level['villain'], "black", 20, 0, 20) cutsceneText.add("Click to continue...", "black", 12, 0, self.__height - 100) cutsceneText.add("Level "+str(self.__currentLevel+1), "black", 12, 0, 0) self.cutscene.add(background) self.cutscene.add(cutsceneText) self.cutscene.draw(window) for i in range (100): cutsceneText.move(5, 0) sleep(1/30) # undraws and hides the cutscene drawn from showCutscene # syntax: hideCutscene() # parameters: None # returns: None def hideCutscene(self): self.cutscene.undraw() self.cutscene = None
def run_games(number_of_games, game, sarsa, with_gui=False): '''Runs a number of games.''' total_games = number_of_games won_games = 0 while number_of_games > 0: if with_gui: gui = GUI(game) game.restart_game() game_ended = game.game_ended() while not game_ended: _, action = sarsa.get_state_and_action() game.pray.set_direction(action) game.play_round() if with_gui: gui.draw() game_ended = game.game_ended() number_of_games -= 1 won_games += (game_ended == Helper.WON) print 'Won ' + str(won_games) + '/' + str(total_games) + ' total games.'
def main(): track_playing = None track_next = None # Load config file config = settings.loadConfig('config.json') # Spawn GUI gui = GUI() # Initialize library lib = Library(config['library']['dbfile']) for folder in config['library']['folders']: lib.addFolder(folder) player = Player() track_playing = lib.getRandomFile() track_next = lib.getRandomFile() player.cue(u"file:///"+track_playing) player.play() print track_playing player.cue(u"file:///"+track_next) print track_next #gui.queueTrack(track_playing) while True: pos = player.get_position() dur = player.get_duration() gui.set_status("%s %02d:%02d / %02d:%02d " % (track_playing, pos/60, (pos%60), dur/60, (dur%60))) gui.update() if player.queue is None: track_playing = track_next track_next = lib.getRandomFile() player.cue(u"file:///"+track_next) print player.queue
def run(): """ starting the interface """ from gui import GUI from Tkinter import Tk import system root = Tk() root.columnconfigure(0,weight=1) root.rowconfigure(1,weight=1) root.title(system.name + " " + system.version) root.minsize(width= system.minwidth , height=system.minheight) root.geometry(system.defsize) gui = GUI(root) gui.makeGUI() root.iconbitmap('hat2.ico') root.mainloop()