I made a border in this pong game, and the paddles on the screen can cross it. I have done this before in another piece of code, but everything\'s different now. I have a ma
To keep the paddles on the field, add a check in the game loop to block paddle movement when the paddle reaches an edge.
.......
if pong.rect.x < 10:
pong.rect.x, pong.rect.y = 375, 250
pong.dx = 1
paddle2.points += 1
# keep paddles in correct range # add this section
if paddle1.rect.y < 0 : paddle1.rect.y = 0
if paddle3.rect.y < 0 : paddle3.rect.y = 0
if paddle2.rect.y < 200 : paddle2.rect.y = 200
if paddle4.rect.y < 200 : paddle4.rect.y = 200
if paddle1.rect.y > 200 - 75 : paddle1.rect.y = 200 - 75
if paddle3.rect.y > 200 - 75 : paddle3.rect.y = 200 - 75
if paddle2.rect.y > 500 - 75 : paddle2.rect.y = 500 - 75
if paddle4.rect.y > 500 - 75 : paddle4.rect.y = 500 - 75
#if the ball and paddle collide, bounce off it
if paddle1.rect.colliderect(pong.rect):
pong.dx = 1
if paddle2.rect.colliderect(pong.rect):
pong.dx = -1
.....
PyGame has a feature that does exactly what you want it to do. Use pygame.Rect objects and pygame.Rect.clamp() respectively pygame.Rect.clamp_ip():
Returns a new rectangle that is moved to be completely inside the argument Rect.
With this function, an object can be kept completely in the window. Get the window rectangle with get_rect
and clamp the object in the window:
while run:
# [...]
key = pygame.key.get_pressed()
if key[pygame.K_w]:
paddle1.rect.y += -paddle_speed
# [...]
winRect = win.get_rect()
paddle1.rect.clamp_ip(winRect)
paddle2.rect.clamp_ip(winRect)
paddle3.rect.clamp_ip(winRect)
paddle4.rect.clamp_ip(winRect)
# [...]