So I am currently working on Ping with Pygame and I just can't figure out how I should do the collision with the paddle. I have one Pong Game without Classes where i did it like this
if paddle.colliderect(ecl):
bewegungx = abs(bewegungx)
ecl is the ball in this case and here is it with my classes. I currently have only one paddle since I wanna first figure the collision out and then do the rest.
Thank you in advance :)
import pygame
white = (255, 255, 255)
black = (0, 0, 0)
WIDTH = 400
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
FPS = 60
clock = pygame.time.Clock()
class Ball():
def __init__(self):
self.ball_w = 30
self.ball_h = 30
self.ball_x = 100
self.ball_y = 150
self.ball_speedx = 3
self.ball_speedy = 3
self.ball_draw = pygame.Rect(self.ball_x, self.ball_y, self.ball_w, self.ball_h)
def draw(self):
pygame.draw.rect(screen, white, self.ball_draw)
def move(self):
self.ball_x += self.ball_speedx
self.ball_y += self.ball_speedy
self.ball_draw.topleft = (self.ball_x, self.ball_y)
def wall_collision(self):
if self.ball_draw.top <=0:
self.ball_speedy = self.ball_speedy *-1
if self.ball_draw.right >= WIDTH:
self.ball_speedx = self.ball_speedx *-1
if self.ball_draw.left <=0:
self.ball_speedx = self.ball_speedx *-1
if self.ball_draw.bottom >= HEIGHT:
self.ball_speedy = self.ball_speedy *-1
class Paddle():
def __init__(self):
self.paddle_w = 30
self.paddle_h = 130
self.paddle_x = 10
self.paddle_y = 150
self.paddle_speed = 0
self.paddle_left = pygame.Rect(self.paddle_x, self.paddle_y, self.paddle_w, self.paddle_h)
def draw(self):
pygame.draw.rect(screen, white, self.paddle_left)
def move(self):
key = pygame.key.get_pressed()
if key[pygame.K_w] and self.paddle_left.top > 0:
self.paddle_left.y -=7
if key[pygame.K_s] and self.paddle_left.bottom < 600:
self.paddle_left.y += 7
ball = Ball()
paddle = Paddle()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.fill(black)
#Ball Functionsw
ball.draw()
ball.move()
ball.wall_collision()
#Paddle Functions
paddle.draw()
paddle.move()
pygame.display.flip()
clock.tick(FPS)