Home > Back-end >  Using formatting to display a score in pygame
Using formatting to display a score in pygame

Time:09-03

so i'm trying to display a score in my game when the player picks up a coin, the score is added by 1:

main.py

scorefont=pygame.font.Font('Fonts/Pixeltype.ttf',50)
score=scorefont.render('Score: {}'.format(level.score),False,'White')
game_active=True
while game_active:
     screen.blit(score,(0,0))

level.py

class Level:
    def __init__(self,level_data,surface):
        self.display_surface=surface
        self.level_building(level_data)
        self.world_shift=0
        self.score=0


playercoin=pygame.sprite.groupcollide(self.coins,self.player,True,False)
        if len(playercoin)==1:
            self.score =1

However, the score does not get updated in the actual game. I've debugged it, and found out the score is being updated, but the display isn't updated. Where did i go wrong in my code? (All variables are defined, i just didn't show me defining them)

(score is supposed to be 1)

enter image description here

value of the score variable

enter image description here

CodePudding user response:

The rendered surface does not magically change when you change the score. The rendered surface and the score are not tied. You need to render the score surface again with the new score when the score changes:

playercoin=pygame.sprite.groupcollide(self.coins,self.player,True,False)
if len(playercoin)==1:
    global score
    self.score =1
    score=scorefont.render('Score: {}'.format(self.score),False,'White')
  • Related