Python pygame.HWSURFACE Examples

The following are 30 code examples of pygame.HWSURFACE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source File: carla_env.py    From gym-carla with MIT License 6 votes vote down vote up
def _init_renderer(self):
    """Initialize the birdeye view renderer.
    """
    pygame.init()
    self.display = pygame.display.set_mode(
    (self.display_size * 3, self.display_size),
    pygame.HWSURFACE | pygame.DOUBLEBUF)

    pixels_per_meter = self.display_size / self.obs_range
    pixels_ahead_vehicle = (self.obs_range/2 - self.d_behind) * pixels_per_meter
    birdeye_params = {
      'screen_size': [self.display_size, self.display_size],
      'pixels_per_meter': pixels_per_meter,
      'pixels_ahead_vehicle': pixels_ahead_vehicle
    }
    self.birdeye_render = BirdeyeRender(self.world, birdeye_params) 
Example #2
Source File: display_test.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def todo_test_flip(self):

        # __doc__ (as of 2008-08-02) for pygame.display.flip:

          # pygame.display.flip(): return None
          # update the full display Surface to the screen
          #
          # This will update the contents of the entire display. If your display
          # mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this
          # will wait for a vertical retrace and swap the surfaces. If you are
          # using a different type of display mode, it will simply update the
          # entire contents of the surface.
          #
          # When using an pygame.OPENGL display mode this will perform a gl buffer swap.

        self.fail() 
Example #3
Source File: run_hearing_snake.py    From project-keyword-spotter with Apache License 2.0 6 votes vote down vote up
def on_init(self):
    pygame.init()

    self._display_surf = pygame.display.set_mode(
        (self.window_width, self.window_height), pygame.HWSURFACE)
    pygame.display.set_caption('The Hearing Snake')

    self.game = Game(self.window_width, self.window_height)

    img = pygame.image.load('pygame_images/bg.jpg')
    img = pygame.transform.scale(img, (self.window_width, self.window_height))
    self._bg_image = img.convert()
    self.on_load_metadata()

    self._running = True
    return True 
Example #4
Source File: display_test.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def todo_test_flip(self):

        # __doc__ (as of 2008-08-02) for pygame.display.flip:

          # pygame.display.flip(): return None
          # update the full display Surface to the screen
          #
          # This will update the contents of the entire display. If your display
          # mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this
          # will wait for a vertical retrace and swap the surfaces. If you are
          # using a different type of display mode, it will simply update the
          # entire contents of the surface.
          #
          # When using an pygame.OPENGL display mode this will perform a gl buffer swap.

        self.fail() 
Example #5
Source File: display_test.py    From fxxkpython with GNU General Public License v3.0 6 votes vote down vote up
def todo_test_flip(self):

        # __doc__ (as of 2008-08-02) for pygame.display.flip:

          # pygame.display.flip(): return None
          # update the full display Surface to the screen
          #
          # This will update the contents of the entire display. If your display
          # mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this
          # will wait for a vertical retrace and swap the surfaces. If you are
          # using a different type of display mode, it will simply update the
          # entire contents of the surface.
          #
          # When using an pygame.OPENGL display mode this will perform a gl buffer swap.

        self.fail() 
Example #6
Source File: PyKinectBodyGame.py    From PyKinect2 with MIT License 5 votes vote down vote up
def __init__(self):
        pygame.init()

        # Used to manage how fast the screen updates
        self._clock = pygame.time.Clock()

        # Set the width and height of the screen [width, height]
        self._infoObject = pygame.display.Info()
        self._screen = pygame.display.set_mode((self._infoObject.current_w >> 1, self._infoObject.current_h >> 1), 
                                               pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)

        pygame.display.set_caption("Kinect for Windows v2 Body Game")

        # Loop until the user clicks the close button.
        self._done = False

        # Used to manage how fast the screen updates
        self._clock = pygame.time.Clock()

        # Kinect runtime object, we want only color and body frames 
        self._kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Color | PyKinectV2.FrameSourceTypes_Body)

        # back buffer surface for getting Kinect color frames, 32bit color, width and height equal to the Kinect color frame size
        self._frame_surface = pygame.Surface((self._kinect.color_frame_desc.Width, self._kinect.color_frame_desc.Height), 0, 32)

        # here we will store skeleton data 
        self._bodies = None 
