Exemplo n.º 1
0
    def __init__(self, settings, color_manager, display_glinfo=False, size=3, verbose=False):
        self.settings = settings
        self.color_manager = color_manager
        self.verbose = verbose
        self.cube_size = size
        self.client = None
        self.colors = None
        self.color_mapping = {}
        self.delta_time = DeltaTime()
        self.fps = Fps(self.settings.fps_update_interval)
        self.mouse_drag = MouseDrag()

        self.command_delimiter = ';'

        self.init_colors()
        self.init_opengl()

        self.textures = {}
        if self.settings.texture_mapping_enabled:
            self.create_textures(self.settings.image_resources)

        self.init_cube()
        self.init_command_handler_map()

        if display_glinfo:
            self.show_gl_info()

        atexit.register(self.on_exit)

        # My Code
        # to keep track of how solved the cube is
        self.states = ['CROSS', 'F2L', 'OLL', 'PLL', 'SOLVED']
        self.state = self.states[0]
        # for a reverse move solver
        self.all_moves = []
Exemplo n.º 2
0
class GravApp(App):
    def build(self):

        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

        self.draw_fps = True
        self.fps = Fps()

        self.time = 0.
        self.last_time = 0.
        self.time_mult = 1.

        Clock.schedule_interval(self.update, 0)

        self.root = Space()
        return self.root

    def update(self, dt):

        # self.dt = dt
        self.time += dt * self.time_mult

        if abs(self.time - self.last_time) >= abs(self.time_mult):
            self.last_time = self.time
            print Clock.get_fps()

        self.root.update(dt * self.time_mult, self.time)

        if self.draw_fps:
            self.fps.update(dt)
            self.fps.draw(self.root)

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        # print keycode
        if keycode[1] == 'd' or keycode[0] == 100:
            self.root.show_acc = not self.root.show_acc
            self.root.show_vel = not self.root.show_vel
        if keycode[1] == 'escape' or keycode[0] == 27 or \
                keycode[1] == 'q' or keycode[0] == 113:
            App.get_running_app().stop()
        if keycode[1] == 'left' or keycode[0] == 276:
            self.time_mult -= 0.1
            print('{:.1f} mult'.format(self.time_mult))
        if keycode[1] == 'right' or keycode[0] == 275:
            self.time_mult += 0.1
            print('{:.1f} mult'.format(self.time_mult))
        if keycode[1] == 'down' or keycode[0] == 274:
            self.root.set_vel([0.])
        return True
Exemplo n.º 3
0
 def __init__(self,
              video_device_id=-1,
              use_thread=True,
              limit_frame_rate=False,
              resolution=None):
     self.video_device_id = video_device_id
     self.limit_frame_rate = limit_frame_rate
     self.resolution = resolution
     self.use_thread = use_thread
     self._image = None
     self.last_image_read = True  # whether last frame has been used
     self.fps = Fps()
     self.fps.start()
     self.event = Event()
Exemplo n.º 4
0
class GravApp(App):
    time = NumericProperty(0)

    def build(self):
        Clock.schedule_interval(self.update, 0)
        self.root = Space()
        self.fps = Fps()
        return self.root

    def update(self, dt):
        self.dt = dt
        self.time += dt
        self.root.update(dt, self.time)
        self.fps.update(dt)
        self.fps.draw(self.root)
Exemplo n.º 5
0
class Main():

    def __init__(self, gru_file=None): 
        self.menu = Menu(self, config, game = None)        
        self.library = Library(self, config)
        self.collider = Collider(self.menu, self.library, game=None)
        self.dispatcher = Dispatcher(self.collider, self.library, self.menu, game=None)
        self.clock = pygame.time.Clock()
        self.fps = Fps(self.clock, config)
        if gru_file is not None:
            game = Game(gru_file)
            self.load(game)
        else:
            self.game = None        
        
    def load(self, game):
        self.library.clear()
        self.game = game
        self.collider.game = game
        self.menu.game = game

    def clear(self):
        self.game = None
        self.collider.game = None
        self.menu.game = None

    def draw(self):    
        tick = self.clock.get_time()
        self.menu.draw()    
        if self.game == None:
            self.library.draw()  
        else:           
            self.game.draw(tick)        

                                  
    def start(self):                          
                     
        while 1:      
            self.clock.tick()                   
            mrect = Rect(mouse.get_pos(), (1,1))  
            self.collider.check()          
            self.draw()  
            self.fps.draw()            

            for ev in event.get():
                self.dispatcher.process(ev)               

            display.update()
Exemplo n.º 6
0
    def build(self):

        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

        self.draw_fps = True
        self.fps = Fps()

        self.time = 0.
        self.last_time = 0.
        self.time_mult = 1.

        Clock.schedule_interval(self.update, 0)

        self.root = Space()
        return self.root
Exemplo n.º 7
0
    def __init__(self, default_gesture_size=10, minimum_gesture_size=7,
                 dc_pin_id=16, reset_pin_id=15):
        """GlovePi class constructor

        :param default_gesture_size:
        :type default_gesture_size: int
        :param minimum_gesture_size:
        :type minimum_gesture_size: int
        """
        self.gesture_size = default_gesture_size
        self.min_gesture_size = minimum_gesture_size

        self.current_label = 0
        self.current_gesture = []

        if os.path.isfile("uuids.npy"):
            print "Loaded from file"
            self.all_gestures = np.load('features.npy').tolist()
            self.all_labels = np.load('labels.npy').tolist()
            self.all_uuids = np.load('uuids.npy').tolist()
            self.all_times = np.load('times.npy').tolist()
        else:
            self.all_gestures = []
            self.all_labels = []
            self.all_uuids = []
            self.all_times = []

        self.led = gaugette.ssd1306.SSD1306(reset_pin=reset_pin_id,
                                            dc_pin=dc_pin_id)
        self.led.begin()
        self.led.clear_display()

        # Where the buttons are plugged into the pi.
        self.button_1_pin = 5  # Red.
        self.button_2_pin = 21  # Black.

        # Instantiate the state object.
        self.state_management = State(self.button_1_pin, self.button_2_pin)

        # Instantiate the object controlling our desired fps.
        self.desired_fps = 8
        self.fps_timer = Fps(self.desired_fps)

        # Are we recording or classifying gestures?
        self.record_mode = False

        # Classification stuff.
        self.amount_neighbours = 1

        logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
        logging.basicConfig()

        # Websockets
        self.socketIO = SocketIO('http://brightsigndemo.eu-gb.mybluemix.net',
                                 80, LoggingNamespace)
Exemplo n.º 8
0
    def do_GET(self):
        fps = Fps()

        init_time = Timer()
        init_time.start()
        cap = cv2.VideoCapture(0)
        try:
            init_time.end()
            print "initialization time : " + str(
                init_time.elapsed()) + " elapsed"
            self.send_response(httplib.OK)
            self.send_header("Content-type",
                             "multipart/x-mixed-replace;boundary=boundarytag")
            self.end_headers()
            fps.start()

            while True:
                t = Timer()
                retval, frame = cap.read()

                img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                jpg = Image.fromarray(img)
                tmp = StringIO.StringIO()
                t.start()
                jpg.save(tmp, 'JPEG')
                t.end()
                print "frame encoding time : " + str(t.elapsed()) + " elapsed"

                self.wfile.write("--boundarytag")
                self.send_header("Content-type", "image/jpeg")
                self.send_header("Content-Length", len(tmp.getvalue()))
                self.end_headers()

                self.wfile.write(tmp.getvalue())
                fps.increase()
        except KeyboardInterrupt:
            print "keboard interrupt"
        finally:
            fps.end()
            cap.release()
            print fps.fps()
