#! /usr/bin/python3 #------Módulos------ import pygame #------Constantes------ ##--------Dimensiones de la ventana de juego ANCHO = 700 ALTO = 500 ##--------Colores en RGB COL_FRENTE = (255,255,255) COL_FONDO = (0,0,0) #------Clases class Bola(pygame.sprite.Sprite): def __init__(self,color,ancho,alto): pygame.sprite.Sprite.__init__(self) self.color=color self.ancho=ancho self.alto=alto #la bola tiene aspecto de rectángulo self.imagen = pygame.Surface([ancho,alto]) self.imagen.fill(COL_FONDO) self.imagen.set_colorkey(COL_FONDO) pygame.draw.rect(self.imagen,color,[0,0,ancho,alto]) self.rect=self.imagen.get_rect() #posición de saque de la bola y dirección de salida self.rect.x=0 self.rect.y=ALTO/2 self.velocidad=[0.5,-0.5] def actualiza(self,tiempo): #La posición de la bola es su velocidad por el tiempo: e=e0+v·t self.rect.x+=self.velocidad[0]*tiempo self.rect.y+=self.velocidad[1]*tiempo #la bola rebota en las paredes if self.rect.x <= 0 or self.rect.x >= ANCHO: self.velocidad[0]=-self.velocidad[0] if self.rect.y <= 0 or self.rect.y >= ALTO: self.velocidad[1]=-self.velocidad[1] def dibuja(self,pantalla): pygame.draw.rect(self.imagen,COL_FRENTE,[0,0,self.ancho,self.alto]) pantalla.blit(self.imagen,self.rect) #------Funciones------ def pintafondo(pantalla): pantalla.fill(COL_FONDO) #dibuja la linea (red) pygame.draw.line(pantalla, COL_FRENTE, [ANCHO/2-1,0], [ANCHO/2-1, ALTO], 5) def muestrapuntos(pantalla,puntos): fuente=pygame.font.Font(None, 48) #jugador texto=fuente.render("JUG "+str(puntos[0]),1,COL_FRENTE) pantalla.blit(texto,(100,10)) #CPU texto=fuente.render("CPU "+str(puntos[1]),1,COL_FRENTE) pantalla.blit(texto,(450,10)) def main(): dim_pantalla=(700,500) pantalla=pygame.display.set_mode(dim_pantalla) pygame.display.set_caption(" P O N G ") jugando=True reloj=pygame.time.Clock() bola=Bola(COL_FRENTE,15,15) puntos=[0,0] while jugando: #Buble del juego tiempo=reloj.tick(60) #El jugador ha hecho algo (pulsar una tecla, cerrar la ventana u otro evento) for evento in pygame.event.get(): if evento.type == pygame.QUIT: jugando=False tecla=pygame.key.get_pressed() if tecla[pygame.K_x]: jugando=False #pintar el tablero de juego pintafondo(pantalla) #actualiza las posiciones de los sprites y díbujalos todos (bola) bola.actualiza(tiempo) bola.dibuja(pantalla) #Escribir marcadores (puntos) muestrapuntos(pantalla,puntos) #actualiza la vista del usuario con todo lo que hemos dibujado pygame.display.flip() return 0 if __name__ == '__main__': pygame.init() main() pygame.quit()