Esempio n. 1
0
    def on_layout(self, winsize):
        width, height = self.image.size
        display_width = Window.width / 3.5
        self.image_rect.pos = (Window.width - display_width) / 20, (
            Window.height - 1 / self.w_h_ratio * display_width) // 2
        self.image_rect.size = (display_width,
                                1 / self.w_h_ratio * display_width)
        self.pixelate_rect.pos = (Window.width - display_width) / 2, (
            Window.height - 1 / self.w_h_ratio * display_width) // 2
        self.pixelate_rect.size = (display_width,
                                   1 / self.w_h_ratio * display_width)
        self.domino_rect.pos = 19 * (Window.width - display_width) / 20, (
            Window.height - 1 / self.w_h_ratio * display_width) // 2
        self.domino_rect.size = (display_width,
                                 1 / self.w_h_ratio * display_width)

        self.generate_button.pos = (
            Window.width - 0.75 * display_width) / 2, self.pixelate_rect.pos[
                1] - Window.height // 10 - 0.75 * display_width / 4.24
        self.generate_button.size = (0.75 * display_width,
                                     0.75 * display_width / 4.24)

        if self.pixel_slider in self.canvas.children:
            self.canvas.remove(self.pixel_slider)

        self.pixel_slider = Slider(1, self.pixelate_rect.pos,
                                   self.pixelate_rect.size)
        self.canvas.add(self.pixel_slider)

        self.label.center_x = Window.width / 2
        self.label.center_y = (Window.height + 1 / self.w_h_ratio *
                               display_width) // 2 + Window.height / 20
        self.label.font_size = str(Window.width // 170) + 'sp'

        self.color_switch.on_layout()
    def __init__(self):
        self.tk = Tk()
        #self.tk.configure(background='black')
        #self.topFrame = Frame(self.tk, background='black')
        #self.bottomFrame = Frame(self.tk, background='black')
        #self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        #self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
        #self.state = False
        self.tk.geometry("{0}x{1}+0+0".format(self.tk.winfo_screenwidth(),
                                              self.tk.winfo_screenheight()))
        self.tk.attributes('-fullscreen', True)
        self.fname = 'assets/rpi_bg.png'  #'assets/rpi_bg.png'
        self.bg_image = ImageTk.PhotoImage(file=self.fname)
        self.cv = Canvas(width=self.tk.winfo_screenwidth(),
                         height=self.tk.winfo_screenheight(),
                         highlightthickness=0)
        self.cv.pack(side=TOP, fill=BOTH, expand=YES)
        self.cv.create_image(0, 0, image=self.bg_image, anchor=NW)

        self.topFrame = Frame(self.cv, background='')
        self.bottomFrame = Frame(self.cv, background='')
        self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
        self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)

        #Clock
        self.clock = Clock(self.topFrame)
        self.clock.pack(side=RIGHT, anchor=N, padx=100, pady=60)

        #Slider
        self.slider = Slider(self.bottomFrame)
        self.slider.pack(side=BOTTOM, anchor=CENTER)

        #Weather
        self.weather = Weather(self.topFrame)
        self.weather.pack(side=LEFT, anchor=N, padx=100, pady=60)
Esempio n. 3
0
    def sliders(self):

        randCols = [0, 50, 200, 250]

        self.startSlider = Slider(
            self.scr,
            pos_size=[200, 100, 160, 40],
            steps=10,
            colour=(randCols[random.randint(0, 3)],
                    randCols[random.randint(0,
                                            3)], randCols[random.randint(0,
                                                                         3)]),
            secondary_colour=(randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)]),
        )

        self.startSlider2 = Slider(
            self.scr,
            pos_size=[200, 50, 160, 40],
            steps=100,
            colour=(randCols[random.randint(0, 3)],
                    randCols[random.randint(0,
                                            3)], randCols[random.randint(0,
                                                                         3)]),
            secondary_colour=(randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)],
                              randCols[random.randint(0, 2)]),
        )
Esempio n. 4
0
    def __init__(self, data_path, params, search_params, threshold):
        # initialize helpers class
        self.FE = FeatureExtraction(params)
        self.Tr = Train(self.FE, data_path)
        self.SL = Slider(self.FE, search_params)
        self.Hr = Heater(threshold)

        # initialize the model and scaler
        self.clf, self.scaler = self.Tr.run()
Esempio n. 5
0
def test_cases_with_html(tmpdir, name):
    slider = Slider()

    pages = slider.parse(os.path.join('cases', '{}.md'.format(name)))
    with open(os.path.join('cases', 'dom', '{}.json'.format(name))) as fh:
        assert pages == json.load(fh)

    target_dir = str(tmpdir)
    print(target_dir)
    slider.generate_html_files(target_dir)
    compare_dirs(target_dir, os.path.join('cases', 'html', name), name)
Esempio n. 6
0
def settings():
    screen.fill([245, 245, 220])
    screen.blit(menu2.image, menu2.rect)
    start = True

    saves = open(os.path.join('data', 'lvl.txt'))
    c = saves.read().split()
    if c[4] == '0':
        hiden = f3.render('Привет я рада что ты сюда заглянул) Как тебе музыка?^-^', True, (80, 150, 80))
        screen.blit(hiden, (0, 600))
    c[4] = '1'
    copy = ' '.join(c)
    saves.close()
    f = open('data\lvl.txt', 'w')
    f.write(copy)
    f.close()

    info1 = f1.render("to move forvard print space or enter :3", True, (138, 43, 226))
    screen.blit(info1, (0, 268))
    info2 = f1.render("to back to menu click esc ", True, (138, 43, 226))
    screen.blit(info2, (0, 320))
    info3 = f1.render("BUT don't forget save your progress", True, (138, 43, 226))
    screen.blit(info3, (0, 372))
    info4 = f1.render("thanks for playing ;)", True, (138, 43, 226))
    screen.blit(info4, (0, 428))

    ex = f3.render('you still need esc to exit to menu', True, (215, 24, 104))
    screen.blit(ex, (0, 676))

    music = Slider("Music Volume", 300, 300, 1, (20, 20), (400, 70), f2)

    off = Button.Button()
    off.create_button(screen, (90, 255, 100), 30, 150, 200, 50, 0, 'off', (68, 45, 37))

    while start:
        music.draw(screen)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                start = False
                pygame.quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    start = False
                    startWindow()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if music.button_rect.collidepoint(pos):
                    music.hit = True
                    pygame.mixer.music.set_volume(int(music.get_value()) / 300)
                if off.pressed(pos):
                    pygame.mixer.music.set_volume(0)
            elif event.type == pygame.MOUSEBUTTONUP:
                music.hit = False
        if music.hit:
            music.move()

    pygame.quit()
