Search code examples
python-3.xpygamesprite

Python pygame writing text in sprite


I am making a game where you shall shoot down diffrent boxes with diffrent nummber and text on and was wondring if you can write text as a sprite


Solution

  • class Text(pygame.sprite.Sprite):
        def __init__(self, text, size, color, width, height):
            # Call the parent class (Sprite) constructor  
            pygame.sprite.Sprite.__init__(self)
        
            self.font = pygame.font.SysFont("Arial", size)
            self.textSurf = self.font.render(text, 1, color)
            self.image = pygame.Surface((width, height))
            W = self.textSurf.get_width()
            H = self.textSurf.get_height()
            self.image.blit(self.textSurf, [width/2 - W/2, height/2 - H/2])
    

    I hope that helps, this will draw text centered on surface in a sprite