Ejemplo n.º 1
0
    def run(self, canvas_color, sidebar_color, questions, time=60):
        """
        Inicia e constrói a parte gráfica do programa.
        """

        # Cria a janela do programa.
        self.__window = Window(self.__title, self.__window_geometry,
                               canvas_color)
        self.__window.protocol("WM_DELETE_WINDOW", self.stop)

        # Instância os parâmetros.
        self.__main_color = canvas_color
        self.__sidebar_color = sidebar_color
        self.__questions_data = questions
        self.__questions = list(self.__questions_data)
        self.__time = time
        self.__stop = False

        # Cria uma lista com a imagem de logo e a imagem do globo.
        images = [self.__logo_image, self.__globe_image]

        # Constrói a janela principal do programa.
        main_screen = MainScreen(self.__window)
        main_screen.build(canvas_color, sidebar_color, self.__start_game,
                          images)

        # Coloca a janela do programa em um loop infinito.
        self.__window.mainloop()
Ejemplo n.º 2
0
class Game(object):
    def __init__(self, engine=PyEngine()):
        self.running = True
        self._engine = engine
        self._window = Window(self._engine)

    def on_event(self):
        for event in self._engine.events:
            self._window.on_event(event)
            if event.type == EVENT_TYPE['QUIT']:
                self.running = False

    def on_update(self):
        self._engine.screen.fill((0, 0, 0))
        self._window.on_update()
        self._engine.display.update()

    def run(self):

        while self.running:
            # TODO change game loop clock system
            self._engine.clock.tick(10)
            self.on_update()
            self.on_event()

        self._engine.on_shutdown()
Ejemplo n.º 3
0
class Simulation:
    def __init__(self, world):
        self.world = world
        self.viewer = Window()
        self.is_paused = False

    def run(self):
        clock = pygame.time.Clock()
        while True:

            dt = clock.tick() / 1000  # ellapsed time in seconds
            if not self.is_paused:
                self.world.update(dt)
            events = self._handle_events()
            self.viewer.update(self.world, events)

    def _handle_events(self):
        events = []
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            events.append(event)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_PAUSE:
                    self.is_paused = not self.is_paused
        return events
Ejemplo n.º 4
0
def main():
    checkEvn()
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    app = QtWidgets.QApplication(sys.argv)

    window = Window()
    app.installEventFilter(window)
    window.show()

    sys.exit(app.exec_())
Ejemplo n.º 5
0
def main():

    localeHandler = AppLocale(Constants.LOCALE)
    my_clock = pygame.time.Clock()
    frameCounter = 0
    """ Set up the game and run the main game loop """
    pygame.init()  # Prepare the pygame module for use
    mainWindow = Window(localeHandler, Conway)
    mainWindow.setWindowUpdateSpeed(1000)

    while True:
        ev = pygame.event.poll()  # Look for any event
        if ev.type == pygame.QUIT:  # Window close button clicked?
            break  #   ... leave game loop
        keys = pygame.key.get_pressed()
        if keys[pygame.K_ESCAPE]:
            break

        # handle MOUSEBUTTONUP
        if ev.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            if not mainWindow.isPlayPauseButtonPressed(pos):
                mainWindow.toggleCell(pos)

        if ev.type == mainWindow.WINDOW_UPDATE_ID:
            mainWindow.updateWindow()

        pygame.display.update()

        #force a constant frame rate of 60fps
        my_clock.tick(Constants.FRAME_RATE)

    pygame.quit()  # Once we leave the loop, close the window.
Ejemplo n.º 6
0
class Application:
    def __init__(self):
        self.app = QApplication(sys.argv)
        self.window = Window()

    def show_window(self):
        """Function shows application window."""
        self.window.show()
        sys.exit(self.app.exec_())

    def run(self):
        """Function starts the application."""
        self.show_window()
Ejemplo n.º 7
0
def main():

    localeHandler = AppLocale(Constants.LOCALE)
    my_clock = pygame.time.Clock()
    frameCounter = 0

    """ Set up the game and run the main game loop """
    pygame.init()  # Prepare the pygame module for use
    mainWindow = Window(localeHandler, Conway)
    mainWindow.setWindowUpdateSpeed(1000)

    while True:
        ev = pygame.event.poll()    # Look for any event
        if ev.type == pygame.QUIT:  # Window close button clicked?
            break                   #   ... leave game loop
        keys = pygame.key.get_pressed()
        if keys[pygame.K_ESCAPE]:
            break

        # handle MOUSEBUTTONUP
        if ev.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            if not mainWindow.isPlayPauseButtonPressed(pos):
                mainWindow.toggleCell(pos)

        if ev.type == mainWindow.WINDOW_UPDATE_ID:
            mainWindow.updateWindow()

        pygame.display.update()

        #force a constant frame rate of 60fps
        my_clock.tick(Constants.FRAME_RATE)

    pygame.quit()     # Once we leave the loop, close the window.
Ejemplo n.º 8
0
def play_images(bag_file: Bag, topics: list) -> None:
    """
    Play the data in a bag file.

    Args:
        bag_file: the bag file to play
        topics: the list of topics to play

    Returns:
        None

    """
    # open windows to stream the camera and a priori image data to
    windows = {topic: None for topic in topics}
    # iterate over the messages
    progress = tqdm(total=bag_file.get_message_count(topic_filters=topics))
    for topic, msg, time in bag_file.read_messages(topics=topics):
        # if topic is camera, unwrap and send to the camera window
        if topic in topics:
            # update the progress bar with an iteration
            progress.update(1)
            # update the progress with a post fix
            progress.set_postfix(time=time)
            # if the camera window isn't open, open it
            if windows[topic] is None:
                title = '{} ({})'.format(bag_file.filename, topic)
                windows[topic] = Window(title, msg.height, msg.width)
            # get the pixels of the camera image and display them
            img = get_camera_image(msg.data, windows[topic].shape)
            if msg.encoding == 'bgr8':
                img = img[..., ::-1]
            windows[topic].show(img[..., :3])

    # shut down the viewer windows
    for window in windows.values():
        if window is not None:
            window.close()
Ejemplo n.º 9
0
def play_superpixel(bag_file: Bag, camera_info: str, camera: str, depth: str,
                    segmentation: str, downscale: int) -> None:
    """
    Play the camera data in a bag file through a super pixel algorithm.

    Args:
        bag_file: the bag file to play
        camera_info: the topic to use to read metadata about the camera
        camera: the topic to use to read compressed or raw camera data
        depth: the topic to use to read 32-bit floating point depth measures
        segmentation: the algorithm to use for segmentation
        downscale: the factor to downscale the image by before segmentation

    Returns:
        None

    """
    # extract the camera dimensions from the bag
    dims = get_camera_dimensions(bag, camera_info)
    # open a window to stream the data to
    window = Window('{} ({})'.format(bag_file.filename, camera), *dims)
    # iterate over the messages
    for topic, msg, _ in bag.read_messages(topics=[camera, depth]):
        # if topic is camera, unwrap the camera data
        if topic == camera:
            camera_img = get_camera_image(msg.data, dims)
        # if topic is depth, unwrap and calculate the segmentation
        elif topic == depth:
            depth_img = get_depth_image(msg.data, dims)
            # combine the image with the depth channel (Red only)
            img = np.concatenate([camera_img, depth_img[..., 0:1]], axis=-1)
            # segment the image and get a copy of the segmented pixels
            img = segment(img, method=segmentation, downscale=downscale)
            # send the segmented image to the window
            window.show(img)
    # shut down the viewer windows
    window.close()
Ejemplo n.º 10
0
def main():

    my_clock = pygame.time.Clock()
    config = Config()
    """ Set up the game and run the main game loop """
    pygame.init()  # Prepare the pygame module for use
    mainWindow = Window(Model(GerritRequester(config)))

    # you have to call this at the start,
    pygame.font.init()

    while True:
        try:
            pos = 0

            ev = pygame.event.poll()  # Look for any event
            if ev.type == pygame.QUIT:  # Window close button clicked?
                break  #   ... leave game loop
            keys = pygame.key.get_pressed()
            if keys[pygame.K_ESCAPE]:
                break

            # handle MOUSEBUTTONUP
            if ev.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()

            mainWindow.updateWindow(pos)
            pygame.display.update()

            #force a constant frame rate of 60fps
            my_clock.tick(Constants.FRAME_RATE)
        except KeyboardInterrupt:
            break

    mainWindow.clean()
    pygame.quit()  # Once we leave the loop, close the window.
Ejemplo n.º 11
0
    def draw_tile(self, window: Window, inverted: bool):
        board_rect = [
            self.position[0], self.position[1], Tile.TILE_WIDTH,
            Tile.TILE_HEIGHT
        ]

        rect: pygame.Surface = pygame.Surface(self.tile_size)
        if self.is_open != inverted:
            rect.set_alpha(12)
            rect.fill(Tile.OPEN_TILE_COLOR)
            window.draw_surface(rect, self.position)
            if self.bug != Bug.NO_BUG:
                if self.bug == Bug.FAKE_BUG:
                    bug_image = pygame.image.load(
                        'resources/fake_bug.gif').convert()
                else:
                    bug_image = pygame.image.load(
                        'resources/bug.gif').convert()
                window.draw_surface(bug_image, self.bug_position)
        else:
            tile_image = pygame.image.load('resources/tile.gif').convert()
            window.draw_surface(tile_image, self.position)

        pygame.draw.rect(window.screen, BOARD_LIMITS_COLOR, board_rect, 1)
Ejemplo n.º 12
0
Archivo: main.py Proyecto: y-vas/game
def main():
    window = Window( width=800, height=600, caption='Pyglet', resizable=True )
    # Hide the mouse cursor and prevent the mouse from leaving the window.
    window.set_exclusive_mouse(True)
    setup()
    pyglet.app.run()
Ejemplo n.º 13
0
from src.window import Window
from AppKit import NSScreen
import pyglet

WIDTH = int(NSScreen.mainScreen().frame().size.width)
HEIGHT = int(NSScreen.mainScreen().frame().size.height) - 100
SQUARES_SIZE = 10

config = [(100, 50), (100, 49), (100, 46), (101, 50), (101, 53), (102, 50),
          (102, 53), (102, 54), (103, 52), (104, 52), (104, 53), (104, 54)]

window = Window(WIDTH, HEIGHT, SQUARES_SIZE, None, WIDTH, HEIGHT,
                "Game of Life")