Example #7
Source File: PyKinectInfraRed.py    From PyKinect2 with MIT License 5 votes vote down vote up
def run(self):
        # -------- Main Program Loop -----------
        while not self._done:
            # --- Main event loop
            for event in pygame.event.get(): # User did something
                if event.type == pygame.QUIT: # If user clicked close
                    self._done = True # Flag that we are done so we exit this loop

                elif event.type == pygame.VIDEORESIZE: # window resized
                    self._screen = pygame.display.set_mode(event.dict['size'], 
                                                pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)
                    

            # --- Getting frames and drawing  
            if self._kinect.has_new_infrared_frame():
                frame = self._kinect.get_last_infrared_frame()
                self.draw_infrared_frame(frame, self._frame_surface)
                frame = None

            self._screen.blit(self._frame_surface, (0,0))
            pygame.display.update()

            # --- Go ahead and update the screen with what we've drawn.
            pygame.display.flip()

            # --- Limit to 60 frames per second
            self._clock.tick(60)

        # Close our Kinect sensor, close the window and quit.
        self._kinect.close()
        pygame.quit() 
Example #8
Source File: carla_manual_control.py    From ros-bridge with MIT License 5 votes vote down vote up
def main():
    """
    main function
    """
    rospy.init_node('carla_manual_control', anonymous=True)

    role_name = rospy.get_param("~role_name", "ego_vehicle")

    # resolution should be similar to spawned camera with role-name 'view'
    resolution = {"width": 800, "height": 600}

    pygame.init()
    pygame.font.init()
    pygame.display.set_caption("CARLA ROS manual control")
    world = None
    try:
        display = pygame.display.set_mode(
            (resolution['width'], resolution['height']),
            pygame.HWSURFACE | pygame.DOUBLEBUF)

        hud = HUD(role_name, resolution['width'], resolution['height'])
        world = World(role_name, hud)
        controller = KeyboardControl(role_name, hud)

        clock = pygame.time.Clock()

        while not rospy.core.is_shutdown():
            clock.tick_busy_loop(60)
            if controller.parse_events(clock):
                return
            hud.tick(clock)
            world.render(display)
            pygame.display.flip()

    finally:
        if world is not None:
            world.destroy()
        pygame.quit() 
Example #9
Source File: war.py    From gamedev with MIT License 5 votes vote down vote up
def __init__(self):
        pygame.init()
        # pygame.mixer.init()
        flags = pygame.DOUBLEBUF | pygame.HWSURFACE  # | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT), flags)
        pygame.display.set_caption(TITLE)
        self.clock = pygame.time.Clock()
        self.OFFSET = OFFSET
        self.load_data() 
Example #10
Source File: part_test2.py    From gamedev with MIT License 5 votes vote down vote up
def __init__(self):
        pygame.init()
        flags = pygame.DOUBLEBUF  # | pygame.HWSURFACE | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT), flags)
        self.clock = pygame.time.Clock()
        self.new() 
Example #11
Source File: part_test_ship.py    From gamedev with MIT License 5 votes vote down vote up
def __init__(self):
        pygame.init()
        flags = pygame.DOUBLEBUF  # | pygame.HWSURFACE | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT), flags)
        self.clock = pygame.time.Clock()
        self.new() 
Example #12
Source File: dash.py    From gamedev with MIT License 5 votes vote down vote up
def __init__(self):
        # initialize game settings
        # os.environ['SDL_VIDEO_CENTERED'] = '1'
        # os.environ['SDL_VIDEO_WINDOW_POS'] = '0,0'
        pygame.init()
        # pygame.mixer.init()
        flags = pygame.DOUBLEBUF | pygame.HWSURFACE  # | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT), flags)
        pygame.display.set_caption("My Game")
        self.clock = pygame.time.Clock()
        self.load_data()
        font = pygame.font.match_font("Ubuntu Mono")
        self.menu = GameMenu(self, "Dash!", ["Play", "Options", "Quit"], font=font, font_size=30,
                             padding=20) 
