Search code examples
pythonpygamepong

How to reflect the ball off paddle


Im trying out pygame for the first time, now ive gotten very comfortable with python as a language, and ive been trying to recreate Pong, like the old school game with 2 paddles and a ball. I cant seem to figure out how to get the ball to reflect off the paddle. Im not looking for angles and stuff yet, cos ill be able to figure that out on my own.

Buttt what ive thought of is to get a range of coordinates, which are the X & Y of the paddle and the x & y + the width and height, and if the ball enters these, it simply reflects as it does at a boundary. Ive tried doing multiple if statements, as you can see in the code below, but ive also tried doing it as a single statement, but that doesnt work. None of the debug prints ive put in actually print, but when i test the coord ranges with print they look fine :D

Ill paste my code here so you guys can run my game as is.

Id really appreciate your guys help!

import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")

x = 50
y = 50
width = 10                                      #sets variables for the main paddle
height = 60
vel = 5

ballx = 250
bally = 250
radius = 5
direction = True                                #True is left, False is right                                                            
bvel = 4                                        #sets variables for the ball
angle = 0

coordxGT = 0
coordxLT = 0                                    #sets variables for the coordinate ranges of the first paddle for collision
coordyGT = 0
coordyLT = 0

def setCoords():
    coordxGT = x
    coordxLT = x + width
    coordyGT = y                                #This function updates the coords throughout the main loop
    coordyLT = y + height
    coordxLT += radius
    coordyLT += radius

run = True
while run == True:
    pygame.time.delay(20)
    for event in pygame.event.get():            #on quit, quit the game and dont throw up an error :)
        if event.type == pygame.QUIT:
            run = False
    setCoords()

    if direction == True:                       #Ball movement
        ballx -= bvel
    else:
        ballx += bvel

    if ballx<0:
        ballx += bvel
        direction = False
    elif bally<0:
        bally += bvel
    elif ballx>495:                             #if the ball hits an edge
        ballx -= bvel
        direction = True
    elif bally>495:
        bally -= bvel

    if ballx<coordxLT and ballx>coordxGT:
        print("S1")
        if bally<coordyLT and bally>coordyGT:                                   #THE PART I CANT FIGURE OUT. If the ball lands within these ranges of coordinates, reflect it and change its direction
            print("S2")
            if direction == True:
                print("YES")
                ballx += bvel
                direction = False

    keys = pygame.key.get_pressed()                         #gets the keys pressed at that current time

    if keys[pygame.K_DOWN]:
        bally += bvel                                       #Ball control (For debugging)
    if keys[pygame.K_UP]:
        bally -= bvel

    if keys[pygame.K_w]:
        y -= vel
    if keys[pygame.K_a]:
        x -= vel
    if keys[pygame.K_s]:                                    #Paddle controls
        y += vel
    if keys[pygame.K_d]:
        x += vel

    if x<0:
        x += vel
    if y<0:
        y += vel
    if x>80:
        x -= vel                                        #Stops the paddle from moving if it hits a boundary
    if y>440:
                                                        #440 because window height - height of cube
        y -= vel

    win.fill((0,0,0))
    pygame.draw.circle(win, (255, 255, 255), (ballx, bally), radius)      #refreshes the screen
    pygame.draw.rect(win,(255,255,255),(x, y, width, height))
    pygame.display.update()
pygame.quit()

Solution

  • You are close, but you missed to declare the variables coordxGT, coordxLT, coordxLT, coordyLT to be global.

    def setCoords():
        global coordxGT, coordxLT, coordxLT, coordyLT
        coordxGT = x
        coordxLT = x + width
        coordyGT = y  
        coordyLT = y + height
        coordxLT += radius
        coordyLT += radius
    

    Note, if you want to write to a variable in global namespace in a function, then the varible has be interpreted as global. Otherwise an new variable in the scope of the function will be created and set. See global statement.