Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import pygame
- pygame.init()
- screen_width, screen_heigth = 800, 600
- rect_width, rect_height = 40, 40
- step = 3
- ai_step = 2
- screen = pygame.display.set_mode((screen_width, screen_heigth))
- screen_rect = screen.get_rect()
- # The player starts in the top left corner, the AI in the bottom right
- player_rect = pygame.Rect(0, 0, rect_width, rect_height)
- ai_rect = pygame.Rect(screen_width - rect_width, screen_heigth - rect_height, rect_width, rect_height)
- clock = pygame.time.Clock()
- running = True
- while running:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = False
- elif event.type == pygame.KEYDOWN:
- if event.key == pygame.K_q:
- running = False
- pressed_keys = pygame.key.get_pressed()
- # First move the player rect in place (move_ip)
- # clamp makes sure the player doesn't go out of the screen
- # Note: This is not necessarily the fastest (perfomance-wise)
- # way to do this.
- if pressed_keys[pygame.K_LEFT]:
- player_rect.move_ip(-step, 0)
- player_rect.clamp(screen_rect)
- if pressed_keys[pygame.K_RIGHT]:
- player_rect.move_ip(step, 0)
- player_rect.clamp(screen_rect)
- if pressed_keys[pygame.K_UP]:
- player_rect.move_ip(0, -step)
- player_rect.clamp(screen_rect)
- if pressed_keys[pygame.K_DOWN]:
- player_rect.move_ip(0, step)
- player_rect.clamp(screen_rect)
- vector = (player_rect.center[0] - ai_rect.center[0], player_rect.center[1] - ai_rect.center[1])
- # math.hypot (Hypotenuse) is equivalent to
- # math.sqrt(vector[0] ** 2 + vector[1] ** 2)
- length = math.hypot(*vector)
- normalized = (vector[0] / length, vector[1] / length)
- # Note: you don't have to round this apparently :)
- ai_rect.x += normalized[0] * ai_step
- ai_rect.y += normalized[1] * ai_step
- # Note: the AI will always move slower than the player (with ai_step <= step),
- # because the player can move 2 * step pixels at once (both horizontally and vertically),
- # while the AI can move only ai_step pixels.
- screen.fill(pygame.Color("White"))
- pygame.draw.rect(screen, pygame.Color("Blue"), player_rect)
- pygame.draw.rect(screen, pygame.Color("Red"), ai_rect)
- pygame.display.flip()
- clock.tick(60)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement