Esempio n. 1
0
    def run(self):
        """
        Main game loop: processes inputs, updates the game status and renders the game scene
        """
        last_update_time = pygame.time.get_ticks()
        while not self.exit_signal:
            #Process inputs       
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    utils.terminate()             
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT and self.is_valid_position(self.falling_piece, offset_x=-1):
                        self.moving_left = True
                        self.moving_right = False
                    elif event.key == pygame.K_RIGHT and self.is_valid_position(self.falling_piece, offset_x=1):
                        self.moving_right = True
                        self.moving_left = False
                    elif event.key == pygame.K_UP:
                        self.rotate = True                       
                    elif event.key == pygame.K_DOWN:
                        self.fall_time = game_config.FAST_FALL_TIME
                        self.fall_time_changed = True
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_DOWN:
                        self.fall_time = self.normal_fall_time
                        self.fall_time_changed = True
                    if event.key == pygame.K_ESCAPE:
                        utils.terminate()
                    if event.key == pygame.K_p: 
                        self.signal_pause = True
                  
            time = pygame.time.get_ticks()    
            delta_time = time - last_update_time
            
            while delta_time > 0:
                sim_step_time = game_config.STEP_TIME
                if delta_time - game_config.STEP_TIME < 0:
                    sim_step_time = delta_time

                self.update(sim_step_time)
                delta_time -= sim_step_time
                
                if self.exit_signal:
                    break
                if self.signal_pause:
                    self.exit_signal = True
                    break

            last_update_time = time
            
            #Draw the board
            graphics.clear_display_surf()
            graphics.draw_board(self.board)
            graphics.draw_score_level_next_piece(self.score.score_value, self.score.get_level(), self.next_piece)
            graphics.draw_statistics(self.piece_type_count, game_config.FONT_SIZE_BASIC)
            if self.falling_piece:
                graphics.draw_piece(self.falling_piece, game_config.BOARD_PIXEL_POSX, game_config.BOARD_PIXEL_POSY)
            graphics.update_display_surf()

            self.fps_clock.tick(game_config.MAX_FPS)
Esempio n. 2
0
    def frames_from_raspivid(self, fmt, w, h, fps, shutter):
        if fmt == 'raw':
            cmd = ['raspividyuv',
                   '--luma']  # stream only the Y (luminance) data
            frame_size = w * h
        elif fmt == 'mjpg':
            cmd = ['raspivid', '-cd', 'MJPEG']
            # we don't have a fixed frame size, stream the data in chunks of 1k
            frame_size = 1024

        cmd += [
            '-t',
            '0',  # no timeout, record forever
            '-w',
            str(w),
            '-h',
            str(h),
            '-fps',
            fps,
            '-o',
            '-'
        ]
        if shutter:
            cmd += ['-ss', str(shutter)]
        print('Executing: %s' % ' '.join(cmd))
        p = subprocess.Popen(cmd, bufsize=0, stdout=subprocess.PIPE)
        try:
            yield from self.getframes(p.stdout, fmt, frame_size)
        finally:
            terminate(p)
