Advertisement
Guest User

Following with vectors test

a guest
Mar 27th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | None | 0 0
  1. import math
  2. import pygame
  3.  
  4. pygame.init()
  5.  
  6. screen_width, screen_heigth = 800, 600
  7. rect_width, rect_height = 40, 40
  8. step = 3
  9. ai_step = 2
  10.  
  11. screen = pygame.display.set_mode((screen_width, screen_heigth))
  12. screen_rect = screen.get_rect()
  13.  
  14. # The player starts in the top left corner, the AI in the bottom right
  15. player_rect = pygame.Rect(0, 0, rect_width, rect_height)
  16. ai_rect = pygame.Rect(screen_width - rect_width, screen_heigth - rect_height, rect_width, rect_height)
  17.  
  18. clock = pygame.time.Clock()
  19. running = True
  20. while running:
  21.     for event in pygame.event.get():
  22.         if event.type == pygame.QUIT:
  23.             running = False
  24.         elif event.type == pygame.KEYDOWN:
  25.             if event.key == pygame.K_q:
  26.                 running = False
  27.  
  28.     pressed_keys = pygame.key.get_pressed()    
  29.     # First move the player rect in place (move_ip)
  30.     # clamp makes sure the player doesn't go out of the screen
  31.     # Note: This is not necessarily the fastest (perfomance-wise)
  32.     #       way to do this.
  33.     if pressed_keys[pygame.K_LEFT]:
  34.         player_rect.move_ip(-step, 0)
  35.         player_rect.clamp(screen_rect)
  36.     if pressed_keys[pygame.K_RIGHT]:
  37.         player_rect.move_ip(step, 0)
  38.         player_rect.clamp(screen_rect)
  39.     if pressed_keys[pygame.K_UP]:
  40.         player_rect.move_ip(0, -step)
  41.         player_rect.clamp(screen_rect)
  42.     if pressed_keys[pygame.K_DOWN]:
  43.         player_rect.move_ip(0, step)
  44.         player_rect.clamp(screen_rect)
  45.  
  46.     vector = (player_rect.center[0] - ai_rect.center[0], player_rect.center[1] - ai_rect.center[1])
  47.     # math.hypot (Hypotenuse) is equivalent to
  48.     # math.sqrt(vector[0] ** 2 + vector[1] ** 2)
  49.     length = math.hypot(*vector)
  50.     normalized = (vector[0] / length, vector[1] / length)
  51.  
  52.     # Note: you don't have to round this apparently :)
  53.     ai_rect.x += normalized[0] * ai_step
  54.     ai_rect.y += normalized[1] * ai_step
  55.  
  56.     # Note: the AI will always move slower than the player (with ai_step <= step),
  57.     #       because the player can move 2 * step pixels at once (both horizontally and vertically),
  58.     #       while the AI can move only ai_step pixels.
  59.  
  60.  
  61.     screen.fill(pygame.Color("White"))
  62.  
  63.     pygame.draw.rect(screen, pygame.Color("Blue"), player_rect)
  64.     pygame.draw.rect(screen, pygame.Color("Red"), ai_rect)
  65.  
  66.  
  67.     pygame.display.flip()
  68.     clock.tick(60)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement