pygame rect follower

Solutions on MaxInterview for pygame rect follower by the best coders in the world

showing results for - "pygame rect follower"
Isaac
18 May 2019
1import pygame
2import random
3import math
4
5# --- constants --- (UPPER_CASE_NAMES)
6
7SCREEN_WIDTH = 800
8SCREEN_HEIGHT = 600
9
10FPS = 25 # for more than 220 it has no time to update screen
11
12BLACK = (0, 0, 0)
13WHITE = (255, 255, 255)
14
15# --- classes --- (CamelCaseNames)
16
17class Player(pygame.sprite.Sprite):
18
19    def __init__(self, x=SCREEN_WIDTH//2, y=SCREEN_HEIGHT//2):
20        super().__init__()
21        self.image = pygame.image.load("image.png").convert()
22        #self.rect = self.image.get_rect(x=x, y=y)
23        self.rect = self.image.get_rect(centerx=x, centery=y)
24
25    def update(self):
26        #self.rect.centerx = random.randint(0, SCREEN_WIDTH)
27        #self.rect.centery = random.randint(0, SCREEN_HEIGHT)
28        move_x = random.randint(-15, 15)
29        move_y = random.randint(-15, 15)
30        self.rect.move_ip(move_x,move_y)
31
32    def draw(self, surface):
33        surface.blit(self.image, self.rect)
34
35class Follower(Player):
36
37    def update(self, player):
38        distance = math.hypot(abs(player.rect.x - self.rect.x), abs(player.rect.y - self.rect.y))
39        angle_radians = math.atan2((player.rect.y - self.rect.y), (player.rect.x - self.rect.x))
40
41        if distance !=  0:
42            self.rect.y += 5*math.sin(angle_radians)
43            self.rect.x += 5*math.cos(angle_radians)        
44
45# --- functions --- (lower_case_names)
46
47# --- main ---
48
49pygame.init()
50
51screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
52
53player = Player()
54follower = Follower(0, 0)
55
56# --- mainloop ---
57
58clock = pygame.time.Clock()
59
60running = True
61while running:
62
63    # --- events ---
64    for event in pygame.event.get():
65        if event.type == pygame.QUIT:
66            running = False
67
68        elif event.type == pygame.KEYUP:
69            if event.key == pygame.K_ESCAPE:
70                running = False
71
72
73    # --- changes/moves/updates ---
74
75    if not pygame.key.get_pressed()[pygame.K_SPACE]:
76        player.update()
77        follower.update(player)
78    # --- draws ---
79
80    screen.fill(BLACK)
81
82    player.draw(screen)
83    follower.draw(screen)
84
85    pygame.display.flip()
86
87    # --- FPS ---
88
89    ms = clock.tick(FPS)
90    #pygame.display.set_caption('{}ms'.format(ms)) # 40ms for 25FPS, 16ms for 60FPS
91    fps = clock.get_fps()
92    pygame.display.set_caption('FPS: {}'.format(fps))
93
94# --- end ---
95
96pygame.quit()
similar questions
queries leading to this page
pygame rect follower