Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pygame. How to render the text like a all_sprites.update() but all_texts.update()?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading