def finish(score: int, total: int, screen: pg.Surface, font: pg.font.Font, background: pg.Surface): screen.fill('black') screen.blit(background, (0, 0)) screen.blit(background, (0, 300)) first_text = font.render('Вы набрали %d очков из %d' % (score, total), True, pg.Color('red')) second_text = font.render('Чтобы начать заново,', True, pg.Color('red')) third_text = font.render('нажмите пробел', True, pg.Color('red')) width, height = screen.get_size() screen.blit(first_text, (width // 2 - first_text.get_width() // 2, height // 2 - first_text.get_height() // 2 - second_text.get_height())) screen.blit(second_text, (width // 2 - second_text.get_width() // 2, height // 2 - second_text.get_height() // 2 + second_text.get_height())) screen.blit(third_text, (width // 2 - third_text.get_width() // 2, height // 2 - second_text.get_height() // 2 + second_text.get_height() * 2)) pg.display.flip() while True: for event in pg.event.get(): if event.type == pg.QUIT: return False elif event.type == pg.KEYDOWN and event.key == pg.K_SPACE: return True
def __init__(self, title: str, pos: Tuple[int, int], title_font: pygame.font.Font): self.title = title_font.render(title, True, (244, 221, 183)) self.shadow = title_font.render(title, True, (61, 49, 42)) self.title_pos = self.title.get_rect(center=pos) self.shadow_pos = self.shadow.get_rect(center=(pos[0] + 10, pos[1] + 2)) self.menu: List[MenuButton] = []
def update_screen(f: pygame.font.Font) -> None: gl.SCREEN.fill(gl.PALEBLUE) pygame.draw.line(gl.SCREEN, gl.WHITE, [0, 30], [gl.WIDTH, 30], 2) text = f.render("Score: " + str(score), 1, gl.WHITE) gl.SCREEN.blit(text, (20, 10)) text = f.render("Lives: " + str(lives), 1, gl.WHITE) gl.SCREEN.blit(text, (gl.WIDTH - 150, 10)) gl.SPRITES.draw(gl.SCREEN) pygame.display.flip() gl.CLOCK.tick(60)
def draw(self, screen: pygame.Surface, font: pygame.font.Font): pygame.draw.rect(screen, self.color, [self.x, self.y, Sett.gridSize, Sett.gridSize]) displayValue = self.value if self.value != math.inf else 'inf' textsurface = font.render(str(displayValue), False, Sett.WHITE) screen.blit( textsurface, (self.x + Sett.gridSize / 2 - 10, self.y + Sett.gridSize / 2 - 10)) textsurface = font.render(self.name, False, Sett.DARK_VIOLET) screen.blit(textsurface, (self.x - 20, self.y - 20))
def score_display(game_font: pygame.font.Font, score: int, high_score: int, game_active: bool, screen) -> None: score_surface = game_font.render(f"Score: {int(score)}", True, (255, 255, 255)) score_rect = score_surface.get_rect(center=(288, 100)) screen.blit(score_surface, score_rect) if not game_active: high_score_surface = game_font.render(f"High Score: {int(high_score)}", True, (255, 255, 255)) high_score_rect = high_score_surface.get_rect(center=(288, 850)) screen.blit(high_score_surface, high_score_rect)
def __init__(self, text: str, font: pygame.font.Font, action_handler: ClickHandler) -> None: super().__init__() self.text = text self.text_surface = font.render(text, True, BLACK) self.text_surface_active = font.render(text, True, WHITE) self.text_rect = self.text_surface.get_rect() self.rect = self.text_surface.get_rect().copy() self.rect.width += 10 self.rect.height += 10 self.action_handler = action_handler self.focused = False self.hovering = False
def __init__(self, font: pygame.font.Font, message: str): self.font = font self.message = message self.image = pygame.Surface(300, 100) self.rect = self.image.get_rect().move(200, 100) message_rendered = font.render(message, False, cfg.WHITE) self.image.blit(message_rendered, (0, 0))
def __init__(self, teamID, x, y, font:pygame.font.Font): super().__init__(teamID, x, y, font) self.name = font.render("Cloning", True, (200, 200, 180)) self.sprID = 4 self.sprite = SPR_CLONE self.buildOptions.append(Button(SPR_CLONE[0], self.font, "Upgrade", cost={'$':80, 'ß':30, '¶':0}, rate=1)) self.buildOptions.append(Button(SPR_MAKEBODY[0], self.font, "Clone Bodies", additionalText="Gain ¶1/2 sec", rate=2.125))
def add_text(self, text, font: pygame.font.Font, colour=(0, 0, 0), *args, **kwargs): """ Adds text as content. """ blit = font.render(text, True, colour) self._content.append(self.PanelContent(self._content_offset, self.next_y(), text, blit)) self._redraw()
def __init__(self, text: str, font: pygame.font.Font, position: tuple, dims: tuple, func, arg: list = None, keybinding=None, text_aa=True, text_colour: tuple = (255, 255, 255), background_colour: tuple = (40, 40, 40), border_colour: tuple = (0, 0, 0), border_width: int = 1, expand: bool = True, padx: int = 0, pady: int = 0, centered: bool = True, *args, **kwargs): self._text = text self._func = func self._args = arg # Create the text blit of the button txt_blit = font.render(text, text_aa, text_colour) txt_dims = (txt_blit.get_width(), txt_blit.get_height()) # IF we want to expand, check if the text is bigger than the given dimensions if not expand: self._dims = dims else: self._dims = (max(txt_dims[0], dims[0]) + padx, max(txt_dims[1], dims[1]) + pady) # Create the final surface and apply the background colour and border blit = pygame.Surface(self._dims, pygame.SRCALPHA, 32).convert_alpha() blit.fill(background_colour) if border_width > 0: pygame.draw.rect(blit, border_colour, pygame.Rect(0, 0, self._dims[0], self._dims[1]), border_width) # Blit the text to it blit.blit(txt_blit, (self._dims[0] / 2 - txt_dims[0] / 2, self._dims[1] / 2 - txt_dims[1] / 2)) self._blit = blit if centered: self._position = (position[0] - blit.get_width() / 2, position[1] - blit.get_height() / 2) else: self._position = position self._hidden = False self._keybinding = keybinding
def _print_to_image(text: str, x: int, y: int, font: pygame.font.Font, image: pygame.Surface, colour: Tuple[int, int, int] = TEXT_COLOUR) -> None: """Use <font> to print <text> to (<x>, <y>) on <image> with <colour>. """ text_surface = font.render(text, 1, colour) image.blit(text_surface, (x, y))
def draw_text(surface: pg.Surface, font: pg.font.Font, text: str, color, rect: pg.Rect): """ Draws outlined text to the given surface """ render = font.render(text, False, color) outline = font.render(text, False, TEXT_OUTLINE_COLOR) surface.blit(outline, [rect.x - TEXT_OUTLINE_THICKNESS, rect.y, *rect.size]) surface.blit(outline, [rect.x + TEXT_OUTLINE_THICKNESS, rect.y, *rect.size]) surface.blit(outline, [rect.x, rect.y - TEXT_OUTLINE_THICKNESS, *rect.size]) surface.blit(outline, [rect.x, rect.y + TEXT_OUTLINE_THICKNESS, *rect.size]) surface.blit(render, rect)
def __init__(self, x: int, y: int, width: int, height: int, surface: pygame.Surface, surface_hover: pygame.Surface, surface_click: pygame.Surface, text: str, text_color: (int, int, int), font: pygame.font.Font, on_click: Callable[[], None]): super().__init__() # Scale the images to the desired size (doesn't modify the originals). self.surface = pygame.transform.scale(surface, (width, height)) self.surface_hover = pygame.transform.scale(surface_hover, (width, height)) self.surface_click = pygame.transform.scale(surface_click, (width, height)) self.image = self.surface self.rect = self.surface.get_rect(topleft=(x, y)) image_center = self.surface.get_rect().center text_surface = font.render(text, True, text_color) text_rect = text_surface.get_rect(center=image_center) # Blit the text onto the images. for image in (self.surface, self.surface_hover, self.surface_click): image.blit(text_surface, text_rect) self.on_click = on_click self.is_clicked = False
def blit(self, dims, text_font: pygame.font.Font): """ Returns the blit of the map. """ surface = pygame.Surface(dims, pygame.SRCALPHA, 32).convert_alpha() for place in self._places: pairs = place.connection_points() for a, b in pairs: self._draw_bezier(surface, a, b) for place in self._places: blit = place.blit() if blit: if place == self._selected_place: blit.fill((0, 120, 240, 20), special_flags=pygame.BLEND_RGB_MULT) txt_blit = text_font.render(place.name, True, (0, 0, 0)) x, y = blit.get_size() x = x / 2 - txt_blit.get_width() / 2 y = y / 2 - txt_blit.get_height() / 2 blit.blit(txt_blit, (x, y)) surface.blit(blit, place.position) return surface
def draw_middle_text(self, string, font: pygame.font.Font, space): text = font.render(string, False, (255, 255, 255)) text_rect = text.get_rect() coordinates = (self.width / 2 - text_rect.width / 2, self.height / 2 - text_rect.height / 2) self.screen.blit(text, (coordinates[0], coordinates[1] + space)) return space + font.get_linesize() - 4 * self.pixel_scale
def render_white_text_alpha_black_bg(font: pygame.font.Font, text: str) -> pygame.surface.Surface: """ Render text with a zero alpha background with 0 in the other colour channels. Appropriate for use with BLEND_PREMULTIPLIED and for colour/gradient multiplication. """ if USE_PREMULTIPLIED_ALPHA: text_render = font.render(text, True, pygame.Color('#FFFFFFFF')) final_surface = pygame.surface.Surface(text_render.get_size(), flags=pygame.SRCALPHA, depth=32) # Can't be exactly transparent black or we trigger SDL1 'bug' final_surface.fill(pygame.Color('#00000001')) final_surface.blit(text_render, (0, 0)) return final_surface else: return font.render(text, True, pygame.Color('#FFFFFFFF'))
def drawText(self, text, color, shadow_color, rect, font: pygame.font.Font, scale=False): rect = pygame.Rect(rect) y = rect.top lineSpacing = -2 fontHeight = font.size("Tg")[1] while text: i = 1 if y + fontHeight > rect.bottom: break while font.size(text[:i])[0] < rect.width and i < len(text): i += 1 if i < len(text): i = text.rfind(" ", 0, i) + 1 image = font.render(text[:i], False, color).convert_alpha() shadow = font.render(text[:i], False, shadow_color).convert_alpha() if scale: image = pygame.transform.smoothscale(image, (int( image.get_rect().size[0] * 0.9), image.get_rect().size[1])) shadow = pygame.transform.smoothscale( shadow, (int(shadow.get_rect().size[0] * 0.9), shadow.get_rect().size[1])) self.screen.blit(shadow, (rect.left + (self.window_size[0] / 240) * (fontHeight / 36), y + (self.window_size[1] / 160) * (fontHeight / 36))) self.screen.blit(image, (rect.left, y)) y += fontHeight + lineSpacing text = text[i:] return text
def _get_instruction_surfaces(instructions, font: pygame.font.Font, color, padding: int): instruction_surfaces = [] for el in instructions: keys, instruction_text = el["keys"], el["text"] text_surface = font.render(instruction_text, True, color) instruction_surface = InstructionSurface(keys, text_surface, padding) instruction_surfaces.append(instruction_surface) return instruction_surfaces
def objets_texte(texte: str, police: pygame.font.Font) -> (list, list): """Une fonction qui retourne un texte comme surface, et le rectangle couvert par le texte :param texte: (str) qui est le texte destiné à être transformé en objet Surface :param police: la police du texte :return: le texte comme objet surface et le rectangle couvert par le texte """ surface_texte = police.render(texte, True, (0, 0, 0)) return surface_texte, surface_texte.get_rect()
def draw_score(self, window: pygame.Surface, font: pygame.font.Font): transparent_rect = pygame.Surface((95, 25), pygame.SRCALPHA) transparent_rect.fill((50, 50, 50, 80)) message = f"Score: {self.score} " w, h = font.size(message) window.blit(pygame.transform.scale(transparent_rect, (w, h)), (8, Application.WINDOW_HEIGHT - 30)) window.blit(font.render(message, True, (255, 255, 255)), (10, Application.WINDOW_HEIGHT - 30))
def __init__(self, teamID, x, y, font:pygame.font.Font): super().__init__(teamID, x, y, font) self.name = font.render("Empty Space", True, (200, 200, 180)) self.sprID = 0 self.buildOptions.append(Button(SPR_FORGE[0], self.font, "Build Forge", cost={'$':50, 'ß':0, '¶':0}, rate=1)) self.buildOptions.append(Button(SPR_ARMOR[0], self.font, "Build Armory", cost={'$':50, 'ß':0, '¶':0}, rate=1)) self.buildOptions.append(Button(SPR_CLONE[0], self.font, "Build Cloning", cost={'$':30, 'ß':0, '¶':0}, rate=1)) self.buildOptions.append(Button(SPR_MINES[0], self.font, "Build Mines", cost={'$':30, 'ß':0, '¶':0}, rate=1)) self.sprite = SPR_EMPTY
def createTextObj(text: str, font_object: pygame.font.Font): """ Creates a text object with a string and a font :type font_object: pygame.font.Font(font_name, 75) :param text: string to display :param font_object: font in which to display text :return: a surface with the text and its rect """ textSurface = font_object.render(text, True, colors["white"]) return textSurface, textSurface.get_rect()
def create_text_obj(self, text: str, font: pg.font.Font = None, color=(255, 0, 0), **kwargs_rect) -> Tuple[pg.Surface, pg.Rect]: if font is None: font = self.default_font surface = font.render(text, 1, color) rect = surface.get_rect(**kwargs_rect) return surface, rect
def __init__(self, teamID, x, y, font:pygame.font.Font): super().__init__(teamID, x, y, font) self.name = font.render("Armory", True, (200, 200, 180)) self.sprID = 2 self.sprite = SPR_ARMOR self.buildOptions.append(Button(SPR_ARMOR[0], self.font, "Upgrade", cost={'$':80, 'ß':30, '¶':0}, rate=1)) if teamID == 0: self.buildOptions.append(Button(Units.SPR_B2IR[0], self.font, "Produce Sword", cost={'$':10, 'ß':0, '¶':1}, rate = 3)) if teamID == 1: self.buildOptions.append(Button(Units.SPR_R2IL[0], self.font, "Produce Sword", cost={'$':10, 'ß':0, '¶':1}, rate = 3)) self.buildOptions.append(Button(SPR_CLONE[0], self.font, "Weapons Research", additionalText="Generates: ß1/sec", rate=4.25))
def __init__(self, teamID, x, y, font:pygame.font.Font): super().__init__(teamID, x, y, font) self.name = font.render("Mine", True, (200, 200, 180)) self.sprID = 3 self.sprite = SPR_MINES self.buildOptions.append(Button(SPR_MINES[0], self.font, "Upgrade", cost={'$':80, 'ß':30, '¶':0}, rate=1)) self.buildOptions.append(Button(SPR_DOLLAR[0], self.font, "Mine Resources", additionalText="Generates: $1/sec", rate=4.25)) if teamID == 0: self.buildOptions.append(Button(Units.SPR_BIR[0], self.font, "Call Militia", cost={'$':5, 'ß':0, '¶':1}, rate = 3)) if teamID == 1: self.buildOptions.append(Button(Units.SPR_RIL[0], self.font, "Call Militia", cost={'$':5, 'ß':0, '¶':1}, rate = 3))
def __init__(self, text: str, font: pygame.font.Font, color: pygame.Color, margin: typing.Optional[typing.Tuple[int, int, int, int]] = (0, 0, 0, 0)): super().__init__(margin) self.__text = text self.__font = font self.__color = color self.__surface = font.render(text, False, color)
def draw(self, window: pygame.Surface, font: pygame.font.Font, camera): view = camera.get_view() pygame.draw.circle(window, BLUE, (self.vec2.x + view.x, self.vec2.y + view.y), self.size * camera.zoom) text = font.render(self.name, True, WHITE) text_rect = text.get_rect(center=(self.vec2.x + view.x, self.vec2.y + view.y)) window.blit(text, text_rect) # Draw score self.draw_score(window, font)
def __init__(self, x : int, y : int, text : Union[str,"pygame.image"], callback : Callable, font : pygame.font.Font = FONT_MENU_ITEM, fontAntialias : bool = True, fontColor : Union[Tuple[int,int,int], pygame.Color] = (0, 0, 0), background : Optional[Union[Tuple[int,int,int], pygame.Color]] = None, **kwargs ) -> None: # use kwargs["padding"] to initially define padding self.padding = kwargs.get("padding", 0) if isinstance(self.padding, int): self.padding = dict((side, self.padding) for side in Side) for side in Side: # update ``padding[side]`` individually self.padding[side] = kwargs.get("padding_{}".format(side), self.padding[side]) self.font = font if isinstance(text, str): self.text_surface = font.render(text, fontAntialias, fontColor) else: # assuume it is a surface self.text_surface = text # great names.. best names.. big hands.. fake news self.text_pos = kwargs.get("text_pos", (0, 0)) w, h = (sum(t) for t in zip( self.text_surface.get_size(), self.text_pos, (self.padding[Side.left], self.padding[Side.top]), (self.padding[Side.right], self.padding[Side.bottom]))) super().__init__(x, y, w, h, **kwargs) self.rect = pygame.Rect( (x, y), tuple(sum(t) for t in zip( self.text_surface.get_size(), self.text_pos, (self.padding[Side.left], self.padding[Side.top]), (self.padding[Side.right], self.padding[Side.bottom]), )) ) if isinstance(text, str): if self.background is None: self.surface.fill((1, 1, 1)) self.surface.set_colorkey((1, 1, 1)) else: self.surface.fill(background) self.surface.blit(self.text_surface, self.text_pos) else: # assume it's a surface self.surface = text # great names.. best names.. big hands.. fake news self.text_pos = tuple(sum(t) for t in zip(self.text_pos, (self.padding[Side.left], self.padding[Side.top]))) self.callback = callback
def __init__(self, lbl_msg: str, pos: tuple, font: pygame.font.Font = main_font(2), color: tuple = (0, 0, 0), has_rect: bool = False, rect_color: tuple = (255, 255, 255)): self.lbl_obj = font.render(lbl_msg, 0, color) self.lbl_box = self.lbl_obj.get_rect() self.lbl_box.topleft = pos self.has_rect = has_rect self.rect_color = rect_color
def update_screen(bf: pygame.font.Font, nf: pygame.font.Font, curr_score: int, scores: List): gl.SPRITES.update() gl.SCREEN.fill(gl.PALEBLUE) gl.SPRITES.draw(gl.SCREEN) text = bf.render("Congratulation!", 1, gl.WHITE) gl.SCREEN.blit(text, (int(gl.WIDTH / 2 - text.get_width() / 2), 100)) text = nf.render("Your score: " + str(curr_score), 1, gl.WHITE) gl.SCREEN.blit(text, (int(gl.WIDTH / 2 - text.get_width() / 2), 175)) text = nf.render("High scores:", 1, gl.WHITE) gl.SCREEN.blit(text, (int(gl.WIDTH / 2 - text.get_width() / 2), 300 - text.get_height() - 10)) for i in range(len(scores)): text = nf.render(f'{i+1}. {scores[i]}', 1, gl.WHITE) gl.SCREEN.blit(text, (int(gl.WIDTH / 2 - text.get_width() / 2), 300 + i * (text.get_height() + 10))) pygame.display.flip() gl.CLOCK.tick(60)
def game_loop(screen: pygame.Surface, font: pygame.font.Font) -> None: clock = pygame.time.Clock() snake = Snake() fruit = Fruit() # sound = pygame.mixer.Sound("/tmp/peep.ogg") while True: events = pygame.event.get() handle_quit(events) # paint the entire screen screen.fill(pygame.color.Color("black")) if snake.pos_x == fruit.pos_x and snake.pos_y == fruit.pos_y: # sound.play() snake.increase() fruit.regenerate() if snake.tail_collision(): snake.reset() # paint the snake snake.update(events) snake.draw(screen) # paint the fruit fruit.update() fruit.draw(screen) score = font.render( "score: %s" % snake.tail, 1, pygame.color.Color("white")) screen.blit(score, (0, 0)) # update the screen pygame.display.update() # deal with frames per second clock.tick(FPS)