Exemplo n.º 9
0
    def build(self, *args, **kwargs):
        self.draw_fps = True
        self.fps = Fps()

        self.time = 0.
        self.last_time = 0.
        self.time_mult = 1.
        self.time_mult_pause = None

        Clock.schedule_interval(self.update, 0)
        self.event_once = None

        self.root = Space()

        Config.read('config.ini')

        # For my window header
        # dx, dy = -1, -32
        dx, dy = 0, 0

        if Config.get('graphics', 'position') != 'auto':
            Window.left, Window.top, Window.size = Config.getint('graphics', 'left') + dx, \
                                                   Config.getint('graphics', 'top') + dy, \
                                                   (Config.getint('graphics', 'width'), \
                                                    Config.getint('graphics', 'height'),)
        if Config.getboolean('graphics', 'maximize'):
            Window.maximize()

        Window.show()

        self.root.bind(on_touch_down=self.on_touch_down,
                       on_touch_move=self.on_touch_move,
                       on_touch_up=self.on_touch_up)

        if self.filename:
            Clock.schedule_once(
                partial(
                    import_module(self.filename).set_state, self.root, self),
                1)

        return self.root
Exemplo n.º 10
0
 def __init__(self, gru_file=None): 
     self.menu = Menu(self, config, game = None)        
     self.library = Library(self, config)
     self.collider = Collider(self.menu, self.library, game=None)
     self.dispatcher = Dispatcher(self.collider, self.library, self.menu, game=None)
     self.clock = pygame.time.Clock()
     self.fps = Fps(self.clock, config)
     if gru_file is not None:
         game = Game(gru_file)
         self.load(game)
     else:
         self.game = None        
Exemplo n.º 11
0
class ImutilsVideoSource(object):
    def __init__(self, video_device_id=-1, use_thread=True):
        self.video_device_id = video_device_id
        self._image = None
        self.use_thread = use_thread
        self.fps = Fps()
        self.fps.start()

    def start_camera(self):
        start = time.time()
        self.video_stream = VideoStream(src=self.video_device_id).start()
        print('>>> opened VideoCapture in %.3f seconds' %
              (time.time() - start))
        # subprocess.check_output(['bash', '-c', 'v4l2-ctl -c backlight_compensation=1,sharpness=130,power_line_frequency=1,white_balance_temperature_auto=1,saturation=128,contrast=128,brightness=128,focus_absolute=0,focus_auto=0'])
        self.running = True
        if self.use_thread:
            start = time.time()
            self.thread = Thread(target=thread_callback(self.grab_frames),
                                 args=())
            self.thread.daemon = True
            self.thread.start()
            print('>>> camera thread started in %.3f seconds' %
                  (time.time() - start))

        return self

    def stop_camera(self):
        self.running = False

    def grab_frames(self):
        while self.running:
            self.fps.update()
            self._image = self.video_stream.read()

    def get_rgb_image(self):
        if self.get_image() is None:
            return None
        return cv2.cvtColor(self.get_image(), cv2.COLOR_BGR2RGB)

    def get_rgb_bgr_image(self):
        bgr_image = self.get_image()
        if bgr_image is None:
            return (None, None)
        return (cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB), bgr_image)

    def get_bgr_image(self):
        return self.get_image()

    def get_image(self):
        if not self.use_thread:
            ret, self._image = self.video_stream.read()
            self.fps.update()
        # if self._image is None:
        #     return None
        # small = cv2.resize(self._image, (0,0), fx=0.5, fy=0.5)
        return self._image
Exemplo n.º 12
0
	def do_GET(self):
		fps = Fps()

		init_time = Timer()
		init_time.start()
		cap = cv2.VideoCapture(0)
		try:
			init_time.end()
			print "initialization time : " + str(init_time.elapsed()) + " elapsed"
			self.send_response(httplib.OK)
			self.send_header("Content-type", "multipart/x-mixed-replace;boundary=boundarytag")
			self.end_headers()
			fps.start()
			
			while True:
				t = Timer()
				retval, frame = cap.read()
				
				img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
				jpg = Image.fromarray(img)
				tmp = StringIO.StringIO()
				t.start()
				jpg.save(tmp, 'JPEG')
				t.end()
				print "frame encoding time : " + str(t.elapsed()) + " elapsed"

				self.wfile.write("--boundarytag")
				self.send_header("Content-type", "image/jpeg")
				self.send_header("Content-Length", len(tmp.getvalue()))
				self.end_headers()
				
				self.wfile.write(tmp.getvalue())
				fps.increase()
		except KeyboardInterrupt:
			print "keboard interrupt"
		finally:
			fps.end()
			cap.release()
			print fps.fps()
Exemplo n.º 13
0
def run_game():
    #初始化游戏、设置和屏幕对象
    pygame.init()
    pygame.mixer.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # 声音实例
    gs = GameSounds()

    #创建Play按钮
    play_button = Button(ai_settings, screen, 'Play')

    #创建一个用于存储游戏统计信息的实例,并创建积分牌
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #创建fps模块实例
    fb = Fps(screen)

    #创建一艘飞船,一个子弹编组和一个外星人编组
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    #创建外星人群
    gf.create_fleet(ai_settings, screen, ship, aliens)

    #开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, stats, play_button, ship, aliens,
                        bullets, sb, fb, gs)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets, gs)
            gf.update_aliens(ai_settings, ship, aliens, stats, bullets, screen,
                             sb)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button, fb)
