Pygame rect seguidor
import pygame
import random
import math
# --- constants --- (UPPER_CASE_NAMES)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25 # for more than 220 it has no time to update screen
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# --- classes --- (CamelCaseNames)
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(x=x, y=y)
self.rect = self.image.get_rect(centerx=x, centery=y)
def update(self):
#self.rect.centerx = random.randint(0, SCREEN_WIDTH)
#self.rect.centery = random.randint(0, SCREEN_HEIGHT)
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)
# --- functions --- (lower_case_names)
# --- main ---
pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
player = Player()
follower = Follower(0, 0)
# --- mainloop ---
clock = pygame.time.Clock()
running = True
while running:
# --- events ---
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
# --- changes/moves/updates ---
if not pygame.key.get_pressed()[pygame.K_SPACE]:
player.update()
follower.update(player)
# --- draws ---
screen.fill(BLACK)
player.draw(screen)
follower.draw(screen)
pygame.display.flip()
# --- FPS ---
ms = clock.tick(FPS)
#pygame.display.set_caption('{}ms'.format(ms)) # 40ms for 25FPS, 16ms for 60FPS
fps = clock.get_fps()
pygame.display.set_caption('FPS: {}'.format(fps))
# --- end ---
pygame.quit()
Determined Dugong