Beispiel #1
0
    def render(self, mode='human', close=False):
        """Renders the environment.

        The set of supported modes varies per environment. (And some
        environments do not support rendering at all.) By convention,
        if mode is:

        - human: render to the current display or terminal and
          return nothing. Usually for human consumption.
        - rgb_array: Return an numpy.ndarray with shape (x, y, 3),
          representing RGB values for an x-by-y pixel image, suitable
          for turning into a video.
        - ansi: Return a string (str) or StringIO.StringIO containing a
          terminal-style text representation. The text can include newlines
          and ANSI escape sequences (e.g. for colors).

        Note:
            Make sure that your class's metadata 'render.modes' key includes
              the list of supported modes. It's recommended to call super()
              in implementations to use the functionality of this method.

        Args:
            mode (str): the mode to render with
            close (bool): close all open renderings

        Example:

        class MyEnv(Env):
            metadata = {'render.modes': ['human', 'rgb_array']}

            def render(self, mode='human'):
                if mode == 'rgb_array':
                    return np.array(...) # return RGB frame suitable for video
                elif mode is 'human':
                    ... # pop up a window and render
                else:
                    super(MyEnv, self).render(mode=mode) # just raise an exception
        """
        if close:
            return self._render(close=close)

        # This code can be useful for calling super() in a subclass.
        modes = self.metadata.get('render.modes', [])
        if len(modes) == 0:
            raise error.UnsupportedMode(
                '{} does not support rendering (requested mode: {})'.format(
                    self, mode))
        elif mode not in modes:
            raise error.UnsupportedMode(
                'Unsupported rendering mode: {}. (Supported modes for {}: {})'.
                format(mode, self, modes))

        return self._render(mode=mode, close=close)
 def render(self, mode='rgb_array', close=False):
     if mode == 'rgb_array':
         return self.last_image
     elif mode == 'human':
         return None
     else:
         raise error.UnsupportedMode("Unsupported render mode: " + mode)
Beispiel #3
0
    def render(self, mode='human', close=False):
        if mode == 'rgb_array':
            return self.last_image
        elif mode == 'human':
            try:
                import pygame
            except ImportError as e:
                raise error.DependencyNotInstalled(
                    "{}. (HINT: install pygame using `pip install pygame`".
                    format(e))

            if close:
                pygame.quit()
            else:
                if self.screen is None:
                    pygame.init()
                    self.clock = pygame.time.Clock()
                    self.screen = pygame.display.set_mode(
                        (self.video_width, self.video_height))
                img = pygame.surfarray.make_surface(
                    self.last_image.swapaxes(0, 1))
                self.screen.blit(img, (0, 0))
                pygame.display.update()
                if self.clock:
                    self.clock.tick(60)
        else:
            raise error.UnsupportedMode("Unsupported render mode: " + mode)
Beispiel #4
0
    def render(self, mode='human', close=False):
        """
        This function renders the current game state in the given mode.
        TODO : render using default gym functions

        """
        if mode == 'console':
            print(self._get_state)
        elif mode == "human":
            try:
                import pygame
            except ImportError as e:
                raise error.DependencyNotInstalled(
                    "{}. (HINT: pygame install karo mere bhai; use `pip install pygame`".format(e))
            if close:
                pygame.quit()
            else:
                if self.screen is None:
                    pygame.init()
                    self.screen = pygame.display.set_mode(
                        (round(self.window_width), round(self.window_height)))
                    # surr = self.surr
                    
                clock = pygame.time.Clock()
                #trick to keep the screen running:
                pygame.event.pump()
                                
                self.screen.blit(self.bg, (0,0))

                # Draw car running
                # TODO : change the car orientation and better resize perhapes
                car_img_angle = pygame.transform.rotate(self.car_img, -self.angle)
                self.screen.blit(car_img_angle, (self.car))

                # show foodbox and delivery
                self.screen.blit(self.foodbox, (self.x1-30, self.y1-30))
                self.screen.blit(self.delivery, (self.x2-50, self.y2-50))

                self.screen.blit(self.surr, (1140,500))


                pygame.display.update()
                clock.tick(self.metadata["video.frames_per_second"])
                
                #trick to quit the screen
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()

                
        else:
            raise error.UnsupportedMode("Unsupported render mode: " + mode)