Exemplo n.º 14
0
class App:
    KEY_BACKSPACE = 8
    KEY_RETURN = 13
    KEY_ESCAPE = 27
    KEY_DELETE = 127

    def __init__(self, settings, color_manager, display_glinfo=False, size=3, verbose=False):
        self.settings = settings
        self.color_manager = color_manager
        self.verbose = verbose
        self.cube_size = size
        self.client = None
        self.colors = None
        self.color_mapping = {}
        self.delta_time = DeltaTime()
        self.fps = Fps(self.settings.fps_update_interval)
        self.mouse_drag = MouseDrag()

        self.command_delimiter = ';'

        self.init_colors()
        self.init_opengl()

        self.textures = {}
        if self.settings.texture_mapping_enabled:
            self.create_textures(self.settings.image_resources)

        self.init_cube()
        self.init_command_handler_map()

        if display_glinfo:
            self.show_gl_info()

        atexit.register(self.on_exit)

        # My Code
        # to keep track of how solved the cube is
        self.states = ['CROSS', 'F2L', 'OLL', 'PLL', 'SOLVED']
        self.state = self.states[0]
        # for a reverse move solver
        self.all_moves = []

    def init_colors(self):
        self.colors = self.settings.cube_default_colors

        group_name = self.settings.cube_color_group
        group = self.color_manager.get_color_group(group_name)
        if group != None:
            self.colors.update(group)

        self.colors.update(self.settings.cube_colors)

        if self.verbose:
            print('Color palette:', self.colors)

        default_color = Constants.FALLBACK_COLOR
        for key, value in self.colors.items():
            self.colors[key] = LittleHelpers.convert_hex_color_to_floats(value, default_color)

    def init_mqtt_client(self):
        print('The mqtt client is unavaliable and will be removed soon.')

    def init_opengl(self):
        glutInit()
        glutInitWindowPosition(self.settings.window_position[0], self.settings.window_position[1])
        glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowSize(self.settings.window_size[0], self.settings.window_size[1])
        glutCreateWindow(self.settings.window_caption)

        glutReshapeFunc(self.on_reshape_window)
        glutKeyboardFunc(self.on_keyboard_input)
        glutMouseFunc(self.on_mouse_input)
        glutMotionFunc(self.on_mouse_move)
        glutSpecialFunc(self.on_special_input)
        glutVisibilityFunc(self.on_visibility_change)
        glutIdleFunc(self.on_update)
        glutDisplayFunc(self.on_display)

        try:
            if sys.platform == 'linux' or sys.platform == 'linux2':
                glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS)
        except Exception as e:
            print(f'Something went wrong while setting platform specific code. You can just ignore this, but if you want the error it is: {e}')

        background_color = LittleHelpers.convert_hex_color_to_floats(self.settings.window_background_color, (0.1, 0.1, 0.1))
        glClearColor(background_color[0], background_color[1], background_color[2], 1)
        glClearDepth(1)
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)
        glShadeModel(GL_SMOOTH)
        glDisable(GL_LIGHTING)

        if self.settings.texture_mapping_enabled:
            glEnable(GL_TEXTURE_2D)
        else:
            glDisable(GL_TEXTURE_2D)

        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)

    def init_cube(self):
        face_rotation_ease_type = Tween.get_ease_type_by_name(self.settings.cube_face_rotation_ease_type)
        texture_id = self.textures.get(self.settings.texture_mapping_active_texture)
        if texture_id == None:
            texture_id = 0
        self.cube = Cube(self.settings, face_rotation_ease_type, texture_id, self.cube_size)
        self.map_cube_colors(self.settings.cube_color_mapping)

    def init_command_handler_map(self):
        self.cmd_handler_map = {
            # standalone commands
            'exit': self.handle_exit_command,
            'quit': self.handle_exit_command,
            'reset_cube': self.handle_reset_cube_command,
            'reset_rotation': self.handle_reset_rotation_command,
            'reset_scale': self.handle_reset_scale_command,
            'stop_rotation': self.handle_reset_scale_command,
            'reset_color_mapping': self.handle_reset_color_mapping_command,
            'reset_colors': self.handle_reset_colors,
            'apply_random_pattern': self.handle_apply_random_pattern_command,
            'apply_random_scramble': self.handle_apply_random_scramble_command,

            # commands with one or more parameters
            'map_colors': self.handle_map_colors_command,

            'add_rotation_x': self.handle_add_rotation_x_command,
            'add_rotation_y': self.handle_add_rotation_y_command,
            'add_scale': self.handle_add_scale_command,
            'rotate_face': self.handle_rotate_face_command,
            'scramble': self.handle_scramble_command,
            'add_padding': self.handle_add_padding_command,
            'set_background_color': self.handle_set_background_color,
            'load_colors': self.handle_load_colors
        }

    def run(self):
        glutMainLoop()

    def show_gl_info(self):
        print('* GL_RENDERER   : ', glGetString(GL_RENDERER))
        print('* GL_VERSION    : ', glGetString(GL_VERSION))
        print('* GL_VENDOR     : ', glGetString(GL_VENDOR))
        print('* GL_EXTENSIONS : ', glgetString(GL_EXTENSIONS))

    def on_exit(self):
        texture_ids = []
        for name, id in self.textures.items():
            if id:
                texture_ids.append(id)
        if len(texture_ids) > 0:
            print('Deleteing textures;', texture_ids)
            glDeleteTextures(texture_ids)

        if self.client:
            self.client.stop()

    def on_reshape_window(self, w, h):
        if h == 0:
            h = 1
        ratio = 1 * w / h

        glViewport(0, 0, w, h)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(45, ratio, 0.1, 100)
        glTranslatef(0, 0, -17.5)
        glMatrixMode(GL_MODELVIEW)

    def on_visibility_change(self, visible):
        if visible == GLUT_VISIBLE:
            glutIdleFunc(self.on_update)
        else:
            glutIdleFunc(None)

    def on_keyboard_input(self, key, x, y):
        ch = key.decode('utf-8')

        # exit app on q or ESC:
        if ch == 'q' or ch == chr(self.KEY_ESCAPE):
            sys.exit()
        # reset cube
        elif ch == chr(self.KEY_BACKSPACE) or ch == chr(self.KEY_DELETE):
            self.reset_cube()
        elif ch == chr(self.KEY_RETURN):
            self.cube.reset_rotation()
            self.cube.reset_scale()
        # stop rotation
        elif ch == ' ':
            self.cube.stop_rotation()
        # scramble cube
        elif ch == '1':
            self.apply_random_scramble()
        # apply random pattern:
        elif ch == '2':
            self.apply_random_pattern()

        # scale cube
        scale = None
        scale_value = 0.1
        if ch == '+': scale = scale_value
        elif ch == '-': scale = -scale_value
        if scale:
            self.cube.add_scale(scale * self.delta_time.elapsed())

        # translate move
        move = None
        if ch == 'f': move = "F"
        elif ch == 'F': move = "F'"
        elif ch == 'b': move = "B"
        elif ch == 'B': move = "B'"
        elif ch == 'u': move = "U"
        elif ch == 'U': move = "U'"
        elif ch == 'd': move = "D"
        elif ch == 'D': move = "D'"
        elif ch == 'l': move = "L"
        elif ch == 'L': move = "L'"
        elif ch == 'r': move = "R"
        elif ch == 'R': move = "R'"
        elif ch == 'S': self.auto_solve(instantly=True)
        elif ch == 's': self.auto_solve('ALL')
        if move: self.add_moves([move])

    def on_mouse_input(self, button, state, x, y):
        if button == GLUT_LEFT_BUTTON:
            if state == GLUT_DOWN:
                self.mouse_drag.begin(x, y)
                self.cube.stop_rotation()
            if state == GLUT_UP:
                self.mouse_drag.end(x, y)

    def auto_solve(self, part='ALL', instantly=False):
        moves = self.calculate_solve(part)
        if instantly:
            self.scramble_cube(moves)
        else:
            self.add_moves(moves)
            self.all_moves = []

    def calculate_solve(self, part='ALL'):
        if type(part != str):
            return 1
        part = part.upper()

        if part == 'ALL': # Solve the entire cube
            formula = pycuber.Formula(self.all_moves)
            formula.reverse()
            return str(formula)

        # I just had elif statements here which i don't feel like typing as thy don't do anything

    def on_mouse_move(self, x, y):
        if self.mouse_drag.is_dragging:
            sensitivity = Mathf.clamp(self.settings.mouse_sensitivity, 0.1, 10)
            value = math.pi / 500 * sensitivity
            self.mouse_drag.update(x, y)
            dx, dy = self.mouse_drag.get_delta()
            if dx != 0:
                self.cube.add_rotate_x(-dy * value * self.delta_time.elapsed())
            if dy != 0:
                self.cube.add_rotate_y(-dx * value * self.delta_time.elapsed())

    def on_special_input(self, key, x, y):
        value = math.pi / 32 * self.delta_time.elapsed()

        if key == GLUT_KEY_UP:
            self.cube.add_rotate_x(value)
        if key == GLUT_KEY_DOWN:
            self.cube.add_rotate_x(-value)
        if key == GLUT_KEY_LEFT:
            self.cube.add_rotate_y(value)
        if key == GLUT_KEY_RIGHT:
            self.cube.add_rotate_y(-value)

    def on_update(self):
        self.delta_time.update()
        self.cube.update(self.delta_time.elapsed())
        self.check_message_queue()
        glutPostRedisplay()

    def on_display(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        self.cube.render()
        glutSwapBuffers()

        if self.settings.fps_show:
            self.fps.update()

    def create_opengl_texture(self, image_size, image_data):
        texture_id = glGenTextures(1)
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
        glBindTexture(GL_TEXTURE_2D, texture_id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)
        glTexImage2D(GL_TEXTURE_2D, 0, 3, image_size[0], image_size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, image_data)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        return texture_id

    def create_textures(self, image_files):
        for name, filename in image_files.items():
            success, image_size, image_data = LittleHelpers.load_image(filename)
            if self.verbose: print(f'Loaded image: {filename} {image_size} {success}')
            if success:
                texture_id = self.create_opengl_texture(image_size, image_data)
                self.textures[name] = texture_id
        if self.verbose:
            for name, id in self.textures.items():
                print(f'Created texture: {name} with id {id}')

    def add_moves(self, moves):
        face_rotations = LittleHelpers.translate_moves_to_face_rotations(moves)
        if face_rotations:
            self.append_face_rotations(face_rotations)
        for move in moves:
            self.all_moves.append(move)

    def append_face_rotations(self, face_rotations):
        for face_rotation in face_rotations:
            self.cube.append_face_rotation(face_rotation)

    def scramble_cube(self, moves):
        format_type = type(moves)
        if format_type == list: pass
        elif format_type == str:
            moves = moves.split(' ')
        else:
            print(f'Error in the scramble_cube function. moves format is {format_type} not list (prefered) or str.')
            return 1
        moves = LittleHelpers.expand_notations(moves)
        face_rotations = LittleHelpers.translate_moves_to_face_rotations(moves)
        self.cube.scramble(face_rotations)

    def map_cube_colors(self, color_mapping):
        if color_mapping:
            self.color_mapping = color_mapping

        default_color = Constants.FALLBACK_COLOR
        colors = self.colors
        front_color = LittleHelpers.get_mapped_color(Face.FRONT, color_mapping, colors, default_color)
        back_color = LittleHelpers.get_mapped_color(Face.BACK, color_mapping, colors, default_color)
        left_color = LittleHelpers.get_mapped_color(Face.LEFT, color_mapping, colors, default_color)
        right_color = LittleHelpers.get_mapped_color(Face.RIGHT, color_mapping, colors, default_color)
        up_color = LittleHelpers.get_mapped_color(Face.UP, color_mapping, colors, default_color)
        down_color = LittleHelpers.get_mapped_color(Face.DOWN, color_mapping, colors, default_color)

        self.cube.map_colors(front_color, back_color, left_color, right_color, up_color, down_color)

    def reset_cube_color_mapping(self):
        self.map_cube_colors(self.settings.cube_color_mapping)
        self.all_moves = []

    def update_cube_color_mapping(self):
        self.map_cube_colors(self.color_mapping)

    def reset_cube_colors(self):
        self.load_colors(self.settings.cube_color_group)

    def reset_cube(self):
        self.cube.reset()
        self.state = 'CROSS'

    def set_background_color(self, hex_color):
        color = LittleHelpers.convert_hex_color_to_floats(hex_color)
        if color:
            glClearColor(color[0], color[1], color[2], 1)

    def apply_random_pattern(self):
        pattern = LittleHelpers.get_random_pattern()
        if self.verbose: print(f'Applying random pattern: {pattern}')
        moves = LittleHelpers.expand_notations(pattern.split(' '))
        for move in moves:
            self.all_moves.append(move)
        face_rotations = LittleHelpers.translate_moves_to_face_rotations(moves)
        self.append_face_rotations(face_rotations)

    def apply_random_scramble(self):
        scramble = [random.choice(KNOWN_NOTATIONS) for i in range(40)]
        if verbose: print(f'Applying scramble: {scramble}')
        self.reset_cube()
        self.all_moves = scramble
        self.scramble_cube(scramble)

    def check_message_queue(self):
        pass

    def load_colors(self, group_name):
        colors = {}
        colors.update(self.colors)

        self.colors = {}
        group = self.color_manager.get_color_group(group_name)
        if group != None:
            self.colors.update(group)
        else:
            return

        self.colors.update(self.settings.cube_colors)
        if self.verbose:
            print(f'Color palette: {self.colors}')

        default_color = Constants.FALLBACK_COLOR
        for key, value in self.colors.items():
            self.colors[key] = LittleHelpers.convert_hex_color_to_floats(value, default_color)

        self.update_cube_color_mapping()

    def handle_command(self, command):
        if not command:
            return

        parts = command.split('=')
        cmd = parts[0].strip()
        params = ''
        if len(parts) > 1:
            params = parts[1].strip()

        handler = self.cmd_handle_map.get(cmd)
        if handler == None:
            print(f'Unknown command: {cmd}')
            return
        if verbose:
            if parms:
                print(f'Processing command: {cmd}={parms}')
            else:
                print(f'Processing command: {cmd}')
        handler(parms)

    def handle_exit_command(self, parms): sys.exit()
    def handle_reset_cube_command(self, params): self.reset_cube()
    def handle_reset_rotation_command(self, params): self.cube.reset_rotation()
    def handle_reset_scale_command(self, params): self.cube.reset_scale()
    def handle_stop_rotation_command(self, params): self.cube.stop_rotation()
    def handle_reset_color_mapping_command(self, params): self.reset_cube_color_mapping()
    def handle_reset_colors(self, params): self.reset_cube_colors()

    def handle_add_rotation_x_command(self, params):
        if params:
            value = LittleHelpers.convert_str_to_float(params)
            if value != None:
                self.cube.add_rotate_x(value * self.delta_time.elapsed())

    def handle_add_rotation_y_command(self, params):
        if params:
            value = LittleHelpers.convert_str_to_float(params)
            if value != None:
                self.cube.add_rotate_y(value * self.delta_time.elapsed())

    def handle_add_scale_command(self, params):
        if params:
            value = LittleHelpers.convert_str_to_float(params)
            if value != None:
                self.cube.add_scale(value * self.delta_time.elapsed())

    def handle_rotate_face_command(self, params):
        if params:
            moves = LittleHelpers.expand_notations(params.upper().split(' '))
            if len(moves):
                self.add_moves(moves)

    def handle_scramble_command(self, params):
        moves = params.upper()
        self.scramble_cube(moves)

    def handle_map_colors_command(self, params):
        color_mapping = LittleHelpers.make_color_mapping_from_string(params)
        self.map_cube_colors(color_mapping)

    def handle_add_padding_command(self, params):
        if params:
            value = LittleHelpers.convert_str_to_float(params)
            if value != None:
                self.cube.geometry.add_padding(value)

    def handle_set_background_color(self, params):
        if params:
            self.set_background_color(params)

    def handle_load_colors(self, params):
        if params:
            self.laod_colors(params)

    def handle_apply_random_pattern_command(self, params): self.apply_random_pattern()
    def handle_apply_random_scramble_command(self, params): self.apply_random_scramble()
Exemplo n.º 15
0
from fps import Fps
from rank import Rank
from difficulty import Difficulty
import GVar

window = Window(GVar.WIDTH, GVar.HEIGHT)
window.set_title("Space Invaders")
window.set_background_color((0, 0, 0))

keyboard = Keyboard()
menu = Menu(window)
play = Play(window, "./assets/lvl/level_1.txt")
difficulty_menu = Difficulty(window)
rank = Rank(window)
clock = Clock()
fps = Fps(window)

window.update()
while GVar.STATE != 4:
    window.set_background_color((0, 0, 0))
    if keyboard.key_pressed("esc"):
        GVar.STATE = 0
        play.__init__(window, "./assets/lvl/level_1.txt")
    if GVar.STATE == 0:
        menu.run()
    if GVar.STATE == 1:
        if GVar.DIFC_CHOSEN == True:
            play.__init__(window, "./assets/lvl/level_1.txt")
            GVar.DIFC_CHOSEN = False
        play.run()
    if GVar.STATE == 2:
Exemplo n.º 16
0
gesture_size = 10

# Making sure we don't record gestures that are too
# small.
min_gesture_size = 7

# Where the buttons are plugged into the pi.
button_1_pin = 5  # Red.
button_2_pin = 21  # Black.

# Instanciate the state object.
state_management = State(button_1_pin, button_2_pin)

# Instanciate the object controlling our desired fps.
desired_fps = 8
fps_timer = Fps(desired_fps)

# Are we recording or classifying gestures?
record_mode = False

# Classification stuff.
amount_neighbours = 1

logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
logging.basicConfig()

# Websockets
socketIO = SocketIO('http://brightsigndemo.eu-gb.mybluemix.net', 80,
                    LoggingNamespace)

# OLED screen stuff
Exemplo n.º 17
0
 def __init__(self, video_device_id=-1, use_thread=True):
     self.video_device_id = video_device_id
     self._image = None
     self.use_thread = use_thread
     self.fps = Fps()
     self.fps.start()
Exemplo n.º 18
0
class OpencvVideoSource(object):
    def __init__(self,
                 video_device_id=-1,
                 use_thread=True,
                 limit_frame_rate=False,
                 resolution=None):
        self.video_device_id = video_device_id
        self.limit_frame_rate = limit_frame_rate
        self.resolution = resolution
        self.use_thread = use_thread
        self._image = None
        self.last_image_read = True  # whether last frame has been used
        self.fps = Fps()
        self.fps.start()
        self.event = Event()

    def start_camera(self):
        start = time.time()
        self.cap = cv2.VideoCapture(self.video_device_id)
        self.cap.set(cv2.cv.CV_CAP_PROP_FPS, 20)
        print('>>> opened VideoCapture (%s) in %.3f seconds' %
              (self.video_device_id, time.time() - start))
        # subprocess.check_output(['bash', '-c', 'v4l2-ctl -c backlight_compensation=1,sharpness=130,power_line_frequency=1,white_balance_temperature_auto=1,saturation=128,contrast=128,brightness=128,focus_absolute=0,focus_auto=0'])
        self.running = True
        if self.use_thread:
            start = time.time()
            self.thread = Thread(target=thread_callback(self.grab_frames),
                                 args=())
            self.thread.daemon = True
            self.thread.start()
            print('>>> camera thread started in %.3f seconds' %
                  (time.time() - start))

        return self

    def stop_camera(self):
        self.running = False

    def grab_frames(self):
        while self.running:
            self.fps.update()
            self._image = self.grab_frame()
            self.last_image_read = False
            # time.sleep(0.02) # useful when reading video from file
            if self.limit_frame_rate:
                self.event.wait()
                self.event.clear()

    def grab_frame(self):
        ret, frame = self.cap.read()
        if self.resolution is not None and frame is not None:
            frame = cv2.resize(frame, self.resolution)
        return frame

    def get_rgb_image(self):
        if self.get_image() is None:
            return None
        return cv2.cvtColor(self.get_image(), cv2.COLOR_BGR2RGB)

    def get_rgb_bgr_image(self):
        bgr_image = self.get_image()
        if bgr_image is None:
            return (None, None)
        return (cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB), bgr_image)

    def get_bgr_image(self):
        return self.get_image()

    def get_image(self):
        if not self.use_thread:
            self._image = self.grab_frame()
            self.fps.update()
        # if self._image is None:
        #     return None
        # small = cv2.resize(self._image, (0,0), fx=0.5, fy=0.5)
        self.last_image_read = True
        if self.limit_frame_rate:
            self.event.set()  # continue grabbing next frame
        return self._image
Exemplo n.º 19
0
class GravApp(App):
    def __init__(self, *args, filename=None, **kwargs):
        self.filename = filename
        super(GravApp, self).__init__(*args, **kwargs)

        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down,
                            on_key_up=self._on_keyboard_up)
        self._keyboard_modifiers = []

        # work aroung bug [1]
        self.y = 0
        '''
                                   'mass={mass} '
                                   'pos={pos} '
                                   'vel={vel} '
                                   'acc={acc} '
        '''
        self.printer = LinePrinter(
            '[{level:<7}] '
            '[{sublevel:<12}] '
            '[{fps:>5.2f} fps] '
            '[{speed:>4.1f}x speed] '
            'npoints=[{points}]'
            '{debug}'
            '{key_form}',
            level='INFO',
            sublevel='Log',
            fps=1.,
            speed=1.,
            mass=0.,
            pos=0.,
            vel=0.,
            acc=0.,
            points=0,
            debug='',
            key='',
            key_form='',
            key_form_default=' key=[{key}]')

        self.last_rot = 0., (0., 0., 1.), (0., 1., 0.), Window.center

        self.nparray2string = partial(
            array2string,
            separator=',',
            formatter={'float_kind': lambda x: f"{x:6.2f}"})

    # work aroung bug [1] https://github.com/kivy/kivy/issues/5359
    def to_window(self, x, y, initial=True, relative=False):
        return x, y

    def build(self, *args, **kwargs):
        self.draw_fps = True
        self.fps = Fps()

        self.time = 0.
        self.last_time = 0.
        self.time_mult = 1.
        self.time_mult_pause = None

        Clock.schedule_interval(self.update, 0)
        self.event_once = None

        self.root = Space()

        Config.read('config.ini')

        # For my window header
        # dx, dy = -1, -32
        dx, dy = 0, 0

        if Config.get('graphics', 'position') != 'auto':
            Window.left, Window.top, Window.size = Config.getint('graphics', 'left') + dx, \
                                                   Config.getint('graphics', 'top') + dy, \
                                                   (Config.getint('graphics', 'width'), \
                                                    Config.getint('graphics', 'height'),)
        if Config.getboolean('graphics', 'maximize'):
            Window.maximize()

        Window.show()

        self.root.bind(on_touch_down=self.on_touch_down,
                       on_touch_move=self.on_touch_move,
                       on_touch_up=self.on_touch_up)

        if self.filename:
            Clock.schedule_once(
                partial(
                    import_module(self.filename).set_state, self.root, self),
                1)

        return self.root

    def update(self, dt):
        # print(f'left={Window.left}, top={Window.top}, width={Window.width}, height={Window.height}')
        # print(self._keyboard_modifiers)
        # self.dt = dt
        self.time += dt * self.time_mult

        if abs(self.time - self.last_time) >= abs(self.time_mult):
            self.last_time = self.time
            mass, pos, vel, acc = self.root.sum_attrib()
            self.printer.print(fps=Clock.get_fps(),
                               mass=mass,
                               pos=self.nparray2string(pos),
                               vel=self.nparray2string(vel),
                               acc=self.nparray2string(acc),
                               points=len(self.root.objects))

        _, pos, _, _ = self.root.sum_attrib()
        # self.root.rotate(-pi/180., (0., 1., 0), (0., 0., 1.))
        # self.root.rotate(dt * self.time_mult * -ANGLE, (1., 0., 0), (0., 0., 1.), pos)

        self.root.update(dt * self.time_mult, self.time)

        if self.draw_fps:
            self.fps.update(dt)
            self.fps.draw(self.root)

    def on_touch_down(self, entity, touch):
        if 'shift' in self._keyboard_modifiers:
            self.last_rot = 0., (0., 0., 1.), (0., 1., 0.), Window.center
            return True
        return False

    def on_touch_move(self, entity, touch):
        if 'shift' in self._keyboard_modifiers:
            if 'pos' in touch.profile:
                # print()
                # print(f'dpos={touch.dpos}')
                dpos = tuple(
                    map(lambda x: x[1] - x[0], zip(touch.opos, touch.pos)))
                length = sum(map(lambda x: x**2, dpos))**.5
                if length == 0:
                    return True
                ndpos = tuple(map(lambda x: x / length + 0.01,
                                  dpos))  # (dx, dy)
                # Rotation -pi/2
                '''
                rot = ((0., -1.),   
                       (1.,  0.),)
                # ((0., dx), (-1., dy))
                x = ((0., -1.), (dx, dy))
                y = (0., dx)
                # (((0., -1.), (dx, dy)), ((1., 0.), (dx, dy)))
                # (((0.0, 0.0), (-1.0, 1.0)), ((1.0, 0.0), (0.0, 1.0)))

                # print(f'ndpos={tuple(ndpos)}')
                xx = tuple(zip(rot, ((ndpos,)*2)))
                # print(f'xx={xx}')
                yy = tuple(map(lambda x: tuple(zip(*x)), xx))
                # print(f'yy={yy}')
                axis = tuple(map(lambda y: sum(map(lambda z: z[0]*z[1], y)), yy))

                # _, pos, _, _ = self.root.sum_attrib()
                '''
                last_rot = (-self.last_rot[0], ) + self.last_rot[1:]
                # print(f'last_rot={last_rot}')
                # print(f'self.last_rot={self.last_rot}')
                self.root.rotate(*last_rot)
                self.last_rot = (ANGLE / 40. * length * ndpos[1] /
                                 abs(ndpos[1]), (0., 0.,
                                                 1.), ndpos, Window.center)
                self.root.rotate(*self.last_rot)
                with self.root.canvas:
                    Color(1, 1, 1, .3)
                    Line(points=[
                        touch.opos[0], touch.opos[1], touch.pos[0],
                        touch.pos[1]
                    ],
                         width=2)
            return True
        return False

    def on_touch_up(self, entity, touch):
        if 'shift' in self._keyboard_modifiers:
            self.last_rot = 0., (0., 0., 1.), (0., 1., 0.), Window.center
            return True
        return False

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_up(self, keyboard, keycode):
        '''
        self.event_once.get_callback()()
        self.event_once.cancel()
        '''

        if keycode[1] in self._keyboard_modifiers:
            self._keyboard_modifiers.remove(keycode[1])
            if self.event_once and self.event_once.is_triggered:
                self.event_once.get_callback()()
                self.event_once.cancel()

        if self._keyboard_modifiers:
            self.event_once = Clock.create_trigger(
                lambda *args: self.printer.print(
                    key_form=self.printer.data['key_form_default'],
                    key='+'.join(self._keyboard_modifiers).upper()), 1)
            '''
            self.printer.print(key_form=self.printer.data['key_form_default'],
                               key='+'.join(self._keyboard_modifiers).upper())
            '''
        else:
            self.event_once = Clock.create_trigger(
                lambda *args: self.printer.print(key_form=''), 1)
        self.event_once()
        return self.root._on_keyboard_up(keyboard, keycode)

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        '''
        print(keycode)
        print(text)
        print(modifiers)
        '''

        if self.event_once and self.event_once.is_triggered:
            # self.event_once.get_callback()()
            self.event_once.cancel()

        # format_string = self.printer.format_string
        # data = self.printer.data
        def to_prev(*args, **kwargs):
            '''
            print(f'callback for {modifiers}')
            '''
            #self.printer.format_string = str(format_string)
            #self.printer.data = dict(data)
            '''
            if self._keyboard_modifiers and not kwargs.get('recur'):
                # print(self._keyboard_modifiers)
                self.event_once = Clock.create_trigger(partial(to_prev, recur=True), 1)
                self.printer.print(format_string + ' key=[{key}]',
                                   key='+'.join(self._keyboard_modifiers).upper())
                self.event_once()
            else:
                self.printer.print()
            '''
            self.printer.print(key_form='')

        # self.event_once = Clock.create_trigger(to_prev, 1)
        self.event_once = Clock.create_trigger(
            lambda *args: self.printer.print(key_form=''), 1)
        if keycode[1] not in modifiers:
            self.event_once()
        text = modifiers + ([
            keycode[1],
        ] if keycode[1] not in modifiers else [])
        self.printer.print(key='+'.join(text).upper(),
                           key_form=self.printer.data['key_form_default'])

        self._keyboard_modifiers = modifiers

        if 'shift' in modifiers:
            # Rotate
            if 'left' == keycode[1] or 276 == keycode[0]:
                _, pos, _, _ = self.root.sum_attrib()
                self.root.rotate(-ANGLE, (1., 0., 0), (0., 0., 1.), pos)
            if 'right' == keycode[1] or 275 == keycode[0]:
                _, pos, _, _ = self.root.sum_attrib()
                self.root.rotate(ANGLE, (1., 0., 0), (0., 0., 1.), pos)
            if 'down' == keycode[1] or 274 == keycode[0]:
                _, pos, _, _ = self.root.sum_attrib()
                self.root.rotate(ANGLE, (0., 1., 0), (0., 0., 1.), pos)
            if 'up' == keycode[1] or 273 == keycode[0]:
                _, pos, _, _ = self.root.sum_attrib()
                self.root.rotate(-ANGLE, (0., 1., 0), (0., 0., 1.), pos)
        elif not modifiers:

            # Debug
            if 'd' == keycode[1] or 100 == keycode[0]:
                self.root.show_acc = not self.root.show_acc
                self.root.show_vel = not self.root.show_vel
                sublevels = ('Log', 'Debug')
                debug_format = ' mass={mass} pos={pos} vel={vel} acc={acc}'
                self.printer.print(
                    sublevel=sublevels[self.root.show_acc],
                    debug=debug_format if self.root.show_acc else '')

            # Exit
            if 'escape' == keycode[1] or 27 == keycode[0] or \
                    'q' == keycode[1] or 113 == keycode[0]:
                del self.printer

                Config.set('graphics', 'position', 'custom')
                Config.set('graphics', 'width', Window.width)
                Config.set('graphics', 'height', Window.height)
                Config.set('graphics', 'left', Window.left)
                Config.set('graphics', 'top', Window.top)
                Config.write()

                App.get_running_app().stop()

            # Speed
            if 'left' == keycode[1] or 276 == keycode[0]:
                self.time_mult -= 0.1
                self.printer.print(speed=self.time_mult)
                if self.time_mult_pause:
                    self.time_mult_pause = None
            if 'right' == keycode[1] or 275 == keycode[0]:
                self.time_mult += 0.1
                self.printer.print(speed=self.time_mult)
                if self.time_mult_pause:
                    self.time_mult_pause = None
            if 'spacebar' == keycode[1] or 32 == keycode[0]:
                if self.time_mult_pause:
                    self.time_mult, self.time_mult_pause = self.time_mult_pause, None
                else:
                    self.time_mult, self.time_mult_pause = 0., self.time_mult

            # Speed and Position to zero
            if 'down' == keycode[1] or 274 == keycode[0]:
                self.root.set_vel([0.])
                _, _, vel, _ = self.root.sum_attrib()
                self.printer.print(vel=self.nparray2string(vel))
            if 'up' == keycode[1] or 273 == keycode[0]:
                self.root.set_pos(Window.center)
                _, pos, _, _ = self.root.sum_attrib()
                self.printer.print(vel=self.nparray2string(pos))

        return self.root._on_keyboard_down(keyboard, keycode, text, modifiers)
