Пример #1
0
    def blit_rotate(surf: pygame.SurfaceType, image: pygame.SurfaceType, pos: Vector, angle: float,
                    origin_pos: Vector = None, show_rect: bool = False) -> None:
        """Many thanks to https://stackoverflow.com/a/54714144."""
        # calculate the axis aligned bounding box of the rotated image
        w, h = image.get_size()
        box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]]
        box_rotate = [p.rotate(angle) for p in box]
        min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1])
        max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1])

        # calculate the translation of the pivot
        if origin_pos is None:
            origin_pos = w / 2, h / 2
        pivot = pygame.math.Vector2(origin_pos[0], -origin_pos[1])
        pivot_rotate = pivot.rotate(angle)
        pivot_move = pivot_rotate - pivot

        # calculate the upper left origin of the rotated image
        origin = (pos[0] - origin_pos[0] + min_box[0] - pivot_move[0],
                  pos[1] - origin_pos[1] - max_box[1] + pivot_move[1])
        # get a rotated image
        rotated_image = pygame.transform.rotate(image, angle)
        # rotate and blit the image
        surf.blit(rotated_image, origin)
        # draw rectangle around the image
        if show_rect:
            pygame.draw.rect(surf, (255, 0, 0), (*origin, *rotated_image.get_size()), 2)
Пример #2
0
 def draw(self, screen: pygame.SurfaceType, name: bool = False):
     screen.blit(self._ball, self.rect)
     if name:
         text = self.font.render(self.name, True, (0, 0, 0))
         text_rect = self.rect
         text_rect.topleft = self.rect.center
         screen.blit(text, self.rect)
Пример #3
0
 def render(self, window_surface: pygame.SurfaceType):
     text_height_offset = 0
     for index, ui_text in enumerate(self.init_text_ui()):
         text_height = ui_text.get_height()
         window_surface.blit(ui_text,
                             (self.x_pos, self.y_pos + text_height_offset +
                              (self.line_spacing if index == 0 else 0)))
         text_height_offset += text_height
Пример #4
0
 def blit_alpha(target: pg.Surface, source: pg.SurfaceType, location: tuple, opacity: int):
     """
     :param target: Screen frame
     :param source: original image
     :param location: drawer location
     :param opacity: opacity of the new image
     """
     x = location[0]
     y = location[1]
     temp: pg.Surface = pg.Surface((source.get_width(), source.get_height())).convert()
     temp.blit(target, (-x, -y))
     temp.blit(source, (0, 0))
     temp.set_alpha(opacity)
     target.blit(temp, location)
Пример #5
0
    def __init__(self,
                 ai_settings: Settings,
                 screen: pygame.SurfaceType,
                 size=(0, 0),
                 image_name="alien-invasion/images/ship1.png"):
        """Initialize the ship and set its starting position."""
        super().__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # Load the ship image and get its rect.
        # fullname = os.path.join(os.getcwd(), image_name
        try:
            self.image = pygame.image.load(image_name)
        except pygame.error as e:
            print('Cannot load image: ', image_name)
            print(e)
            raise SystemExit
        if size == (0, 0):
            size = ai_settings.ship_size
        self.image = pygame.transform.scale(self.image, size)

        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # Store a float value for the ship's center.
        self.center = float(self.rect.centerx)

        # Movement Flags.
        self.moving_right = False
        self.moving_left = False
Пример #6
0
    def __init__(self,
                 screen: pygame.SurfaceType,
                 msg: str,
                 size=48,
                 b_color=(-1, -1, -1)):
        self.screen = screen
        self.screen_rect = screen.get_rect()

        # Properties of button.
        self.button_transparency = 80
        self.button_color = (0, 255, 0) if b_color == (-1, -1, -1) else b_color
        if len(self.button_color) == 3:
            self.button_color += (self.button_transparency,
                                  )  # add alpha channel
        self.text_color = (255, 255, 255)

        self.font = pygame.font.Font('fonts/RussoOne.ttf', size)

        self.prep_msg(msg)

        button_width = self.msg_image_rect.width + 30
        button_height = self.msg_image_rect.height + 10

        self.rect = pygame.Rect(0, 0, button_width, button_height)
        self.rect.center = self.msg_image_rect.center
