¡Claro! Aquí tienes un ejemplo completo de un minijuego 2D hecho con Pygame: “Evita los Meteoritos”.
El jugador controla una nave (rectángulo) que se mueve horizontalmente en la parte inferior de la pantalla mientras caen meteoritos desde arriba.
¡Si te golpean pierdes una vida; cuanto más sobrevivas, más puntos obtienes!
Estructura de carpetas
No necesitas nada especial, basta con un único archivo meteoritos.py (todo el código está debajo).
Código completo (copialo tal cual en meteoritos.py)
python
import pygame
import random
import sys
# ------------------ Configuración ------------------
WIDTH, HEIGHT = 480, 640
FPS = 60
PLAYER_W = 50
PLAYER_H = 20
PLAYER_SPEED = 6
METEOR_SIZE = 30
METEOR_SPEED = (3, 7) # rango de velocidad vertical
SPAWN_DELAY = 600 # ms entre meteoritos
LIVES = 3
BG_COLOR = (20, 20, 30)
FONT_COLOR = (255, 255, 255)
# ------------------ Inicialización -----------------
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Evita los Meteoritos")
clock = pygame.time.Clock()
font_big = pygame.font.SysFont("consolas", 40)
font_small= pygame.font.SysFont("consolas", 24)
# ------------------ Clases -------------------------
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((PLAYER_W, PLAYER_H))
self.image.fill((0, 200, 255))
self.rect = self.image.get_rect(midbottom=(WIDTH//2, HEIGHT-10))
self.speed = PLAYER_SPEED
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT]:
self.rect.x += self.speed
# Mantener dentro de la pantalla
self.rect.x = max(0, min(self.rect.x, WIDTH - self.rect.width))
class Meteor(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((METEOR_SIZE, METEOR_SIZE), pygame.SRCALPHA)
# Dibujar un círculo “meteorito”
pygame.draw.circle(self.image, (200, 80, 40), (METEOR_SIZE//2, METEOR_SIZE//2), METEOR_SIZE//2)
self.rect = self.image.get_rect(midtop=(random.randint(0, WIDTH - METEOR_SIZE), -METEOR_SIZE))
self.speedy = random.randint(*METEOR_SPEED)
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT: # Se fue de la pantalla
self.kill()
# ------------------ Funciones auxiliares -----------
def draw_hud(score, lives):
score_surf = font_small.render(f"Puntos: {score}", True, FONT_COLOR)
lives_surf = font_small.render(f"Vidas: {lives}", True, FONT_COLOR)
screen.blit(score_surf, (10, 8))
screen.blit(lives_surf, (WIDTH - lives_surf.get_width() - 10, 8))
def game_over_screen(score):
text1 = font_big.render("GAME OVER", True, FONT_COLOR)
text2 = font_small.render(f"Puntuación: {score}", True, FONT_COLOR)
text3 = font_small.render("Pulsa ESPACIO para reiniciar", True, FONT_COLOR)
screen.blit(text1, text1.get_rect(center=(WIDTH//2, HEIGHT//2 - 40)))
screen.blit(text2, text2.get_rect(center=(WIDTH//2, HEIGHT//2)))
screen.blit(text3, text3.get_rect(center=(WIDTH//2, HEIGHT//2 + 40)))
pygame.display.flip()
wait_restart()
def wait_restart():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
return
clock.tick(15)
# ------------------ Bucle principal ----------------
def main():
while True:
# resetear juego
player = Player()
all_sprites = pygame.sprite.Group(player)
meteors = pygame.sprite.Group()
score = 0
lives = LIVES
pygame.time.set_timer(pygame.USEREVENT, SPAWN_DELAY)
running = True
while running:
dt = clock.tick(FPS) # ms entre frames
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
if event.type == pygame.USEREVENT: # Spawn meteorito
meteors.add(Meteor())
all_sprites.add(meteors)
# Lógica
all_sprites.update()
score += dt // 10 # más tiempo vivo, más puntos
# Colisiones
hits = pygame.sprite.spritecollide(player, meteors, True)
if hits:
lives -= 1
if lives <= 0:
running = False
# Dibujar
screen.fill(BG_COLOR)
all_sprites.draw(screen)
draw_hud(score, lives)
pygame.display.flip()
# Pantalla de Game Over
game_over_screen(score)
if __name__ == "__main__":
main()
¿Cómo se juega?
• Flecha izquierda ⬅️ y derecha ➡️ para mover tu nave.
• Evita que los meteoritos (círculos naranjas) te golpeen.
• Tienes 3 vidas; la puntuación sube cuanto más tiempo sobrevivas.
• Cuando pierdes todas las vidas, pulsa ESPACIO para reiniciar.
¿Cómo ejecutar?
bash
pip install pygame
python meteoritos.py
¿Cómo personalizarlo?
• Cambiar tamaño/velocidad de meteoritos: ajusta METEOR_SIZE y METEOR_SPEED.
• Aumentar dificultad: reduce SPAWN_DELAY o incrementa METEOR_SPEED.
• Reemplazar el rectángulo del jugador por una imagen (pygame.image.load).
• Agregar sonido: usa pygame.mixer.Sound('explosion.wav').play() cuando haya colisión.
• Registrar récords: guarda score en un archivo al finalizar.
Próximos pasos / Retos:
Añadir power-ups (escudo, disparos).
Implementar fondo estrellado en movimiento.
Menú de inicio y pantalla de pausa.
Modos de dificultad.
¡Listo! Con este esqueleto tienes un juego 2D funcional y fácil de extender. Si quieres algo más específico o tienes dudas con Pygame, avísame 😊