pyglet.clock.schedule_interval(window.update, 4)
pyglet.app.run()
Ejemplo n.º 14
0
    def SigGen(gentype, f, T, fs, *arg):
        """Creating signal generator:
        Options gentype: Sine; Sawtooth; Triangle; Square PW; ...
        White/Pink noise; Chirp; Poly Chirp"""
        # http://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function
        import numpy as np
        import scipy.signal as sig
        sg = SigGen()
        f = np.array(f)
        if gentype == "Sine":
            if sg.varlist(f, 1) == (True, True):
                f0 = f
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = np.sin(2 * np.pi * f0 * t)
                return (Sig, t)
            elif sg.varlist(f, 1) == (False, True):
                f0 = f[0]
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = np.sin(2 * np.pi * f0 * t)
                return (Sig, t)
            else:
                # Sig = []
                raise MeasError.EmptyError(sig, 'Nothing to return')
        elif gentype == "Sawtooth":
            if sg.varlist(f, 1) == (True, True):
                f0 = f
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = sig.Sawtooth(2 * np.pi * f0 * t)
                return (Sig, t)
            elif SigGen.varlist(f, 1) == (False, True):
                f0 = f[0]
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = sig.Sawtooth(2 * np.pi * f0 * t)
                return (Sig, t)
            else:
                # Sig = []
                raise MeasError.EmptyError(sig, 'Nothing to return')
        elif gentype == 'Square':
            if sg.varlist(f, 1) == (True, True):
                f0 = f
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = sig.Square(2 * np.pi * f0 * t)
                return (Sig, t)
            elif sg.varlist(f, 1) == (False, True):
                f0 = f[0]
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = sig.Square(2 * np.pi * f0 * t)
                return (Sig, t)
            else:
                # Sig = []
                raise MeasError.EmptyError(sig, 'Nothing to return')
        elif gentype == 'Triangle':
            if sg.varlist(f, 1) == (True, True):
                f0 = f
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = sig.Sawtooth(2 * np.pi * f0 * t, width=0.5)
                return (Sig, t)
            elif sg.varlist(f, 1) == (False, True):
                f0 = f[0]
                ps = fs / f  # samples per period
                periods = np.ceil(T * fs / ps)
                T = periods * ps / fs

                t = np.arange(0, T * fs) / fs
                Sig = sig.Sawtooth(2 * np.pi * f0 * t, width=0.5)
                return (Sig, t)
            else:
                # Sig = []
                raise MeasError.EmptyError(sig, 'Nothing to return')
        elif gentype == 'ChirpLin':
            from src.window import Window
            if sg.varlist(f, 2) == (True, True):
                f0 = f[0]
                f1 = f[1]
            elif SigGen.varlist(f, 2) == (False, True):
                f0 = f[0]
                f1 = f[1]
            else:
                # Sig = []
                raise MeasError.EmptyError(sig, 'Nothing to return')
            t = np.arange(0, T * fs) / fs

            factor_f = fs / f1  # factor fs/f1
            T = T - (np.ceil(factor_f) + 1) / fs
            Sig_unw = sig.chirp(t, f0, T, f1, 'linear',
                                90)  # unwindowed Signal
            # phi = (f0 * (f1 / f0) ** (t[-4:] / T)) % np.pi

            if factor_f < 2:
                # print error
                raise ValueError('variable f1 < as fs/2')
            elif round(factor_f, 0) < 3:
                wl = 2  # window length
                # overlap = 0.5
            elif round(factor_f, 0) < 6:
                wl = 4  # window length
                # overlap = 0.5
            elif round(factor_f, 0) < 13:
                wl = 8  # window length
                # overlap = 0.5
            else:
                wl = 16  # window length
                # overlap = 0.5
            hanwindow = window(wl)  # window
            dummy, W = hanwindow.hanwind()
            dsample = len(
                Sig_unw) % wl  # delta in samples between mod (x/windw length)
            dW = wl / 2  # dW = delta Window
            if dsample == 0:
                Sig = np.zeros(len(Sig_unw))
                # ul = np.arange((len(Sig_unw) - (wl - 1)) / 2) * 2
            else:
                Sig_unw = np.append(Sig_unw, np.zeros(wl - dsample))
                t = np.arange(0, len(Sig_unw)) / fs
                Sig = np.zeros(len(Sig_unw))
            ul = np.arange(
                (len(Sig_unw) - (wl - 1)) / dW) * dW  # dW = delta Window
            it = np.nditer(np.int_(ul),
                           flags=['buffered'],
                           casting='same_kind')  # , 'external_loop'])
            for idx in it:
                Sig[idx:idx + wl] += Sig_unw[idx:idx + wl] * W
            return (Sig, t)
            # http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.signal.chirp.html
        elif gentype == 'ChirpLog':
            # http://dsp.stackexchange.com/questions/30245/clicks-at-end-of-chirp-signal
            from src.window import Window
            if sg.varlist(f, 2) == (True, True):
                f0 = f[0]
                f1 = f[1]
            elif SigGen.varlist(f, 2) == (False, True):
                f0 = f[0]
                f1 = f[1]
            else:
                # Sig = []
                raise MeasError.EmptyError(sig, 'Nothing to return')
            t = np.arange(0, T * fs) / fs

            factor_f = fs / f1  # factor fs/f1
            T = T - (np.ceil(factor_f) + 1) / fs
            Sig_unw = sig.chirp(t, f0, T, f1, 'linear',
                                90)  # unwindowed Signal
            # phi = (f0 * (f1 / f0) ** (t[-4:] / T)) % np.pi

            if factor_f < 2:
                # print error
                raise ValueError('variable f1 < as fs/2')
            elif round(factor_f, 0) < 3:
                wl = 2  # window lenght
                # overlap = 0.5
            elif round(factor_f, 0) < 6:
                wl = 4  # window lenght
                # overlap = 0.5
            elif round(factor_f, 0) < 13:
                wl = 8  # window lenght
                # overlap = 0.5
            else:
                wl = 16  # window lenght
                # overlap = 0.5
            hanwindow = Window(wl)  # window
            dummy, W = hanwindow.hanwind()
            dsample = len(
                Sig_unw) % wl  # delta in samples between mod (x/windw length)
            dW = wl / 2  # dW = delta Window
            if dsample == 0:
                Sig = np.zeros(len(Sig_unw))
                # ul = np.arange((len(Sig_unw) - (wl - 1)) / 2) * 2
            else:
                Sig_unw = np.append(Sig_unw, np.zeros(wl - dsample))
                t = np.arange(0, len(Sig_unw)) / fs
                Sig = np.zeros(len(Sig_unw))
            ul = np.arange(
                (len(Sig_unw) - (wl - 1)) / dW) * dW  # dW = delta Window
            it = np.nditer(np.int_(ul),
                           flags=['buffered'],
                           casting='same_kind')  # , 'external_loop'])
            for idx in it:
                Sig[idx:idx + wl] += Sig_unw[idx:idx + wl] * W
            return (Sig, t)
            # http://docs.scipy.org/doc/scipy-0.17.0/
        elif gentype == 'Wnoise':  # White Noise
            t = np.arange(0, T * fs) / fs
            Sig = np.random.normal(0, 1, len(t))
            return (Sig, t)
        elif gentype == 'Pnoise':  # Pink noise
            raise MeasError.FunctionError(
                'Pnoise', 'Signal generator Not Implemented (Yet)')
        elif gentype == 'bnoise':  # Brown noise
            # integral of white noise
            # white noise with random ofset or something like that see wikipedia
            raise MeasError.FunctionError(
                'Bnoise', 'Signal generator Not Implemented (Yet)')
        elif gentype == 'multitone':  # multi sine tone
            raise MeasError.FunctionError(
                'Multitonee', 'Signal generator Not Implemented (Yet)')
        elif gentype == 'ChirpPoly':
            raise MeasError.FunctionError(
                'ChirpPoly', 'Signal generator Not Implemented (Yet)')
            #poly= scipy.signal.sweep_poly(t, poly, phi=0)[source]
            # http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.signal.sweep_poly.html#scipy.signal.sweep_poly
        else:
            raise MeasError.FunctionError([], 'No Valid Signal generator')