Пример #7
0
 def __init__(self, x: int, y: int, img: pygame.SurfaceType, buttons=None):
     if buttons is None:
         buttons = []
     self.pos = x, y
     self.rect = pygame.Rect(x, y, *img.get_size())
     self.img = img
     self.buttons = buttons
Пример #8
0
    def __init__(self,
                 ai_settings: Settings,
                 screen: pygame.SurfaceType,
                 image_name='images/alien1.png'):
        """Initialize the alien and set its starting position."""

        super().__init__()
        self.screen = screen
        self.ai_settings = ai_settings
        self.screen_rect = screen.get_rect()

        # Load the alien image and set its rect attribute.
        fullname = os.path.join('.', image_name)
        try:
            self.image = pygame.image.load(fullname)
        except pygame.error:
            print('Cannot load image:', image_name)
            raise SystemExit
        self.image = pygame.transform.scale(self.image, ai_settings.alien_size)
        self.rect = self.image.get_rect()

        # Start each new alien near the top left of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        self.x = float(self.rect.x)
        self.y = float(self.rect.y)

        self.drop_dist = self.y + self.ai_settings.alien_drop_dist
Пример #9
0
def update_screen(ai_settings, screen: pyg.SurfaceType, stats, score_board,
                  ship, aliens, bullets, play_button):
    """Update images on the screen and flip to the new screen"""
    screen.fill(ai_settings.bg_color)

    for bullet in bullets.sprites():
        bullet.draw_bullet()

    ship.blitme()
    aliens.draw(screen)

    # Draw the Score information.
    score_board.show_score()

    # Draw the play button if the game is inactive.
    if not stats.game_active:
        play_button.draw_button()

    # Make the most recently drawn screen visible.
    pyg.display.flip()
Пример #10
0
 def __init__(self,
              x: int,
              y: int,
              img: pygame.SurfaceType,
              command=lambda: None,
              cost: int = 0):
     self.pos = x, y
     self.rect = pygame.Rect(x, y, *img.get_size())
     self.img = img
     self.cost = cost
     self.command = command