Exemplo n.º 20
0
    def __init__(self, window, game_mode, game_options):
        """
        Game constructor.
        """
        self.window = window
        self.window_rect = window.get_rect()

        self.game_options = game_options

        #Creating a bacground of game
        self.background = pg.Surface(self.window.get_size()).convert()
        self.background.fill((0, 0, 0))
        bg_strip = pg.Surface([
            self.window.get_width() * 1 / 128,
            self.window.get_height() * 1 / 40
        ]).convert()
        bg_strip.fill((200, 200, 200))
        strip_pos = bg_strip.get_rect(center=(self.window.get_width() / 2,
                                              self.window.get_height() * 1 /
                                              40))
        strip_distance = self.window.get_height() * 1 / 40

        for i in range(0, 20):
            self.background.blit(bg_strip,
                                 (strip_pos[0], strip_pos[1] + i *
                                  (strip_distance + bg_strip.get_height())))

        self.window.blit(self.background, (0, 0))
        pg.display.flip()

        if pg.font:
            # self.text_menu, self.text_menu_pos = make_text( text= "game_section", font_name= 'casio-fx-702p\casio-fx-702p.ttf'\
            #                                             , size= 70, pos= (self.window.get_width()/2, self.window.get_height() * 3/20)\
            #                                             , text_color= (200, 200, 200), text_background_color= (0, 0, 0))
            self.text_pause, self.text_pause_pos = make_text( text= "PAUSE", font_name= 'casio-fx-702p\casio-fx-702p.ttf'\
                                                        , size= 80, pos= (self.window.get_width()/2, self.window.get_height() * 1/2)\
                                                        , text_color= (200, 200, 200), text_background_color= (0, 0, 0))

        # Initialize Game Groups
        self.all_paddles = pg.sprite.Group()
        self.p_paddles = pg.sprite.Group()
        self.e_paddles = pg.sprite.Group()
        self.balls = pg.sprite.Group()
        self.fps_group = pg.sprite.Group()
        self.score = pg.sprite.Group()
        self.all = pg.sprite.RenderUpdates()

        # assign default groups to each sprite class
        Player_paddle.containers = self.all_paddles, self.p_paddles, self.all
        Environment_paddle.containers = self.all_paddles, self.e_paddles, self.all
        Ball.containers = self.balls, self.all
        Fps.containers = self.fps_group
        Score.containers = self.score, self.all

        #region initiate balls
        number_of_balls = 1
        for i in range(0, number_of_balls):
            Ball( start_pos = (self.window.get_width()/2, self.window.get_height() * 1/3 + i * self.window.get_height() * 1/40),\
                 x_start_speed = self.game_options[0], y_start_speed = self.game_options[0] if i%2 == 0 else  -10   )
        #endregion

        #region save game mode
        self.game_mode = game_mode
        #endregion

        #region initiate players
        number_of_players = 2

        if number_of_players >= 1:
            Player_paddle( pos= ( self.window.get_width() * 1/30, self.window.get_height()/2 ), score = Score( (self.window_rect.right * 1/3, self.window_rect.bottom * 1/10) )\
                                , move_up_button= self.game_options[3], move_down_button= self.game_options[4], speed= 2* self.game_options[1])
        if number_of_players >= 2:
            if self.game_mode == "pvp":
                Player_paddle( pos= ( self.window.get_width() * 29/30, self.window.get_height()/2 ), score = Score( (self.window_rect.right * 2/3, self.window_rect.bottom * 1/10) )\
                                , move_up_button= self.game_options[5], move_down_button= self.game_options[6], speed= 2* self.game_options[1])
            elif self.game_mode == "pve":
                if self.game_options[2] == 'easy':
                    Environment_paddle( pos= ( self.window.get_width() * 29/30, self.window.get_height()/2 ), \
                                        score = Score( (self.window_rect.right * 2/3, self.window_rect.bottom * 1/10) ), speed= 2* self.game_options[1])
                elif self.game_options[2] == 'hard':
                    Environment_paddle( pos= ( self.window.get_width() * 29/30, self.window.get_height()/2 ), \
                                        score = Score( (self.window_rect.right * 2/3, self.window_rect.bottom * 1/10) ), speed= round(2.5* self.game_options[1]))
        #future plan, never realized
        # if number_of_players >= 3:
        #     Player_paddle( pos= ( self.window.get_width() * 22/30, self.window.get_height()/2 ), move_up_button= 119, move_down_button= 115, score = Score( (self.window_rect.x * 1/3, self.window_rect.y * 5/10)), mode = "player" )
        # if number_of_players >= 4:
        #     Player_paddle( pos= ( self.window.get_width() * 1/30, self.window.get_height()/2 ), move_up_button= 273, move_down_button= 274, score = Score( (self.window_rect.x * 1/3, self.window_rect.y * 8/10) ), mode = "player" )
        #endregion

        #initiate fps
        self.fps = Fps()

        #set mouse invisible
        pg.mouse.set_visible(0)
        #initiate time in game
        self.clock = pg.time.Clock()
Exemplo n.º 21
0
class Game(object):
    def __init__(self, window, game_mode, game_options):
        """
        Game constructor.
        """
        self.window = window
        self.window_rect = window.get_rect()

        self.game_options = game_options

        #Creating a bacground of game
        self.background = pg.Surface(self.window.get_size()).convert()
        self.background.fill((0, 0, 0))
        bg_strip = pg.Surface([
            self.window.get_width() * 1 / 128,
            self.window.get_height() * 1 / 40
        ]).convert()
        bg_strip.fill((200, 200, 200))
        strip_pos = bg_strip.get_rect(center=(self.window.get_width() / 2,
                                              self.window.get_height() * 1 /
                                              40))
        strip_distance = self.window.get_height() * 1 / 40

        for i in range(0, 20):
            self.background.blit(bg_strip,
                                 (strip_pos[0], strip_pos[1] + i *
                                  (strip_distance + bg_strip.get_height())))

        self.window.blit(self.background, (0, 0))
        pg.display.flip()

        if pg.font:
            # self.text_menu, self.text_menu_pos = make_text( text= "game_section", font_name= 'casio-fx-702p\casio-fx-702p.ttf'\
            #                                             , size= 70, pos= (self.window.get_width()/2, self.window.get_height() * 3/20)\
            #                                             , text_color= (200, 200, 200), text_background_color= (0, 0, 0))
            self.text_pause, self.text_pause_pos = make_text( text= "PAUSE", font_name= 'casio-fx-702p\casio-fx-702p.ttf'\
                                                        , size= 80, pos= (self.window.get_width()/2, self.window.get_height() * 1/2)\
                                                        , text_color= (200, 200, 200), text_background_color= (0, 0, 0))

        # Initialize Game Groups
        self.all_paddles = pg.sprite.Group()
        self.p_paddles = pg.sprite.Group()
        self.e_paddles = pg.sprite.Group()
        self.balls = pg.sprite.Group()
        self.fps_group = pg.sprite.Group()
        self.score = pg.sprite.Group()
        self.all = pg.sprite.RenderUpdates()

        # assign default groups to each sprite class
        Player_paddle.containers = self.all_paddles, self.p_paddles, self.all
        Environment_paddle.containers = self.all_paddles, self.e_paddles, self.all
        Ball.containers = self.balls, self.all
        Fps.containers = self.fps_group
        Score.containers = self.score, self.all

        #region initiate balls
        number_of_balls = 1
        for i in range(0, number_of_balls):
            Ball( start_pos = (self.window.get_width()/2, self.window.get_height() * 1/3 + i * self.window.get_height() * 1/40),\
                 x_start_speed = self.game_options[0], y_start_speed = self.game_options[0] if i%2 == 0 else  -10   )
        #endregion

        #region save game mode
        self.game_mode = game_mode
        #endregion

        #region initiate players
        number_of_players = 2

        if number_of_players >= 1:
            Player_paddle( pos= ( self.window.get_width() * 1/30, self.window.get_height()/2 ), score = Score( (self.window_rect.right * 1/3, self.window_rect.bottom * 1/10) )\
                                , move_up_button= self.game_options[3], move_down_button= self.game_options[4], speed= 2* self.game_options[1])
        if number_of_players >= 2:
            if self.game_mode == "pvp":
                Player_paddle( pos= ( self.window.get_width() * 29/30, self.window.get_height()/2 ), score = Score( (self.window_rect.right * 2/3, self.window_rect.bottom * 1/10) )\
                                , move_up_button= self.game_options[5], move_down_button= self.game_options[6], speed= 2* self.game_options[1])
            elif self.game_mode == "pve":
                if self.game_options[2] == 'easy':
                    Environment_paddle( pos= ( self.window.get_width() * 29/30, self.window.get_height()/2 ), \
                                        score = Score( (self.window_rect.right * 2/3, self.window_rect.bottom * 1/10) ), speed= 2* self.game_options[1])
                elif self.game_options[2] == 'hard':
                    Environment_paddle( pos= ( self.window.get_width() * 29/30, self.window.get_height()/2 ), \
                                        score = Score( (self.window_rect.right * 2/3, self.window_rect.bottom * 1/10) ), speed= round(2.5* self.game_options[1]))
        #future plan, never realized
        # if number_of_players >= 3:
        #     Player_paddle( pos= ( self.window.get_width() * 22/30, self.window.get_height()/2 ), move_up_button= 119, move_down_button= 115, score = Score( (self.window_rect.x * 1/3, self.window_rect.y * 5/10)), mode = "player" )
        # if number_of_players >= 4:
        #     Player_paddle( pos= ( self.window.get_width() * 1/30, self.window.get_height()/2 ), move_up_button= 273, move_down_button= 274, score = Score( (self.window_rect.x * 1/3, self.window_rect.y * 8/10) ), mode = "player" )
        #endregion

        #initiate fps
        self.fps = Fps()

        #set mouse invisible
        pg.mouse.set_visible(0)
        #initiate time in game
        self.clock = pg.time.Clock()

    def run(self):
        """
        Game loop
        """

        while not self.handle_events():

            self.all.clear(self.window, self.background)
            for i in range(0, 2):
                self.all.update()
                for ball in self.balls:
                    ball.paddle_collide(self.all_paddles)

            for paddle in self.e_paddles:
                paddle.move(self.balls)
            # for ball in self.balls:
            #     ball.paddle_collide( self.all_paddles )

            self.fps.current_fps(self.clock)

            dirty = self.all.draw(self.window)

            pg.display.update(dirty)

            self.clock.tick(50)

    def handle_events(self):
        """
        Handling system events

        :return True if pygame reported a quit event
        """
        for event in pg.event.get():
            if event.type == pg.locals.QUIT:
                pg.quit()
                sys.exit()
                if self.game_mode == "pve":
                    save_result(
                        self.p_paddles.sprites()[0].score.current_score -
                        self.e_paddles.sprites()[0].score.current_score)
                return True
            if event.type == KEYDOWN and event.key == K_ESCAPE:
                pg.mouse.set_visible(1)
                if self.game_mode == "pve":
                    save_result(
                        self.p_paddles.sprites()[0].score.current_score -
                        self.e_paddles.sprites()[0].score.current_score)
                return True
            if event.type == KEYDOWN and event.key == self.game_options[8]:
                self.fps.reverse_visibility(self.all)
            if event.type == KEYDOWN and event.key == self.game_options[7]:
                self.pause()

        pressed = pg.key.get_pressed()

        for player in self.p_paddles:
            player.move(pressed)

    def pause(self):
        self.window.blit(self.text_pause, self.text_pause_pos)
        pg.display.update()
        pause_mode = True
        while pause_mode:
            for event in pg.event.get():
                if event.type == KEYDOWN and event.key == self.game_options[7]:
                    pause_mode = False
        self.window.blit(self.background, (0, 0))
        pg.display.update()
