Why the formated variable is not being updated on the screen and how to fix it

Viewed 32

The key space adds +2 to the variable player.mana, when pressed i see the variable incrementing on the console, but the formated string text on the screen don't. How to show it correctly on the screen?

import pygame
import sys

pygame.init()

clock = pygame.time.Clock()
font = pygame.font.SysFont('Arial', 30)
screen = pygame.display.set_mode((640, 480))
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)


class Players:
    def __init__(self, mana):
        self.mana = mana


player = Players(0)

text_player_mana = font.render(f'Mana: {player.mana}', True, WHITE)

running = True
while running:
    screen.fill(BLACK)
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        keys = pygame.key.get_pressed()

        if event.type == pygame.KEYDOWN:
            if keys[pygame.K_ESCAPE]:
                running = False
            if keys[pygame.K_SPACE]:
                player.mana += 2

    screen.blit(text_player_mana, (200, 200))
    print(player.mana)
    pygame.display.update()

pygame.quit()
sys.exit()
1 Answers

The variable and the rendered Surface are not tied. The Surface does not magically change when you change the variable. You need to re-render the Surface when the variable changes:

text_player_mana = font.render(f'Mana: {player.mana}', True, WHITE)

running = True
while running:
    screen.fill(BLACK)
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        keys = pygame.key.get_pressed()

        if event.type == pygame.KEYDOWN:
            if keys[pygame.K_ESCAPE]:
                running = False
            if keys[pygame.K_SPACE]:
                player.mana += 2

                # player.mana has changed, so text_player_mana needs to be rendered
                text_player_mana = font.render(f'Mana: {player.mana}', True, WHITE)

    screen.blit(text_player_mana, (200, 200))
    print(player.mana)
    pygame.display.update()
Related