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

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

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

>Solution :

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

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