Ejemplo n.º 15
0
 def __init__(self, engine=PyEngine()):
     self.running = True
     self._engine = engine
     self._window = Window(self._engine)
Ejemplo n.º 16
0
class App(object):
    """
    Classe principal.
    """
    def __init__(self, title, window_geometry, images_path, buffer=1024):

        # Instância os parâmetros
        self.__title = title
        self.__window_geometry = window_geometry
        self.__images_path = images_path

        # Obtém o caminho de todas as imagens usadas.
        self.__coins_image = os.path.join(images_path, "coins.png")
        self.__globe_image = os.path.join(images_path, "globe.png")
        self.__logo_image = os.path.join(images_path, "logo.png")
        self.__nerd_image = os.path.join(images_path, "nerd.png")

        # Inicializa o mixer.
        mixer.init(buffer=buffer)

    def __new_question(self):
        """
        Cria uma nova questão.
        """

        # Obtém aleatóriamente o ID de uma questão e o remove da lista.
        question_id = random.choice(self.__questions)
        self.__questions.remove(question_id)

        # Obtém os dados da questão.
        question = self.__questions_data[question_id]

        # Atualiza o texto dos botões de escolhas.
        options = [question["op%i" % i] for i in range(1, 6)]
        self.__quiz_screen.update_buttons(options)

        # Instância a resposta da nova pergunta.
        self.__answer = question["answer"]

        # Coloca a nova pergunta no jogo.
        question_number = len(self.__questions_data) - len(self.__questions)
        self.__quiz_screen.update_question(question["question"],
                                           question_number)

    def __start_game(self):
        """
        Inicia o jogo.
        """
        def wait_while_callback():
            """
            Retorna um booleano verificando se o método 
            wait_while deve continuar esperando.
            """

            return self.__quiz_screen.is_next() or self.__stop

        # Cria um objeto de timer.
        timer = Timer(self.__window)

        # Constrói a janela de quiz para iniciar o jogo.
        self.__quiz_screen = QuizScreen(self.__window)
        self.__quiz_screen.build(self.__main_color, self.__sidebar_color,
                                 self.__logo_image)

        # Pontuação inicial do jogador e tempo em que o jogo começou.
        self.__score = [0, 0]
        self.__time_in_game = time.time()

        # Executa o jogo enquanto houver questões e enquanto o usuário não pedir para fechar.
        while self.__questions and not self.__stop:

            # Toca uma música para informar que apareceu uma nova questão.
            play_sound("sounds/next.mp3")

            # Esconde o botão de next.
            self.__quiz_screen.hide_next_button()

            # Cria uma nova questão no jogo.
            self.__new_question()

            # Espera um tempo em segundos que será multiplicado por 10 para que a GUI não trave.
            for i in range(self.__time * 10):

                # Obtém a escolha do usuário.
                choice = self.__quiz_screen.get_choice()
                if choice or self.__stop: break

                # Mostra para o jogador o tempo restante e espera um tempo de 100ms.
                self.__quiz_screen.create_timer(self.__time - i // 10,
                                                self.__time)
                timer.wait(100)

            # Verifica se o usuário escolheu uma opção e depois valida a escolha.
            if choice:
                self.__validate_answer(choice)
                self.__quiz_screen.create_timer(-1)

            # Verifica se o usuário pediu para sair.
            elif self.__stop:
                break

                # Se o tempo tiver acabado, uma mensagem será colocada na tela.
            else:
                play_sound("sounds/fail.mp3")
                self.__quiz_screen.create_timer(0)

            # Mostra botão de next e espera até o usuário apertar este botão.
            self.__quiz_screen.show_next_button()
            timer.wait_while(wait_while_callback)

        # Se o usuário não tiver pedido para sair, será criada uma tela final.
        if not self.__stop:

            # Obtém as informações do jogador da sessão.
            total_time = time.strftime(
                "%M:%S", time.localtime(time.time() - self.__time_in_game))
            images = [self.__logo_image, self.__nerd_image, self.__coins_image]
            points = self.__score[0] * 10

            # Reproduz música para fim de jogo.
            play_sound("sounds/end.mp3")

            # Cria a tela final.
            finalscreen = FinalScreen(self.__window)
            finalscreen.build(self.__score, points, total_time, *images)

    def __validate_answer(self, button):
        """
        Método para validar a resposta.
        """

        if button["text"] == self.__answer:
            button["bg"] = "green"
            self.__score[0] += 1

            play_sound("sounds/correct.mp3")

        else:
            button["bg"] = "red"
            self.__score[1] += 1

            play_sound("sounds/fail.mp3")

    def run(self, canvas_color, sidebar_color, questions, time=60):
        """
        Inicia e constrói a parte gráfica do programa.
        """

        # Cria a janela do programa.
        self.__window = Window(self.__title, self.__window_geometry,
                               canvas_color)
        self.__window.protocol("WM_DELETE_WINDOW", self.stop)

        # Instância os parâmetros.
        self.__main_color = canvas_color
        self.__sidebar_color = sidebar_color
        self.__questions_data = questions
        self.__questions = list(self.__questions_data)
        self.__time = time
        self.__stop = False

        # Cria uma lista com a imagem de logo e a imagem do globo.
        images = [self.__logo_image, self.__globe_image]

        # Constrói a janela principal do programa.
        main_screen = MainScreen(self.__window)
        main_screen.build(canvas_color, sidebar_color, self.__start_game,
                          images)

        # Coloca a janela do programa em um loop infinito.
        self.__window.mainloop()

    def stop(self):
        """
        Método para encerrar o programa.
        """

        mixer.music.stop()

        self.__stop = True
        self.__window.after(150, self.__window.destroy)
