2
import pygame
pygame.init()


FPS=50
fpsClock=pygame.time.Clock()
screenh=500
screenw=300

screen=pygame.display.set_mode((screenh,screenw))


paddle1=pygame.image.load('paddle1.png')
rect=paddle1.get_rect()

p1x=130
p1y=10

paddle2=pygame.image.load('paddle2.png')
rect=paddle2.get_rect()
p2x=130
p2y=465
 
*the ball* 
ball=pygame.image.load('player.png')
ballrect=ball.get_rect()
ball_speed=1
ballx=250
bally=150

*ball moving*

def ball_move():
    global ballx, bally
    bally+=ball_speed
    ballx-=ball_speed

***# this is the problem am facing the ball wont bounce of the screenw***
def ball_collide():
    global ballx,bally
    if bally >= screenw:
        print('hello')
        bally *= -ball_speed
    




running=True
while running:

    screen.fill((255,255,0))

    screen.blit(paddle2, (p2y,p2x))
    
    screen.blit(paddle1, (p1y,p1x))
    
    screen.blit(ball, (ballx,bally))

    ball_collide()

    ball_move()

    pygame.display.update()

    fpsClock.tick(FPS)

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
*the key press movement is handdled here*
        if event.type==pygame.KEYDOWN:
            if event.key==pygame.K_q:
                p1x-=10 
            if event.key==pygame.K_a:
                p1x+=10
            if event.key==pygame.K_UP:
                p2x-=10
            if event.key==pygame.K_DOWN:
                p2x+=10
    

pliz help with this coz i got little time to finish this i dont know but the ball wont bounce of the screen w *if there are other technics to solve this pliz help becoz it giving me hard time coz whenever the ball excedes the screen w it prints hello but doesnt reverse the ball movement So i realized that my problem is the ball bouncing of the screen and my code has no prob and am jus a beginner in python pygame so really need your help *

1 Answers1

1

You'll simply need to change

    if bally >= screenw:
        print('hello')
        bally *= -ball_speed

to

    if bally >= screenw:
        print('hello')
        ball_speedx *= -1

Now you can see that you actually need 2 speed variables; one for the x direction and one for the y direction. So this:

ball_speed=1

should be

ball_speedx=1
ball_speedy=1

and this:

    bally+=ball_speed
    ballx-=ball_speed

should be

    bally+=ball_speedy
    ballx-=ball_speedx
Red
  • 26,798
  • 7
  • 36
  • 58