Пример #11
0
    def __init__(self, screen: pygame.SurfaceType):
        """ Inicializa a espaçonave e define sua posição inicial """
        self.screen = screen

        # Carrega a imagem da espaçonave e obtém seu rect
        self.image = pygame.image.load('images/ship70x70.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # Inicializa cada nova espaçonave na parte inferior central da tela
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom
 def render(self, window_surface: pygame.SurfaceType):
     if self.is_obstacle():
         self.block.fill(OBSTACLE_COLOR)
     elif self.marked:
         self.block.fill(MARKER_COLOR)
     elif self.is_path:
         self.block.fill(PATH_COLOR)
     elif self.get_visited():
         self.block.fill(VISITED_COLOR)
     else:
         if self.get_distance() == sys.maxsize:
             self.block.fill(UNVISITED_COLOR)
         else:
             self.block.fill(SEARCHED_COLOR)
     if self.debug_mode:
         if self.get_distance() != sys.maxsize:
             if type(self.debug_text) is list:
                 render_multiline_text(self.block, self.debug_text, 8, (0, 0, 0))
             if type(self.debug_text) == str:
                 render_inline_text(self.block, self.debug_text, 8, (0, 0, 0))
     window_surface.blit(self.border, self.border_rect)
     window_surface.blit(self.block, self.block_rect)
Пример #13
0
    def __init__(self, ai_settings: Settings, screen: SurfaceType, msg: str):
        self._screen = screen
        self._screen_rect = screen.get_rect()

        self._width, self._height = 200, 50
        self._button_color = (0, 255, 0)
        self._text_color = (255, 255, 255)
        self._font = SysFont(None, 48)

        self.rect = pygame.Rect(0, 0, self._width, self._height)
        self.rect.center = self._screen_rect.center

        self._prep_msg(msg)
Пример #14
0
    def __init__(self, ai_settings: Settings, screen: SurfaceType,
                 stats: GameStats):
        self._screen = screen
        self._screen_rect = screen.get_rect()
        self._ai_settings = ai_settings
        self._stats = stats

        self._text_color = 90, 200, 50
        self._font = SysFont(None, 48)

        self.prep_score()
        self.prep_high_score()
        self.prep_level()
        self.prep_ships()
Пример #15
0
    def draw(self, surface: pygame.SurfaceType):
        surface.fill(BACKGROUND_COLOR)
        image = self.scaled_image.copy()

        for plant in self.environment.plants:
            radius = self.scale // 2 - 1
            params = (image, *(plant.position * self.scale + radius), radius, plant.get_color())
            gfxdraw.aacircle(*params)
            gfxdraw.filled_circle(*params)

        for corpse in self.environment.corpses:
            radius = self.scale // 2 - 1
            params = (image, *(corpse.position * self.scale + radius), radius, corpse.get_color())
            gfxdraw.aacircle(*params)
            gfxdraw.filled_circle(*params)

        for creature in self.environment.creatures:
            radius = int(self.scale / 2 * creature.get_size())
            radius = radius if creature.get_size() < 1 else radius - 1
            params = (image, *(creature.position * self.scale + radius), radius, creature.get_color())
            gfxdraw.aacircle(*params)
            gfxdraw.filled_circle(*params)

        surface.blit(image, -np.array(self.rect.center) + self.position)
Пример #16
0
    def __init__(self, ai_settings: Settings, stats: GameStats, screen: pygame.SurfaceType):

        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.ai_settings = ai_settings
        self.stats = stats
        self.score_ship_size = self.ai_settings.score_ship_size  # size of ship in the scoreboard.
        self.dur_highscore_msg = 3000        # duration of highscore msg = 3 sec

        # Font settings.
        font_name = 'fonts/PoiretOne.ttf'       # try changing the font
        self.font_color = self.ai_settings.score_font_color
        self.font = pygame.font.Font(font_name, self.ai_settings.score_font_size)

        # Prepare the initial score image.
        self.prep_images()
Пример #17
0
    def draw(self, screen: pygame.SurfaceType):
        p = self.pos_platform
        x, y = self.pos

        screen.blit(self.imgs[self.level][0], (x,  y + p))
        screen.blit(self.imgs[self.level][1], self.pos)
        screen.blit(self.imgs[self.level][2],
                    (x, y + p + self.imgs[self.level][0].get_height() - 3))

        for stone in self.stones:
            stone.draw(screen)
Пример #18
0
    def resize_tags(self, image: pg.SurfaceType, is_cross: bool) -> pg.SurfaceType:
        """
        Funckja zmieniajaca rozmiar obrazkow X oraz O
        :param image: klasa pygame reprezentujaca obraz
        :param size: rozmiar planszy
        :param is_cross: ktory obraz przyjmuje X czy O
        :return: obraz o zmienionej wielkosci
        """
        if is_cross:
            x = 1.38
            y = 1.38
        else:
            x = 1.87
            y = 1.87

        image_rect = image.get_rect()
        image = pg.transform.scale(image, (int(x / self.size * image_rect.width), int(y / self.size * image_rect.height)))
        return image
Пример #19
0
    def resize_tags(self, image: pg.SurfaceType,
                    is_cross: bool) -> pg.SurfaceType:
        """
        Function that is responsible for resizing the passed image. The app is build the way, that only cross or circle
        are possible to be passed.

        :param image: This is the pygames class, that represents image
        :param size: Size of game board
        :param is_cross: Deciding which image is passed
        :return: Resized image
        """
        if is_cross:
            x = 1.38
            y = 1.38
        else:
            x = 1.87
            y = 1.87

        image_rect = image.get_rect()
        image = pg.transform.scale(image,
                                   (int(x / self.size * image_rect.width),
                                    int(y / self.size * image_rect.height)))
        return image
Пример #20
0
 def draw(self, screen: pygame.SurfaceType):
     # pygame.draw.rect(screen, (255, 0, 0), self.rect)
     screen.blit(self.img, self.pos)
     for button in self.buttons:
         button.draw(screen)
Пример #21
0
    def draw(self, surface: pygame.SurfaceType):
        surface.blit(self.surface, self.position)

        # only draw if there is something to draw
        if self.text.text:
            self.text.draw(surface)
Пример #22
0
 def draw(self, surface: pygame.SurfaceType):
     """
     Doesnt draw text to decrease time spent on drawing
     """
     surface.blit(self.surface, self.position)
Пример #23
0
 def draw(self, screen: pygame.SurfaceType):
     if self.good:
         screen.blit(self.img, self.pos)
Пример #24
0
    def draw(self, surface: pygame.SurfaceType):
        s = pygame.Surface(self.size, pygame.SRCALPHA)
        s.fill(self.color)

        surface.blit(s, self.position)
        self.text.draw(surface)