Example #13
Source File: map_test.py    From gamedev with MIT License 5 votes vote down vote up
def __init__(self):
        pygame.init()
        os.environ['SDL_VIDEODRIVER'] = 'fbcon'
        flags = pygame.DOUBLEBUF | pygame.HWSURFACE  # | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT), flags)
        self.screen_rect = self.screen.get_rect()
        pygame.display.set_caption("Map Test")
        self.clock = pygame.time.Clock()
        self.load_data() 
Example #14
Source File: freetype_test.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def test_freetype_Font_render_mono(self):
        font = self._TEST_FONTS['sans']
        color = pygame.Color('black')
        colorkey = pygame.Color('white')
        text = "."

        save_antialiased = font.antialiased
        font.antialiased = False
        try:
            surf, r = font.render(text, color, size=24)
            self.assertEqual(surf.get_bitsize(), 8)
            flags = surf.get_flags()
            self.assertTrue(flags & pygame.SRCCOLORKEY)
            self.assertFalse(flags & (pygame.SRCALPHA | pygame.HWSURFACE))
            self.assertEqual(surf.get_colorkey(), colorkey)
            self.assertIsNone(surf.get_alpha())

            translucent_color = pygame.Color(*color)
            translucent_color.a = 55
            surf, r = font.render(text, translucent_color, size=24)
            self.assertEqual(surf.get_bitsize(), 8)
            flags = surf.get_flags()
            self.assertTrue(flags & (pygame.SRCCOLORKEY | pygame.SRCALPHA))
            self.assertFalse(flags & pygame.HWSURFACE)
            self.assertEqual(surf.get_colorkey(), colorkey)
            self.assertEqual(surf.get_alpha(), translucent_color.a)

            surf, r = font.render(text, color, colorkey, size=24)
            self.assertEqual(surf.get_bitsize(), 32)
        finally:
            font.antialiased = save_antialiased 
Example #15
Source File: freetype_test.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def test_freetype_Font_render_mono(self):
        font = self._TEST_FONTS['sans']
        color = pygame.Color('black')
        colorkey = pygame.Color('white')
        text = "."

        save_antialiased = font.antialiased
        font.antialiased = False
        try:
            surf, r = font.render(text, color, size=24)
            self.assertEqual(surf.get_bitsize(), 8)
            flags = surf.get_flags()
            self.assertTrue(flags & pygame.SRCCOLORKEY)
            self.assertFalse(flags & (pygame.SRCALPHA | pygame.HWSURFACE))
            self.assertEqual(surf.get_colorkey(), colorkey)
            self.assertIsNone(surf.get_alpha())

            translucent_color = pygame.Color(*color)
            translucent_color.a = 55
            surf, r = font.render(text, translucent_color, size=24)
            self.assertEqual(surf.get_bitsize(), 8)
            flags = surf.get_flags()
            self.assertTrue(flags & (pygame.SRCCOLORKEY | pygame.SRCALPHA))
            self.assertFalse(flags & pygame.HWSURFACE)
            self.assertEqual(surf.get_colorkey(), colorkey)
            self.assertEqual(surf.get_alpha(), translucent_color.a)

            surf, r = font.render(text, color, colorkey, size=24)
            self.assertEqual(surf.get_bitsize(), 32)
        finally:
            font.antialiased = save_antialiased 