Exemplo n.º 22
0
 def build(self):
     Clock.schedule_interval(self.update, 0)
     self.root = Space()
     self.fps = Fps()
     return self.root
Exemplo n.º 23
0
messenger = MqttMessenger(host=mqtt_host,
                          port=mqtt_port,
                          client_id=mqtt_client_id,
                          username=mqtt_username,
                          password=mqtt_password,
                          topic=mqtt_topic,
                          source_name=source_name)
tracker = Tracker(
    messenger,
    MIN_NUMBER_OF_OCCURENCES=TRACKER_MIN_NUMBER_OF_OCCURENCES,
    MAX_NUMBER_OF_FRAMES_TO_PROCESS=TRACKER_MAX_NUMBER_OF_FRAMES_TO_PROCESS,
    MIN_NUMBER_OF_MISSES=TRACKER_MIN_NUMBER_OF_MISSES,
    enable_events=enable_events)
updater = DataUpdater(dataset, messenger,
                      lambda: camera.get_rgb_bgr_image()[0])
fps = Fps()
if enable_display:
    display = DisplayWindow()

fps.start()
updater.listen()

not_ready_printed = False
frame_number = 0

while True:
    # while fps.elapsed()<15:
    frame_number = frame_number + 1
    (img, bgr_image) = camera.get_rgb_bgr_image()
    if img is None:
        if not not_ready_printed: