Proyecto Extra: Creación de un Juego#

Introducción#

En este notebook, exploraremos el desarrollo de un juego sencillo utilizando la librería PyGame. Este proyecto tiene como objetivo aplicar conceptos básicos de programación y física en un entorno interactivo.

Objetivo#

Crear un juego simple como Pong o Breakout, que utilice elementos como colisiones, movimiento de objetos, y control mediante el teclado.


Instalación de PyGame#

PyGame es una librería en Python diseñada para la creación de juegos 2D. Para instalarla, ejecuta la siguiente celda.

# Instalación de PyGame
%pip install pygame
Requirement already satisfied: pygame in c:\users\calum\appdata\local\programs\python\python313\lib\site-packages (2.6.1)
Note: you may need to restart the kernel to use updated packages.
[notice] A new release of pip is available: 24.2 -> 24.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip

Configuración del Juego#

Creación de la Ventana del Juego#

En esta sección, configuraremos los elementos básicos:

  • Tamaño de la ventana.

  • Colores principales.

  • Frames por segundo (FPS).

# Importar PyGame
import pygame
import sys

# Inicializar PyGame
pygame.init()

# Configuración básica
ANCHO = 800
ALTO = 600
COLOR_FONDO = (0, 0, 0)
FPS = 60

# Crear la ventana
ventana = pygame.display.set_mode((ANCHO, ALTO))
pygame.display.set_caption("Juego: Pong")

# Reloj para controlar los FPS
reloj = pygame.time.Clock()

Diseño del Juego: Pong#

Descripción#

En este juego, los jugadores controlarán paletas para devolver la pelota hacia el oponente. El objetivo es evitar que la pelota cruce la línea detrás de la paleta propia.

Implementación de los Componentes#

Definiremos:

  1. Paletas.

  2. Pelota.

  3. Reglas básicas del juego.

# Definición de colores y tamaños
COLOR_PALETA = (255, 255, 255)
COLOR_PELOTA = (255, 255, 0)
ANCHO_PALETA = 20
ALTO_PALETA = 100
DIAMETRO_PELOTA = 15

# Posiciones iniciales
x_paleta_izq = 30
y_paleta_izq = ALTO // 2 - ALTO_PALETA // 2
x_paleta_der = ANCHO - 30 - ANCHO_PALETA
y_paleta_der = ALTO // 2 - ALTO_PALETA // 2
x_pelota, y_pelota = ANCHO // 2, ALTO // 2

# Velocidades
velocidad_paleta = 7
velocidad_pelota = [4, 4]

# Puntuaciones
puntaje_izq = 0
puntaje_der = 0

Bucle Principal del Juego#

El bucle principal manejará:

  • Actualización de posiciones.

  • Detección de colisiones.

  • Entrada del teclado.

  • Renderizado de los gráficos.

# Bucle principal
jugando = True
while jugando:
    for evento in pygame.event.get():
        if evento.type == pygame.QUIT:
            jugando = False

    # Teclas para mover las paletas
    teclas = pygame.key.get_pressed()
    if teclas[pygame.K_w] and y_paleta_izq > 0:
        y_paleta_izq -= velocidad_paleta
    if teclas[pygame.K_s] and y_paleta_izq < ALTO - ALTO_PALETA:
        y_paleta_izq += velocidad_paleta
    if teclas[pygame.K_UP] and y_paleta_der > 0:
        y_paleta_der -= velocidad_paleta
    if teclas[pygame.K_DOWN] and y_paleta_der < ALTO - ALTO_PALETA:
        y_paleta_der += velocidad_paleta

    # Actualizar posición de la pelota
    x_pelota += velocidad_pelota[0]
    y_pelota += velocidad_pelota[1]

    # Detección de colisiones con paredes
    if y_pelota <= 0 or y_pelota >= ALTO - DIAMETRO_PELOTA:
        velocidad_pelota[1] *= -1

    # Detección de colisiones con paletas
    if (x_pelota <= x_paleta_izq + ANCHO_PALETA and
        y_paleta_izq <= y_pelota <= y_paleta_izq + ALTO_PALETA) or \
       (x_pelota >= x_paleta_der - DIAMETRO_PELOTA and
        y_paleta_der <= y_pelota <= y_paleta_der + ALTO_PALETA):
        velocidad_pelota[0] *= -1

    # Detección de goles
    if x_pelota < 0:
        puntaje_der += 1
        x_pelota, y_pelota = ANCHO // 2, ALTO // 2
    if x_pelota > ANCHO:
        puntaje_izq += 1
        x_pelota, y_pelota = ANCHO // 2, ALTO // 2

    # Dibujar elementos
    ventana.fill(COLOR_FONDO)
    pygame.draw.rect(ventana, COLOR_PALETA, (x_paleta_izq, y_paleta_izq, ANCHO_PALETA, ALTO_PALETA))
    pygame.draw.rect(ventana, COLOR_PALETA, (x_paleta_der, y_paleta_der, ANCHO_PALETA, ALTO_PALETA))
    pygame.draw.ellipse(ventana, COLOR_PELOTA, (x_pelota, y_pelota, DIAMETRO_PELOTA, DIAMETRO_PELOTA))
    pygame.display.flip()

    # Control de FPS
    reloj.tick(FPS)

# Asegurarse de cerrar pygame y sys de manera adecuada
try:
    pygame.quit()
    sys.exit()
except SystemExit:
    pass

Conclusión#

En este proyecto adicional, exploramos cómo usar PyGame para desarrollar un juego simple como Pong. Este ejemplo introduce conceptos fundamentales de programación gráfica y física interactiva.

¡Sigue practicando y expandiendo este juego, o crea tus propias versiones!