def rainbow_effect_on_water(screen: pygame.surface.Surface, water_tile: pygame.surface.Surface) -> None: orig_screen = screen.copy() water_color = pygame.transform.average_color(water_tile, water_tile.get_rect()) # Cycle through the rainbow colors clock = pygame.time.Clock() for i in range(4): for rainbow_color in rainbow_colors: try: pygame.transform.threshold(screen, orig_screen, search_color=water_color, threshold=pygame.Color(50, 50, 50), set_color=rainbow_color, inverse_set=True) clock.tick(5) pygame.display.flip() except: print('Color not found: ', rainbow_color, flush=True) # Restore original screen screen.blit(orig_screen, (0, 0)) pygame.display.flip()
def draw(self, screen: pygame.surface.Surface, text_to_display: str, *, radius: float = 0.4) -> None: """ Draw a button on a screen with a given attributes. Parameters ---------- screen: pygame.surface.Surface A screen on which button will be displayed. text_to_display: str A text displayed on the button. radius: float, optional The radius of circle used to create round vertices. """ self.draw_round_rectangle(screen, radius) text: pygame.surface.Surface = self.font.render( text_to_display, True, self.text_color) screen.blit(text, (self.screen_cords[0] + (self.screen_cords[2] / 2 - text.get_width() / 2), self.screen_cords[1] + (self.screen_cords[3] / 2 - text.get_height() / 2)))
def render(self, surf: pygame.surface.Surface, events): self.screen = pygame.surface.Surface(size) self.screen.set_colorkey((0, 0, 0)) self.screen = self.screen.convert_alpha() pygame.draw.rect(self.screen, (0, 0, 0), (width // 2 - 350, height // 2 - 300, 700, 600), 0, 15) tmp_r = pygame.rect.Rect(0, 0, self.max_text_width + self.margin * 2, self.text[0].get_height() * len(self.text) + self.margin * 2) tmp_r.center = (width // 2, height // 2) pygame.draw.rect(self.screen, (0, 0, 22), tmp_r, 0, 15) self.screen.blit(self.main_label, self.main_label.get_rect( center=(width // 2, height // 2 - self.margin - 20 - self.text[0].get_height() * len(self.text)))) tmp_s = pygame.surface.Surface((self.max_text_width, self.text[0].get_height() * len(self.text))) for text in enumerate(self.text): tmp_s.blit(text[1], text[1].get_rect(topleft=(0, text[1].get_height() * text[0]))) self.screen.blit(tmp_s, tmp_s.get_rect(center=(width // 2, height // 2))) self.button.surf = self.screen self.button.draw(list(filter(lambda xx: xx.type == pygame.MOUSEBUTTONUP, events))) surf.blit(self.background, (0, 0)) surf.blit(self.screen, (0, 0))
def draw(self, display: pygame.surface.Surface): if not self.ended: display.blit(self.box, (0, 0)) pressed = pygame.key.get_pressed() if not pressed[pygame.K_z] and self.leave: self.leave = False if len(self.texts) > 0: if self.actual_text == '': self.actual_text = self.texts.pop(0) self.ended = False if pressed[pygame.K_z] and not self.leave: self.actual_text = self.texts.pop(0) self.ended = False self.leave = True else: if pressed[pygame.K_z] and not self.leave: self.ended = True self.leave = True if self.actual_text == '': self.ended = True if not self.ended: drawText(display, self.actual_text, pygame.Color("White"), (LOCATION, (WIDTH - 24, HEIGHT - 24)), self.font)
def draw(self, screen: pygame.surface.Surface): current_time = self.current_time() seconds = current_time.seconds miliseconds = int(current_time.microseconds/10000) rojo = 255 - 255 * (seconds/self.TIME_OUT.seconds) text = self.font.render(f'{seconds}:{miliseconds}', True, (rojo, 128, 0)) screen.blit(text, (0, 0))
def apply_colour_to_surface(colour: pygame.Color, shape_surface: pygame.surface.Surface, rect: Union[pygame.Rect, None] = None): """ Apply a colour to a shape surface by multiplication blend. This works best when the shape surface is predominantly white. :param colour: The colour to apply. :param shape_surface: The shape surface to apply the colour to. :param rect: A rectangle to apply the colour inside of. """ if rect is not None: colour_surface = pygame.surface.Surface(rect.size, flags=pygame.SRCALPHA, depth=32) colour_surface.fill(colour) shape_surface.blit(colour_surface, rect, special_flags=pygame.BLEND_RGBA_MULT) else: colour_surface = pygame.surface.Surface(shape_surface.get_size(), flags=pygame.SRCALPHA, depth=32) colour_surface.fill(colour) shape_surface.blit(colour_surface, (0, 0), special_flags=pygame.BLEND_RGBA_MULT)
def draw(self, screen: pygame.surface.Surface): """ Draws all text from the self.rendered_text list. Each entry in this list is a tuple with a rendered string first followed by its position. The rendered string is a surface, so we draw it onto the screen, our main surface. """ for line in self.rendered_text: if line != None: screen.blit(line[0], line[1])
def rendermaze(screen: pygame.surface.Surface, maze: list[Tile], render_walls: bool, render_prev: bool): for entity in maze: screen.blit(entity.surf, entity.rect) if render_walls: renderlines(screen, entity) if render_prev: renderprev(screen, entity)
def draw(screen:pygame.surface.Surface, state:ImageArray) -> None: img = state.copy() # swap axes from cv2 [x][y] style to pygame [y][x] style img = np.swapaxes(img, 0, 1) # move BGR to RGB img = img[...,::-1] surface = pygame.surfarray.make_surface(img) screen.blit(surface, (0, 0)) pygame.display.update()
def draw_colourless_rounded_rectangle( large_corner_radius: int, large_shape_surface: pygame.surface.Surface, clear_colour_string: str = '#00000000', corner_offset: int = 0): """ Draw a rounded rectangle shape in pure white so it is ready to be multiplied by a colour or gradient. :param large_corner_radius: The radius of the corners. :param large_shape_surface: The surface to draw onto, the shape fills the surface. :param clear_colour_string: The colour to clear the background to. :param corner_offset: Offsets the corners, used to help avoid overlaps that look bad. """ if pygame.version.vernum[0] >= 2 and PYGAME_DEV_NUM >= 8: pygame.draw.rect( large_shape_surface, pygame.Color('#FFFFFFFF'), pygame.Rect( (corner_offset, corner_offset), (large_shape_surface.get_width() - corner_offset, large_shape_surface.get_height() - corner_offset)), border_radius=large_corner_radius) else: pygame.draw.circle(large_shape_surface, pygame.Color('#FFFFFFFF'), (large_corner_radius + corner_offset, large_corner_radius + corner_offset), large_corner_radius) if corner_offset > 0: large_shape_surface.fill( pygame.Color(clear_colour_string), pygame.Rect(0, int(large_shape_surface.get_height() / 2), large_shape_surface.get_width(), int(large_shape_surface.get_height() / 2))) large_shape_surface.fill( pygame.Color(clear_colour_string), pygame.Rect(int(large_shape_surface.get_width() / 2), 0, int(large_shape_surface.get_width() / 2), large_shape_surface.get_height())) x_flip = pygame.transform.flip(large_shape_surface, True, False) large_shape_surface.blit(x_flip, (0, 0)) y_flip = pygame.transform.flip(large_shape_surface, False, True) large_shape_surface.blit(y_flip, (0, 0)) large_shape_surface.fill( pygame.Color("#FFFFFFFF"), pygame.Rect((large_corner_radius, 0), (large_shape_surface.get_width() - (2 * large_corner_radius), large_shape_surface.get_height()))) large_shape_surface.fill( pygame.Color("#FFFFFFFF"), pygame.Rect((0, large_corner_radius), (large_shape_surface.get_width(), large_shape_surface.get_height() - (2 * large_corner_radius))))
def render(self, surf: pygame.surface.Surface, events): tmp_screen = copy(self.screen) tmp_events = list(filter(lambda xx: xx.type == pygame.MOUSEBUTTONUP, events)) for bt in self.buttons: bt.surf = tmp_screen bt.draw(tmp_events) surf.blit(tmp_screen, (0, 0))
def draw(self, screen: pygame.surface.Surface): """ Dibuja el tablero en la ventana Args: screen (pygame.surface.Surface): Superficie donde se va a dibujar el tablero. """ screen.blit(self.skin, (0, 0))
def draw_text(self, text, size: int, color: Tuple[tuple, tuple], x: int, y: int, surface: pg.surface.Surface = None) -> Tuple[Surface, Rect]: """A method that draws a text of a surface or the main screen. Fonts have been hardcoded intentionally. Parameters ---------- text: string -> text to be drawn size: int -> size of the text color: tuple -> rgb color of the text x: int -> x coordinate of the text y: int -> y coordinate of the text surface: pg.surface.Surface -> (optional) draws a text on a surface. Tests ----- - passing an invalid surface - passing invalid tuple for the color - passing negative size - passing very large size """ # get the two arcade fonts font_in = pg.font.Font(FONT_ARCADE_IN, size) font_out = pg.font.Font(FONT_ARCADE_OUT, size) # render them to get two surfaces text_in_surface: Surface = font_in.render(str(text), True, color[0]) text_out_surface: Surface = font_out.render(str(text), True, color[1]) text_in_rect: Rect = text_in_surface.get_rect() text_out_rect: Rect = text_out_surface.get_rect() text_in_rect.topleft = (0, 0) text_out_rect.topleft = (0, 0) # create a final surface and blit the two surfaces on it text_surface = Surface(text_in_surface.get_size()) text_surface.blit(text_in_surface, text_in_rect) text_surface.blit(text_out_surface, text_out_rect) # change position to match given x and y text_surface_rect = text_surface.get_rect() text_surface_rect.x = x text_surface_rect.y = y # blit on the given surface if any are provided if surface is None: self.screen.blit(text_surface, text_surface_rect) else: surface.blit(text_surface, text_surface_rect) # return the text_surface so you dont have to draw it again. return text_surface, text_surface_rect
def fade_out(screen: pygame.surface.Surface, background_surface: pygame.surface.Surface, fade_surface: pygame.surface.Surface) -> None: clock = pygame.time.Clock() for i in range(15, 256, 16): fade_surface.set_alpha(i) screen.blit(background_surface, (0, 0)) screen.blit(fade_surface, (0, 0)) clock.tick(20) pygame.display.flip()
def drawTile( self: "MapView", screen: pg.surface.Surface, position: Vector, # World Position tile: pg.surface.Surface, ) -> None: scaledTile = pg.transform.smoothscale( tile, (self.scaledTileSize, self.scaledTileSize) ) screen.blit(scaledTile, self.worldToScreen(position).toTuple())
def main_menu(surface: pygame.surface.Surface): """ Initiates a few required variables (GUI management, fonts, text) """ gui_manager = pygame_gui.UIManager( (constants.window_width, constants.window_height), 'main_menu_theme.json') clock = pygame.time.Clock() font = pygame.font.Font("ARCADECLASSIC.TTF", 98, bold=True) title_img = font.render("Smart Asteroids", True, (200, 200, 200, 200), background_color) title_rect = title_img.get_rect() title_rect.center = (constants.window_width * 0.5, constants.window_height * 235 / 720) title_rect.size = (constants.window_width * 700 // 1280, constants.window_height * 250 // 720) play_button_rect = pygame.Rect((constants.window_width * 470 // 1280, constants.window_height * 405 // 720), (constants.window_width * 340 // 1280, constants.window_height * 80 // 720)) play_button = pygame_gui.elements.UIButton(relative_rect=play_button_rect, text="Play", manager=gui_manager) quit_button_rect = pygame.Rect((constants.window_width * 470 // 1280, constants.window_height * 529 // 720), (constants.window_width * 340 // 1280, constants.window_height * 80 / 720)) quit_button = pygame_gui.elements.UIButton(relative_rect=quit_button_rect, text="Quit", manager=gui_manager) is_running = True while is_running: dt = clock.tick(60) / 1000.0 for event in pygame.event.get(): if event.type == pygame.QUIT: is_running = False if event.type == pygame.USEREVENT: if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == play_button: return game_states.GAME_STATES.IN_GAME elif event.ui_element == quit_button: return game_states.GAME_STATES.QUIT gui_manager.process_events(event) gui_manager.update(dt) surface.fill(background_color) surface.blit(title_img, title_rect) gui_manager.draw_ui(surface) pygame.display.update()
def drawText(surface: pygame.surface.Surface, text: str, size: int, pos: tuple, color: tuple = (0, 0, 0), fontName: str = None): try: font = pygame.font.Font(fontName, size) except: font = pygame.font.SysFont(fontName, size) render = font.render(text, True, color) surface.blit(render, pos)
def draw(screen: pygame.surface.Surface, state: StateArray) -> None: # out = "" # #out = clear_screen() # out += move_cursor(0,0) # for row in state: # for col in row: # out += fg(greys[col])+"██" # out+="\n" # print(out, attr('reset')) surface = pygame.surfarray.make_surface(state) screen.blit(surface, (0, 0)) pygame.display.update()
def draw(self, screen: pygame.surface.Surface): # Фоновое изображение screen.blit(self.image, self.rect) # Вывод текста MARGIN = 24 # Чтобы избежать пустого отступа next_y = 0 for text_surface in self.text_surfaces: y_pos = self.rect.centery + next_y - text_surface.get_height() screen.blit(text_surface, text_surface.get_rect(center=(self.rect.centerx, y_pos))) next_y += MARGIN
def drawEntity( self: "MapView", screen: pg.surface.Surface, entity: GameObject ) -> None: position = entity.location.position # Center position texture = entity.getSprite().image w, h = texture.get_rect().size scaledW, scaledH = int(w * self.zoomRatio), int(h * self.zoomRatio) scaledTexture = pg.transform.scale(texture, (scaledW, scaledH)) screenPos = self.worldToScreen(position) topLeft = screenPos - Vector(scaledW // 2, scaledH // 2) screen.blit(scaledTexture, topLeft.toTuple())
def draw(self, screen: pygame.surface.Surface): """画到屏幕上""" # 状态码为0, 代表正常的表情 if self.status_code == 0: self.image: pygame.surface.Surface = self.images["face_normal"] # 状态码为1, 代表失败的表情 elif self.status_code == 1: self.image: pygame.surface.Surface = self.images["face_fail"] # 状态码为2, 代表成功的表情 elif self.status_code == 2: self.image: pygame.surface.Surface = self.images["face_success"] # 绑定图片到屏幕 screen.blit(self.image, self.rect)
def clear_and_create_shape_surface( surface: pygame.surface.Surface, rect: pygame.Rect, overlap: int, aa_amount: int, clear: bool = True) -> pygame.surface.Surface: """ Clear a space for a new shape surface on the main state surface for this state. The surface created will be plain white so that it can be easily multiplied with a colour surface. :param surface: The surface we are working on. :param rect: Used to size and position the new shape. :param overlap: The amount of overlap between this surface and the one below. :param aa_amount: The amount of Anti Aliasing to use for this shape. :param clear: Whether we should clear our surface. :return: The new shape surface. """ # For the visible AA shape surface we only want to blend in the alpha channel large_shape_surface = pygame.surface.Surface((rect.width, rect.height), flags=pygame.SRCALPHA, depth=32) large_shape_surface.fill(pygame.Color('#00000000')) pygame.draw.ellipse(large_shape_surface, pygame.Color("#FFFFFFFF"), large_shape_surface.get_rect()) if clear: # before we draw a shape we clear a space for it, to allow for transparency. # This works best if we leave a small overlap between the old background # and the new shape subtract_rect = pygame.Rect( rect.x + (overlap * aa_amount), rect.y + (overlap * aa_amount), max(0, rect.width - 2 * (overlap * aa_amount)), max(0, rect.height - 2 * (overlap * aa_amount))) # for the subtract surface we want to blend in all RGBA channels to clear correctly # for our new shape large_sub_surface = pygame.surface.Surface( (subtract_rect.width, subtract_rect.height), flags=pygame.SRCALPHA, depth=32) large_sub_surface.fill(pygame.Color('#00000000')) pygame.draw.ellipse(large_sub_surface, pygame.Color("#FFFFFFFF"), large_sub_surface.get_rect()) surface.blit(large_sub_surface, subtract_rect, special_flags=pygame.BLEND_RGBA_SUB) return large_shape_surface
def drawForeground( self: "MapView", screen: pg.surface.Surface, position: Vector, # World position texture: pg.surface.Surface, ) -> None: w, h = texture.get_rect().size scaledHeight = int(h * self.zoomRatio) scaledTexture = pg.transform.scale(texture, (self.scaledTileSize, scaledHeight)) screenPos = self.worldToScreen(position) topLeft = screenPos + Vector(0, self.scaledTileSize - scaledHeight) screen.blit(scaledTexture, topLeft.toTuple())
def draw(self, screen: pygame.surface.Surface): # Фоновое изображение screen.blit(self.image, self.rect.topleft) # Вывод текста margin = self.font.get_height() * 0.9 # Следующая позиции y (по началу, просто отступ от самого верха) next_y = 20 # Отрисовка поверхностей с текстом # (каждая поверхность - отдельная строка) for text_surface in self.text_surfaces: y_pos = self.rect.top + next_y screen.blit( text_surface, text_surface.get_rect(midtop=(self.rect.centerx, y_pos))) next_y += margin
def flickering(screen: pygame.surface.Surface) -> None: background_surface = screen.copy() flicker_surface = pygame.surface.Surface(screen.get_size()) flicker_surface.fill('white') flicker_surface.set_alpha(128) clock = pygame.time.Clock() for flicker_times in range(10): screen.blit(flicker_surface, (0, 0)) clock.tick(30) pygame.display.flip() screen.blit(background_surface, (0, 0)) clock.tick(30) pygame.display.flip()
def write_text(screen: pg.surface.Surface, size: int, pos: Coordinate, text: str, color: Tuple[int, int, int]) -> None: """왼쪽 위를 위치의 기준으로 하여 텍스트를 쓴다. Args: screen: 텍스트가 렌더링될 Surface size: 텍스트 크기 pos: 텍스트 위치 text: 텍스트 내용 color: 텍스트 색상 """ font = pg.font.SysFont(pg.font.get_default_font(), size) textsurf = font.render(text, True, color) screen.blit(textsurf, parseVector(pos).as_trimmed_tuple())
def premul_alpha_surface( surface: pygame.surface.Surface) -> pygame.surface.Surface: """ Perform a pre-multiply alpha operation on a pygame surface's colours. """ surf_copy = surface.copy() surf_copy.fill(pygame.Color('#FFFFFF00'), special_flags=pygame.BLEND_RGB_MAX) manipulate_surf = pygame.surface.Surface(surf_copy.get_size(), flags=pygame.SRCALPHA, depth=32) # Can't be exactly transparent black or we trigger SDL1 'bug' manipulate_surf.fill(pygame.Color('#00000001')) manipulate_surf.blit(surf_copy, (0, 0)) surface.blit(manipulate_surf, (0, 0), special_flags=pygame.BLEND_RGB_MULT) return surface
def __init__(self, pos: tuple, method, image: pygame.surface.Surface, text: pygame.surface.Surface, mixer, *groups, args: tuple = (), anchor: tuple = (0, 0)): image.blit(text, (image.get_rect().centerx - text.get_rect().centerx, image.get_rect().centery - text.get_rect().centery)) self.method = method self.args = args self.mixer = mixer super().__init__(pos, image, *groups, anchor=anchor)
def render(self, surf: pygame.surface.Surface, field: Field) -> None: # Get the robot pose pose = self.getPose() # Map the coords x = field.getMappedX(pose[0]) + (self._size[1] / 2) y = field.getMappedY(pose[1]) # print((x, y)) # Transform the sprite based on theta rot_sprite = pygame.transform.rotate(self._surf, pose[2] * -1) # Blit the surface to the base surface surf.blit(rot_sprite, (x - (rot_sprite.get_width() / 2), y - (rot_sprite.get_height() / 2)))
def basic_blit(destination: pygame.surface.Surface, source: pygame.surface.Surface, pos: Union[Tuple[int, int], pygame.Rect], area: Union[pygame.Rect, None] = None): """ The basic blitting function to use. WE need to wrap this so we can support pre-multiplied alpha on post 2.0.0.dev10 versions of pygame and regular blitting on earlier versions. :param destination: Destination surface to blit on to. :param source: Source surface to blit from. :param pos: The position of our blit. :param area: The area of the source to blit from. """ destination.blit(source, pos, area, special_flags=pygame.BLEND_PREMULTIPLIED)