import pygame
import random
import math
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
class Player(pygame.sprite.Sprite):
def __init__(self, x=SCREEN_WIDTH//2, y=SCREEN_HEIGHT//2):
super().__init__()
self.image = pygame.image.load("image.png").convert()
self.rect = self.image.get_rect(centerx=x, centery=y)
def update(self):
move_x = random.randint(-15, 15)
move_y = random.randint(-15, 15)
self.rect.move_ip(move_x,move_y)
def draw(self, surface):
surface.blit(self.image, self.rect)
class Follower(Player):
def update(self, player):
distance = math.hypot(abs(player.rect.x - self.rect.x), abs(player.rect.y - self.rect.y))
angle_radians = math.atan2((player.rect.y - self.rect.y), (player.rect.x - self.rect.x))
if distance != 0:
self.rect.y += 5*math.sin(angle_radians)
self.rect.x += 5*math.cos(angle_radians)
pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
player = Player()
follower = Follower(0, 0)
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.KEYUP:
if event.key == pygame.K_ESCAPE:
running = False
if not pygame.key.get_pressed()[pygame.K_SPACE]:
player.update()
follower.update(player)
screen.fill(BLACK)
player.draw(screen)
follower.draw(screen)
pygame.display.flip()
ms = clock.tick(FPS)
fps = clock.get_fps()
pygame.display.set_caption('FPS: {}'.format(fps))
pygame.quit()