# Leo Salazar # 2/15/25 # Catch the ball solution import pygame import random pygame.init() # basic setup screen = pygame.display.set_mode((800,600)) clock = pygame.time.Clock() running = True dt = 0 # for the paddle paddle = pygame.Rect(350, 570, 100, 30) speed = 300 alive = True score = 0 iterations = 0 # font setup font = pygame.font.Font(None, 40) end = pygame.font.Font(None, 60) # for the ball ball = pygame.Rect(380, -40, 40, 40) gravity = 250 # to reset the position of the ball at a random location def ball_reset(ball): ball.x = random.randint(0, 760) ball.y = -40 return ball # game loop while running: for event in pygame.event.get(): # to quit if event.type == pygame.QUIT: running = False # fill the background (always goes first) screen.fill("white") # if we're still playing if alive: # draw the paddle pygame.draw.rect(screen, 'blue', paddle) # move the paddle keys = pygame.key.get_pressed() if keys[pygame.K_a]: paddle.x -= speed * dt if keys[pygame.K_d]: paddle.x += speed * dt # move the ball ball.y += gravity * dt # draw the ball pygame.draw.ellipse(screen, 'red', ball) # increment score and reset position of ball if it hits the paddle if ball.colliderect(paddle): score += 1 iterations += 1 ball = ball_reset(ball) # reset position of ball if miss/offscreen if ball.top > screen.get_height(): ball = ball_reset(ball) iterations += 1 # game over else: end_text = end.render(f"Game Over", False, 'black') end_rect = end_text.get_rect() end_rect.center = (screen.get_width() // 2, screen.get_height() // 2) pygame.Surface.blit(screen, end_text, end_rect) # end condition if iterations > 9: alive = False # show score pygame.Surface.blit(screen, font.render(f"Score: {score}", False, 'black'), (0,0)) # update display pygame.display.flip() # time > fps dt = clock.tick(60) / 1000 # quit the process (so you can close the window) pygame.quit()