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 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, 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 __init__(self, relative_rect: pygame.Rect, image_surface: pygame.surface.Surface, manager: IUIManagerInterface, container: Union[IContainerLikeInterface, None] = None, parent_element: UIElement = None, object_id: Union[ObjectID, str, None] = None, anchors: Dict[str, str] = None, visible: int = 1): super().__init__(relative_rect, manager, container, starting_height=1, layer_thickness=1, anchors=anchors, visible=visible) self._create_valid_ids(container=container, parent_element=parent_element, object_id=object_id, element_id='image') self.original_image = None # GUI images must support an alpha channel & must have their alpha channel pre-multiplied # with their colours. image_surface = premul_alpha_surface(image_surface.convert_alpha()) if (image_surface.get_width() != self.rect.width or image_surface.get_height() != self.rect.height): self.original_image = image_surface self.set_image( pygame.transform.smoothscale(self.original_image, self.rect.size)) else: self.set_image(image_surface)
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 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(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(self, screen: pygame.surface.Surface): width = screen.get_width() height = screen.get_height() for i in range(config.vertInrNum): pygame.draw.line(screen, (0, 0, 0), (0, i * config.vertInr), (width, i * config.vertInr)) for i in range(1, config.horzInrNum): pygame.draw.line(screen, (0, 0, 0), (i * config.horzInr, 0), (i * config.horzInr, height))
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 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 draw(self, screen: pygame.surface.Surface): for pos in self.pos: # 绘制蛇身 rect = pygame.rect.Rect(pos[0] * config.horzInr, pos[1] * config.vertInr, config.horzInr + 2, config.vertInr + 2) color = (0, 0, 255) screen.fill(color, rect) # 绘制蛇的两个眼睛 if pos == self.pos[0]: rectL = rect rectL.width /= 4 rectL.height /= 4 rectR = rectL.copy() curDir = self.getCurDir() if curDir == Direction.UP: rectL.center = (pos[0] * config.horzInr + config.horzInr / 4, pos[1] * config.vertInr + config.vertInr / 4) rectR.center = (pos[0] * config.horzInr + config.horzInr / 4 * 3, pos[1] * config.vertInr + config.vertInr / 4) elif curDir == Direction.DOWN: rectL.center = (pos[0] * config.horzInr + config.horzInr / 4 * 3, pos[1] * config.vertInr + config.vertInr / 4 * 3) rectR.center = (pos[0] * config.horzInr + config.horzInr / 4, pos[1] * config.vertInr + config.vertInr / 4 * 3) elif curDir == Direction.LEFT: rectL.center = (pos[0] * config.horzInr + config.horzInr / 4, pos[1] * config.vertInr + config.vertInr / 4 * 3) rectR.center = (pos[0] * config.horzInr + config.horzInr / 4, pos[1] * config.vertInr + config.vertInr / 4) elif curDir == Direction.RIGHT: rectL.center = (pos[0] * config.horzInr + config.horzInr / 4 * 3, pos[1] * config.vertInr + config.vertInr / 4) rectR.center = (pos[0] * config.horzInr + config.horzInr / 4 * 3, pos[1] * config.vertInr + config.vertInr / 4 * 3) color = (250, 235, 215) pygame.draw.ellipse(screen, color, rectL) pygame.draw.ellipse(screen, color, rectR)
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 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 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(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 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 __init__(self, surf: pygame.surface.Surface, border: int, border_radius: int, progress: int, max_progress=100): self.color = (243, 246, 250) self.border_radius = border_radius self.border_color = (0, 22, 87) self.x = 0 self.y = 0 self.height = surf.get_height() self.width = surf.get_width() self.surf = surf self.border_width = border self.progress = progress self.max_progress = max_progress self.bg_color = (0, 0, 34)
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 fall(self, gameObject: Game, fen: pygame.surface.Surface, frames: int = 30): #Animation to do start_pos = (self.p.x + self.p.w, self.p.y) alphas = [pi / (2 * frames) * i for i in range(frames + 1)][::-1] for alpha in alphas: fen.fill((0, 0, 0)) end_pos = (start_pos[0] + self.l * cos(-alpha), start_pos[1] + self.l * sin(-alpha)) pygame.draw.line(fen, (0, 255, 0), start_pos, end_pos, 1) gameObject.rendering([False, True, False, True])
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 result(displaysurf: pg.surface.Surface, clock: pg.time.Clock, diff: str, diff_color: Tuple[int, int, int], score: int) -> None: """스코어보드를 업데이트하고 출력한다. Args: displaysurf: init 함수에 의해 반환된 최상위 Surface clock: init 함수에 의해 반환된 Clock diff: prompt_difficulty 함수에 의해 반환된 난이도 diff_color: prompt_difficulty 함수에 의해 반환된 난이도에 해당하는 색상 score: game 함수에 의해 반환된 점수 """ scorefile: Path = Path.cwd() / ct.SCOREDIR / f"{diff}.pkl" scores: List[int] = [] try: scores = pickle.load(scorefile.open("rb")) except FileNotFoundError: pass scores.append(score) scores.sort() scores.reverse() scores = scores[:5] pickle.dump(scores, scorefile.open("wb")) displaysurf.fill(ct.BLACK) write_text_ct(displaysurf, 60, (ct.WIDTH / 2, ct.HEIGHT * 0.15), f'Score ({diff})', diff_color) for i, sco in enumerate(scores): write_text_ct(displaysurf, 40, (ct.WIDTH / 2, ct.HEIGHT * (0.3 + 0.1 * i)), f'{i + 1}. {sco}', ct.WHITE) write_text_ct(displaysurf, 40, (ct.WIDTH / 2, ct.HEIGHT * 0.85), f'Your score: {score}', ct.WHITE) while True: for event in pg.event.get(): if event.type == pg.QUIT\ or (event.type == pg.KEYDOWN and event.key == ord('q')): # 종료 pg.quit() sys.exit() pg.display.update() clock.tick(ct.FPS)
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 update(self, screen: pygame.surface.Surface) -> bool: self.rect = screen.get_rect() self.update_humans_to_zombies() self.update_eaten_food() self.check_and_fix_edges() self.check_food() return not self.all_dead()
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 draw(self, surface: pygame.surface.Surface) -> None: """Draws all sprites in the group on the provided surface :param surface: A surface """ sprites = self.sprites() if self._is_flipped: # pyre-ignore[6]: to_blits = [(spr.image, self.transform_rect_y(surface, spr.rect)) for spr in sprites] else: # pyre-ignore[6]: to_blits = [(spr.image, self.transform_rect_x(surface, spr.rect)) for spr in sprites] self.spritedict.update( # pyre-ignore[6]: zip( sprites, # pyre-ignore[6]: # pyre-ignore[20]: surface.blits(to_blits))) # pyre-ignore[8]: self.lostsprites = [] # pylint: disable=W0201
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)