Beispiel #5
0
    def render(self,
               mode: str = 'console',
               close: Optional[bool] = False) -> None:
        """
        Render the Connect-Four board.

        :param mode: "console" if render to console;
            "human" if render to PyGame window.
        :param close: whether to quit PyGame window or not.
        :return: None
        """
        if mode == 'console':
            replacements = {
                self.__player_color: 'A',
                0: ' ',
                -1 * self.__player_color: 'B'
            }

            def render_line(line):
                line = "|".join([f"{replacements[x]:^3}" for x in line])
                line = f"|{line}|"
                return line

            hline = '|---+---+---+---+---+---+---|'
            print(f"{self.__n_step}. Player {self.current_player}")
            print(hline)
            for line in np.apply_along_axis(render_line,
                                            axis=1,
                                            arr=self.__board):
                print(line)
            print(hline)
            print()

        elif mode == 'human':
            if self.__screen is None:
                pygame.init()
                self.__screen = pygame.display.set_mode(
                    (round(self.__window_width), round(self.__window_height)))

            if close:
                pygame.quit()

            self.__rendered_board = self._update_board_render()
            frame = self.__rendered_board
            surface = pygame.surfarray.make_surface(frame)
            surface = pygame.transform.rotate(surface, 90)
            self.__screen.blit(surface, (0, 0))

            pygame.display.update()
        else:
            raise error.UnsupportedMode()
Beispiel #6
0
    def render(self, mode='human', close=False):
        """
        This function renders the current game state in the given mode.
        """

        if mode == 'console':
            print(self._get_game_state)
        elif mode == "human":
            try:
                import pygame
                from pygame import gfxdraw
            except ImportError as e:
                raise error.DependencyNotInstalled(
                    "{}. (HINT: install pygame using `pip install pygame`".format(e))
            if close:
                pygame.quit()
            else:
                if self.screen is None:
                    pygame.init()
                    self.screen = pygame.display.set_mode(
                        (round(self.window_width), round(self.window_height)))
                clock = pygame.time.Clock()

                self.screen.fill((255, 255, 255))
                # for line in self.lines:
                #    pygame.gfxdraw.line(self.screen, *line, BLACK)
                for key in self.resources:
                    self.resources[key].draw(pygame, self.screen)

                for key in self.spots:
                    self.spots[key].draw(pygame, self.screen)

                for key in self.roads:
                    self.roads[key].draw(pygame, self.screen)

                i = 0
                for key in self.collected_resources:
                    font = pygame.font.SysFont("arial", 25)
                    text = font.render(
                        str(key[:2])+str(self.collected_resources[key]), 3, (0, 0, 255))
                    self.screen.blit(text, (400, 20*i))
                    i += 1

                font = pygame.font.SysFont("arial", 25)
                text = font.render(str(self.episode), 3, (0, 0, 255))
                self.screen.blit(text, (10, 10))

                pygame.display.update()

        else:
            raise error.UnsupportedMode("Unsupported render mode: " + mode)
Beispiel #7
0
    def render(self, mode='human', close=False):
        """
    Renders the game to a window, or as an image.
    Override render_image() to define what's shown.
    Close is a hint that the window should b
    """
        try:
            import pygame
            from pygame import gfxdraw
        except ImportError as e:
            raise error.DependencyNotInstalled(
                "{}. (HINT: install pygame using `pip install pygame`".format(
                    e))
        if close:
            pygame.quit()

        background_colour = self._get_background_colour()
        self.screen.fill(background_colour)

        #img = self.render_image()
        #surface = pygame.surfarray.make_surface(img)
        #self.screen.blit(surface, (0, 0))  # Draw game state
        self.render_screen(self.screen)

        if mode == 'rgb_array':
            pass
        elif mode == 'human':
            #print('HUMAN')
            if self.display_screen is None:
                screen_shape = self.get_screen_shape()
                self.window_height = screen_shape[0]  # height
                self.window_width = screen_shape[1]  # width
                self.display_screen = pygame.display.set_mode(
                    (round(self.window_width), round(self.window_height)))
                pygame.display.set_caption(self._get_caption())

            # Update the window
            #surface = pygame.surfarray.make_surface(img)
            #self.screen.blit(surface, (0, 0))  # Draw game state
            self.display_screen.blit(self.screen, (0, 0))  # Draw game state
            pygame.display.update()
        else:
            raise error.UnsupportedMode("Unsupported render mode: " + mode)

        # Convert to numpy array
        rgb_array = pygame.surfarray.array3d(self.screen)
        #print("RENDER OBJ = ", type(rgb_array))
        #print("RENDER OBJ SHAPE = ", rgb_array.shape)
        return rgb_array
Beispiel #8
0
    def render(self, mode='human', close=False):
        """
        This function renders the current game state in the given mode.
        """
        if mode == 'console':
            print(self.board.blit(self.current_piece, ret=True))
        elif mode == "rgb_array":
            aux = self.board.blit(self.current_piece, ret=True).reshape([self.board.size[0], self.board.size[1], 1])
            return np.concatenate([aux for i in range(3)], axis=2)
        elif mode == "human":
            try:
                import pygame
                from pygame import gfxdraw
            except ImportError as e:
                raise error.DependencyNotInstalled(
                    "{}. (HINT: install pygame using `pip install pygame`".format(e))
            if close:
                pygame.quit()
            else:
                if self.screen is None:
                    pygame.init()
                    self.screen = pygame.display.set_mode(
                        (round(self.board.size[1]*10), round(self.board.size[0]*10)))
                clock = pygame.time.Clock()
                
                board = self.board.blit(self.current_piece, ret=True)
                # Draw old bubbles
                self.screen.fill((255, 255, 255))
                for row in range(board.shape[0]):
                    for column in range(board.shape[1]):
                        if board[row, column]:
                            pygame.draw.rect(self.screen, (0,0,0), pygame.Rect(column*10, row*10, 9, 9))
                            #pygame.box(self.screen, pygame.Rect(column*10, row*10, 9, 9), (0,0,0))

                pygame.display.update()
        else:
            raise error.UnsupportedMode("Unsupported render mode: " + mode)
        
        
        
        
        
        
        
        
        """if mode == 'human':
Beispiel #9
0
    def render(self, mode: str = 'console', close: bool = False) -> None:
        if mode == 'console':
            replacements = {
                self.__player_color: 'A',
                0: ' ',
                -1 * self.__player_color: 'B'
            }

            def render_line(line):
                return "|" + "|".join(
                    ["{:>2} ".format(replacements[x]) for x in line]) + "|"

            hline = '|---+---+---+---+---+---+---|'
            print(hline)
            for line in np.apply_along_axis(render_line,
                                            axis=1,
                                            arr=self.__board):
                print(line)
            print(hline)

        elif mode == 'human':
            if self.__screen is None:
                pygame.init()
                self.__screen = pygame.display.set_mode(
                    (round(self.__window_width), round(self.__window_height)))

            if close:
                pygame.quit()

            self.__rendered_board = self._update_board_render()
            frame = self.__rendered_board
            surface = pygame.surfarray.make_surface(frame)
            surface = pygame.transform.rotate(surface, 90)
            self.__screen.blit(surface, (0, 0))

            pygame.display.update()
        elif mode == 'rgb_array':
            self.__rendered_board = self._update_board_render()
            frame = self.__rendered_board
            return np.flip(frame, axis=(0, 1))
        else:
            raise error.UnsupportedMode()
Beispiel #10
0
    def render(self, mode='human', close=False):
        if mode == 'console':
            print(np.flip(self.board.board, axis=0))
        elif mode == 'human':
            if self.screen is None:
                pygame.init()
                self.screen = pygame.display.set_mode(
                    (round(self.window_width), round(self.window_height)))

            if close:
                pygame.quit()

            frame = render_board(self.board.board)
            surface = pygame.surfarray.make_surface(frame)
            surface = pygame.transform.rotate(surface, -90)
            surface = pygame.transform.flip(surface, True, False)
            self.screen.blit(surface, (0, 0))

            pygame.display.update()
        else:
            raise error.UnsupportedMode()
Beispiel #11
0
 def render(self, mode='human', close=False):
     if mode == 'rgb_array':
         return self.last_image
     # elif mode == 'human':
     #     try:
     #         import pygame
     #     except ImportError as e:
     #         raise error.DependencyNotInstalled("{}. (HINT: install pygame using `pip install pygame`".format(e))
     #
     #     if close:
     #         pygame.quit()
     #     else:
     #         if self.screen is None:
     #             pygame.init()
     #             self.screen = pygame.display.set_mode((640, 480))
     #         scaled_image = pygame.surfarray.make_surface(np.swapaxes(self._image, 0,1))
     #         # scaled_image = pygame.transform.scale(img, BIGGER_RENDER)
     #         self.screen.blit(scaled_image, (0, 0))
     #         pygame.event.get()
     #         pygame.display.update()
     else:
         raise error.UnsupportedMode("Unsupported render mode: " + mode)
    def render(self, mode='console'):
        """Renderowanie bieżącego stanu środowiska z wykorzystniem wybranej opcji
        Obsługiwane są następujące tryby:
        - 'human' - interfejs graficzny
        - 'console' - wersja konsolowa."""

        if mode == 'human':
            # interfejs graficzny
            if self._viewer is None:
                self._win = Window(self._players[0].hand_splitted, self._players[1].hand_splitted,
                                   self._players[2].hand_splitted, self._players[3].hand_splitted, self._dealer_name)
                self._viewer = True

            else:
                if self._double:
                    last_contract = self._last_contract.__str__() + 'X'

                elif self._redouble:
                    last_contract = self._last_contract.__str__() + 'XX'

                else:
                    last_contract = self._last_contract.__str__()

                self._win.update_view(last_contract, self._players[0].player_contracts.__str__(),
                                      self._players[1].player_contracts.__str__(),
                                      self._players[2].player_contracts.__str__(),
                                      self._players[3].player_contracts.__str__(),
                                      PAIR,
                                      self._score,
                                      self._optimum_contract_score,
                                      self.metadata['video.frames_per_second'])

        elif mode == 'console':
            # wersja konsolowa
            if self._viewer is None:
                print(' ')
                print('Dealer: ' + self._dealer_name)

                for i in range(0, self._n_players):
                    print(self._players[i].name + ' hand:')
                    print(spade + ' ' + self._players[i].hand_splitted[0])
                    print(heart + ' ' + self._players[i].hand_splitted[1])
                    print(diamond + ' ' + self._players[i].hand_splitted[2])
                    print(club + ' ' + self._players[i].hand_splitted[3])

                print(' ')

                self._viewer = False

            else:
                print('')
                if self._double:
                    print('LAST_contract: ' + self._last_contract.__str__() + ' X')

                elif self._redouble:
                    print('LAST_contract: ' + self._last_contract.__str__() + ' XX')

                else:
                    print('LAST_contract: ' + self._last_contract.__str__())

                print('Pair: ' + PAIR[0] + '  ' + PAIR[1])
                print('Score: ' + str(self._score[0]) + '  ' + str(self._score[1]))
                print('Optimum score: ' + str(self._optimum_contract_score[0]) + '  ' +
                      str(self._optimum_contract_score[1]))
                print(' ')
                print('NORTH_contract: ' + self._players[0].player_contracts.__str__())
                print('EAST_contract: ' + self._players[1].player_contracts.__str__())
                print('SOUTH_contract: ' + self._players[2].player_contracts.__str__())
                print('WEST_contract: ' + self._players[3].player_contracts.__str__())
                print(' ')

        else:
            # błąd przy wpisaniu niedostępnej opcji
            raise error.UnsupportedMode('Unsupported render mode' + mode)
    def render(self, mode='human', close=False):
        """
        This function renders the current game state in the given mode.
        """
        if mode == 'console':
            print(self._get_game_state)
        elif mode == "human":
            try:
                import pygame
                from pygame import gfxdraw
            except ImportError as e:
                raise error.DependencyNotInstalled(
                    "{}. (HINT: install pygame using `pip install pygame`".
                    format(e))
            if close:
                pygame.quit()
            else:
                if self.screen is None:
                    pygame.init()
                    self.screen = pygame.display.set_mode(
                        (round(self.window_width), round(self.window_height)))
                clock = pygame.time.Clock()

                # Draw old bubbles
                self.screen.fill((255, 255, 255))
                for row in range(self.array_height):
                    for column in range(self.array_width):
                        if self.last_board[row][column].color is not None:
                            bubble = self.last_board[row][column]
                            pygame.gfxdraw.filled_circle(
                                self.screen, round(bubble.center_x),
                                round(bubble.center_y), self.bubble_radius,
                                bubble.color)
                pygame.display.update()

                # Draw flying bubble
                last_x, last_y = None, None
                for position in self.last_positions:
                    if last_x is not None and last_y is not None:
                        pygame.gfxdraw.filled_circle(self.screen,
                                                     round(last_x),
                                                     round(last_y),
                                                     self.bubble_radius,
                                                     (255, 255, 255))
                    last_x, last_y = position[0], position[1]
                    pygame.gfxdraw.filled_circle(self.screen,
                                                 round(position[0]),
                                                 round(position[1]),
                                                 self.bubble_radius,
                                                 self.last_color)
                    pygame.display.update()
                    clock.tick(self.metadata["video.frames_per_second"])

                # Draw new bubbles
                self.screen.fill((255, 255, 255))
                for row in range(self.array_height):
                    for column in range(self.array_width):
                        if self.board[row][column].color is not None:
                            bubble = self.board[row][column]
                            pygame.gfxdraw.filled_circle(
                                self.screen, round(bubble.center_x),
                                round(bubble.center_y), self.bubble_radius,
                                bubble.color)
                pygame.display.update()
        else:
            raise error.UnsupportedMode("Unsupported render mode: " + mode)
Beispiel #14
0
    def render(self, mode='human', close=False):
        """
        This function renders the current game state in the given mode.
        TODO : render using default gym functions

        """
        if mode == 'console':
            print(self._get_state)
        elif mode == "human":
            try:
                import pygame
            except ImportError as e:
                raise error.DependencyNotInstalled(
                    "{}. (HINT: pygame install kar mere bhai; use `pip install pygame`"
                    .format(e))
            if close:
                pygame.quit()
            else:
                if self.screen is None:
                    pygame.init()

                    self.screen = pygame.display.set_mode(
                        (round(self.window_width), round(self.window_height)))
                clock = pygame.time.Clock()
                myfont = pygame.font.SysFont('Comic Sans MS', 20)

                #trick to keep the screen running:
                pygame.event.pump()

                self.screen.blit(self.bg, (0, 0))

                # Draw car running
                # TODO : change the car orientation and resize perhapes
                car_img_angle = pygame.transform.rotate(
                    self.car_img, -self.angle)
                self.screen.blit(car_img_angle, (self.car))

                # show dabba and delivery
                self.screen.blit(self.dabba, (self.x1 - 30, self.y1 - 30))
                self.screen.blit(self.delivery, (self.x2 - 50, self.y2 - 50))

                if self.last_reward < -0.6:
                    reward_text = myfont.render(
                        'Reward: ' + str(self.last_reward), False, (255, 0, 0))
                else:
                    reward_text = myfont.render(
                        'Reward: ' + str(self.last_reward), False, (0, 255, 0))
                self.screen.blit(reward_text, (1240, 500))
                # the surrounding stuff
                #TODO: use LIDAR values from the CNN Model
                self.screen.blit(self.lidar, (1140, 500))

                pygame.display.update()
                clock.tick(self.metadata["video.frames_per_second"])

                #trick to quit the screen
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()

        else:
            raise error.UnsupportedMode("Rebder mode is Unsupported: " + mode)