Home > Mobile >  How to render the text like a all_sprites.update() but all_texts.update()?
How to render the text like a all_sprites.update() but all_texts.update()?

Time:10-23

I have a programm where i have a lot of text objects.

And i want to render it all by 1 command like a sprite.

For example:

all_sprites = pygame.sprite.Group()
sprite1 = mySprite([args])
sprite2 = mySprite([args])
all_sprite.add(sprite1, sprite2)
while True:
     all_sprites.update(([width, height])) 

in the Class mySprite() we have a def update() what working with calling by Class Group()

I want to doo this operation not with sprites but with text. Can i did that by pygame instrumental? Or i want make this class (like a class Group()) by myself? If the second option, then how i can make it

CodePudding user response:

A rendered text is simply a pygame.Surface object. All you need to do is set the image attribute of the pygame.sprite.Sprite object with the rendered text surface and the rect attribute with the position of the text.

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

font = pygame.font.SysFont(None, 100)

class Text(pygame.sprite.Sprite):
    def __init__(self, font, text, color, center_pos):
        super().__init__() 
        self.image = font.render(text, True, color)
        self.rect = self.image.get_rect(center = center_pos)

all_text = pygame.sprite.Group()
all_text.add(Text(font, "Hello", "white", (200, 150)))
all_text.add(Text(font, "World!", "white", (200, 250)))

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    window.fill(0)
    all_text.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

  • Related