Shcoder001

Pygame part 2

Feb 10th, 2023
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. import pygame
  2.  
  3. pygame.init()
  4. screen = pygame.display.set_mode((900, 500))
  5. pygame.display.set_caption('My game')
  6. clock = pygame.time.Clock()
  7. player = pygame.rect.Rect(10, 200, 20, 100)
  8. bot = pygame.rect.Rect(870, 200, 20, 100)
  9. ball = pygame.rect.Rect(445, 245, 10, 10)
  10. running = True
  11. player_speed_y = 0
  12. ball_speed_x = -2
  13. ball_speed_y = 2
  14.  
  15.  
  16. def move_bot():
  17.     if ball.centery > bot.centery and ball.centerx>450:
  18.         bot.y += 1
  19.     if ball.centery < bot.centery and ball.centerx>450:
  20.         bot.y -= 1
  21.  
  22.  
  23. def ball_check():
  24.     global ball_speed_y
  25.     global ball_speed_x
  26.     if ball.top <= 0:
  27.         ball_speed_y = -ball_speed_y
  28.     if ball.bottom >= 500:
  29.         ball_speed_y = - ball_speed_y
  30.     if ball.colliderect(bot) or ball.colliderect(player):
  31.         ball_speed_x = -ball_speed_x
  32.  
  33.  
  34. while running:
  35.     for event in pygame.event.get():
  36.         if event.type == pygame.QUIT:
  37.             running = False
  38.         if event.type == pygame.KEYDOWN:
  39.             if event.key == pygame.K_UP:
  40.                 player_speed_y -= 1
  41.             if event.key == pygame.K_DOWN:
  42.                 player_speed_y += 1
  43.  
  44.         if event.type == pygame.KEYUP:
  45.             if event.key == pygame.K_UP:
  46.                 player_speed_y += 1
  47.             if event.key == pygame.K_DOWN:
  48.                 player_speed_y -= 1
  49.  
  50.     player.y += player_speed_y
  51.     ball.x += ball_speed_x
  52.     ball.y += ball_speed_y
  53.     ball_check()
  54.     move_bot()
  55.     screen.fill((0, 0, 0))
  56.     pygame.draw.rect(screen, (20, 200, 20), player)
  57.     pygame.draw.rect(screen, (200, 20, 20), bot)
  58.     pygame.draw.ellipse(screen, (255, 255, 255), ball)
  59.     pygame.display.flip()
  60.     clock.tick(60)
  61.  
Advertisement
Add Comment
Please, Sign In to add comment