Ejemplo n.º 17
0
import subprocess
import sys
import os

from PyQt4.Qt import QApplication

from django.conf import settings
import src.db.settings as my_settings
settings.configure(
    DATABASE_ENGINE=my_settings.DATABASE_ENGINE,
    DATABASE_NAME=my_settings.DATABASE_NAME,
    INSTALLED_APPS=my_settings.INSTALLED_APPS
)

from src.window import Window

if __name__ == '__main__':
    dirname = os.path.dirname(__file__)
    sys.path.insert(0, os.path.join(dirname, 'src', 'db'))
    manange_py = os.path.join(dirname, 'src', 'db', 'manage.py')
    if subprocess.check_call(['python', manange_py, 'syncdb']) != 0:
        print "Could not create the database."
        sys.exit(-1)

    app = QApplication([])
    window = Window()
    window.show()
    sys.exit(app.exec_())

Ejemplo n.º 18
0
Globals.debug = False

for s in range(0, 1):
    sumA = 0.0
    sumB = 0.0
    sumC = 0.0
    for k in range(0, times):
        Globals.cur_time = 0
        Statistics.wait_time = 0.0
        Statistics.wait_area = 0.0
        Statistics.usage_time = 0.0
        customers = []
        windows = []
        for i in range(0, Globals.window_number):
            # 创建窗口
            windows.append(Window(id=i))

        time = 0
        for i in range(0, Globals.max_cus):
            # 创建所有顾客
            start_time = time + float(
                np.random.poisson(Globals.mean_arrive_time * 10)) / 10
            time = start_time
            # start_time = float(np.random.exponential(Globals.mean_arrive_time))
            # duration = -Globals.mean_serve_time * np.log(float(np.random.randint(1, 11) / 10))
            duration = float(np.random.exponential(Globals.mean_serve_time))
            customers.append(Request(arrive_time=start_time,
                                     duration=duration))

        if Globals.debug:
            print("准备工作完毕")
