Keep Score
Lesson 13 of 40 in Coddy's Make Games with Pygame course.
Text in pygame is a picture of the words. A pygame.font.Font turns a string into a surface, and you draw that surface with screen.blit.
font = pygame.font.Font(None, 32)
text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(text, (10, 10))Font(None, 32) is pygame's built-in font, 32 pixels high. Make it once, before the loop. render(text, True, color) draws the words; True smooths their edges. blit(surface, (x, y)) copies the picture onto the screen with its top left corner at (x, y).
Render the text inside the loop, after the fill. The score changes, and a picture made once keeps showing the old number.
Challenge
Easy- Before the loop, make
font = pygame.font.Font(None, 32)andscore = 0. - Add 1 to
scorewhen the basket catches a block. - After drawing the block, render
f"Score: {score}"in(240, 240, 240)and blit it at(10, 10).
Try it yourself
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
basket.x -= 8
if keys[pygame.K_RIGHT]:
basket.x += 8
basket.clamp_ip(screen.get_rect())
block.y += 3
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
pygame.display.flip()
clock.tick(60)
pygame.quit()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
Practice on your own: Pygame playground