AnonymousPerson
AnonymousPerson

Reputation: 15

Pygame how do I display a variable?

I am making a game in which you click on a coin and get coins, and I am trying to display the amount of coins you get, but it isn't displayed.

the code:

text = basicFont.render(str(coins), True, WHITE, BLACK)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery

Upvotes: 1

Views: 3629

Answers (2)

Anthony Pham
Anthony Pham

Reputation: 3106

You can use something similar to this:

score = 0
score_font = pygame.font.Font(None, 50)
score_surf = score_font.render(str(score), 1, (0, 0, 0))
score_pos = [10, 10]

score here is the variable, which can be changed via functions in the class(es). score_font will determine the font and size the text will be in. score_surf will be used to render the text onto the surface. It will need the variable with the necessary string, the number 1 (I not quite sure why), and the color in which the text will be. score_pos will be used to blit the text onto the specific coordinates given. Here is how you blit the text onto the screen:

screen.blit(score_surf, score_pos)

I hope this helps you!

Upvotes: 0

A.J. Uppal
A.J. Uppal

Reputation: 19264

Once you make your object, draw it into your screen with windowSurface.blit(text, (x1, y1). Then call pygame.display.flip() to show it.

As in:

import pygame, sys
from pygame.locals import *

pygame.init()
windowSurface = pygame.display.set_mode()

myfont = pygame.font.SysFont("monospace", 15)

while True
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    # render text
    label = myfont.render("Some text!", 1, (255,255,0))
    windowSurface.blit(label, (100, 100))
    pygame.display.flip()

Upvotes: 1

Related Questions