Ejemplo n.º 19
0
 def __init__(self):
     self.app = QApplication(sys.argv)
     self.window = Window()
def main():
    window = Window()
    window.run()
Ejemplo n.º 21
0
def play_depth(bag_file: Bag, camera: str, depth: str) -> None:
    """
    Play the ZED data in a bag file.

    Args:
        bag_file: the bag file to play
        camera: the topic to use to read compressed or raw camera data
        depth: the topic to use to read 32-bit floating point depth measures

    Returns:
        None

    """
    # open windows to stream the camera and depth image data to
    camera_window = None
    depth_window = None
    # iterate over the messages
    for topic, msg, _ in bag.read_messages(topics=[camera, depth]):
        # if topic is depth, unwrap and send to the depth window
        if topic == depth:
            # if the depth window is not setup yet, open it
            if depth_window is None:
                # create a title for the window
                title = '{} ({})'.format(bag_file.filename, depth)
                # initialize the window
                depth_window = Window(title, msg.height, msg.width)
            # get a depth image from the data and dimensions
            img = get_depth_image(msg.data, depth_window.shape)
            # show the image on the depth window
            depth_window.show(img)
        # if topic is camera, unwrap and send to the camera window
        elif topic == camera:
            # if the camera window is not setup yet, open it
            if camera_window is None:
                # create a title for the window
                title = '{} ({})'.format(bag_file.filename, camera)
                # initialize the window
                camera_window = Window(title, msg.height, msg.width)
            # get an image from the data and dimensions
            img = get_camera_image(msg.data, camera_window.shape)
            # show the image on the camera window
            camera_window.show(img)
    # shut down the viewer windows
    camera_window.close()
    depth_window.close()
Ejemplo n.º 22
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""""""

from src.window import Window

win = Window()
win.mainloop()
Ejemplo n.º 23
0
def semantic_segment(
    metadata: str,
    input_bag: Bag,
    model: 'keras.models.Model',
    predict: str,
    output_bag: Bag = None,
    output_dir: str = None,
    base: str = None,
    num_samples: int = 200,
    encoding: str = 'rgb',
) -> None:
    """
    Predict a stream of images from an input ROSbag.

    Args:
        metadata: the metadata about the semantic segmentations from the model
        input_bag: the input bag to predict targets from a topic
        model: the semantic segmentation model to use to make predictions
        predict: the topic to get a priori estimates from
        output_bag: the output bag to write the a priori estimates to
        output_dir: the output directory to write image pairs to
        base: the base-name for the prediction image topic
        num_samples: the number of image pairs to sample for output directory
        encoding: the encoding for the images to write

    Returns:
        None

    """
    # create the base endpoint for the topics
    base = '' if base is None else '{}'.format(base)

    # setup the output directories
    if output_dir is not None:
        x_dir = os.path.join(output_dir, 'X', 'data')
        if not os.path.isdir(x_dir):
            os.makedirs(x_dir)
        y_dir = os.path.join(output_dir, 'y', 'data')
        if not os.path.isdir(y_dir):
            os.makedirs(y_dir)

    # read the RGB map and vectorized method from the metadata file
    rgb_map, unmap_rgb = read_rgb_map(metadata)

    # write the color map metadata to the output bag
    if output_bag is not None:
        ros_stamp = rospy.rostime.Time(input_bag.get_start_time())
        msg = String(repr(rgb_map))
        output_bag.write('{}/rgb_map'.format(rgb_map), msg, ros_stamp)

    # open a Window to play the video
    x_window = Window('img', model.input_shape[1], model.input_shape[2])
    y_window = Window('sem-seg', model.output_shape[1], model.output_shape[2])
    # create a progress bar for iterating over the messages in the bag
    total_messages = input_bag.get_message_count(topic_filters=predict)
    with tqdm(total=total_messages, unit='message') as prog:
        # iterate over the messages in this input bag
        for _, msg, time in input_bag.read_messages(topics=predict):
            # update the progress bar with a single iteration
            prog.update(1)
            if np.random.random() > num_samples / total_messages:
                continue
            # create a tensor from the raw pixel data
            pixels = get_camera_image(msg.data,
                                      (msg.height, msg.width))[..., :3]
            # flip the BGR image to RGB
            if encoding == 'bgr':
                pixels = pixels[..., ::-1]
            # resize the pixels to the shape of the model
            _pixels = resize(
                pixels,
                model.input_shape[1:],
                anti_aliasing=False,
                mode='symmetric',
                clip=False,
                preserve_range=True,
            ).astype('uint8')
            # pass the frame through the model
            y_pred = model.predict(_pixels[None, ...])[0]
            y_pred = np.stack(unmap_rgb(y_pred.argmax(axis=-1)), axis=-1)
            y_pred = y_pred.astype('uint8')
            # show the pixels on the windows
            x_window.show(_pixels)
            y_window.show(y_pred)
            # create an Image message and write it to the output ROSbag
            if output_bag is not None:
                msg = image_msg(y_pred, msg.header.stamp, y_pred.shape[:2],
                                'rgb8')
                output_bag.write('{}/image_raw'.format(base), msg,
                                 msg.header.stamp)
            # sample a number and write the image pair to disk
            if output_dir is not None:
                x_file = os.path.join(x_dir, '{}.png'.format(time))
                Image.fromarray(pixels).save(x_file)
                y_file = os.path.join(y_dir, '{}.png'.format(time))
                y_pred = resize(
                    y_pred,
                    pixels.shape[:2],
                    anti_aliasing=False,
                    mode='symmetric',
                    clip=False,
                    preserve_range=True,
                ).astype('uint8')
                Image.fromarray(y_pred).save(y_file)
Ejemplo n.º 24
0

def bug_init(board: List[Tile]) -> List[Bug]:
    bugs: List[Bug] = []
    tiles_used: List[int] = []
    for bug in range(0, 8):
        bugs.append(Bug(bug))
        position = randrange(NUMBER_OF_COLUMNS * NUMBER_OF_ROWS)
        while position in tiles_used:
            position = randrange(NUMBER_OF_COLUMNS * NUMBER_OF_ROWS)
        board[position].bug = Bug(bug)
        tiles_used.append(position)
    return bugs


window = Window(WIN_WIDTH, WIN_HEIGHT, 'Bugs on the desert')
text_surface: pygame.Surface = window.render_text('Click on the bugs!')
Tile.set_tile_size(window_size=window.size, height_offset=HEIGHT_OFFSET)

playing_board: List[Tile] = board_init(HEIGHT_OFFSET)
on_play_bugs: List[Bug] = bug_init(playing_board)

window.background_image = pathlib.Path('resources/background.jpg')
bug_found = Bug.NO_BUG

event_list: List[events.Event] = {
    events.BugMoverEvent(5),
    events.BugFakerEvent(2),
    events.BugTileCloserEvent(5)
}
Ejemplo n.º 25
0
 def __init__(self, world):
     self.world = world
     self.viewer = Window()
     self.is_paused = False