Example #16
Source File: display_test.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def todo_test_flip(self):

        # __doc__ (as of 2008-08-02) for pygame.display.flip:

          # pygame.display.flip(): return None
          # update the full display Surface to the screen
          #
          # This will update the contents of the entire display. If your display
          # mode is using the flags pygame.HWSURFACE and pygame.DOUBLEBUF, this
          # will wait for a vertical retrace and swap the surfaces. If you are
          # using a different type of display mode, it will simply update the
          # entire contents of the surface.
          #
          # When using an pygame.OPENGL display mode this will perform a gl buffer swap.

        self.fail() 
Example #17
Source File: freetype_test.py    From fxxkpython with GNU General Public License v3.0 5 votes vote down vote up
def test_freetype_Font_render_mono(self):
        font = self._TEST_FONTS['sans']
        color = pygame.Color('black')
        colorkey = pygame.Color('white')
        text = "."

        save_antialiased = font.antialiased
        font.antialiased = False
        try:
            surf, r = font.render(text, color, size=24)
            self.assertEqual(surf.get_bitsize(), 8)
            flags = surf.get_flags()
            self.assertTrue(flags & pygame.SRCCOLORKEY)
            self.assertFalse(flags & (pygame.SRCALPHA | pygame.HWSURFACE))
            self.assertEqual(surf.get_colorkey(), colorkey)
            self.assertIsNone(surf.get_alpha())

            translucent_color = pygame.Color(*color)
            translucent_color.a = 55
            surf, r = font.render(text, translucent_color, size=24)
            self.assertEqual(surf.get_bitsize(), 8)
            flags = surf.get_flags()
            self.assertTrue(flags & (pygame.SRCCOLORKEY | pygame.SRCALPHA))
            self.assertFalse(flags & pygame.HWSURFACE)
            self.assertEqual(surf.get_colorkey(), colorkey)
            self.assertEqual(surf.get_alpha(), translucent_color.a)

            surf, r = font.render(text, color, colorkey, size=24)
            self.assertEqual(surf.get_bitsize(), 32)
        finally:
            font.antialiased = save_antialiased 
Example #18
Source File: no_rendering_mode.py    From scenario_runner with MIT License 5 votes vote down vote up
def game_loop(args):
    try:
        # Init Pygame
        pygame.init()
        display = pygame.display.set_mode(
            (args.width, args.height),
            pygame.HWSURFACE | pygame.DOUBLEBUF)
        pygame.display.set_caption(args.description)

        font = pygame.font.Font(pygame.font.get_default_font(), 20)
        text_surface = font.render('Rendering map...', True, COLOR_WHITE)
        display.blit(text_surface, text_surface.get_rect(center=(args.width / 2, args.height / 2)))
        pygame.display.flip()

        # Init modules
        input_module = ModuleInput(MODULE_INPUT)
        hud_module = ModuleHUD(MODULE_HUD, args.width, args.height)
        world_module = ModuleWorld(MODULE_WORLD, args, timeout=2.0)

        # Register Modules
        module_manager.register_module(world_module)
        module_manager.register_module(hud_module)
        module_manager.register_module(input_module)

        module_manager.start_modules()

        clock = pygame.time.Clock()
        while True:
            clock.tick_busy_loop(60)

            module_manager.tick(clock)
            module_manager.render(display)

            pygame.display.flip()

    except KeyboardInterrupt:
        print('\nCancelled by user. Bye!')

    finally:
        if world_module is not None:
            world_module.destroy() 
Example #19
Source File: PyKinectInfraRed.py    From PyKinect2 with MIT License 5 votes vote down vote up
def __init__(self):
        pygame.init()

        # Used to manage how fast the screen updates
        self._clock = pygame.time.Clock()

        # Loop until the user clicks the close button.
        self._done = False

        # Used to manage how fast the screen updates
        self._clock = pygame.time.Clock()

        # Kinect runtime object, we want only color and body frames 
        self._kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Infrared)

        # back buffer surface for getting Kinect infrared frames, 8bit grey, width and height equal to the Kinect color frame size
        self._frame_surface = pygame.Surface((self._kinect.infrared_frame_desc.Width, self._kinect.infrared_frame_desc.Height), 0, 24)
        # here we will store skeleton data 
        self._bodies = None
        
        # Set the width and height of the screen [width, height]
        self._infoObject = pygame.display.Info()
        self._screen = pygame.display.set_mode((self._kinect.infrared_frame_desc.Width, self._kinect.infrared_frame_desc.Height), 
                                                pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)

        pygame.display.set_caption("Kinect for Windows v2 Infrared") 
