Words on the Screen
Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 8 of 32.
Press Run: the word Comet sits in the top left corner. Three lines put it there:
font = pygame.font.Font(None, 36)
text = font.render("Comet", True, (230, 230, 240))
screen.blit(text, (20, 20))The font is made once, in the setup part: pygame's own font at size 36. render turns a string into a picture in a colour (True smooths its edges), and screen.blit puts that picture on the window, its top left corner at (20, 20). Every game that shows text uses these three lines.
To show a variable's value, write an f-string: an f before the opening quote, and the name in curly brackets:
f"Comet x: {comet_x}"When comet_x holds 58, this is the string Comet x: 58. Without the f, the curly brackets and the name show as written.
Challenge
MediumMake the label show where the comet is: change "Comet" to f"Comet x: {comet_x}". The number counts up as the comet flies.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()
# Set things up here, before the game loop.
moon_x = 160
moon_y = 120
comet_x = 40
comet_y = 200
font = pygame.font.Font(None, 36)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Change things here, once a frame.
comet_x = comet_x + 2
screen.fill((20, 24, 48))
# Draw here, after the fill.
pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)
pygame.draw.circle(screen, (120, 200, 255), (comet_x, comet_y), 8)
text = font.render("Comet", True, (230, 230, 240))
screen.blit(text, (20, 20))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Python in a Game Window
2Numbers and Variables
Name a ValueDo the MathsMove Every FrameWords on the ScreenWhole and Half NumbersPractice on your own: Pygame playground