Herramientas de usuario

Herramientas del sitio


informatica:programacion:python:pyxel:juego_tipo_pong

¡Esta es una revisión vieja del documento!


Pong clon

import pyxel
 
class Pong:
    def __init__(self):
        # Inicializar ventana (256x256, 16 colores)
        pyxel.init(256, 256, title="Pyxel Pong", fps=60)
 
        # Posiciones iniciales
        self.paddle1_y = 100  # Jugador izquierdo
        self.paddle2_y = 100  # Jugador derecho
        self.ball_x = 128
        self.ball_y = 128
        self.ball_dx = 3  # Velocidad X
        self.ball_dy = 3  # Velocidad Y
 
        # Puntuación
        self.score1 = 0
        self.score2 = 0
 
        # Ejecutar el juego
        pyxel.run(self.update, self.draw)
 
    def update(self):
        # Movimiento paletas (W/S y Flechas Arriba/Abajo)
        if pyxel.btn(pyxel.KEY_W) and self.paddle1_y > 0:
            self.paddle1_y -= 3
        if pyxel.btn(pyxel.KEY_S) and self.paddle1_y < 180:
            self.paddle1_y += 3
 
        if pyxel.btn(pyxel.KEY_UP) and self.paddle2_y > 0:
            self.paddle2_y -= 3
        if pyxel.btn(pyxel.KEY_DOWN) and self.paddle2_y < 180:
            self.paddle2_y += 3
 
        # Movimiento de la pelota
        self.ball_x += self.ball_dx
        self.ball_y += self.ball_dy
 
        # Rebote en paredes superior/inferior
        if self.ball_y < 0 or self.ball_y > 256:
            self.ball_dy *= -1
 
        # Colisión con paletas
        if (self.ball_x < 20 and 
            self.paddle1_y < self.ball_y < self.paddle1_y + 60):
            self.ball_dx *= -1  # Invertir dirección X
 
        if (self.ball_x > 236 and 
            self.paddle2_y < self.ball_y < self.paddle2_y + 60):
            self.ball_dx *= -1
 
        # Puntuación y reset
        if self.ball_x < 0:
            self.score2 += 1
            self.reset_ball()
        elif self.ball_x > 256:
            self.score1 += 1
            self.reset_ball()
 
    def reset_ball(self):
        # Reiniciar pelota al centro con dirección aleatoria
        self.ball_x, self.ball_y = 128, 128
        self.ball_dx = 3 if pyxel.rndi(0, 1) else -3
        self.ball_dy = 3 if pyxel.rndi(0, 1) else -3
 
    def draw(self):
        pyxel.cls(0)  # Fondo negro
 
        # Dibujar elementos
        pyxel.rect(0, self.paddle1_y, 10, 60, 9)          # Paleta izquierda (azul)
        pyxel.rect(246, self.paddle2_y, 10, 60, 8)        # Paleta derecha (rojo)
        pyxel.rect(self.ball_x, self.ball_y, 8, 8, 7)     # Pelota (blanco)
 
        # Línea central
        for y in range(0, 256, 20):
            pyxel.rect(128, y, 4, 10, 3)
 
        # Marcador
        pyxel.text(50, 10, f"JUGADOR 1: {self.score1}", 9)
        pyxel.text(150, 10, f"JUGADOR 2: {self.score2}", 8)
 
# Ejecutar el juego
Pong()
informatica/programacion/python/pyxel/juego_tipo_pong.1741963505.txt.gz · Última modificación: por tempwin