Example #20
Source File: cnc_display.py    From MonitorDarkly with GNU General Public License v3.0 5 votes vote down vote up
def main():
    pg.init()
    screen = pg.display.set_mode((1920,1200), pg.FULLSCREEN|pg.DOUBLEBUF|pg.HWSURFACE)

    lock = image.DellImage("lock_https.gif")
    packet = cnc_packet.build_upload_packet(cnc_packet.build_image_blob(lock, 50, 50))
    display_packet(packet, screen)

    while True:
        x, y = pg.mouse.get_pos()
        packet = cnc_packet.build_cursor_packet(x, y)
        display_packet(packet, screen) 
Example #21
Source File: render.py    From macad-gym with MIT License 5 votes vote down vote up
def multi_view_render(images, unit_dimension, actor_configs):
    """Render images based on pygame > 1.9.4

    Args:
        images (dict):
        unit_dimension (list): window size, e.g., [84, 84]
        actor_configs (dict): configs of actors

    Returns:
        N/A.
    """
    global i
    pygame.init()
    surface_seq = ()
    poses, window_dim = get_surface_poses(
        len(images), unit_dimension, images.keys())

    # Get all surfaces.
    for actor_id, im in images.items():
        if not actor_configs[actor_id]["render"]:
            continue
        surface = pygame.surfarray.make_surface(im.swapaxes(0, 1) * 128 + 128)
        surface_seq += ((surface, (poses[actor_id][1], poses[actor_id][0])), )

    display = pygame.display.set_mode((window_dim[0], window_dim[1]),
                                      pygame.HWSURFACE | pygame.DOUBLEBUF)
    display.blits(blit_sequence=surface_seq, doreturn=1)
    pygame.display.flip()
    # save to disk
    # pygame.image.save(display,
    #                   "/mnt/DATADRIVE1/pygame_surfs/" + str(i) + ".jpeg")
    i += 1 
Example #22
Source File: manual_control.py    From macad-gym with MIT License 5 votes vote down vote up
def game_loop(args):
    pygame.init()
    pygame.font.init()
    world = None

    try:
        client = carla.Client(args.host, args.port)
        client.set_timeout(2.0)

        display = pygame.display.set_mode(
            (args.width, args.height),
            pygame.HWSURFACE | pygame.DOUBLEBUF)

        hud = HUD(args.width, args.height)
        world = World(client.get_world(), hud)
        controller = KeyboardControl(world, args.autopilot)

        clock = pygame.time.Clock()
        while True:
            clock.tick_busy_loop(60)
            if controller.parse_events(world, clock):
                return
            world.tick(clock)
            world.render(display)
            pygame.display.flip()

    finally:

        if world is not None:
            world.destroy()

        pygame.quit()


# ==============================================================================
# -- main() --------------------------------------------------------------------
# ============================================================================== 
Example #23
Source File: Fullcode.py    From Learning-Python-by-building-games with MIT License 5 votes vote down vote up
def loader(self):
        pygame.init()
        self.surface = pygame.display.set_mode((self.Width, self.Height), pygame.HWSURFACE)

        self._running = True
        self._image_surf = pygame.image.load("snake.png").convert()
        self._Frog_surf = pygame.image.load("frog-main.png").convert() 
