Simple pong: but on the 5th hit the ball goes into the corner and bounces the wrong way vertically off the player1 rectangle, and then it goes to the opponent AI in the corner, also bounces the wrong way vertically off the AI rectangle, and then keeps cycling. How can I fix this? I'm very new to python and pygame so maybe there's something obvious I missed. I made the AI speed faster on purpose.
import pygame, sys, random
pygame.init()
WIDTH = 1100
HEIGHT = 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
opponent = pygame.Rect(10, HEIGHT/2 - 50, 10, 100)
player = pygame.Rect(WIDTH - 20, HEIGHT/2 - 50, 10, 100)
ball = pygame.Rect(WIDTH/2 - 15 , HEIGHT/2 - 15,30,30)
clock = pygame.time.Clock()
player_speed = 0
opponent_speed = 15
ball_speed_x = 5
ball_speed_y = 5
score_player = 0
score_ai = 0
score = (score_ai, score_player)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_speed -= 9
if event.key == pygame.K_DOWN:
player_speed += 9
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
player_speed += 9
if event.key == pygame.K_DOWN:
player_speed -= 9
#ball movement
ball.x += ball_speed_x
ball.y += ball_speed_y
# ball colliding with ceiling/floor
if ball.top <= 0:
ball_speed_y *= -1
if ball.bottom >= HEIGHT:
ball_speed_y *= -1
# if player misses ball
if ball.left <= 0:
ball = pygame.Rect(WIDTH/2 - 15 , HEIGHT/2 - 15,30,30)
ball_speed_x = 5
ball_speed_y = 5
score_player += 1
pygame.time.delay(1000)
continue
if ball.right >= WIDTH:
ball = pygame.Rect(WIDTH / 2 - 15, HEIGHT / 2 - 15, 30, 30)
ball_speed_x = 5
ball_speed_y = 5
score_ai += 1
pygame.time.delay(1000)
continue
# hitting the ball
if ball.colliderect(opponent):
ball_speed_x = -10
ball_speed_x *= -1
ball_speed_y = -9
ball_speed_y *= -1
if ball.colliderect(player):
ball_speed_x = 10
ball_speed_x *= -1
ball_speed_y = 9
ball_speed_y *= -1
# AI for opponent, if ball is higher, go up, if ball is lower, go down
if ball.y <= opponent.centery:
opponent.y -= opponent_speed
if ball.y >= opponent.centery:
opponent.y += opponent_speed
# don't let the slides go too high
player.y += player_speed
if player.top <= 0:
player.top = 0
if player.bottom >= HEIGHT:
player.bottom = HEIGHT
if opponent.top <= 0:
opponent.top = 0
if opponent.bottom >= HEIGHT:
opponent.bottom = HEIGHT
screen.fill((0,0,0))
pygame.draw.rect(screen, (0, 255, 0), player)
pygame.draw.rect(screen, (255, 0, 0), opponent)
pygame.draw.ellipse(screen, (255, 255, 255), ball)
pygame.draw.aaline(screen, (0,0,255), (WIDTH/2, 0), (WIDTH/2, HEIGHT))
pygame.display.update()
clock.tick(60)