Ejemplo n.º 1
0
    def __init__(self):
        self.clock = None
        self.show_path = False
        self.game = Game()
        self.surface = pygame.display.set_mode(cfg.WINDOW_SIZE)
        self.players_alg = [
            Algorithm.PLAYER, Algorithm.PLAYER, Algorithm.DIJKSTRA,
            Algorithm.DFS
        ]

        # Controllers initialization
        self.control_list_select1 = [("Key1", 0)]
        self.control_list_select2 = [("Key2", 1)]
        pygame.joystick.init()
        self.num_of_gamepads = pygame.joystick.get_count()

        self.controllers = [
            Controls(pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT,
                     pygame.K_RCTRL),
            Controls(pygame.K_w, pygame.K_s, pygame.K_a, pygame.K_d,
                     pygame.K_LCTRL)
        ]

        for i in range(self.num_of_gamepads):
            gamepad = pygame.joystick.Joystick(i)
            gamepad.init()
            self.controllers.append(gamepad)
            if i % 2 == 0:
                self.control_list_select1.append((f"Joy{i+1}", i + 2))
            else:
                self.control_list_select2.append((f"Joy{i+1}", i + 2))

        self.player_controls = [self.controllers[0], self.controllers[1]]
Ejemplo n.º 2
0
def initialize(standard_screen):
    globals.STDSCR = standard_screen
    globals.MAIN = MainMenu()
    globals.INTERFACES.append(globals.MAIN)
    globals.MAP = GameMap()
    globals.INTERFACES.append(globals.MAP)
    globals.INVENTORY = Inventory()
    globals.INTERFACES.append(globals.INVENTORY)
    globals.PAUSE = PauseMenu()
    globals.INTERFACES.append(globals.PAUSE)
    globals.STORY = StoryScreen()
    globals.INTERFACES.append(globals.STORY)
    globals.CONTROLS_MAP = Controls(Controls.Type.game_map)
    globals.INTERFACES.append(globals.CONTROLS_MAP)
    globals.CONTROLS_INVENTORY = Controls(Controls.Type.inventory)
    globals.INTERFACES.append(globals.CONTROLS_INVENTORY)
    globals.CREDITS = Credits()
    globals.INTERFACES.append(globals.CREDITS)
    globals.NEW_GAME = NewGameDialog()
    globals.INTERFACES.append(globals.NEW_GAME)
    globals.QUIT_GAME = EndGameDialog()
    globals.INTERFACES.append(globals.QUIT_GAME)
    globals.SAVE_GAME = SaveGameDialog()
    globals.INTERFACES.append(globals.SAVE_GAME)
    globals.MONSTER = MonsterDialog()
    globals.INTERFACES.append(globals.MONSTER)
    globals.ITEM = ItemDialog()
    globals.INTERFACES.append(globals.ITEM)
    globals.GAME_OVER = GameOverDialog()
    globals.INTERFACES.append(globals.GAME_OVER)
    globals.LADDER = LadderDialog()
    globals.INTERFACES.append(globals.LADDER)
Ejemplo n.º 3
0
    def create_widgets(self):
        if globals.debug > 1: print("gui.create_widgets")
        self.menubar = MenuBar(self.window, self)
        self.interactiveplot = InteractivePlot(
            self,
            relief='sunken',
            bd=1,
        )
        # Wait until the plot becomes visible to proceed
        self.update_idletasks()
        self.update()

        self.plotcontrols = PlotControls(
            self,
            self.interactiveplot.canvas,
            bg='white',
            relief='sunken',
            bd=1,
        )
        self.controls = Controls(
            self,
            width=2 * self.dpi,  # pixels = inches * dpi
            bd=1,
            relief='sunken',
            padx=5,
            pady=5,
        )

        self.message_label = tk.Label(self,
                                      textvariable=self.message_text,
                                      bg='white')
Ejemplo n.º 4
0
    def handle_event(self, slack_event):
        event = slack_event['event']
        event_type = event['type']
        if 'user' not in event:
            return 'OK'

        user = event['user']
        if user == self.config.bot_id:
            return 'OK'  # Dont do anything about own messages

        channel = event['channel']

        if 'text' in event:
            text = event['text']
            print('in handle_event')
            print('event_type = ' + event_type + ' channel = ' + channel + ' user = '******' text = ' + text)
            print('---------------')

            # Reply to request
            AT_BOT = '<@' + self.config.bot_id + '>'

            command = text
            if  True:
                if text.startswith(AT_BOT):
                    command = text.split(AT_BOT)[1].strip().lower()

#                if command.startswith('quote') or command.startswith('q ') or command.startswith('Q ') or command.startswith('Quote'):
                sym_or_name = ''
                if command.lower().startswith('help') == False:
                    toks = command.split(' ')
                    if len(toks) <= 1:
                        sym_or_name = command.strip().upper()
                    else:
                        tok1 = toks[0]
                        tok2 = toks[1]
                        if tok1.lower().startswith('q'):
                            sym_or_name = tok2.upper()
                        
                    user_command = StockQuote(name="stock_quote", intent="get_stock_quote", params={}, raw=command,
                                             urls={})
                    user_command.set_param('company-trie', Bot.company_trie)
                    user_command.set_param('symbol-trie', Bot.symbol_trie)
                    user_command.set_param('selected', sym_or_name)

                    val = Bot.symbol_trie.get(sym_or_name)
                    if val is not None:
                        self.postToSlack(channel, user_command.execute(), {})
                    else:
                        controls = Controls()
                        Bot.user_commands[channel+user] = user_command
                        controls.message_attachments_company_name_options[0]['actions'][0]['name'] = sym_or_name
                        message = 'Hmm, I don\'t know that stock symbol.\n Please use the search box below'
                        self.postToSlack(channel, message, controls.message_attachments_company_name_options)

                else:
                    # Fallback to saying hello!
                    user_command = Hello(name="hello", intent="say_hello", params={}, raw=command, urls={})
                    self.postToSlack(channel, user_command.execute(), {})

        return 'OK'
Ejemplo n.º 5
0
    def __init__(self, interface):
        gtk.Window.__init__(self)
        self.set_title("mogbar3000")

        #Create child widgets
        self.statusbar = gtk.Statusbar()
        self.controls = Controls(interface)
        self.notebook = gtk.Notebook()
        self.notebook.set_scrollable(True)

        #Add children to VBox
        self.box = gtk.VBox()
        self.box.pack_start(self.controls, False, False, 0)
        self.box.pack_start(self.notebook, True, True, 0)
        self.box.pack_start(self.statusbar, False, False, 0)
        self.add(self.box)

        self.connect('delete_event', gtk.main_quit)

        def create_playlist(tracks, name):
            self.notebook.append_page(Playlist(interface), name)

        interface.create_playlist = create_playlist

        def add_tracks(tracks):
            cur = self.notebook.get_current_page()
            if cur == None: return
            cur.store.append()

        #done loading
        self.show_all()
Ejemplo n.º 6
0
    def __init__(self, nop):

        rows, columns = self.get_terminal_dimensions()
        self.screen = {'rows': rows, 'columns': columns}
        if not self.multi_player_support(nop):
            print("Sorry " + str(nop) +
                  " is not supported at present screen aspect ratio.")
            return
        self.initialise_screen()
        self.num_players = nop
        self.players = []
        self.maps = []
        self.gameplay_settings = self.configure_gameplay_settings()
        # os.system('tput civis')
        # print("the ratio is ", columns / nop)
        self.welcome_screen()
        for num_id in range(nop):
            self.maps.append(
                level1_map.Level1Map(num_id, self.screen['rows'],
                                     int(self.screen['columns'] / nop - 1)))
            self.players.append(
                Player(self.maps[-1].initial_player_position, config.PLAYER,
                       num_id, self.maps[-1]))
        self.controls = Controls()
        # self.maps[0].view_map()
        # self.print_screen()
        # exit(1)
        if ROOT:
            for player_id in range(self.num_players):
                inp_thread = Thread(target=self.get_input_for_player,
                                    args=(player_id, ))
                inp_thread.daemon = True
                inp_thread.start()
                time_thread = Thread(target=self.decrease_time,
                                     args=(player_id, ))
                time_thread.daemon = True
                time_thread.start()
            control_input_thread = Thread(target=self.get_input_for_control)
            control_input_thread.daemon = True
            control_input_thread.start()
        else:
            time_thread = Thread(target=self.decrease_time, args=(0, ))
            time_thread.daemon = True
            time_thread.start()
            all_input_thread = Thread(target=self.game_input)
            all_input_thread.daemon = True
            all_input_thread.start()
        msc.play_music_for_action('Player at start')
        while True:
            try:
                if config.stop.is_set() or config.timeout.is_set():
                    break
                sleep(0.1)
                [self.make_updates(x) for x in range(self.num_players)]
                self.updates()

            except KeyboardInterrupt:
                break
        self.exit()
Ejemplo n.º 7
0
def temp_run():
    temp_signals = {
        'green': False,
        'red': False,
        'blue': False,
        'stop': False,
        'metal': False,
        'maxTime': False,
        'finish': False,
        'path': '/home/pi/Filakov/',
        'pltCnt': 1,
        'imgCnt': 1
    }

    C = Controls("/dev/ttyACM0")
    if not C.started:
        debug_print(
            "Controls of the motors are not started. Aborting program...")
        return

    time.sleep(3)
    cam = cv2.VideoCapture(0)
    time.sleep(1)
    if not cam.isOpened():
        debug_print("Camera is not opened. Aborting program...")
        return

    T_metal = threading.Thread(target=metalCheck, args=(
        C,
        temp_signals,
    ))
    T_cam = threading.Thread(target=cameraLoop, args=(
        cam,
        temp_signals,
    ))
    T_metal.start()
    T_cam.start()

    #    calibrateCamera(C, temp_signals)
    #    if temp_signals['stop']:
    #        return
    #
    #    C.Lights(1)

    safeMove(C, 2, 'M', -90, temp_signals)

    while True:
        time.sleep(.5)
        if temp_signals['stop']:
            temp_signals['finish'] = True
            break

    T_cam.join()
    T_metal.join()
    #    C.Lights(0)
    C.Close()
def main():
  root = Tk()
  root.title("Simple 3-D Renderer :: Noah Ansel (nba38)")

  display = Display(root)
  controls = Controls(root, display)
  controls.grid(row = 0, column = 0, sticky = N+W)
  display.grid(row = 0, column = 1, sticky = N+W+E+S)

  root.mainloop()
Ejemplo n.º 9
0
    def __init__(self, resolution=Dimensions(1001, 601), calcThread=None):
        # Declare constants
        # General
        self.fpsLimit = 60
        self.simRunning = False
        self.calcThread = calcThread
        # Section sizes
        self.control_width = 200
        # Key presses
        self.L_SHIFT = 1
        self.R_SHIFT = 2
        self.L_CTRL = 64
        self.R_CTRL = 128
        self.L_ALT = 256
        self.R_ALT = 512

        # Declare variables
        self.populationLimit = 3
        self.populationMin = 2
        self.generation = 0

        # Declare mouse event flags
        self.processMouse = False
        self.multiCellDrag = False
        self.multiCellDragState = True
        self.mouseHeld = False
        self.mouseRepeatDelayed = False
        self.mouseClickTime = 0

        # Initialize pygame window
        pygame.init()
        self.window = pygame.display.set_mode(resolution, pygame.RESIZABLE)
        pygame.display.set_caption("Conway's Game of Life")

        # Create clock to limit FPS
        self.fpsClock = pygame.time.Clock()

        # Enable key and mouse hold repeating and set limits
        pygame.key.set_repeat(500, 75)
        self.mouseRepeat = (500, 75)

        # Create the initial grid
        self.grid = Grid(
            Dimensions(self.window.get_rect().width - self.control_width,
                       self.window.get_rect().height), Position(0, 0))

        # Create control section
        self.controls = Controls(
            Dimensions(self.control_width,
                       self.window.get_rect().height),
            Position(self.grid.width, 0), self)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--player", help="player 1-6", type=int, default=1)
    args = parser.parse_args()

    config = Config(CONFIG_FILE, args.player)

    comms_config = {
        'rx_ip': config.client_ip,
        'rx_port': config.client_port,
        'tx_ip': config.sim_ip,
        'tx_port': config.sim_port
    }
    print("Rx at {}:{}".format(comms_config["rx_ip"], comms_config["rx_port"]))
    print("Tx to {}:{}".format(comms_config["tx_ip"], comms_config["tx_port"]))

    commands_mutex = Lock()

    # Launch comms in background thread
    comms = CommsThread(comms_config, False, commands_mutex)
    comms.daemon = True
    comms.start()

    # Launch perception, motion planning, and controls in main thread
    sweep_builder = SweepBuilder()
    perception = Perception(config)
    planning = Planning(config)
    controls = Controls(config)
    visualize = Visualize(config)

    try:
        while True:
            vehicle_state = sweep_builder.run(comms.get_vehicle_states())
            if vehicle_state is not None:
                t1 = time.time()

                world_state = perception.run(vehicle_state)
                plan = planning.run(world_state)
                vehicle_commands = controls.run(plan)

                t2 = time.time()
                freq = 1 / (t2 - t1)
                print(f"Running at {freq} Hz")

                vehicle_commands['draw'] = visualize.run(world_state, plan)
                with commands_mutex:
                    # hold the lock to prevent the Comms thread from
                    # sending the commands dict while we're modifying it
                    comms.vehicle_commands.update(vehicle_commands)
    except KeyboardInterrupt:
        pass
Ejemplo n.º 11
0
    def __init__(self):
        pygame.init()

        self.outputs = Outputs()
        self.stream = Stream(channels=1,
                             sample_rate=60 * 10**3,
                             sample_size=2**11)

        self.mouse_frequency = 0.0

        # visual params
        self.background_color = pygame.Color(50, 50, 50)
        self.colorA = pygame.Color("#ff0000")
        self.colorB = pygame.Color("#0000ff")
        self.num_bars = self.outputs.get_divisor()

        # surface params
        self.height = 1000
        self.dimensions = numpy.array([self.outputs.get_width(), self.height])
        self.surface_flags = pygame.HWSURFACE | pygame.DOUBLEBUF
        self.surface = pygame.display.set_mode(self.dimensions,
                                               self.surface_flags)
        self.time_surface = pygame.Surface(self.dimensions //
                                           numpy.array([1, 2]))
        self.freq_surface = pygame.Surface(self.dimensions //
                                           numpy.array([1, 2]))
        self.control_surface = pygame.Surface(self.dimensions // 2)
        self.control_surface.set_colorkey(self.background_color)

        self.controls = Controls(self.control_surface)

        self.sliders = {
            'pull':
            Slider(self.control_surface,
                   pygame.Rect(300, 46, 100, 10),
                   10,
                   15,
                   value=0.5),
            'smooth':
            Slider(self.control_surface,
                   pygame.Rect(300, 66, 100, 10),
                   10,
                   15,
                   value=0.5)
        }

        # smoothing history array
        self.t_history = numpy.full(self.num_bars, 0.5)
        self.f_history = numpy.full(self.num_bars, 0.0)
Ejemplo n.º 12
0
 def __init__(self, verbose=True, path=False, width=WIDTH, height=HEIGHT):
     self.verbose = verbose
     self.logger = Logerer()
     self.controls = Controls(verbose=self.verbose)
     self.path = self.controls.path if not path else path
     self.log("Game started in " + self.path)
     self.levels = {}
     self.current_level = (0, 0)
     self.width = width
     self.height = height
     self.size = self.width, self.height
     self.slow_clock = 90
     self.screen = pygame.display.set_mode(
         (self.width, self.height), pygame.RESIZABLE)
     self.npcs_loaded = False
Ejemplo n.º 13
0
    def createObjects(self):
        self.intake_motor = ctre.TalonSRX(10)
        self.intake_arm_motor = PIDSparkMax(7)

        self.shooter_motor = PIDSparkMax(16)
        self.shooter_feeder_motor = ctre.TalonSRX(19)

        self.drivetrain_motorr1 = CANSparkMax(5, MotorType.kBrushless)
        self.drivetrain_motorr2 = CANSparkMax(8, MotorType.kBrushless)
        self.drivetrain_motorl1 = CANSparkMax(17, MotorType.kBrushless)
        self.drivetrain_motorl2 = CANSparkMax(13, MotorType.kBrushless)

        self.joystick_left = wpilib.Joystick(0)
        self.joystick_right = wpilib.Joystick(1)

        self.controls = Controls(self.joystick_left, self.joystick_right)
Ejemplo n.º 14
0
 def __init__(self, window=None, objects=(), controllers=()):
     # Create a font for score
     self.font = font.load('Arial', 18)
     # pyglet.font.Text object to display the score
     self.score = font.Text(self.font, x=10, y=10, color=(1, 1, 1, 1))
     self.control = Controls(window)
     self.bind_objects(*objects)
     self.bind_controllers(*controllers)
     self.score_right = 0
     self.score_left = 0
     self.draw_score()
     self.height = window.width
     self.width = window.height
     # should this not be handled within the object?
     # map effects to different objects in the game
     effects_map = {"fire": None}
Ejemplo n.º 15
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.connect("delete-event", Gtk.main_quit)

        root_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        self.board = Board()
        self.controls = Controls()
        self.console = Gtk.Label("Input angle, initial velocity and fire!")

        self.controls.reset_btn.connect("clicked", self.__on_reset_clicked)
        self.controls.fire_btn.connect("clicked", self.__on_fire_clicked)

        root_box.pack_start(self.board, False, False, 0)
        root_box.pack_end(self.controls, False, False, 10)
        root_box.pack_end(self.console, False, False, 10)

        self.add(root_box)
Ejemplo n.º 16
0
    def appStarted(self):
        # Citation: this is a modified version of image from user BENL at link
        # https://www.chiefdelphi.com/t/top-down-orthographic-view-of-frcs-2019-playing-field/335397/9
        self._fieldImage = self.loadImage("2019-field-blue.png")
        self.fieldImageScaled = ImageTk.PhotoImage(self._fieldImage)
        # Citation: from cleanpng.com, contributor: georgen
        url = "https://icon2.cleanpng.com/20180417/bxw/kisspng-steve-harvey-still-trippin-act-like-a-lady-thin-steve-jobs-5ad626cde40c49.3709911715239840779341.jpg"
        self._robotImage = self.scaleImage(self.loadImage(url), 0.6)
        self._WAYPOINT_RADIUS = 30
        self.setAppDims()
        self.resetUserInputs()

        self.FIELD_REAL_WIDTH = 8.23  # meters
        self.FIELD_REAL_HEIGHT = 9  # 16.46

        self.timerDelay = 30  # milliseconds

        self.robot = RobotModel(1.0, 1.0, 0.0)
        self.leftVoltage, self.rightVoltage = 0.0, 0.0
        self.simTime = 0.0
        self.ODOMETRY_UPDATE_RATE = 100
        odometryThread = threading.Thread(target=self.odometryPeriodic,
                                          daemon=True)
        odometryThread.start()

        self.waypoints = []

        self.controls = Controls(self.waypoints, self.robot)
        self.CONTROLS_UPDATE_RATE = 100
        controlThread = threading.Thread(target=self.controlsPeriodic,
                                         daemon=True)
        controlThread.start()

        self.logger = Logger()
        self.logger.registerLoggerDict(self.robot.logDict, "robot")
        self.logger.registerLoggerDict(self.controls.logDict, "controls")
        yAxes = [
            self.logger.dict["robot.heading"], self.logger.dict["robot.vel"],
            self.logger.dict["controls.ffSpeed"]
        ]
        self.graph = StackedTimeGraph(self.logger.time, yAxes,
                                      (self.fieldImageWidth, self.width),
                                      (self.height, 0))
def main():
    app = QtWidgets.QApplication(sys.argv)
    main_view = MainView(app)
    controls = Controls()
    main_view.subscribe_controls(controls)

    metrics_engine = MetricsEngine()
    metrics_engine.subscribe_view(main_view)
    metrics_engine.load_metrics()
    controls.subscribe_view(main_view)
    image_handler = ImageHandler()
    image_handler.subscribe_view(main_view)
    modifications_provider = ModificationsProvider()
    modifications_provider.subscribe_image_handler(image_handler)
    controls.subscribe_image_handler(image_handler)
    controls.subscribe_modifications_provider(modifications_provider)
    image_handler.subscribe_metrics_engine(metrics_engine)

    main_view.show()
    sys.exit(app.exec_())
Ejemplo n.º 18
0
    def appStarted(self):
        self._fieldImage = self.loadImage("2019-field-blue.png")
        self.fieldImageScaled = ImageTk.PhotoImage(self._fieldImage)
        self.setAppDims()
        self.FIELD_REAL_WIDTH = 8.23  # meters
        self.FIELD_REAL_HEIGHT = 9  # 16.46

        self.robot = RobotModel(1.0, 1.0, 0.0)
        self._robotImage = self.scaleImage(self.loadImage("steve.jpg"), 0.6)
        self.leftVoltage, self.rightVoltage = 0.0, 0.0
        self.ODOMETRY_UPDATE_RATE = 100
        odometryThread = threading.Thread(target=self.odometryPeriodic,
                                          daemon=True)
        odometryThread.start()

        self.logger = {}

        self.waypoints = []
        self.waypointRadius = 30
        self.selectedWaypoint = None
        self.rotatingWaypoint = False
        self.lastClickTime = 0
        self.DOUBLE_CLICK_TIME = 0.2

        self.timerDelay = 50  # milliseconds
        self.timer = 0
        self.releaseDelay = 0.1
        self.inputKeys = {
            "Up": KeyLatch(self.releaseDelay),
            "Down": KeyLatch(self.releaseDelay),
            "Right": KeyLatch(self.releaseDelay),
            "Left": KeyLatch(self.releaseDelay)
        }
        self.autoDriving = False
        self.autoDrivingStart = False

        self.controls = Controls(self.waypoints, self.robot)
        self.CONTROLS_UPDATE_RATE = 100
        controlThread = threading.Thread(target=self.controlsPeriodic,
                                         daemon=True)
        controlThread.start()
Ejemplo n.º 19
0
    def test_controls(self):
        '''Fake some key ups and key downs then check that changes control booleans'''
        self.screen = pygame.display.set_mode((50, 50), pygame.RESIZABLE)
        test_controls = Controls(verbose=False)
        test_controls.path = test_controls.path.replace(
            'static', 'test/static')
        events = [
            pygame.event.Event(pygame.KEYDOWN, key=control, mod=4096)
            for control in test_controls.control_lookup
        ]
        test_controls.get_events(events, self.screen, 50, 50)
        for key in test_controls.buttons:
            self.assertTrue(test_controls.buttons[key])

        events = [
            pygame.event.Event(pygame.KEYUP, key=control, mod=4096)
            for control in test_controls.control_lookup
        ]
        test_controls.get_events(events, self.screen, 50, 50)
        for key in test_controls.buttons:
            self.assertFalse(test_controls.buttons[key])
Ejemplo n.º 20
0
    def __init__(self, screen: Surface, map_: str, heroes: int, monsters: int,
                 items: int):
        """  Создаёт игру
        :param heroes: колличество героев в игре. Если players_count=0, то создаст читера.
        """
        self.start_time = datetime.now()
        self.screen = screen
        # map
        self.map: Map = self._init_map(map_)  # карта
        self.maps: Group = Group(self.map)
        # sprites
        self.characters: Group = Group()  # спрайты с героями и монстрами
        self.heroes: Group = self._init_heroes(heroes)  # спрайты с героями
        self.monsters: Group = self._init_monsters(
            monsters)  # спрайты с монстрами
        self.items: Group = self._init_items(items)  # спрайты с вещами

        self._start_turn()
        self.dashboard = Dashboard(self)  # приборная панель
        self.backpack: Backpack = Backpack(self)  # рюкзак
        self.controls: Controls = Controls(self)  # help
        self.monsters_killed = 0
Ejemplo n.º 21
0
 def __init__(self):
     self.snake = Snake()
     self.controls = Controls()
     self.textFont = pygame.font.Font(config.FONT, 13)
     self.game_over = False
     self.textOffset = (3, 3)
     self.scoreText = Text(
         self.textFont,
         "Your Score: {:}".format(self.snake.snake_length - 1),
         config.BLACK,
         tX=self.textOffset[0],
         tY=self.textOffset[0])
     self.spawnTime = 50  # In frames
     self.foodSmall = Food(
         (config.DIS_WIDTH,
          config.DIS_HEIGHT - self.scoreText.tH - self.textOffset[1]), 2)
     self.foodBig = Food(
         (config.DIS_WIDTH,
          config.DIS_HEIGHT - self.scoreText.tH - self.textOffset[1]),
         3,
         self.spawnTime,
         0.5,
         config.GREEN,
         blink_rate=2)
     self.foodBig.turn_idle()
     self.cursorPos = 0
     self.eatSound = pygame.mixer.Sound("sounds/eat.wav")
     self.eatBigSound = pygame.mixer.Sound("sounds/eatBig_2.wav")
     self.selectSound = pygame.mixer.Sound("sounds/select.wav")
     self.nextScene = self
     self.screen_shake = 0
     self.menuScene = None
     self.pauseMenu = Menu(self.textFont, ('P A U S E', config.WHITE),
                           ('Continue', config.WHITE),
                           ('Exit', config.WHITE))
     self.gameOverMenu = Menu(self.textFont,
                              ('G A M E   O V E R', config.RED),
                              ('Retry', config.WHITE),
                              ('Exit', config.WHITE))
    def setUp(self):
        config = Mock()
        config.drive_kp = 40
        config.drive_ki = 1
        config.drive_kd = 1
        config.heading_error_threshold = 0.2
        config.max_forward_speed = 512
        config.max_intake_speed = 512
        config.max_outtake_speed = 512

        self.controls = Controls(config)

        self.plan_state = {
            'pose': ((0, 0), 0),
            'trajectory': None,
            'tube_mode': 'NONE',
            'direction': 0,
            'field_outtake': 0,
            'flail': False,
            'goal': None,
        }

        self.vehicle_commands = {}
Ejemplo n.º 23
0
def run():
    signals = {
        'green': False,
        'red': False,
        'blue': False,
        'stop': False,
        'metal': False,
        'maxTime': False,
        'finish': False,
        'path': '/home/pi/Filakov/',
        'pltCnt': 1,
        'imgCnt': 1
    }

    start = time.time()

    # Make directory for the pictures
    directory = datetime.datetime.today().strftime('%Y-%m-%d_%H-%M-%S')
    signals['path'] += directory + '/'
    try:
        os.makedirs(signals['path'])
    except Exception as e:
        debug_print(str(e))
        debug_print('Folder for pictures was not created. Aborting program...')
        return

    global output_file
    output_file = open(signals['path'] + 'log.txt', 'w', encoding='utf-8')

    C = Controls("/dev/ttyACM0", output_file)
    if not C.started:
        debug_print(
            "Controls of the motors are not started. Aborting program...")
        output_file.close()
        return

    cam = cv2.VideoCapture(0)
    time.sleep(1)
    if not cam.isOpened():
        debug_print("Camera is not opened. Aborting program...")
        output_file.close()
        return

    # Run the process
    T_metal = threading.Thread(target=metalCheck, args=(
        C,
        signals,
    ))
    T_cam = threading.Thread(target=cameraLoop, args=(
        cam,
        signals,
    ))
    T_metal.start()
    T_cam.start()

    # Canvas down
    C.Move(3, 'M', 250, wait=True)

    C.Lights(1)
    # Camera calibration
    #    C.Move(2, 'M', 180, wait = True)
    #    calibrateCamera(C, signals)
    #    if signals['stop']:
    #        stopRoutine(C, signals)
    #        return

    C.Move(2, 'M', 180, wait=True)
    #    debug_print('Camera calibrated successfully.')

    # First iteration of plant imaging
    plantIter(C, cam, '-', signals)
    if signals['stop']:
        stopRoutine(C, signals)
        signals['finish'] = True
        T_cam.join()
        T_metal.join()
        output_file.close()
        return

    # Second iteration of plant imaging
    debug_print('Preparing plant imaging on the other side.')
    C.Move(2, 'M', -180, wait=True)
    plantIter(C, cam, '+', signals)
    if signals['stop']:
        stopRoutine(C, signals)
        signals['finish'] = True
        T_cam.join()
        T_metal.join()
        output_file.close()
        return

    # Finishing routine
    debug_print('Vertical motor returning to home position.')
    C.Move(1, 'H', wait=True)
    debug_print('Job done: ' + str(time.time() - start) + ' secs')

    signals['finish'] = True
    T_cam.join()
    T_metal.join()
    C.Lights(0)
    # Canvas up
    C.Move(3, 'M', -250, wait=True)
    C.Close()

    uploadCloudFolder(signals['path'])
    output_file.close()
    sendDoneMail(signals['path'] + 'log.txt')
Ejemplo n.º 24
0
    def __init__(self):
        super().__init__()
        self.canvas_show = 'pie'  # or 'sleep'

        self.withdraw()
        splash = Splash(self)
        splash.pgb['maximum'] = 5

        import matplotlib
        import math
        self.math = math
        import matplotlib.pyplot as plt
        self.plt = plt
        from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
        from tkinter.ttk import Progressbar, Style

        splash.pgb['value'] = 1
        splash.label.image = splash.gif1
        splash.update()

        plt.style.use('ggplot')

        matplotlib.rcParams['font.family'] = 'SimHei'
        self.Set3 = plt.cm.Set3(range(10))
        self.Paired = plt.cm.Paired(range(10))

        splash.pgb['value'] = 2
        splash.label.image = splash.gif1
        splash.update()

        # +++++++++++++++
        # +  GUI_setup  +
        # +++++++++++++++
        from tkinter import Frame, Text
        from tkinter import ttk
        from tkinter.ttk import Button
        self.title('Weekery')
        #Style().theme_use('clam')
        '''
        root
        |- Progressbar.bottom
        |- Frame_Left
        |  |- Frame_btn_left.top
        |  |  |- left(btn{d,w,m,y})
        |  |  |- right(btn{sleep,freq_pic,freq_bar})
        |  |  |- Frame_btn_mid
        |  |     |- <.left
        |  |     |- +.left
        |  |     |- >.right
        |  |     |- -.right
        |  |     |- calendar.middle
        |  |     |- label_date
        |  |- fig_up.top
        |  |- fig_down.top
        |- Frame_Right
           |- Frame_btn_right
           |  |- btn_setting.right
           |  |- btn_reload.right
           |- Text.bottom.top expand=both
        '''
        # ====== Frames ======
        self.frame_left = Frame(self)

        self.frame_right = Frame(self)

        self.frame_btn_left = Frame(self.frame_left)
        self.frame_btn_left.config(bg='white')
        self.frame_btn_mid = Frame(self.frame_btn_left)

        self.frame_btn_right = Frame(self.frame_right)
        self.frame_btn_right.config(bg='white')

        # ====== Buttons ======
        ttk.Style().configure("TButton", background='white')
        ttk.Style().configure("symbol.TButton", font=(20))
        #ttk.Style().configure("TButton", foreground='white')
        self.btn_days = Button(self.frame_btn_left, text='日', command=self.days, width=3)
        self.btn_days.config(state='disable') #bg='white', 
        self.btn_weeks = Button(self.frame_btn_left, text='周', command=self.weeks, width=3)
        #self.btn_weeks.config(bg='white')
        self.btn_months = Button(self.frame_btn_left, text='月', command=self.months, width=3)
        #self.btn_months.config(bg='white')
        self.btn_years = Button(self.frame_btn_left, text='年', command=self.years, width=3)
        #self.btn_years.config(bg='white')
        self.btn_switch_freq_pie = Button(self.frame_btn_left, text='饼图', command=self.pie, width=6)
        #self.btn_switch_freq_pie.config(bg='white')
        self.btn_switch_sleep = Button(self.frame_btn_left, text='睡眠', command=self.sleep, width=6)
        #self.btn_switch_sleep.config(bg='white')
        self.btn_switch_freq_bar = Button(self.frame_btn_left, text='词频', command=self.bar, width=6)
        #self.btn_switch_freq_bar.config(bg='white')

        self.btn_previous = Button(self.frame_btn_mid, text='◀', style='symbol.TButton', command=self.previous, width=2)
        #self.btn_previous.config(bg='white')
        self.btn_backward = Button(self.frame_btn_mid, text='▶', style='symbol.TButton',command=self.backward, width=2)
        #self.btn_backward.config(bg='white')
        self.btn_calendar = Button(self.frame_btn_mid, text="▦", style='symbol.TButton',command=self.ask_selected_date, width=2)
        #self.btn_calendar.config(bg='white')
        self.btn_plus = Button(self.frame_btn_mid, text='+', style='symbol.TButton', command=self.plus, width=2)
        #self.btn_plus.config(bg='white')
        self.btn_minus = Button(self.frame_btn_mid, text='-',style='symbol.TButton', command=self.minus, width=2)
        #self.btn_minus.config(bg='white')

        self.btn_reload = Button(self.frame_btn_right, text='重载', command=self.reload, width=6)
        #self.btn_reload.config(bg='white')
        self.btn_settings = Button(self.frame_btn_right, text='设置', command=self.settings, width=6)
        #self.btn_settings.config(bg='white')

        # ====== Others ======
        self.fig_up = plt.figure(figsize=(7, 3))
        self.fig_down = plt.figure(figsize=(7, 3))
        self.canvas_up = FigureCanvasTkAgg(self.fig_up, master=self.frame_left)
        self.canvas_down = FigureCanvasTkAgg(self.fig_down, master=self.frame_left)

        self.pgb = Progressbar(self, orient='horizontal', length=1000, mode='determinate')

        self.notes = Text(self.frame_right, width=50)
        self.notes.config(bg='azure')
        
        self.label_date = Label(self.frame_btn_mid, text='加载中...', width=15)

        splash.pgb['value'] = 3
        splash.label.image = splash.gif1
        splash.update()

        # ++++++++++++++++++
        # +  GUI Packing   +
        # ++++++++++++++++++
        # level-1
        self.pgb.pack(side='bottom', fill='both')

        # level-1
        self.frame_left.pack(side='left', fill='both', expand='YES')
        # # level-2
        self.frame_btn_left.pack(side='top', fill='both')
        self.canvas_up.get_tk_widget().pack(side='top', fill='both', expand='YES')
        self.canvas_down.get_tk_widget().pack(side='top', fill='both', expand='YES')
        # # # level-3
        self.btn_days.pack(side='left')
        self.btn_weeks.pack(side='left')
        self.btn_months.pack(side='left')
        self.btn_years.pack(side='left')
        self.btn_switch_freq_bar.pack(side='right')
        self.btn_switch_freq_pie.pack(side='right')
        self.btn_switch_sleep.pack(side='right')
        self.frame_btn_mid.pack(side='top')
        # # # # level-4
        self.btn_previous.pack(side='left')
        self.btn_minus.pack(side='left')
        self.btn_backward.pack(side='right')
        self.btn_plus.pack(side='right')
        self.btn_calendar.pack(side='left')
        self.label_date.pack(side='right')

        # level-1
        self.frame_right.pack(side='left', fill='both', expand='YES')
        # # level-2
        self.frame_btn_right.pack(side='top', fill='both')
        # # # level-3
        self.btn_settings.pack(side='right')
        self.btn_reload.pack(side='right')
        # # level-2
        self.notes.pack(side='top', fill='both', expand='YES')

        splash.pgb['value'] = 4
        splash.label.image = splash.gif1
        splash.update()

        # ++++++++++++++++++
        # +  Import class  +
        # ++++++++++++++++++
        import sqlite3
        from config import Config
        from controls import Controls
        from load_data import wiz_week_index, read_data
        splash.pgb['value'] = 5
        splash.label.image = splash.gif1
        splash.update()
        splash.destroy()
        # ============= Show Main GUI ==============
        self.protocol('WM_DELETE_WINDOW', self.close_window)
        self.wm_state('zoomed')  # maximize windows
        self.deiconify()

        self.cfg = Config(self)
        
        # user choose to cancle in configuration
        if self.cfg.cancel:
            return
            
        self.db_path = self.cfg.cache_dir + '/weekery.db'
        self.conn = sqlite3.connect(self.db_path)

        self.id_filenames, self.id_dates = wiz_week_index(self.cfg)

        if self.cfg.last_read == 20160000:
            read_data(self, self.cfg, self.pgb, self.id_dates, self.id_filenames, 'all')
        else:
            read_data(self, self.cfg, self.pgb, self.id_dates, self.id_filenames, dialog=False)

        self.controls = Controls(self.conn)
        self.conn.commit()

        self.colors = {v: (int(f[4:7])/255, int(f[9:12])/255, int(f[14:17])/255, 1) for f, v in self.cfg.color_kind.items()}
        self._paint()
def main():

    # Initialize the library
    if not glfw.init():
        raise RuntimeError("Failed to initialize GLFW")

    glfw.window_hint(glfw.SAMPLES, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # To make MacOS happy; should not be needed
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(1024, 768, "Tutorial 09 - VBO Indexing", None, None)
    if not window:
        glfw.terminate()
        raise RuntimeError("Failed to open GLFW window.")

    # Make the window's context current
    glfw.make_context_current(window)

    # Ensure we can capture the escape key being pressed below
    glfw.set_input_mode(window, glfw.STICKY_KEYS, True)

    # Hide the mouse and enable unlimited mouvement
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    # Set the mouse at the center of the screen
    glfw.poll_events()
    glfw.set_cursor_pos(window, 1024/2, 768/2)

    # Dark blue background
    glClearColor(0.0, 0.0, 0.4, 0.0)

    # Enable depth test
    glEnable(GL_DEPTH_TEST)
    # Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS)

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    # Create and compile our GLSL program from the shaders
    shader = Shader("StandardShading.vertexshader", "StandardShading.fragmentshader")
    shader.compile()

    # Create Controls object
    controls = Controls(window)
    
    # Load the texture using any two methods
    Texture = loadDDS("uvmap2.DDS")

    # Read our .obj file
    vertices, uvs, normals = loadOBJ("suzanne.obj",invert_v=True)

    indices,indexed_vertices,indexed_uvs,indexed_normals = indexVBO(vertices,uvs,normals)

    # Create the vertex buffer object
    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, indexed_vertices.nbytes, indexed_vertices, GL_STATIC_DRAW)

    # Create the uv buffer object
    uvbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, uvbo)
    glBufferData(GL_ARRAY_BUFFER, indexed_uvs.nbytes, indexed_uvs, GL_STATIC_DRAW)

    # Create normal buffer object
    nbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, nbo)
    glBufferData(GL_ARRAY_BUFFER, indexed_normals.nbytes, indexed_normals, GL_STATIC_DRAW)

    # Generate a buffer for the indices as well
    ibo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, ibo)
    glBufferData(GL_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW)

    # For speed computation
    lastTime = glfw.get_time()
    nbFrames = 0

    # Loop until the user closes the window
    while( glfw.get_key(window, glfw.KEY_ESCAPE ) != glfw.PRESS and
            glfw.window_should_close(window) == 0 ):

        # Measure speed
        currentTime = glfw.get_time()
        nbFrames += 1
        if currentTime-lastTime >= 1.0: 
            # If last prinf() was more than 1sec ago
            # printf and reset
            print("{:.5f} ms/frame".format(1000.0/float(nbFrames)))
            nbFrames = 0
            lastTime += 1.0
        
        # Clear the screen
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )

        # Use our shader
        shader.enable()

        # Compute the MVP matrix from keyboard and mouse input
        controls.update()

        # Send our transformation to the currently bound shader, 
        # in the "MVP" uniform
        shader.setUniform("V", "mat4", np.array(controls.ViewMatrix,dtype=np.float32))
        shader.setUniform("M", "mat4", np.array(controls.ModelMatrix,dtype=np.float32))
        shader.setUniform("MVP", "mat4", controls.MVP)

        shader.setUniform("LightPosition_worldspace", "vec3", 
                np.array([4,4,4],dtype=np.float32))

        # Bind our texture in Texture Unit 0
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, Texture)

        # Set our "myTextureSampler" sampler to user Texture Unit 0
        shader.setUniform("myTextureSampler","sampler2D",0)

        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, vbo)
        glVertexAttribPointer(
                0,         # attribute 0.
                3,         # size
                GL_FLOAT,  # type
                GL_FALSE,  # normalized?
                0,         # stride
                None       # array buffer offset
        )

        # 2nd attribute buffer : UVs
        glEnableVertexAttribArray(1)
        glBindBuffer(GL_ARRAY_BUFFER, uvbo)
        glVertexAttribPointer(
                1,         # attribute.
                2,         # size
                GL_FLOAT,  # type
                GL_FALSE,  # normalized?
                0,         # stride
                None       # array buffer offset
        )

        # 3rd attribute buffer : UVs
        glEnableVertexAttribArray(2)
        glBindBuffer(GL_ARRAY_BUFFER, nbo)
        glVertexAttribPointer(
                2,         # attribute.
                3,         # size
                GL_FLOAT,  # type
                GL_FALSE,  # normalized?
                0,         # stride
                None       # array buffer offset
        )
        
        # Index buffer
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo)

        # Draw the triangles !
        glDrawElements(
            GL_TRIANGLES,      # mode
            len(indices),      # count
            GL_UNSIGNED_SHORT, # type
            None               # element array buffer offset
        )

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)
    
        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Ejemplo n.º 26
0
from controls import Controls
from entity import particle
from entity.player import LocalPlayer, Player
from gui import examine
from gui.cursor import Cursor
from net import client, host, common

# debug imports
from weapon.gun import Gun
from perk import DroppedPerk, perk_collide
from perk.angelboots import AngelBoots

EXIT = 0
RUNNING = 1

controls = Controls()
player1 = LocalPlayer("pluto", controls)
player2 = None

cursor = Cursor(options.centre(), font.regular)
state = 1

ab = AngelBoots()

is_host = False


def init():
    particle.init()

    render.add_screen_sprites(cursor, cursor.hover_text)
Ejemplo n.º 27
0
            if (keys[pygame.K_6]):
                playersWaiting["total"] = 6
            if (keys[pygame.K_7]):
                playersWaiting["total"] = 7
            if (keys[pygame.K_8]):
                playersWaiting["total"] = 8
        pygame.display.flip()

    # actually make the game
    controls = []
    joysticks = [
        pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())
    ]
    for joystick in joysticks:
        joystick.init()
        controls.append(Controls(None, joystick, None))

    for network in network_player.players:
        controls.append(Controls(None, None, network_player.players[network]))

    for i in range(0, playersWaiting["total"] - len(controls)):
        controls.append(Controls(CONTROLS[i], None, None))

    game_mode = game_modes.generate_basic(SCREEN_WIDTH, SCREEN_HEIGHT,
                                          controls)

    p = Game(screen, game_mode)
    p.run()

    pygame.quit()
    sys.exit(0)
Ejemplo n.º 28
0
from os import listdir
from os.path import isfile, join
from controls import Controls
from ocr import OCR
import time

#MAIN
ocrEngine = OCR("log/model.ckpt", "log/dict.pickle")
#get list of source images in images folder
imageList = [join("./images/",f) for f in listdir("./images/") if isfile(join("./images/",f)) and f[0] != '.' and f != 'test.jpeg']
if len(imageList) == 0:
    raise StandardError("No files in images/ directory")
#initialize window and control panel positions with stock trackbars
cv2.namedWindow('display', cv2.WINDOW_NORMAL)
controlsList = [(0,150,255), (0,255,255), (3,5,10), (0,0,len(imageList) - 1)]
ctrl = Controls(controlsList)
cv2.resizeWindow('display', 800,600)
cv2.moveWindow('display', 100,0)
image = cv2.imread(imageList[ctrl.t[3]])
currentImageNo = ctrl.t[3]

#initialize variables
cv2.imshow('display',image)
while True:
    if currentImageNo != ctrl.t[3]: 
        image = cv2.imread(imageList[ctrl.t[3]])
        currentImageNo = ctrl.t[3]

    cv2.imshow('display',image)
    key = cv2.waitKey(10000)
    cutouts, chars = ocrEngine.ProcessImage(image)
Ejemplo n.º 29
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.player = None

        self._alert = None
        self._playlist_jobject = None

        self.set_title(_('Jukebox Activity'))
        self.max_participants = 1

        toolbar_box = ToolbarBox()
        activity_button = ActivityToolbarButton(self)
        activity_toolbar = activity_button.page
        toolbar_box.toolbar.insert(activity_button, 0)
        self.title_entry = activity_toolbar.title

        self._view_toolbar = ViewToolbar()
        self._view_toolbar.connect('go-fullscreen', self.__go_fullscreen_cb)
        self._view_toolbar.connect('toggle-playlist',
                                   self.__toggle_playlist_cb)
        view_toolbar_button = ToolbarButton(page=self._view_toolbar,
                                            icon_name='toolbar-view')
        self._view_toolbar.show()
        toolbar_box.toolbar.insert(view_toolbar_button, -1)
        view_toolbar_button.show()

        self._control_toolbar = Gtk.Toolbar()
        self._control_toolbar_button = ToolbarButton(
            page=self._control_toolbar, icon_name='media-playback-start')
        self._control_toolbar.show()
        toolbar_box.toolbar.insert(self._control_toolbar_button, -1)
        self._control_toolbar_button.hide()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.connect('key_press_event', self.__key_press_event_cb)
        self.connect('playlist-finished', self.__playlist_finished_cb)

        # We want to be notified when the activity gets the focus or
        # loses it. When it is not active, we don't need to keep
        # reproducing the video
        self.connect('notify::active', self.__notify_active_cb)

        self._video_canvas = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        self._playlist_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        self.playlist_widget = PlayList()
        self.playlist_widget.connect('play-index', self.__play_index_cb)
        self.playlist_widget.connect('missing-tracks',
                                     self.__missing_tracks_cb)
        self.playlist_widget.set_size_request(
            Gdk.Screen.width() * PLAYLIST_WIDTH_PROP, 0)
        self.playlist_widget.show()

        self._playlist_box.pack_start(self.playlist_widget,
                                      expand=True,
                                      fill=True,
                                      padding=0)

        self._playlist_toolbar = Gtk.Toolbar()

        move_up = ToolButton("go-up")
        move_up.set_tooltip(_("Move up"))
        move_up.connect("clicked", self._move_up_cb)
        self._playlist_toolbar.insert(move_up, 0)

        move_down = ToolButton("go-down")
        move_down.set_tooltip(_("Move down"))
        move_down.connect("clicked", self._move_down_cb)
        self._playlist_toolbar.insert(move_down, 1)

        self._playlist_box.pack_end(self._playlist_toolbar, False, False, 0)
        self._video_canvas.pack_start(self._playlist_box, False, False, 0)

        # Create the player just once
        logging.debug('Instantiating GstPlayer')
        self.player = GstPlayer()
        self.player.connect('eos', self.__player_eos_cb)
        self.player.connect('error', self.__player_error_cb)
        self.player.connect('play', self.__player_play_cb)

        self.control = Controls(self, toolbar_box.toolbar,
                                self._control_toolbar)

        self._separator = Gtk.SeparatorToolItem()
        self._separator.props.draw = False
        self._separator.set_expand(True)
        self._separator.show()
        toolbar_box.toolbar.insert(self._separator, -1)

        self._stop = StopButton(self)
        toolbar_box.toolbar.insert(self._stop, -1)

        self._empty_widget = Gtk.Label(label="")
        self._empty_widget.show()
        self.videowidget = VideoWidget()
        self.set_canvas(self._video_canvas)
        self._init_view_area()
        self.show_all()
        # need hide the playlist by default
        self._playlist_box.hide()

        self._configure_cb()

        self.player.init_view_area(self.videowidget)

        self._volume_monitor = Gio.VolumeMonitor.get()
        self._volume_monitor.connect('mount-added', self.__mount_added_cb)
        self._volume_monitor.connect('mount-removed', self.__mount_removed_cb)

        if handle.object_id is None:
            # The activity was launched from scratch. We need to show
            # the Empty Widget
            self.playlist_widget.hide()
            emptypanel.show(self, 'activity-jukebox', _('No media'),
                            _('Choose media files'),
                            self.control.show_picker_cb)

        self.control.check_if_next_prev()

        Gdk.Screen.get_default().connect('size-changed', self._configure_cb)
Ejemplo n.º 30
0
 def enterControls(self):
     self.controls = Controls()