Example #24
Source File: game_items.py    From alien-invasion-game with MIT License 5 votes vote down vote up
def __init__(self, ai_settings: Settings, stats: GameStats, **kwargs: game_items_types):
        """Initialize with default items unless specified in kwargs."""

        # Default initializations for game items.
        # Initialize screen.
        flags = pygame.HWSURFACE | pygame.DOUBLEBUF    # | pygame.FULLSCREEN
        self.screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height), flags)
        pygame.display.set_caption("Alien Invasion Game")

        # Initialize ship.
        self.ship = Ship(ai_settings, self.screen)

        # Initialize aliens group.
        self.aliens = Group()

        # Initialize bullets group.
        self.bullets = Group()

        # Initialize buttons.
        self.play_button = Button(self.screen, "Play!")

        # TODO implement Restart and Cancel buttons.
        # self.restart_button = Button(self.screen, "Restart")
        # self.cancel_button = Button(self.screen, "Cancel", (255, 0, 0, 80))
        # self.set_button_pos()

        # Initialize scorecard.
        self.sb = Scorecard(ai_settings, stats, self.screen)

        # Set the game items for those default values are given.
        for game_item in kwargs:
            if game_item in self.acceptable_game_items:
                self.__setattr__(game_item, kwargs[game_item]) 
Example #25
Source File: env_utils.py    From tensorforce with Apache License 2.0 5 votes vote down vote up
def get_display(window_size, mode=pygame.HWSURFACE | pygame.DOUBLEBUF):
    """Returns a display used to render images and text.
        :param window_size: a tuple (width: int, height: int)
        :param mode: pygame rendering mode. Default: pygame.HWSURFACE | pygame.DOUBLEBUF
        :return: a pygame.display instance.
    """
    return pygame.display.set_mode(window_size, mode) 
Example #26
Source File: carla_task.py    From VerifAI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_task(self, sample):
        try:
            pygame.init()
            pygame.font.init()
            self.hud = HUD(*self.display_dim)
            self.display = pygame.display.set_mode(
                self.display_dim,
                pygame.HWSURFACE | pygame.DOUBLEBUF
            )
            # print("[carla_task] Setting up world.")
            if self.client.get_world().get_map().name == self.world_map:
                self.world = World(self.client.get_world(), self.hud, 
                        cam_transform=self.cam_transform)
            else:
                self.world = World(self.client.load_world(self.world_map), 
                        self.hud, cam_transform=self.cam_transform)
            # print("[carla_task] World setup complete.")
            self.use_sample(sample)
            self.world.restart()
            self.timestep = 0
            while self.timestep < self.n_sim_steps:
                self.step_world()
                self.timestep += 1
            traj = self.trajectory_definition()
        finally:
            self.world.destroy()
            pygame.quit()
        return traj 
Example #27
Source File: human_agent.py    From scenario_runner with MIT License 5 votes vote down vote up
def __init__(self, parent):
        self.quit = False
        self._parent = parent
        self._width = 800
        self._height = 600
        self._throttle_delta = 0.05
        self._steering_delta = 0.01
        self._surface = None

        pygame.init()
        pygame.font.init()
        self._clock = pygame.time.Clock()
        self._display = pygame.display.set_mode((self._width, self._height), pygame.HWSURFACE | pygame.DOUBLEBUF)
        pygame.display.set_caption("Human Agent") 
Example #28
Source File: manual_control.py    From scenario_runner with MIT License 5 votes vote down vote up
def game_loop(args):
    pygame.init()
    pygame.font.init()
    world = None

    try:
        client = carla.Client(args.host, args.port)
        client.set_timeout(2.0)

        display = pygame.display.set_mode(
            (args.width, args.height),
            pygame.HWSURFACE | pygame.DOUBLEBUF)

        hud = HUD(args.width, args.height)
        world = WorldSR(client.get_world(), hud, args)
        controller = KeyboardControl(world, args.autopilot)

        clock = pygame.time.Clock()
        while True:
            clock.tick_busy_loop(60)
            if controller.parse_events(client, world, clock):
                return
            if not world.tick(clock):
                return
            world.render(display)
            pygame.display.flip()

    finally:

        if (world and world.recording_enabled):
            client.stop_recorder()

        if world is not None:
            world.destroy()

        pygame.quit()


# ==============================================================================
# -- main() --------------------------------------------------------------------
# ============================================================================== 
Example #29
Source File: PyKinectBodyGame.py    From PyKinect2 with MIT License 4 votes vote down vote up
def run(self):
        # -------- Main Program Loop -----------
        while not self._done:
            # --- Main event loop
            for event in pygame.event.get(): # User did something
                if event.type == pygame.QUIT: # If user clicked close
                    self._done = True # Flag that we are done so we exit this loop

                elif event.type == pygame.VIDEORESIZE: # window resized
                    self._screen = pygame.display.set_mode(event.dict['size'], 
                                               pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE, 32)
                    
            # --- Game logic should go here

            # --- Getting frames and drawing  
            # --- Woohoo! We've got a color frame! Let's fill out back buffer surface with frame's data 
            if self._kinect.has_new_color_frame():
                frame = self._kinect.get_last_color_frame()
                self.draw_color_frame(frame, self._frame_surface)
                frame = None

            # --- Cool! We have a body frame, so can get skeletons
            if self._kinect.has_new_body_frame(): 
                self._bodies = self._kinect.get_last_body_frame()

            # --- draw skeletons to _frame_surface
            if self._bodies is not None: 
                for i in range(0, self._kinect.max_body_count):
                    body = self._bodies.bodies[i]
                    if not body.is_tracked: 
                        continue 
                    
                    joints = body.joints 
                    # convert joint coordinates to color space 
                    joint_points = self._kinect.body_joints_to_color_space(joints)
                    self.draw_body(joints, joint_points, SKELETON_COLORS[i])

            # --- copy back buffer surface pixels to the screen, resize it if needed and keep aspect ratio
            # --- (screen size may be different from Kinect's color frame size) 
            h_to_w = float(self._frame_surface.get_height()) / self._frame_surface.get_width()
            target_height = int(h_to_w * self._screen.get_width())
            surface_to_draw = pygame.transform.scale(self._frame_surface, (self._screen.get_width(), target_height));
            self._screen.blit(surface_to_draw, (0,0))
            surface_to_draw = None
            pygame.display.update()

            # --- Go ahead and update the screen with what we've drawn.
            pygame.display.flip()

            # --- Limit to 60 frames per second
            self._clock.tick(60)

        # Close our Kinect sensor, close the window and quit.
        self._kinect.close()
        pygame.quit() 
Example #30
Source File: vehicle_manager.py    From macad-gym with MIT License 4 votes vote down vote up
def apply_control(self, ctrl_args):
        """Apply control to current vehicle.

        Args:
            ctrl_args(list): send control infor, e.g., throttle.

        Returns:
            N/A.

        """
        config = self._config
        if config['manual_control']:
            clock = pygame.time.Clock()
            # pygame
            self._display = pygame.display.set_mode(
                (800, 600), pygame.HWSURFACE | pygame.DOUBLEBUF)
            logging.debug('pygame started')
            controller = KeyboardControl(self._world, False)
            controller.actor_id = ctrl_args[5]  # only in manual_control mode
            controller.parse_events(self, clock)
            self._on_render()
        elif config["auto_control"]:
            self._vehicle.set_autopilot()
        else:
            # TODO: Planner based on waypoints.
            # cur_location = self._vehicle.get_location()
            # dst_location = carla.Location(
            #   x = self.end_pos[i][0],
            #   y = self.end_pos[i][1],
            #   z = self.end_pos[i][2])
            # cur_map = self.world.get_map()
            # next_point_transform =
            #   get_transform_from_nearest_way_point(
            #       cur_map, cur_location, dst_location)
            # next_point_transform.location.z = 40
            # self.actor_list[i].set_transform(next_point_transform)
            self._vehicle.apply_control(
                carla.VehicleControl(
                    throttle=ctrl_args[0],
                    steer=ctrl_args[1],
                    brake=ctrl_args[2],
                    hand_brake=ctrl_args[3],
                    reverse=ctrl_args[4]))

    # TODO: use the render in cam_manager instead of this.