Menu
CoddyTech

Puntos de anclaje

Parte de la sección Reglas del juego del Journey de Pygame de Coddy. Lección 7 de 29.

Una puntuación dibujada en (10, 10) empieza en el borde izquierdo. Para que termine en el borde derecho, necesitas su ancho, y el ancho cambia a medida que aumenta el número. Un Rect hace los cálculos por ti.

text.get_rect() acepta argumentos con nombre para cualquiera de sus puntos: center, topleft, topright, midtop, midbottom y más. El Rect se coloca de modo que ese punto quede donde indiques:

score_rect = score_text.get_rect(topright=(470, 10))
screen.blit(score_text, score_rect)

Ahora el borde derecho de la puntuación se mantiene en 470, tanto si muestra 0 como si muestra 1000.

El texto sobre un fondo recargado es más fácil de leer sobre una placa. inflate(12, 8) devuelve una copia del Rect 12 píxeles más ancha y 8 más alta, con el mismo centro. Dibújala primero y después dibuja el texto encima:

pygame.draw.rect(screen, PLATE, score_rect.inflate(12, 8))

El borde derecho de la placa queda 6 píxeles más allá del texto, en 476, y su parte superior queda 4 píxeles más arriba, en 6.

challenge icon

Desafío

Intermedio
  1. Agrega PLATE = (60, 60, 90).
  2. Coloca la puntuación con topright=(470, 10) y dibuja detrás un rectángulo PLATE: su Rect ampliado en (12, 8).
  3. En el menú, dibuja un rectángulo PLATE detrás de Meteor Dodge: el Rect del título, centrado en (240, 140), ampliado en (24, 12).

Pruébalo tú mismo

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
big_font = pygame.font.Font("assets/fonts/pixel.ttf", 48)
WHITE = (240, 240, 240)


def reset():
    global player, rock, score
    player = pygame.Rect(220, 300, 40, 40)
    rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
    score = 0


def draw_menu():
    screen.fill((30, 30, 46))
    title = big_font.render("Meteor Dodge", True, WHITE)
    screen.blit(title, title.get_rect(center=(240, 140)))
    hint = font.render("Press Enter to play", True, WHITE)
    screen.blit(hint, hint.get_rect(center=(240, 200)))


def draw_game():
    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), player)
    pygame.draw.rect(screen, (235, 80, 80), rock)
    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))


def play_frame():
    global score, state
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player.x -= 6
    if keys[pygame.K_RIGHT]:
        player.x += 6
    player.clamp_ip(screen.get_rect())

    rock.y += 4
    if rock.top > 360:
        rock.y = -24
        rock.x = random.randint(0, 456)
        score += 1
    if rock.colliderect(player):
        state = "over"
    draw_game()


def draw_over():
    draw_game()
    message = big_font.render("Game over", True, WHITE)
    screen.blit(message, message.get_rect(center=(240, 160)))
    hint = font.render("Press R to play again", True, WHITE)
    screen.blit(hint, hint.get_rect(center=(240, 200)))


reset()
state = "menu"

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN and state == "menu":
                state = "play"
            elif event.key == pygame.K_r and state == "over":
                reset()
                state = "play"

    if state == "menu":
        draw_menu()
    elif state == "play":
        play_frame()
    else:
        draw_over()
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Reglas del juego

Practica por tu cuenta: Playground de Pygame