I've been trying to work out how to make collision logic for pong in pygame for a CS class.
I've tried multiple things and it works 99.9% of the time for the left paddle which isn't a issue but however, it only works about 10% of the time for the right paddle and I can't figure out why.
Thank you in advanced :)
from pygame.constants import K_DOWN, K_UP, K_s, K_w
pygame.init()
width=640
height=480
white = (255,255,255)
black = (0,0,0)
red = (255, 0, 0)
screen = pygame.display.set_mode((width, height ))
pygame.display.set_caption('Pong')
blue = (0,0,255)
#Setting set frame rate
clock = pygame.time.Clock()
#Global Paddle Settings
paddleWidth = 20
paddleHeight = 100
paddleSpeed = 10
#Left Paddle
lPaddleX = 20
lPaddleY = 200
#Right Paddle
rPaddleX = 600
rPaddleY = 200
#Ball
ballHeight = 25
ballWidth = 25
ballStartX = 310
ballStartY = 240
ballX = 310
ballY = 240
ballStartSpeed = 1
ballSpeed = 2
ballDirection = [0,1]
#[xdirection, ydirection]
running = True
while (running): # loop listening for end of game
keys = pygame.key.get_pressed()
# dt = clock.tick(30)
#Ball Physics
#Movement Logic
if ballDirection[0] == 1 and ballDirection[1] == 1:
ballX += ballSpeed
ballY += ballSpeed
if ballDirection[0] == 1 and ballDirection[1] == 0:
ballX += ballSpeed
ballY -= ballSpeed
if ballDirection[0] == 0 and ballDirection[1] == 1:
ballX -= ballSpeed
ballY += ballSpeed
if ballDirection[0] == 0 and ballDirection[1] == 0:
ballX -= ballSpeed
ballY -= ballSpeed
#Top and Bottom Colision Logic
if ballY <= 0:
ballDirection[1] = 1
if (ballY + ballHeight) >= height:
ballDirection[1] = 0
#Paddle Colision Logic
#Right Paddle
if (ballX + ballWidth) == (rPaddleX) and ballY <= (rPaddleY + paddleHeight) and (ballY + ballHeight) >= rPaddleY:
ballDirection[0] = 0
ballSpeed += 1
#Left Paddle
if ballX == (lPaddleX + paddleWidth) and ballY <= (lPaddleY + paddleHeight) and (ballY + ballHeight) >= lPaddleY:
ballDirection[0] = 1
ballSpeed += 1
#Right Paddle Controls
if keys[K_UP]:
if rPaddleY >=0:
rPaddleY -= paddleSpeed
if keys[K_DOWN]:
if (rPaddleY + paddleHeight) <= height:
rPaddleY += paddleSpeed
#Left Paddle Controls
if keys[K_w]:
if lPaddleY >= 0:
lPaddleY -= paddleSpeed
if keys[K_s]:
if (lPaddleY + paddleHeight) <= height:
lPaddleY += paddleSpeed
screen.fill(black)
# pygame.draw.rect(screen, blue, (ax,ay,squareWidth,squareHeight), 0)
# pygame.draw.rect(screen, red, (bx,by,squareWidth,squareHeight), 0)
#Paddles
pygame.draw.rect(screen, white, (lPaddleX,lPaddleY,paddleWidth,paddleHeight), 0)
pygame.draw.rect(screen, white, (rPaddleX,rPaddleY,paddleWidth,paddleHeight), 0)
pygame.draw.rect(screen, red, (ballX,ballY, ballWidth, ballHeight),0)
pygame.display.flip() # paint screen one time
pygame.time.wait(5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#loop over, quite pygame
pygame.quit()