Menu
CoddyTech
flag Pt iconPortuguêsdown icon

Vidas

Lição 14 de 40 do curso Crie jogos com Pygame da Coddy.

Uma colisão deve ter um custo. Dê 3 vidas ao jogador e retire uma sempre que um bloco cair além da parte inferior. Você já tem o trecho do código onde isso acontece: o ramo block.top > 360.

if block.top > 360:
    block.y = -20
    block.x = random.randint(0, 460)
    lives -= 1

Exiba as vidas da mesma forma que exibe a pontuação: renderize f"Lives: {lives}" a cada quadro e faça o blit no canto superior direito, em (370, 10).

challenge icon

Desafio

Fácil
  1. Antes do laço, defina lives = 3.
  2. Subtraia uma vida quando um bloco cair além da parte inferior.
  3. Renderize f"Lives: {lives}" em (240, 240, 240) e copie-o para (370, 10).

Experimente você mesmo

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()
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Crie jogos com Pygame

Pratique por conta própria: Playground de Pygame