Esempio n. 7
0
    def __init__(self, filepath, **kwargs):
        super(Homepage, self).__init__(**kwargs)

        self.filepath = filepath
        self.filename = filepath.replace('.', '/').split('/')[-2]

        Window.clearcolor = (0.2, 0.2, 0.2, 1)
        self.color_switch = Switch()
        self.canvas.add(self.color_switch)

        # LEFT IMAGE #
        im = Image.open(filepath).convert("RGBA")
        self.image = im.copy()
        width, height = self.image.size
        self.w_h_ratio = width / height
        self.image_rect = Rectangle(texture=CoreImage(self.filepath).texture)
        self.canvas.add(self.image_rect)

        # CENTER PIXELATED IMAGE & SLIDER #
        self.pixeate_image = im.copy()
        self.pixelate_rect = Rectangle()
        self.canvas.add(self.pixelate_rect)
        self.value = None
        self.pixel_slider = Slider(
            1, ((Window.width - self.image_rect.size[0]) // 2,
                (Window.height - self.image_rect.size[1]) // 2),
            self.pixelate_rect.size)

        self.generate_pressed = False
        self.generate_button = Rectangle(
            texture=CoreImage('./buttons/generate_button.png').texture)
        self.canvas.add(self.generate_button)

        # RIGHT DOMINO IMAGE #
        self.domino_image = Image.new(mode='RGBA',
                                      size=(width, height),
                                      color=(235, 74, 90, 150))
        data = BytesIO()
        self.domino_image.save(data, format='png')
        data.seek(0)
        self.domino_rect = Rectangle(
            texture=CoreImage(BytesIO(data.read()), ext='png').texture)
        self.canvas.add(self.domino_rect)

        self.label = Label()
        self.add_widget(self.label)

        self.imgSmall = None

        self.on_update()
        self.on_layout((Window.width, Window.height))
    def create_widgets(self):
        self.base_var = tk.IntVar()
        self.base_slider = Slider("Base Value",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.base_var)
        self.base_slider.grid(row=0, column=0)

        self.extra_var = tk.IntVar()
        self.extra_slider = Slider("Extra Value",
                                   from_=0,
                                   to_=40,
                                   master=self,
                                   variable=self.extra_var)
        self.extra_slider.grid(row=0, column=1)

        self.accA_var = tk.IntVar()
        self.accA_slider = Slider("Acceleration A",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.accA_var)
        self.accA_slider.grid(row=1, column=0)

        self.accB_var = tk.IntVar()
        self.accB_slider = Slider("Acceleration B",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.accB_var)
        self.accB_slider.grid(row=1, column=1)
Esempio n. 9
0
    def create_sliders(self):
        left_pos = (L_GOAL_LINE + SLIDER_DISTX, self.field.rect.centery)
        self.left_slider = Slider(self.field.surface,
                                  left_pos,
                                  group=self.sprites,
                                  color='red')
        self.sliders.append(self.left_slider)

        right_pos = (R_GOAL_LINE - SLIDER_DISTX, self.field.rect.centery)
        self.right_slider = Slider(self.field.surface,
                                   right_pos,
                                   group=self.sprites,
                                   color='blue')
        self.sliders.append(self.right_slider)
class Sliders(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.grid()
        self.create_widgets()
        self.bind_sliders()
        self.on_slider_value_changed(None)

    def create_widgets(self):
        self.base_var = tk.IntVar()
        self.base_slider = Slider("Base Value",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.base_var)
        self.base_slider.grid(row=0, column=0)

        self.extra_var = tk.IntVar()
        self.extra_slider = Slider("Extra Value",
                                   from_=0,
                                   to_=40,
                                   master=self,
                                   variable=self.extra_var)
        self.extra_slider.grid(row=0, column=1)

        self.accA_var = tk.IntVar()
        self.accA_slider = Slider("Acceleration A",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.accA_var)
        self.accA_slider.grid(row=1, column=0)

        self.accB_var = tk.IntVar()
        self.accB_slider = Slider("Acceleration B",
                                  from_=10,
                                  to_=50,
                                  master=self,
                                  variable=self.accB_var)
        self.accB_slider.grid(row=1, column=1)

    def bind_sliders(self):
        self.base_slider.slider.bind('<ButtonRelease-1>',
                                     self.on_slider_value_changed)
        self.extra_slider.slider.bind('<ButtonRelease-1>',
                                      self.on_slider_value_changed)
        self.accA_slider.slider.bind('<ButtonRelease-1>',
                                     self.on_slider_value_changed)
        self.accB_slider.slider.bind('<ButtonRelease-1>',
                                     self.on_slider_value_changed)

    def on_slider_value_changed(self, event):
        base = self.base_var.get()
        extra = self.extra_var.get()
        accA = self.accA_var.get()
        accB = self.accB_var.get()

        if self.master:
            self.master.on_slider_value_changed(base, extra, accA, accB)
Esempio n. 11
0
class SliderButton(ToggleButton):
    """
    Displays a button that will show a slider when toggled on, and hide it when toggled off.
    Provides a callback to receive the value of the slider, and one for when the sliding has stopped.
    """
    def __init__(self, interactor, value, min_val, max_val, label, on_show_slider=None, update=None, end=None, corner_radius=5, width=None,
                 height=None, left=0, top=0, image=None, bgcolor=(.5, .5, .5), fgcolor=(1,1,1), font="Arial",
                 opacity=1, size=14, states=None, halign=LEFT_ALIGN, valign=CENTER_ALIGN, point1=(0,.1), point2=(1,.1)):

        self.slider = Slider(interactor, update=update, end=end, title= label, value=value, min_val=min_val, max_val=max_val, point1=point1, point2=point2)

        def _show_slider():
            if on_show_slider:
                on_show_slider()
            self.slider.show()

        super(SliderButton, self).__init__(interactor, label, on=_show_slider, off=self.slider.hide, corner_radius=corner_radius, width=width,
                 height=height, left=left, top=top, image=image, bgcolor=bgcolor, fgcolor=fgcolor, font=font,
                 opacity=opacity, size=size, states= states, on_prefix="Show", off_prefix="Hide", halign=halign, valign=valign)

    def get_value(self):
        return self.slider.repr.GetValue()

    def set_value(self, value):
        self.slider.repr.SetValue(value)

    def show(self):
        state = self.repr.GetState()
        if state == 1:
            self.slider.show()

        super(SliderButton, self).show()

    def hide(self):
        self.slider.hide()
        super(SliderButton, self).hide()

    def detach(self):
        super(SliderButton, self).detach()
        self.slider.detach()

    def copy(self, interactor):
        value = self.slider.repr.GetValue()
        min_val = self.slider.repr.GetMinimumValue()
        max_val = self.slider.repr.GetMaximumValue()
        p1x, p1y, _ = self.slider.repr.GetPoint1Coordinate().GetValue()
        p2x, p2y, _ = self.slider.repr.GetPoint2Coordinate().GetValue()

        b = SliderButton(interactor, value, min_val, max_val, self.label, update=self.slider.update_callback, end=self.slider.end_callback,
                          corner_radius=self.radius, width=self.width, height=self.height, left=self.left, top=self.top, image=self.image,
                         bgcolor=self.bgcolor, fgcolor=self.fgcolor, opacity=self.opacity, size=self.size, states=self.states, halign=self.halign, valign=self.valign,
                         point1=(p1x,p1y), point2=(p2x, p2y))

        state = self.repr.GetState()
        if state != 0:
            b.set_state(state)
            b.action(state)

        return b
Esempio n. 12
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)
    def sliderMoved(self, active_slider):
        """
            update slider values and label texts according to slider coupling
        """
        alt_slider_list = []
        slide1 = Slider(slider=self.finger_slider_1,
                        label_val=self.value_slider_1,
                        tick=self.tick_f1.isChecked())
        slide2 = Slider(slider=self.finger_slider_2,
                        label_val=self.value_slider_2,
                        tick=self.tick_f2.isChecked())
        slide3 = Slider(slider=self.finger_slider_3,
                        label_val=self.value_slider_3,
                        tick=self.tick_f3.isChecked())
        slide4_tick = self.tick_f4.isChecked() if self.tick_f4.isVisible(
        ) else False
        slide4 = Slider(slider=self.finger_slider_4,
                        label_val=self.value_slider_4,
                        tick=slide4_tick)
        slide5 = Slider(slider=self.finger_slider_5,
                        label_val=self.value_slider_5,
                        tick=False)
        if active_slider == 1:
            this_slider = slide1
            alt_slider_list = [slide2, slide3,
                               slide4]  #slider 5 cant be coupled
        elif active_slider == 2:
            this_slider = slide2
            alt_slider_list = [slide1, slide3,
                               slide4]  #slider 5 cant be coupled
        elif active_slider == 3:
            this_slider = slide3
            alt_slider_list = [slide1, slide2,
                               slide4]  #slider 5 cant be coupled
        elif active_slider == 4:
            this_slider = slide4
            alt_slider_list = [slide1, slide2,
                               slide3]  #slider 5 cant be coupled
        elif active_slider == 5:
            this_slider = slide5

        curr_value = float(this_slider.getVal())
        float_value = curr_value / 100.0
        this_slider.setLabel("%2.2f" % float_value)
        if this_slider.getTickCheck():
            for slide in alt_slider_list:
                if slide.getTickCheck():
                    slide.setLabel("%2.2f" % float_value)
                    slide.setSlider(this_slider.getVal())
Esempio n. 14
0
    def __init__(self):
        Scene.__init__(self)

        self.BACKGROUND_COLOR = (0, 0, 0, 255)

        self.slider1 = Slider(
            (50, utils.SCREEN_H // 2 - Slider.HEIGHT),
            (pygame.K_w, pygame.K_s),
        )
        self.slider2 = Slider(
            (utils.SCREEN_W - Slider.WIDTH - 50, utils.SCREEN_H // 2 - Slider.HEIGHT),
            (pygame.K_UP, pygame.K_DOWN),
        )
        self.square  = Square(
            (utils.SCREEN_W // 2 - Square.WIDTH // 2, utils.SCREEN_H // 2 - Square.HEIGHT // 2),
        )
Esempio n. 15
0
    def __init__(self, ctl_settings, screen, label, top_y, height,
                 fullsize):
        super().__init__(ctl_settings, screen, label, top_y, height,
                         fullsize)

        self.timer = False

        self.padding = 50  # custom padding here

        self.button_x_spacing = 30

        # add slider to control playback speed: ctl_settings.bpm
        self.slider_bottom = self.rect.bottom - 10

        self.BPM = Slider(self.ctl_settings, self.screen, 0, 200,
                          self.rect.left + self.button_x_spacing,
                          self.slider_bottom, 'BPM', 'linear')
        self.BPM.automate(30) # set initial value

        # Display buttons in sequencer - to show sequence
        row1_y = self.rect.top + self.padding
        pb1 = Button(ctl_settings, screen,
                     self.BPM.rect.right + self.button_x_spacing, row1_y, '1')
        pb2 = Button(ctl_settings, screen,
                     pb1.rect.right + self.button_x_spacing, row1_y, '2')
        pb3 = Button(ctl_settings, screen,
                     pb2.rect.right + self.button_x_spacing, row1_y, '3')
        pb4 = Button(ctl_settings, screen,
                     pb3.rect.right + self.button_x_spacing, row1_y, '4')
        pb5 = Button(ctl_settings, screen,
                     pb4.rect.right + self.button_x_spacing, row1_y, '5')
        pb6 = Button(ctl_settings, screen,
                     pb5.rect.right + self.button_x_spacing, row1_y, '6')
        pb7 = Button(ctl_settings, screen,
                     pb6.rect.right + self.button_x_spacing, row1_y, '7')
        pb8 = Button(ctl_settings, screen,
                     pb7.rect.right + self.button_x_spacing, row1_y, '8')

        self.buttons = [pb1, pb2, pb3, pb4, pb5, pb6, pb7, pb8]  # add all buttons here

        # Control buttons in sequencer - to show sequence
        row2_y = pb1.rect.bottom + 13
        brick1 = Button(ctl_settings, screen,
                        self.BPM.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick2 = Button(ctl_settings, screen,
                        brick1.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick3 = Button(ctl_settings, screen,
                        brick2.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick4 = Button(ctl_settings, screen,
                        brick3.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick5 = Button(ctl_settings, screen,
                        brick4.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick6 = Button(ctl_settings, screen,
                        brick5.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick7 = Button(ctl_settings, screen,
                        brick6.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick8 = Button(ctl_settings, screen,
                        brick7.rect.right + self.button_x_spacing, row2_y, 'brick')
        self.brick_buttons = [brick1, brick2, brick3, brick4, brick5, brick6,
                              brick7, brick8]
Esempio n. 16
0
    def __init__(self, interactor, value, min_val, max_val, label,
                 on_show_slider=None, update=None, end=None, corner_radius=5, width=None,
                 height=None, left=0, top=0, image=None,
                 bgcolor=(.5, .5, .5), fgcolor=(1, 1, 1), font="Arial",
                 opacity=1, size=14, states=None, halign=LEFT_ALIGN,
                 valign=CENTER_ALIGN, point1=(0, .1), point2=(1, .1)):

        self.slider = Slider(
            interactor,
            update=update,
            end=end,
            title=label,
            value=value,
            min_val=min_val,
            max_val=max_val,
            point1=point1,
            point2=point2)

        def _show_slider():
            if on_show_slider:
                on_show_slider()
            self.slider.show()

        super(SliderButton, self).__init__(interactor, label, on=_show_slider, off=self.slider.hide,
                                           corner_radius=corner_radius, width=width,
                                           height=height, left=left, top=top, image=image,
                                           bgcolor=bgcolor, fgcolor=fgcolor, font=font,
                                           opacity=opacity, size=size, states=states, on_prefix="Show",
                                           off_prefix="Hide", halign=halign, valign=valign)
Esempio n. 17
0
    def __init__(self, pos, planet_from, planet_to, on_order):
        super().__init__(pos, planet_from)
        self.planet_from = planet_from
        self.planet_to = planet_to
        self.on_order = on_order

        self.tab = {'text': "Send Ships", 'color': PICO_PINK}

        ships = {**self.planet_from.ships}
        ships['colonist'] = self.planet_from.population

        y = 0
        self.sliders = {}
        for ship in ships.keys():
            if ships[ship]:
                if ship == "colonist":
                    name = "Worker"
                else:
                    name = ship.title()

                self.add(SimpleSprite((0, 0), 'assets/i-%s.png' % ship),
                         V2(0, y))
                self.add(
                    Text("%ss" % name, "small", (0, 0), PICO_WHITE, False),
                    V2(14, y + 2))
                slider = Slider(V2(0, 0), 80, 0, ships[ship])
                self.add(slider, V2(0, y + 12))
                self.sliders[ship] = slider
                y += 45

        self.add(Button(V2(0, 0), "LAUNCH", "small", self.on_launch_click),
                 V2(20, y))

        self.redraw()
Esempio n. 18
0
    def __init__(self, pos, planet_from, planet_to, on_order):
        super().__init__(pos, planet_to)
        self.planet_from = planet_from
        self.planet_to = planet_to
        self.on_order = on_order

        siegers_only = isinstance(self.planet_to, asteroid.Asteroid)

        self.tab = {'text': "Send Ships", 'color': PICO_PINK}

        ships = {**self.planet_from.ships}
        ships['colonist'] = self.planet_from.population

        y = 0
        self.sliders = {}
        for ship in ships.keys():
            if ships[ship]:
                if ship == "colonist":
                    name = "Worker"
                else:
                    name = SHIPS_BY_NAME[ship].get_display_name()

                color = PICO_WHITE
                disabled = False
                if siegers_only and not SHIPS_BY_NAME[ship].BOMBS:
                    disabled = True
                    color = PICO_DARKGRAY
                self.add(SimpleSprite((0, 0), 'assets/i-%s.png' % ship),
                         V2(0, y))
                self.add(Text("%ss" % name, "small", (0, 0), color, False),
                         V2(14, y + 2))
                disable_nums = None
                if self.planet_from.owning_civ.worker_loss > 0:
                    disable_nums = list(
                        range(1, self.planet_from.owning_civ.worker_loss + 1))
                slider = Slider(V2(0, 0),
                                80,
                                0,
                                ships[ship],
                                disabled=disabled,
                                disable_nums=disable_nums)
                self.add(slider, V2(0, y + 12))
                self.sliders[ship] = slider
                y += 45

        if not self.sliders:
            self.add(Text("No ships!", "small", V2(0, 0)), V2(0, 0))
            y += 25

        t = "LAUNCH"
        if game.Game.inst.input_mode == "joystick":
            t = "[*x*] LAUNCH"
        if not self.sliders:
            t = "BACK"
            if game.Game.inst.input_mode == "joystick":
                t = "[*circle*] BACK"
        self.add(Button(V2(0, 0), t, "small", self.on_launch_click), V2(20, y))

        self.redraw()
def sliderThread(name, frame, boxes):
    logging.info("Thread %s : starting...", name)
    for (x, y, window) in Slider(frame, name, stepSize=16, windowSize = (64, 64)):# name is a numerical value that determines what row this thread should handle
        ex_features, ex_hog_image = hog(window, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualize=True, multichannel = True)
        arr = ex_features.reshape(1, -1)
        if(arr.shape == (1, 128)):
            if bc.predict(arr):
                boxes.append((x, y, window))
Esempio n. 20
0
def startGame():
    global ticks 
    global mapWidth
    global mapHeight
    global pps
    global window
    global isPlaying 
    global subText
    global snakeHead
    global isPlayer
    global data
    global highScore
    global score
    global controls
    global sliders
    global preTraining
    global border
    global buttons
    
    
    reset()
    controls = pygame.image.load(dir_path+ '\imgs\controls.png')
    
    buttons = []
    
    buttons.append(Button(0, 480, 481, 60, "Pause", subText, (255,255,255), "pause"))
    buttons.append(Button(0, 541, 481, 60, "Menu", subText, (255,255,255), "menu"))
    if (not (isPlayer) and sliders == []):
        sliders.append(Slider(500, 20, 300, 20, 'ticks', (100, 40), 'Ticks', subText))
    
    
    
    border = pygame.Rect(0-borderWidth, 0-borderWidth, mapWidth*pps+(2*borderWidth), mapHeight*pps+(2*borderWidth))
    isPlaying = True
    
    clock = pygame.time.Clock()
    window.fill((0,0,0))
    
    update(buttons, sliders)
    if (not preTraining):
        snakeHead.addTail(direction)
    while isPlaying:
        if (preTraining or not isPlayer):
            isPlaying = False
            return 
        else:
            clock.tick(ticks)
            update(buttons, sliders)
        
    if (not preTraining):
        lost = subText.render('GAME OVER', True, (200,200,200))
        if (score > highScore):
            highScore = score
        window.blit(lost, (180, 200))
        pygame.display.update()
        titleScreen()
    return
Esempio n. 21
0
 def __init__(self):
     self.running = True
     self.numLoops = 300  # the number of times to loop around the circle
     self.step = 0.05  # take little steps
     self.spinAngle = 0.0
     self.controls: Dict[str, Control] = {
         "lblNumerator": Label((10, 14), "Numerator:"),
         "Numerator": Slider((150, 20), 1, 10, 4.3, 0.1),
         "lblDenominator": Label((10, 44), "Denominator:"),
         "Denominator": Slider((150, 50), 1, 10, 7.6, 0.1),
         "lblSpinning": Label((10, 80), "Spin?"),
         "Spinning": Checkbox((150, 80), True),
         "lblSpeed": Label((10, 104), "Spin speed:"),
         "Speed": Slider((150, 110), 1, 50, 3, 1),
         "lblScale": Label((10, 144), "Scale:"),
         "Scale": Slider((150, 150), 50, 380, 200, 10),
         "Color": Button((150, 200), "Change Color", Program.ChangeColor),
     }
Esempio n. 22
0
def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()

    Program.use()

    Program.forward_float("center_x", Display.center_x)
    Program.forward_float("center_y", Display.center_y)
    Program.forward_float("scale", Display.scale)
    Program.forward_int("iterations", Slider.iterations)

    Canvas.paint()

    Program.disable()

    Slider.paint()

    glutSwapBuffers()
Esempio n. 23
0
    def motion(x, y):
        position_x = x
        position_y = y

        if Controls._last_btn == GLUT_LEFT_BUTTON:
            if Slider.is_in_slider(Controls._last_position_x,
                                   Controls._last_position_y):
                Slider.update_slider_by_x(position_x, position_y)
            else:
                Display.center_x -= (position_x - Controls._last_position_x
                                     ) * Display.mouse_force
                Display.center_y += (position_y - Controls._last_position_y
                                     ) * Display.mouse_force

        Controls._last_position_x = position_x
        Controls._last_position_y = position_y

        glutPostRedisplay()
Esempio n. 24
0
def test_md_to_html_no_file_extension(tmpdir, name):
    slider = Slider()

    md_file = os.path.join('cases', 'input', '{}.md'.format(name))
    pages = slider.parse(md_file)
    with open(os.path.join('cases', 'output', 'dom',
                           '{}.json'.format(name))) as fh:
        assert pages == json.load(fh)

    target_dir = str(tmpdir)
    print(target_dir)

    html = OnePage(
        chapter=pages,
        includes=os.path.dirname(md_file),
    )
    html.generate_html_files(target_dir)
    compare_dirs(target_dir, os.path.join('cases', 'output', 'plain_html',
                                          name), name)
Esempio n. 25
0
    def __init__(self, ctl_settings, screen, label, top_y, wall_index):
        super().__init__(ctl_settings, screen, label, top_y)
        self.wall_index = wall_index
        self.wall_label = "Wall " + str(wall_index + 1)

        # sensor reading

        self.sensor_reading = DisplayValue(ctl_settings,
                                           self.screen,
                                           40,
                                           self.rect.bottom - self.padding,
                                           wall_index=wall_index,
                                           title='Sensor')

        self.slider_spacing = 50  # distance between sliders

        # fix the way wall number is added to message (move to slider.py?)
        self.slider_bottom = self.rect.bottom - self.padding

        micGainSL = Slider(self.ctl_settings, self.screen, 0, 1,
                           self.sensor_reading.rect.right + 10,
                           self.slider_bottom, '/micGain', wall_index, 'log')
        hpCutoffSL = Slider(self.ctl_settings, self.screen, 0, 10000,
                            micGainSL.rect.right + self.slider_spacing,
                            self.slider_bottom, '/hpCutoff', wall_index, 'exp')
        lpCutoffSL = Slider(self.ctl_settings, self.screen, 0, 20000,
                            hpCutoffSL.rect.right + self.slider_spacing,
                            self.slider_bottom, '/lpCutoff', wall_index, 'exp')
        resSL = Slider(self.ctl_settings, self.screen, 0, 1,
                       lpCutoffSL.rect.right + self.slider_spacing,
                       self.slider_bottom, '/res', wall_index, 'log')
        thresholdSL = Slider(self.ctl_settings, self.screen, 0.1, 50,
                             resSL.rect.right + self.slider_spacing,
                             self.slider_bottom, '/threshold', wall_index,
                             'linear')
        packetLengthSL = Slider(self.ctl_settings, self.screen, 0, 1000,
                                thresholdSL.rect.right + self.slider_spacing,
                                self.slider_bottom, '/packetLength',
                                wall_index, 'linear')
        delayLengthSL = Slider(self.ctl_settings, self.screen, 0, 10000,
                               packetLengthSL.rect.right + self.slider_spacing,
                               self.slider_bottom, '/delayLength', wall_index,
                               'linear')

        # Add all sliders to this list
        self.sliders = [
            micGainSL, hpCutoffSL, lpCutoffSL, resSL, thresholdSL,
            packetLengthSL, delayLengthSL
        ]

        # prep wall label
        self.prep_wall_label()
Esempio n. 26
0
def test_other_dir(tmpdir):
    root = str(tmpdir)
    original = os.getcwd()
    with cwd(root):
        slider = Slider()

        target_dir = os.path.join(root, 'html')
        os.mkdir(target_dir)
        md_file = os.path.join(original, 'cases', 'input', 'all.md')
        pages = slider.parse(md_file)
        with open(os.path.join(original, 'cases/output/dom/all.json')) as fh:
            expected = json.load(fh)
        assert expected == pages

        html = OnePage(
            chapter=pages,
            includes=os.path.dirname(md_file),
            ext='html',
        )

        html.generate_html_files(target_dir)
        compare_dirs(target_dir,
                     os.path.join(original, 'cases', 'output', 'html', 'all'),
                     'all')
Esempio n. 27
0
def test_exceptions(tmpdir):
    slider = Slider()
    path = os.path.join('cases', 'no-chapter-title.md')
    with pytest.raises(Exception) as exinfo:
        slider.parse(path)
    assert exinfo.type == SliderError
    assert str(exinfo.value) == 'Chapter title is missing in {}'.format(path)


    path = os.path.join('cases', 'no-chapter-id.md')
    with pytest.raises(Exception) as exinfo:
        slider.parse(path)
    assert exinfo.type == SliderError
    assert str(exinfo.value) == 'Chapter id is missing in {}'.format(path)


    path = os.path.join('cases', 'chapters.md')
    with pytest.raises(Exception) as exinfo:
        slider.parse(path)
    assert exinfo.type == SliderError
    assert str(exinfo.value) == 'Second chapter found in the same file in {}'.format(path)
Esempio n. 28
0
    def init_sliders(self):
        self.sliders.append(
            Slider(-5000, (-10000, 5000), 'g', (0, 5), "Gravity"))
        self.sliders.append(Slider(.1, (-1.0, 1.0), 'k', (0, 35), "Spring"))
        self.sliders.append(Slider(.6, (0, 1.0), 'd', (0, 65), "Dampening"))

        self.color_sliders.append(
            Slider(150, (0, 255), 'red', (0, 5), "red", (100, 10),
                   (255, 0, 0)))
        self.color_sliders.append(
            Slider(150, (0, 255), 'green', (0, 35), "green", (100, 10),
                   (0, 255, 0)))
        self.color_sliders.append(
            Slider(150, (0, 255), 'blue', (0, 65), "blue", (100, 10),
                   (0, 0, 255)))
Esempio n. 29
0
class Play(Scene):
    
    def __init__(self):
        Scene.__init__(self)

        self.BACKGROUND_COLOR = (0, 0, 0, 255)

        self.slider1 = Slider(
            (50, utils.SCREEN_H // 2 - Slider.HEIGHT),
            (pygame.K_w, pygame.K_s),
        )
        self.slider2 = Slider(
            (utils.SCREEN_W - Slider.WIDTH - 50, utils.SCREEN_H // 2 - Slider.HEIGHT),
            (pygame.K_UP, pygame.K_DOWN),
        )
        self.square  = Square(
            (utils.SCREEN_W // 2 - Square.WIDTH // 2, utils.SCREEN_H // 2 - Square.HEIGHT // 2),
        )

    def go_to_menu(self):
        from menu import Menu
        utils.set_scene( Menu() )

    def on_escape(self):
        self.go_to_menu()

    def update(self):
        keys = pygame.key.get_pressed()
        self.slider1.update(keys)
        self.slider2.update(keys)
        self.square.update( (self.slider1.fPos, self.slider2.fPos) )

    def blit(self):
        self.slider1.blit(utils.screen)
        self.slider2.blit(utils.screen)
        self.square.blit(utils.screen)
Esempio n. 30
0
def test_other_dir(tmpdir):
    root = str(tmpdir)
    cwd = os.getcwd()
    os.chdir(root)
    from slider import Slider, SliderError
    slider = Slider()

    target_dir = os.path.join(root, 'html')
    os.mkdir(target_dir)
    pages = slider.parse(os.path.join(cwd, 'cases', 'all.md'))
    slider.generate_html_files(target_dir)
    compare_dirs(target_dir, os.path.join(cwd, 'cases', 'html', 'all'), 'all')

    data = slider.process_yml(os.path.join(cwd, 'cases', 'multi.yml'))
    assert data == {}

    os.chdir(cwd)
Esempio n. 31
0
class videoPipeline():
    def __init__(self, data_path, params, search_params, threshold):
        # initialize helpers class
        self.FE = FeatureExtraction(params)
        self.Tr = Train(self.FE, data_path)
        self.SL = Slider(self.FE, search_params)
        self.Hr = Heater(threshold)

        # initialize the model and scaler
        self.clf, self.scaler = self.Tr.run()

    def process_image(self, img, draw=True):
        current_windows = self.SL.run_efficient(img, self.clf, self.scaler)
        draw_img, heatmap = self.Hr.run(img, current_windows)
        result = draw_img if draw else heatmap
        return draw_img

    def run(self, input_video, output_video):
        print('Starting video processing...')
        raw_clip = VideoFileClip(input_video)
        processed_clip = raw_clip.fl_image(self.process_image)
        processed_clip.write_videofile(output_video, audio=False)
        print('End of video processing...')
Esempio n. 32
0
def main():
    mouseDown = False

    pygame.init()
    screen = makeWindow((600, 400))

    maxParticlesSlider = Slider(100, 1, 450, 10, 100, "maxParticles")
    gravityXSlider = Slider(0.5, -0.5, 450, 50, 100, "gravityX")
    gravityXSlider.t = 0.5
    gravityYSlider = Slider(0.5, -0.5, 450, 90, 100, "gravityY")
    gravityYSlider.t = 0.5
    frictionSlider = Slider(1, 0, 450, 130, 100, "friction")
    minSizeSlider = Slider(20, 5, 450, 170, 100, "minSize")
    thetaSlider = Slider(360, 0, 450, 210, 100, "theta")
    velocitySlider = Slider(10, 0.5, 450, 250, 100, "velocity")

    emitter = Emitter(1, 15, 20, 5, 0.15, Particle, [200, 200])

    walls = []
    walls.append(Wall([10, 390], [390, 390], True))
    walls.append(Wall([10, 10], [10, 390], True))
    walls.append(Wall([10, 10], [390, 10], False))
    walls.append(Wall([390, 390], [390, 10], True))
    walls.append(Wall([200, 390], [390, 200], True))

    running = True
    while running:
        screen.fill((0, 0, 0))
        emitter.update(round(maxParticlesSlider.getValue()), round(minSizeSlider.getValue()), round(thetaSlider.getValue()), velocitySlider.getValue())
        for particleI in emitter.particles:
            particleI.update(walls, (gravityXSlider.getValue(), gravityYSlider.getValue()), frictionSlider.getValue())
            pygame.draw.circle(screen, (255, 255, 255), (particleI.position.x, particleI.position.y), particleI.size, 1)
        
        for wall in walls:
            pygame.draw.line(screen, (255, 255, 255), (wall.start.x, wall.start.y), (wall.end.x, wall.end.y), 1)
        
        for wall in walls:
            pygame.draw.line(screen, (255, 0, 0), (wall.start.x, wall.start.y), (wall.start.x + wall.normal.x * 10, wall.start.y + wall.normal.y * 10), 1)

        maxParticlesSlider.drawSlider(screen)
        gravityXSlider.drawSlider(screen)
        gravityYSlider.drawSlider(screen)
        frictionSlider.drawSlider(screen)
        minSizeSlider.drawSlider(screen)
        thetaSlider.drawSlider(screen)
        velocitySlider.drawSlider(screen)

        if mouseDown:
            pos = pygame.mouse.get_pos()
            maxParticlesSlider.setT(pos[0], pos[1])
            gravityXSlider.setT(pos[0], pos[1])
            gravityYSlider.setT(pos[0], pos[1])
            frictionSlider.setT(pos[0], pos[1])
            minSizeSlider.setT(pos[0], pos[1])
            thetaSlider.setT(pos[0], pos[1])
            velocitySlider.setT(pos[0], pos[1])

        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouseDown = True
            if event.type == pygame.MOUSEBUTTONUP:
                mouseDown = False

        time.sleep(0.0166)
Esempio n. 33
0
class PlaybackPanel(Panel):
    """A Panel subclass for the ternary code control."""

    def __init__(self, ctl_settings, screen, label, top_y, height,
                 fullsize):
        super().__init__(ctl_settings, screen, label, top_y, height,
                         fullsize)

        self.timer = False

        self.padding = 50  # custom padding here

        self.button_x_spacing = 30

        # add slider to control playback speed: ctl_settings.bpm
        self.slider_bottom = self.rect.bottom - 10

        self.BPM = Slider(self.ctl_settings, self.screen, 0, 200,
                          self.rect.left + self.button_x_spacing,
                          self.slider_bottom, 'BPM', 'linear')
        self.BPM.automate(30) # set initial value

        # Display buttons in sequencer - to show sequence
        row1_y = self.rect.top + self.padding
        pb1 = Button(ctl_settings, screen,
                     self.BPM.rect.right + self.button_x_spacing, row1_y, '1')
        pb2 = Button(ctl_settings, screen,
                     pb1.rect.right + self.button_x_spacing, row1_y, '2')
        pb3 = Button(ctl_settings, screen,
                     pb2.rect.right + self.button_x_spacing, row1_y, '3')
        pb4 = Button(ctl_settings, screen,
                     pb3.rect.right + self.button_x_spacing, row1_y, '4')
        pb5 = Button(ctl_settings, screen,
                     pb4.rect.right + self.button_x_spacing, row1_y, '5')
        pb6 = Button(ctl_settings, screen,
                     pb5.rect.right + self.button_x_spacing, row1_y, '6')
        pb7 = Button(ctl_settings, screen,
                     pb6.rect.right + self.button_x_spacing, row1_y, '7')
        pb8 = Button(ctl_settings, screen,
                     pb7.rect.right + self.button_x_spacing, row1_y, '8')

        self.buttons = [pb1, pb2, pb3, pb4, pb5, pb6, pb7, pb8]  # add all buttons here

        # Control buttons in sequencer - to show sequence
        row2_y = pb1.rect.bottom + 13
        brick1 = Button(ctl_settings, screen,
                        self.BPM.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick2 = Button(ctl_settings, screen,
                        brick1.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick3 = Button(ctl_settings, screen,
                        brick2.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick4 = Button(ctl_settings, screen,
                        brick3.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick5 = Button(ctl_settings, screen,
                        brick4.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick6 = Button(ctl_settings, screen,
                        brick5.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick7 = Button(ctl_settings, screen,
                        brick6.rect.right + self.button_x_spacing, row2_y, 'brick')
        brick8 = Button(ctl_settings, screen,
                        brick7.rect.right + self.button_x_spacing, row2_y, 'brick')
        self.brick_buttons = [brick1, brick2, brick3, brick4, brick5, brick6,
                              brick7, brick8]


    def update(self, mouse_y): # updates every screen for mouse values
        self.BPM.update(mouse_y)
        # convert BPM to ms
        try:
            self.ctl_settings.bpm_ms = int(60000 / self.BPM.ctl_value)
        except ZeroDivisionError:
            self.ctl_settings.bpm_ms = 0


    def draw_panel_and_buttons(self):
        self.draw_panel()
        for button in self.buttons:
            button.draw_button()
        for button in self.brick_buttons:
            button.draw_button()
        self.BPM.draw_slider()
Esempio n. 34
0
def main():
    proxSensor = proximitySensor()
    contScale = False
    minDist = 0
    maxIndex = 0
    if '-d' in argv:
        minDist = 5000
        maxDist = 30000
    else:
        minDist, maxDist = proxSensor.initialize()
    err = 50
    if '-e' in argv:
        err = int(raw_input("Please enter an error threshold"))
    print str(minDist) + ' ' + str(maxDist)
    raw_input('Press any key to continue')
    stepLength = maxDist - minDist
    scaleFactor = 220.0 / stepLength
    stepLength /= 8
    note = ' '

    last = -1
    first = None

    pitchSlider = Slider(err, minDist, True, False, 150, 0, "pitch")

    lastVolume = 1.0
    timing = False
    vstartTime = 0
    vstart = 0
    vcontrolenabled = True

    wav.out()
    stopped = False
    pitchBendEnable = True
    #main loop
    while True:
        ret, orgframe, cframe = proxSensor.setFrame(show)
        if not ret:
            continue

        #frames for displaying
        orgpframe = orgframe[100:400, 500:900]
        orgvframe = orgframe[0:100, 300:500]
        orgframe = orgframe[100:300, 100:300]

        #cropping frame for more accurate detection
        thresh, curr, numcnts = proxSensor.getValcropped(100, 300, 100, 300)
        vthresh, vcurr, vnumcnts = proxSensor.getValcropped(0, 100, 300, 500)
        pitchframe = cframe[100:400, 500:900]
        pnumcnts, pitchBend, _ = pitchSlider.getVal(pitchframe, orgpframe)
        cv2.imshow('vthresh', vthresh)

        #changes amplitude when the object in the detection zone is still
        estimate = int(lastVolume)
        if vcontrolenabled and vnumcnts < err:
            if timing:
                if abs(vstart - vcurr) > 500:
                    timing = False
                else:
                    if time() - vstartTime >= 2 and vcurr >= minDist / 2:
                        timing = False
                        lastVolume = 10 * (vcurr -
                                           (minDist / 2)) / (maxDist / 2)
                    estimate = int(10 * (vcurr - (minDist / 2)) /
                                   (maxDist / 2))
            else:
                timing = True
                vstartTime = time()
                vstart = vcurr
        else:
            timing = False
        s.setAmp(lastVolume)

        #Setting frequency based off of distance
        #normal mode sets frequency to one of the frequencies in the
        #dictionary. Continuous mode maps the frequency to the range
        #220Hz(a) to 440Hz(HighA)
        if abs(curr - last) > 10:
            f = curr - minDist
            if contScale:
                f = 220 + scaleFactor * f
                note = str(f) + 'Hz'
                pitchBend = 0
            else:
                f /= stepLength
                f = int(f)
                f %= 8
                if curr > maxDist:
                    f = 7
                if curr < minDist:
                    f = 0
                keys = notes.keys()
                keys.sort()
                temp = f
                note = keys[f]
                f = notes[note]

                #pitchbend
                if pitchBendEnable and pnumcnts < err and pitchBend != 0:
                    if pitchBend < 150:
                        upper = 0
                        if temp + 1 > 7:
                            upper = f + 100
                        else:
                            upper = keys[temp + 1]
                            upper = notes[upper]
                        upper = upper - f
                        pitchBend = upper - pitchBend * (upper / 150)
                    else:
                        lower = 0
                        if temp - 1 < 0:
                            lower = f - 100
                        else:
                            lower = keys[temp - 1]
                            lower = notes[lower]
                        lower = f - lower
                        pitchBend = -1 * (pitchBend - 150) * (lower / 150)
                    f += pitchBend
                else:
                    pitchBend = 0

            #invalid detection
            if numcnts > err or curr < minDist / 2:
                f = 0
                note = " "

            cls()
            print 'current note: ' + note
            print 'pitch bend: ' + str(pitchBend)
            print 'amp: ' + str(lastVolume)
            print 'changing amp: ' + str(timing) + ' time remaining: ' + str(
                5 - time() + vstartTime)
            if timing:
                print 'projected new amp: ' + str(estimate)

            #change frequencies incrementally
            f = 2 * Pi * f
            oldFreq = wav.freq
            if oldFreq != 0:
                while abs(oldFreq - f) > 0.05:
                    #oldFreq = (oldFreq+f)/2
                    if oldFreq < f:
                        oldFreq += 0.05
                    else:
                        oldFreq -= 0.05
                    wav.setFreq(oldFreq)
            wav.setFreq(f)
        last = curr

        #useful for debugging
        if show:
            cv2.imshow("t", thresh)

        cv2.imshow("Theremin", orgframe)
        k = cv2.waitKey(30)

        #keyboard controls
        if k == ord('q'):
            return
        elif k == ord('c'):
            contScale = not contScale
        elif k == ord('m'):
            if stopped:
                wav.out()
                stopped = False
            else:
                wav.stop()
                stopped = True
        elif k == ord('p'):
            pitchBendEnable = not pitchBendEnable
        elif k == ord('v'):
            vcontrolenabled = not vcontrolenabled
        elif k == ord(']') and not vcontrolenabled:
            lastVolume += 0.5
        elif k == ord('[') and not vcontrolenabled:
            lastVolume -= 0.5
        elif k == ord('\\'):
            lastVolume = int(lastVolume)
Esempio n. 35
0
    def __init__(self,
                 interactor,
                 value,
                 min_val,
                 max_val,
                 label,
                 on_show_slider=None,
                 update=None,
                 end=None,
                 corner_radius=5,
                 width=None,
                 height=None,
                 left=0,
                 top=0,
                 image=None,
                 bgcolor=(.5, .5, .5),
                 fgcolor=(1, 1, 1),
                 font="Arial",
                 opacity=1,
                 size=14,
                 states=None,
                 halign=LEFT_ALIGN,
                 valign=CENTER_ALIGN,
                 point1=(0, .1),
                 point2=(1, .1)):

        self.slider = Slider(interactor,
                             update=update,
                             end=end,
                             title=label,
                             value=value,
                             min_val=min_val,
                             max_val=max_val,
                             point1=point1,
                             point2=point2)

        def _show_slider():
            if on_show_slider:
                on_show_slider()
            self.slider.show()

        super(SliderButton, self).__init__(interactor,
                                           label,
                                           on=_show_slider,
                                           off=self.slider.hide,
                                           corner_radius=corner_radius,
                                           width=width,
                                           height=height,
                                           left=left,
                                           top=top,
                                           image=image,
                                           bgcolor=bgcolor,
                                           fgcolor=fgcolor,
                                           font=font,
                                           opacity=opacity,
                                           size=size,
                                           states=states,
                                           on_prefix="Show",
                                           off_prefix="Hide",
                                           halign=halign,
                                           valign=valign)
Esempio n. 36
0
class SliderButton(ToggleButton):
    """
    Displays a button that will show a slider when toggled on, and hide it when toggled off.
    Provides a callback to receive the value of the slider, and one for when the sliding has stopped.
    """
    def __init__(self,
                 interactor,
                 value,
                 min_val,
                 max_val,
                 label,
                 on_show_slider=None,
                 update=None,
                 end=None,
                 corner_radius=5,
                 width=None,
                 height=None,
                 left=0,
                 top=0,
                 image=None,
                 bgcolor=(.5, .5, .5),
                 fgcolor=(1, 1, 1),
                 font="Arial",
                 opacity=1,
                 size=14,
                 states=None,
                 halign=LEFT_ALIGN,
                 valign=CENTER_ALIGN,
                 point1=(0, .1),
                 point2=(1, .1)):

        self.slider = Slider(interactor,
                             update=update,
                             end=end,
                             title=label,
                             value=value,
                             min_val=min_val,
                             max_val=max_val,
                             point1=point1,
                             point2=point2)

        def _show_slider():
            if on_show_slider:
                on_show_slider()
            self.slider.show()

        super(SliderButton, self).__init__(interactor,
                                           label,
                                           on=_show_slider,
                                           off=self.slider.hide,
                                           corner_radius=corner_radius,
                                           width=width,
                                           height=height,
                                           left=left,
                                           top=top,
                                           image=image,
                                           bgcolor=bgcolor,
                                           fgcolor=fgcolor,
                                           font=font,
                                           opacity=opacity,
                                           size=size,
                                           states=states,
                                           on_prefix="Show",
                                           off_prefix="Hide",
                                           halign=halign,
                                           valign=valign)

    def get_value(self):
        return self.slider.repr.GetValue()

    def set_value(self, value):
        self.slider.repr.SetValue(value)

    def show(self):
        state = self.repr.GetState()
        if state == 1:
            self.slider.show()

        super(SliderButton, self).show()

    def hide(self):
        self.slider.hide()
        super(SliderButton, self).hide()

    def detach(self):
        super(SliderButton, self).detach()
        self.slider.detach()

    def copy(self, interactor):
        value = self.slider.repr.GetValue()
        min_val = self.slider.repr.GetMinimumValue()
        max_val = self.slider.repr.GetMaximumValue()
        p1x, p1y, _ = self.slider.repr.GetPoint1Coordinate().GetValue()
        p2x, p2y, _ = self.slider.repr.GetPoint2Coordinate().GetValue()

        b = SliderButton(interactor,
                         value,
                         min_val,
                         max_val,
                         self.label,
                         update=self.slider.update_callback,
                         end=self.slider.end_callback,
                         corner_radius=self.radius,
                         width=self.width,
                         height=self.height,
                         left=self.left,
                         top=self.top,
                         image=self.image,
                         bgcolor=self.bgcolor,
                         fgcolor=self.fgcolor,
                         opacity=self.opacity,
                         size=self.size,
                         states=self.states,
                         halign=self.halign,
                         valign=self.valign,
                         point1=(p1x, p1y),
                         point2=(p2x, p2y))

        state = self.repr.GetState()
        if state != 0:
            b.set_state(state)
            b.action(state)

        return b
Esempio n. 37
0
def main():
  proxSensor = proximitySensor() 
  contScale = False
  minDist = 0
  maxIndex = 0
  if '-d' in argv:
    minDist = 5000
    maxDist = 30000
  else:
    minDist, maxDist = proxSensor.initialize()

  err = 50
  if '-e' in argv:
    err = int(raw_input("Please enter an error threshold"))

  print(str(minDist) + ' ' + str(maxDist))
  raw_input('Press any key to continue')

  stepLength = maxDist-minDist
  scaleFactor = 220.0/stepLength
  stepLength/=8
  note = ' '
  
  last = -1
  first = None

  pitchSlider = Slider(err, minDist, True, False, 150, 0, "pitch") 

  lastVolume = 1.0
  timing = False
  vstartTime = 0
  vstart = 0
  vcontrolenabled = True

  wav.out()
  stopped = False
  pitchBendEnable = True
  #main loop
  while True:
    ret, orgframe, cframe = proxSensor.setFrame(show)
    if not ret:
      continue

    #frames for displaying
    orgpframe = orgframe[100:400, 500:900]
    orgvframe = orgframe[0:100, 300:500]
    orgframe = orgframe[100:300, 100:300]
    
    #cropping frame for more accurate detection
    thresh, curr, numcnts = proxSensor.getValcropped(100, 300, 100, 300)
    vthresh, vcurr, vnumcnts = proxSensor.getValcropped(0, 100, 300, 500)
    pitchframe = cframe[100:400, 500:900]
    pnumcnts, pitchBend, _ = pitchSlider.getVal(pitchframe, orgpframe)
    cv2.imshow('vthresh', vthresh)
    
    #changes amplitude when the object in the detection zone is still
    estimate = int(lastVolume)
    if vcontrolenabled and vnumcnts<err:
      if timing:
        if abs(vstart-vcurr)>500:
          timing = False
        else:
          if time()-vstartTime>=2 and vcurr>=minDist/2:
            timing = False
            lastVolume = 10*(vcurr-(minDist/2))/(maxDist/2)
          estimate = int(10*(vcurr-(minDist/2))/(maxDist/2)) 
      else:
        timing = True
        vstartTime = time()
        vstart = vcurr
    else:
      timing = False
    s.setAmp(lastVolume)

    #Setting frequency based off of distance
    #normal mode sets frequency to one of the frequencies in the 
    #dictionary. Continuous mode maps the frequency to the range
    #220Hz(a) to 440Hz(HighA)
    if abs(curr-last)>10:
      f = curr - minDist
      if contScale: 
        f = 220 + scaleFactor*f
        note = str(f) + 'Hz'
        pitchBend = 0
      else:
        f/=stepLength
        f = int(f)
        f%=8
        if curr>maxDist:
          f = 7
        if curr<minDist:
          f = 0
        keys = notes.keys()
        keys.sort()
        temp = f
        note = keys[f]
        f = notes[note]

        #pitchbend
        if pitchBendEnable and pnumcnts<err and pitchBend!=0:
          if pitchBend<150:
            upper = 0
            if temp + 1>7:
              upper = f + 100
            else:
              upper = keys[temp + 1] 
              upper = notes[upper]
            upper = upper - f
            pitchBend = upper - pitchBend*(upper/150)
          else:
            lower = 0
            if temp-1<0:
              lower = f-100
            else:
              lower = keys[temp-1] 
              lower = notes[lower]
            lower = f - lower
            pitchBend = -1*(pitchBend-150)*(lower/150)
          f +=pitchBend
        else:
          pitchBend = 0

      #invalid detection 
      if numcnts>err or curr<minDist/2:
        f = 0
        note = " "

      cls()
      print('current note: ' + note)
      print('pitch bend: ' + str(pitchBend))
      print('amp: ' + str(lastVolume))
      print('changing amp: ' + str(timing) + ' time remaining: ' + str(5-time() + vstartTime))
      if timing:
        print('projected new amp: ' + str(estimate))
      
      #change frequencies incrementally
      f = 2*Pi*f
      oldFreq = wav.freq
      if oldFreq!=0:
        while abs(oldFreq-f)>0.05:
          #oldFreq = (oldFreq + f)/2 
          if oldFreq<f:
            oldFreq +=0.05
          else:
            oldFreq-=0.05
          wav.setFreq(oldFreq)
      wav.setFreq(f)
    last = curr
    
    #useful for debugging
    if show:
      cv2.imshow("t", thresh)
    
    cv2.imshow("Theremin", orgframe)
    k = cv2.waitKey(30)
    
    #keyboard controls
    if k==ord('q'):
      return
    elif k==ord('c'):
      contScale = not contScale 
    elif k==ord('m'):
      if stopped:
        wav.out()
        stopped = False
      else:
        wav.stop()
        stopped = True
    elif k==ord('p'):
      pitchBendEnable = not pitchBendEnable
    elif k==ord('v'):
      vcontrolenabled = not vcontrolenabled
    elif k==ord(']') and not vcontrolenabled:
      lastVolume += 0.5
    elif k==ord('[') and not vcontrolenabled:
      lastVolume -= 0.5
    elif k==ord('\\'):
      lastVolume = int(lastVolume)
Esempio n. 38
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.NonModal)
        MainWindow.resize(750, 637)
        MainWindow.setMinimumSize(QtCore.QSize(700, 600))
        MainWindow.setMouseTracking(False)
        MainWindow.setWindowTitle("WatchVideo")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/media/watchvideo-32x32.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.verticalLayout.setObjectName("verticalLayout")
        self.tab_widget = QtGui.QTabWidget(self.centralwidget)
        self.tab_widget.setObjectName("tab_widget")
        self.tab_player = QtGui.QWidget()
        self.tab_player.setObjectName("tab_player")
        self.verticalLayout_4 = QtGui.QVBoxLayout(self.tab_player)
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.nameLabel = QtGui.QLabel(self.tab_player)
        self.nameLabel.setStyleSheet("None")
        self.nameLabel.setText("")
        self.nameLabel.setObjectName("nameLabel")
        self.verticalLayout_4.addWidget(self.nameLabel)
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.videoWidget = QtGui.QWidget(self.tab_player)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.videoWidget.sizePolicy().hasHeightForWidth())
        self.videoWidget.setSizePolicy(sizePolicy)
        self.videoWidget.setMinimumSize(QtCore.QSize(0, 300))
        self.videoWidget.setMouseTracking(True)
        self.videoWidget.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.videoWidget.setObjectName("videoWidget")
        self.horizontalLayout_3.addWidget(self.videoWidget)
        self.playlistWidget = QtGui.QTreeWidget(self.tab_player)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.playlistWidget.sizePolicy().hasHeightForWidth())
        self.playlistWidget.setSizePolicy(sizePolicy)
        self.playlistWidget.setMouseTracking(True)
        self.playlistWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.playlistWidget.setRootIsDecorated(False)
        self.playlistWidget.setObjectName("playlistWidget")
        self.playlistWidget.headerItem().setText(0, "-")
        self.playlistWidget.headerItem().setText(1, "-")
        self.playlistWidget.header().setVisible(False)
        self.playlistWidget.header().setDefaultSectionSize(30)
        self.horizontalLayout_3.addWidget(self.playlistWidget)
        self.verticalLayout_4.addLayout(self.horizontalLayout_3)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.stackedWidget = QtGui.QStackedWidget(self.tab_player)
        self.stackedWidget.setEnabled(True)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.stackedWidget.sizePolicy().hasHeightForWidth())
        self.stackedWidget.setSizePolicy(sizePolicy)
        self.stackedWidget.setMinimumSize(QtCore.QSize(47, 36))
        self.stackedWidget.setMaximumSize(QtCore.QSize(47, 34))
        self.stackedWidget.setObjectName("stackedWidget")
        self.page = QtGui.QWidget()
        self.page.setObjectName("page")
        self.btn_play = QtGui.QPushButton(self.page)
        self.btn_play.setEnabled(True)
        self.btn_play.setGeometry(QtCore.QRect(0, 0, 46, 34))
        self.btn_play.setMinimumSize(QtCore.QSize(46, 34))
        self.btn_play.setMaximumSize(QtCore.QSize(46, 34))
        self.btn_play.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/media/start.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_play.setIcon(icon1)
        self.btn_play.setObjectName("btn_play")
        self.stackedWidget.addWidget(self.page)
        self.page_2 = QtGui.QWidget()
        self.page_2.setEnabled(True)
        self.page_2.setObjectName("page_2")
        self.btn_pause = QtGui.QPushButton(self.page_2)
        self.btn_pause.setEnabled(True)
        self.btn_pause.setGeometry(QtCore.QRect(0, 0, 46, 34))
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btn_pause.sizePolicy().hasHeightForWidth())
        self.btn_pause.setSizePolicy(sizePolicy)
        self.btn_pause.setMinimumSize(QtCore.QSize(46, 34))
        self.btn_pause.setMaximumSize(QtCore.QSize(46, 34))
        self.btn_pause.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/media/pause.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_pause.setIcon(icon2)
        self.btn_pause.setObjectName("btn_pause")
        self.stackedWidget.addWidget(self.page_2)
        self.horizontalLayout.addWidget(self.stackedWidget)
        self.btn_stop = QtGui.QPushButton(self.tab_player)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(46)
        sizePolicy.setVerticalStretch(34)
        sizePolicy.setHeightForWidth(self.btn_stop.sizePolicy().hasHeightForWidth())
        self.btn_stop.setSizePolicy(sizePolicy)
        self.btn_stop.setText("")
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(":/media/stop.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_stop.setIcon(icon3)
        self.btn_stop.setObjectName("btn_stop")
        self.horizontalLayout.addWidget(self.btn_stop)
        self.btn_replay = QtGui.QPushButton(self.tab_player)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(46)
        sizePolicy.setVerticalStretch(34)
        sizePolicy.setHeightForWidth(self.btn_replay.sizePolicy().hasHeightForWidth())
        self.btn_replay.setSizePolicy(sizePolicy)
        self.btn_replay.setMinimumSize(QtCore.QSize(46, 34))
        self.btn_replay.setText("")
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap(":/media/refresh.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.btn_replay.setIcon(icon4)
        self.btn_replay.setFlat(True)
        self.btn_replay.setObjectName("btn_replay")
        self.horizontalLayout.addWidget(self.btn_replay)
        self.progressBar = Slider(self.tab_player)
        self.progressBar.setMaximum(1000)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.horizontalLayout.addWidget(self.progressBar)
        self.timeLabel = QtGui.QLabel(self.tab_player)
        self.timeLabel.setStatusTip("None")
        self.timeLabel.setText("00:00/00:00")
        self.timeLabel.setObjectName("timeLabel")
        self.horizontalLayout.addWidget(self.timeLabel)
        self.verticalLayout_4.addLayout(self.horizontalLayout)
        self.tab_widget.addTab(self.tab_player, "")
        self.tab_downloads = QtGui.QWidget()
        self.tab_downloads.setObjectName("tab_downloads")
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.tab_downloads)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.tree_downloads = QtGui.QTreeWidget(self.tab_downloads)
        self.tree_downloads.setAlternatingRowColors(True)
        self.tree_downloads.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.tree_downloads.setItemsExpandable(True)
        self.tree_downloads.setAllColumnsShowFocus(True)
        self.tree_downloads.setColumnCount(5)
        self.tree_downloads.setObjectName("tree_downloads")
        self.tree_downloads.header().setDefaultSectionSize(140)
        self.tree_downloads.header().setMinimumSectionSize(60)
        self.tree_downloads.header().setStretchLastSection(True)
        self.verticalLayout_2.addWidget(self.tree_downloads)
        self.tab_widget.addTab(self.tab_downloads, "")
        self.verticalLayout.addWidget(self.tab_widget)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 750, 21))
        self.menubar.setObjectName("menubar")
        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuEdit = QtGui.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")
        self.menuHelp = QtGui.QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        self.menuView = QtGui.QMenu(self.menubar)
        self.menuView.setObjectName("menuView")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.toolBar = QtGui.QToolBar(MainWindow)
        self.toolBar.setEnabled(True)
        self.toolBar.setWindowTitle("toolBar")
        self.toolBar.setIconSize(QtCore.QSize(32, 32))
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.ToolBarArea(QtCore.Qt.TopToolBarArea), self.toolBar)
        self.dockWidget = SearchWidget(MainWindow)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.dockWidget.sizePolicy().hasHeightForWidth())
        self.dockWidget.setSizePolicy(sizePolicy)
        self.dockWidget.setMinimumSize(QtCore.QSize(101, 131))
        self.dockWidget.setWindowTitle("")
        self.dockWidget.setObjectName("dockWidget")
        self.dockWidgetContents = QtGui.QWidget()
        self.dockWidgetContents.setObjectName("dockWidgetContents")
        self.verticalLayout_3 = QtGui.QVBoxLayout(self.dockWidgetContents)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.searchLine = SearchField(self.dockWidgetContents)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.searchLine.sizePolicy().hasHeightForWidth())
        self.searchLine.setSizePolicy(sizePolicy)
        self.searchLine.setStyleSheet("None")
        self.searchLine.setObjectName("searchLine")
        self.horizontalLayout_2.addWidget(self.searchLine)
        self.b_search = QtGui.QPushButton(self.dockWidgetContents)
        self.b_search.setText("")
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap(":/media/search.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.b_search.setIcon(icon5)
        self.b_search.setObjectName("b_search")
        self.horizontalLayout_2.addWidget(self.b_search)
        self.verticalLayout_3.addLayout(self.horizontalLayout_2)
        self.resultsWidget = QtGui.QTreeWidget(self.dockWidgetContents)
        self.resultsWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.resultsWidget.setRootIsDecorated(False)
        self.resultsWidget.setWordWrap(True)
        self.resultsWidget.setHeaderHidden(True)
        self.resultsWidget.setObjectName("resultsWidget")
        self.resultsWidget.headerItem().setText(0, "1")
        self.resultsWidget.header().setMinimumSectionSize(50)
        self.verticalLayout_3.addWidget(self.resultsWidget)
        self.dockWidget.setWidget(self.dockWidgetContents)
        MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.dockWidget)
        self.a_addVideos = QtGui.QAction(MainWindow)
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap(":/media/harddisk-add.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_addVideos.setIcon(icon6)
        self.a_addVideos.setObjectName("a_addVideos")
        self.a_searchBrowser = QtGui.QAction(MainWindow)
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap(":/media/Web-browser.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_searchBrowser.setIcon(icon7)
        self.a_searchBrowser.setObjectName("a_searchBrowser")
        self.a_clearCompleted = QtGui.QAction(MainWindow)
        self.a_clearCompleted.setEnabled(False)
        icon8 = QtGui.QIcon()
        icon8.addPixmap(QtGui.QPixmap(":/media/edit-clear-list.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_clearCompleted.setIcon(icon8)
        self.a_clearCompleted.setObjectName("a_clearCompleted")
        self.a_about = QtGui.QAction(MainWindow)
        self.a_about.setIcon(icon)
        self.a_about.setObjectName("a_about")
        self.a_preferences = QtGui.QAction(MainWindow)
        icon9 = QtGui.QIcon()
        icon9.addPixmap(QtGui.QPixmap(":/media/preferences.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_preferences.setIcon(icon9)
        self.a_preferences.setObjectName("a_preferences")
        self.a_quit = QtGui.QAction(MainWindow)
        icon10 = QtGui.QIcon()
        icon10.addPixmap(QtGui.QPixmap(":/media/quit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_quit.setIcon(icon10)
        self.a_quit.setObjectName("a_quit")
        self.a_clipboard = QtGui.QAction(MainWindow)
        icon11 = QtGui.QIcon()
        icon11.addPixmap(QtGui.QPixmap(":/media/klipper.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_clipboard.setIcon(icon11)
        self.a_clipboard.setObjectName("a_clipboard")
        self.a_play = QtGui.QAction(MainWindow)
        icon12 = QtGui.QIcon()
        icon12.addPixmap(QtGui.QPixmap(":/media/internet-play.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_play.setIcon(icon12)
        self.a_play.setObjectName("a_play")
        self.a_download = QtGui.QAction(MainWindow)
        icon13 = QtGui.QIcon()
        icon13.addPixmap(QtGui.QPixmap(":/media/internet-download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.a_download.setIcon(icon13)
        self.a_download.setObjectName("a_download")
        self.a_viewSearch = QtGui.QAction(MainWindow)
        self.a_viewSearch.setCheckable(True)
        self.a_viewSearch.setChecked(True)
        self.a_viewSearch.setObjectName("a_viewSearch")
        self.menuFile.addAction(self.a_quit)
        self.menuEdit.addAction(self.a_preferences)
        self.menuHelp.addAction(self.a_about)
        self.menuView.addAction(self.a_viewSearch)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuView.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())
        self.toolBar.addAction(self.a_addVideos)
        self.toolBar.addAction(self.a_searchBrowser)
        self.toolBar.addAction(self.a_clipboard)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.a_play)
        self.toolBar.addAction(self.a_download)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.a_clearCompleted)
        self.toolBar.addSeparator()

        self.retranslateUi(MainWindow)
        self.tab_widget.setCurrentIndex(0)
        self.stackedWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Esempio n. 39
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480),pygame.SWSURFACE)
    pygame.key.set_repeat(100, 100)
    '''TEST'''
    g=Gui()
    #g.enableDirtyRect()
    g.optimizeDraw()
    i=PygameInput()
    Image.mImageLoader=PygameImageLoader()
    gr=PygameGraphics()
    gr.setTarget(screen)
    f=ImageFont("C:\Python25\Projects\Guichan\consolefont.bmp")
    #f=ImageFont("consolefont.bmp")
    f.setColorkey( Color(255,0,255) )
    f.setGlyphSpacing(2)
    f2=PygameFont("C:\Python25\Projects\Guichan\LiberationMono-Regular.ttf",14,Color(0,0,0,255))
    #f2=PygameFont("C:\Python25\Projects\Guichan\Caracteres L1.ttf",13,Color(0,0,0,255))
    f2.setGlyphSpacing(1)
    Widget.setGlobalFont(f2)
    
    c=Container()
    c.setOpaque(False)
    c.setPosition(0,0)
    c.setSize(640,480)
    c.setBaseColor( Color(255,0,0,255) )
    
    a=ActionListener()
    a.action=action
    b, b2=Button("YEY!"), Button("WHa?")
    b.setPosition(0,50)
    b.setActionEventId("Button 1")
    b.addActionListener(a)
    b2.setPosition(100,100)
    b2.setActionEventId("Button 2")
    b2.addActionListener(a)
    b2.setBaseColor( Color(200,200,200) )
    b2.setCaption("ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()")
    w,w2=Window("Hey over here!"), Window("Trapped in a window!")
    wColor=w.getBaseColor()
    wColor.a=200
    w.setBaseColor(wColor)
    w.setTextColor(Color(255,0,255))
    xyz=Button("XYZ")
    xyz.setTextColor(Color(0,255,255))
    pb=ProgressBar(100.0)
    pb.setBaseColor( Color(255,255,0) )
    pb.setForegroundColor( Color(0,255,255) )
    pb.setSize(100, 20)
    pb.setPosition(300, 300)
    pb.setValue(50.0)
    c.add(w,0,100)
    c.add(b)
    c.add(b2)
    c.add(xyz,10,10)
    c.add(pb)
    
    check=Checkbox("Ye what? GET BACK HERE BOY!")
    check.setActionEventId("Checkbox")
    check.addActionListener(a)
    text=TextField("Hey Hey Hey Hey Hey Hey Hey Hey")
    text.setBackgroundColor( Color(255,255,255,255) )
    text.setMaxSize(150)
    text2=TextBox("Hey, HeyTrapped in a window!\nWhat's goin' onTrapped in a window!\ntodays???Trapped in a window!")
    text2.setTabSize(10)
    sc=ScrollArea(text2)
    sc.setSize(200,100)
    rBox=Container()
    r1=RadioButton("1984","Dystopia")
    r2=RadioButton("Fahrenheit 451","Dystopia")
    r3=RadioButton("Brave New World","Dystopia")
    rBox.add(r1,0,0)
    rBox.add(r2,0,r1.getY()+r1.getHeight())
    rBox.add(r3,0,r2.getY()+r2.getHeight())
    label=Label("WE AIN'T GOT IT")
    ico_image=Image.load("C:\Python25\Projects\Guichan\May.bmp")
    ico=Icon(ico_image)
    lb=ListBox( List_ListModel(["Bollocks!","Never!","Cuppa tea, mate?","Hello!","Goodbye!","OK Computer!","Oh Inverted World!","How To Disappear Completely!","Hold Still!","It Takes A Train To Cry!","A","B","C","D","E","F","G","H","I",]) )
    sc2=ScrollArea(lb)
    sc2.setSize(125,100)
    lb.setWidth(110)
    slider=Slider(0,100)
    slider.setOrientation(Slider.Orientation.VERTICAL)
    slider.setSize(15,100)
    slider.setActionEventId("Slider")
    #slider.addActionListener(a)
    ib=ImageButton(ico_image)
    ta=TabbedArea()
    c.add(w2)
    ta.addTab("Text",[ (text,0,0), (sc,0,50) ])
    ta.addTab("Check",check)
    ta.addTab("Radio",rBox)
    ta.addTab("List",[ (sc2,0,0) ])
    ta.addTab("Label",label)
    ta.addTab("Icon",[ (ico,0,0), (ib,100,0) ])
    ta.addTab("Slider",slider)
    ta.setSize(300,300)
    w2.add(ta,0,0)
    g.setGraphics(gr)
    w2.resizeToContent()
    w.setSize(300,300)
    g.setInput(i)
    g.setTop(c)
    clock=pygame.time.Clock()
    
    g.mDirtyRect.addRect( Rectangle(0,0,640,480) )
    done=False
    while done == False:
        clock.tick(0)

        for event in pygame.event.get():
            if event.type==KEYDOWN:
                if event.key == K_ESCAPE:
                    c.remove(b)
                    c.remove(b2)
                    done=True
                
                elif event.key == K_RETURN:
                    w=Window("It'a window!")
                    w.add(Checkbox("Kool thing"))
                    w.resizeToContent()
                    c.add(w, 10, 10)
                    
                elif event.key == K_LEFT:
                    pb.setValue( pb.getValue()-1.0 )
                elif event.key == K_RIGHT:
                    pb.setValue( pb.getValue()+1.0 )                
                    
            if event.type == ACTIVEEVENT:
                if event.gain == 1:
                    g.mDirtyRect.addRect( Rectangle(0,0,640,480) )
                    
            i.pushInput(event)
            g.logic()
            
        b2.setCaption( str( int(clock.get_fps()) ) )
        fRect=GuichanToPygameDirtyRect(g.mDirtyRect.getList())
        #for ix in fRect: screen.fill((255,0,0),ix)
        
        screen.fill((255,0,0))    
        g.draw()
        #pygame.display.update( GuichanToPygameDirtyRect(g.mDirtyRect.getList()) )
        pygame.display.update()
        
        g.mDirtyRect.clearList()