Lives
Lesson 14 of 40 in Coddy's Make Games with Pygame course.
A miss should cost something. Give the player 3 lives and take one away each time a block falls past the bottom. You already have the place in the code where that happens: the block.top > 360 branch.
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1Show the lives the way you show the score: render f"Lives: {lives}" every frame and blit it in the top right corner, at (370, 10).
Challenge
Easy- Before the loop, set
lives = 3. - Take one away when a block falls past the bottom.
- Render
f"Lives: {lives}"in(240, 240, 240)and blit it at(370, 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()
font = pygame.font.Font(None, 32)
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
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)
score += 1
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
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