Esempio n. 3
0
def main():
    cmd = [
        'gphoto2',
        #'--port', 'ptpip:192.168.1.180',
        '--set-config',
        'output=TFT + PC',
        '--capture-movie',
        '--stdout'
    ]
    p = subprocess.Popen(cmd,
                         bufsize=0,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out0 = p.stdout.read(1024)
    out1 = p.stdout.read(1024)
    if out1 == b'':
        # gphoto is not streaming anything, so it must be an error
        stderr = p.stderr.read()
        p.wait()
        print('ERROR')
        print(out0)
        print(stderr)
        return

    frame_times = collections.deque([time.time()], maxlen=25)
    try:
        for i, frame in enumerate(iter_mjpg(p.stdout, out0 + out1)):
            frame_times.append(time.time())
            fps = len(frame_times) / (frame_times[-1] - frame_times[0])
            if i % 10 == 0:
                print('%.2f fps' % fps)
    finally:
        terminate(p)
Esempio n. 4
0
 def handle_events(self) -> None:
     for event in pygame.event.get():
         if event.type == pygame.QUIT:
             managers.DatabaseManager.get_instance().close()
             utils.terminate()
         elif event.type == pygame.KEYDOWN and pygame.key.get_pressed()[pygame.K_ESCAPE]:
             self.handle_escape_event()
         else:
             self.handle_event(event)
Esempio n. 5
0
def check_for_quit(): 
    """
    Checks if the user has pressed the EXIT button
    """     
    for event in pygame.event.get(pygame.QUIT):
        utils.terminate()
    for event in pygame.event.get(pygame.KEYUP):
        if event.key == pygame.K_ESCAPE:
            utils.terminate() 
        pygame.event.post(event)
Esempio n. 6
0
def check_for_quit(): 
    """
    Checks if the user has pressed the EXIT button
    """     
    for event in pygame.event.get(pygame.QUIT):
        utils.terminate()
    for event in pygame.event.get(pygame.KEYUP):
        if event.key == pygame.K_ESCAPE:
            utils.terminate() 
        pygame.event.post(event)
Esempio n. 7
0
 def run(self):
     """
     Main game loop: processes inputs, updates the game status and renders the game scene
     """        
     last_update_time = pygame.time.get_ticks()
     accumulated = 0.0
     while self.game_status == GameLayer.INITIALIZATION or self.game_status == GameLayer.GAME_LOOP:
         #Process inputs       
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 utils.terminate()             
             elif event.type == pygame.KEYDOWN:
                 if event.key == pygame.K_LEFT:
                     self.moving_left = True
                 elif event.key == pygame.K_RIGHT:
                     self.moving_right = True
                 elif event.key == pygame.K_a:
                     self.push_balls = True 
                 elif event.key == pygame.K_p: 
                     self.game_status = GameLayer.GAME_PAUSE_SCREEN
             elif event.type == pygame.KEYUP:
                 if event.key == pygame.K_ESCAPE:
                     utils.terminate()
                 elif event.key == pygame.K_RIGHT:
                     self.moving_right = False
                 elif event.key == pygame.K_LEFT:
                     self.moving_left = False  
               
         time = pygame.time.get_ticks()    
         delta_time = time - last_update_time
         
         accumulated = accumulated + delta_time                
         if accumulated > BALL_PUSH: 
             self.push_balls = True
             accumulated = 0.0
         
         while delta_time > 0:
             sim_step_time = STEP_TIME
             if delta_time - STEP_TIME < 0:
                 sim_step_time = delta_time
             self.update(sim_step_time)
             self.physics_world.step_simulation(sim_step_time)
             
             if len(self.bricks) < 1:
                 if not self.current_map.has_next_map():
                     self.game_status = GameLayer.GAME_WIN_SCREEN
                 else:
                     self.update_map()
                     self.game_status = GameLayer.INITIALIZATION
                     accumulated = 0
             delta_time -= sim_step_time
         last_update_time = time
         graphics.clear_display_surf(BLUE)        
         for entity in self.entities:            
             dest_rect = pygame.Rect(entity.body.rect.position.x,
                                     entity.body.rect.position.y,
                                     entity.body.rect.w,
                                     entity.body.rect.h)
             graphics.draw(entity.surface, entity.surface_src, dest_rect)
         graphics.flip_display_surf()
         
         self.fps_clock.tick(MAX_FPS)
                # train
                history = current_model.fit(
                    x = X_train, y = Y_train,
                    epochs=general_conf['iterations'],
                    batch_size=general_conf['batch_size'],
                    validation_data=(X_test, Y_test),
                    callbacks = callbacks)
                # load best weights
                current_model.load_weights('{}-weights.h5'.format(outdir(out_name)))
                # test
                preds = current_model.evaluate(x = X_test, y = Y_test)
                show_stats(start_time, preds)
                
                # output results
                predictions = current_model.predict(X_test)
                Y_pred = ohe_to_label(predictions)
                Y_true = ohe_to_label(Y_test)
                
                conf_matrix(Y_true, Y_pred, class_conversion, out_name, save = True)
                
                # export model
                if general_conf['export_models']:
                    export_model(current_model, out_name)
                # notify
                telegram_send.send(['Training {}/{} finished'.format(cycle, total_cycles)])
            cycle += 1
                
# send finish signal via telegram and close aws instance
if general_conf['prod']:
    terminate()
Esempio n. 9
0
    def run(self):
        """
        Main game loop: processes inputs, updates the game status and renders the game scene
        """
        last_update_time = pygame.time.get_ticks()
        accumulated = 0.0
        while self.game_status == GameLayer.INITIALIZATION or self.game_status == GameLayer.GAME_LOOP:
            #Process inputs
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    utils.terminate()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        self.moving_left = True
                    elif event.key == pygame.K_RIGHT:
                        self.moving_right = True
                    elif event.key == pygame.K_a:
                        self.push_balls = True
                    elif event.key == pygame.K_p:
                        self.game_status = GameLayer.GAME_PAUSE_SCREEN
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_ESCAPE:
                        utils.terminate()
                    elif event.key == pygame.K_RIGHT:
                        self.moving_right = False
                    elif event.key == pygame.K_LEFT:
                        self.moving_left = False

            time = pygame.time.get_ticks()
            delta_time = time - last_update_time

            accumulated = accumulated + delta_time
            if accumulated > BALL_PUSH:
                self.push_balls = True
                accumulated = 0.0

            while delta_time > 0:
                sim_step_time = STEP_TIME
                if delta_time - STEP_TIME < 0:
                    sim_step_time = delta_time
                self.update(sim_step_time)
                self.physics_world.step_simulation(sim_step_time)

                if len(self.bricks) < 1:
                    if not self.current_map.has_next_map():
                        self.game_status = GameLayer.GAME_WIN_SCREEN
                    else:
                        self.update_map()
                        self.game_status = GameLayer.INITIALIZATION
                        accumulated = 0
                delta_time -= sim_step_time
            last_update_time = time
            graphics.clear_display_surf(BLUE)
            for entity in self.entities:
                dest_rect = pygame.Rect(entity.body.rect.position.x,
                                        entity.body.rect.position.y,
                                        entity.body.rect.w, entity.body.rect.h)
                graphics.draw(entity.surface, entity.surface_src, dest_rect)
            graphics.flip_display_surf()

            self.fps_clock.tick(MAX_FPS)
Esempio n. 10
0
 def reload(self):
     managers.DatabaseManager.get_instance().close()
     utils.terminate()
Esempio n. 11
0
 def handle_escape_event(self) -> None:
     managers.DatabaseManager.get_instance().close()
     utils.terminate()
Esempio n. 12
0
def main():
    capture = opencv.VideoCapture(0)

    model = Model()
    model.load()

    time_since_NO_user = 0
    time_since_user = 0

    while True:
        try:
            _, frame = capture.read()

            try:
                frame_gray = opencv.cvtColor(frame, opencv.COLOR_BGR2GRAY)
            except OpenCVError:
                raise OpenCVError("ADFIS: Camera not found or already in use.")

            cascade = opencv.CascadeClassifier(CASCADE_PATH)
            face_rect = cascade.detectMultiScale(frame_gray,
                                                 scaleFactor=1.2,
                                                 minNeighbors=3,
                                                 minSize=(10, 10))

            if is_face(face_rect):
                time_since_user += 1
                time_since_NO_user = 0

                for rect in face_rect:
                    x, y = rect[0:2]
                    width, height = rect[2:4]
                    image = frame[y - 10:y + height, x:x + width]

                    result = model.predict(image)

                    if is_user(result):
                        adfis('User recognized.')
                        sleep(1)
                    else:
                        adfis('User not recognized, locking screen.')
                        lockscreen()

            else:
                adfis("Face not detected: {0}.".format(time_since_NO_user))

                if time_since_NO_user == LIMIT:
                    adfis("User is not present, locking screen.")
                    lockscreen()

                time_since_NO_user += 1
                time_since_user = 0
                sleep(1)

            key_press = opencv.waitKey(100)

            if key_press == EXIT_CODE:
                terminate()
                break
        except KeyboardInterrupt:
            terminate()
            break

    capture.release()
    opencv.destroyAllWindows()