Home > OS >  How to insert a text into a sprite in Pygame?
How to insert a text into a sprite in Pygame?

Time:08-15

class Player(pygame.sprite.Sprite):
    def __init__(self, Team, Position):
        super().__init__()
        self.window = pygame.display.set_mode((1280, 800))

        self.red = (255, 0, 0)
        self.blue = (0, 0, 255)

        self.Team = Team
        self.Position = Position
        self.CurrentPosition = ""
        self.PlayerName = self.PlayerFinder('Name')
        if self.PlayerName is None:
            if self.Position == 'LW':
                self.Position = 'LM'
            elif self.Position == 'RW':
                self.Position = 'RM'
            self.PlayerName = self.PlayerFinder('Name')
        self.Nationality = ""
        self.Pace = ""
        self.Shoot = ""
        self.Pass = ""
        self.Dribble = ""
        self.GKDive = ""
        self.Reflex = ""
        # Player
        self.image = pygame.Surface([20, 20])
        self.rect = self.image.get_rect()

    def DrawPlayerShape(self, co_ordinate, colouropt):
        self.CurrentPosition = co_ordinate
        # Colour option
        colour = ""
        if colouropt == 'R':
            colour = self.red
        elif colouropt == 'B':
            colour = self.blue

        # Player's shape as a sprite
        self.image.fill(colour)
        self.rect.center = co_ordinate

        # Player's football position shown in the shape
        if self.Position == 'CDM':  # this ensures that they will fit inside the player shape
        text_type = pygame.font.SysFont('arialunicode', 11).render(self.Position, True, (
            0, 0, 0))
        else:
            text_type = pygame.font.SysFont('arialunicode', 15).render(self.Position, True, (
            0, 0, 0))
        self.image.blit(text_type, self.image)

st = Player()
st.DrawPlayerShape()

I have tried to add text to my sprite, but it does not work. The closest I have gotten to it, is I managed to write text, but it was underneath the sprite. How do I add text to the sprite which will stay there, even if it moves?

CodePudding user response:

self.image.blit(text_type, self.image) makes no sense because the second argument of blit must be a tuple with the coordinates or a rectangle. If you want to put the text in the center of the Surface, you have to get the bounding rectangle of the text Surface and set the center of the rectangle with the center of the target Surface. Use the rectangle to blit the text on the Surface:

image_center = self.image.get_rect().center
self.image.blit(text_type, text_type.get_rect(center = image_center))
  • Related