how to usepygame sprite spritecollide

Solutions on MaxInterview for how to usepygame sprite spritecollide by the best coders in the world

showing results for - "how to usepygame sprite spritecollide"
Valentina
25 May 2017
1import pygame
2import math
3pygame.init()
4screen = pygame.display.set_mode((640, 480))
5clock = pygame.time.Clock()
6
7# some helpful vector math functions
8def normalize(v):
9    vmag = magnitude(v)
10    return [v[i]/vmag  for i in range(len(v))]
11def magnitude(v):
12    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
13def add(u, v):
14    return [ u[i]+v[i] for i in range(len(u)) ]
15
16class Paddle(pygame.sprite.Sprite):
17    def __init__(self, start_pos, up_key, down_key):
18        pygame.sprite.Sprite.__init__(self)
19        # the image is just a white rect
20        self.image = pygame.surface.Surface((20, 100))
21        self.image.fill(pygame.color.Color('White'))
22        self.image.set_colorkey(pygame.color.Color('Black'))
23        self.rect = self.image.get_rect(topleft=start_pos)
24        # using a mask so we can use pixel perfect collision
25        self.mask = pygame.mask.from_surface(self.image)
26        self.up_key, self.down_key = up_key, down_key
27    def update(self, pressed):
28        if pressed[self.up_key]:   self.rect.move_ip(0, -3)
29        if pressed[self.down_key]: self.rect.move_ip(0,  3)
30        # keep the paddle inside the screen
31        self.rect.clamp_ip(pygame.display.get_surface().get_rect())
32
33class Ball(pygame.sprite.Sprite):
34    def __init__(self, start_pos):
35        pygame.sprite.Sprite.__init__(self)
36        # the image is just a white ball
37        self.image = pygame.surface.Surface((20, 20))
38        self.rect = self.image.get_rect(center=start_pos)
39        pygame.draw.circle(self.image, pygame.color.Color('White'), self.image.get_rect().center, 10)
40        self.image.set_colorkey(pygame.color.Color('Black'))
41        # using a mask so we can use pixel perfect collision
42        self.mask = pygame.mask.from_surface(self.image)
43        # the vector we use to move the ball
44        self.move_v = (1, 0.7)
45        # store the absolute position in self.pos
46        # because a rect can only use integers
47        self.pos = self.rect.center
48    def update(self, pressed):
49        # check if the ball collides with any other sprite
50        collide = [s for s in pygame.sprite.spritecollide(self, self.groups()[0], False, pygame.sprite.collide_mask) if s != self]
51        if collide:
52            # warning: this does not handle the case of the ball hits 
53            # the top or bottom of the paddle, only the sides.
54            self.move_v = [-self.move_v[0], self.move_v[1]]
55
56        # check if the ball would go out of screen
57        display = pygame.display.get_surface().get_rect()
58        if self.rect.top < display.top and self.move_v[1] < 0 or \
59           self.rect.bottom > display.bottom and self.move_v[1] > 0:
60            self.move_v = [self.move_v[0], -self.move_v[1]]
61
62        # apply a constant speed and update the position
63        move_vector = [c * 4 for c in normalize(self.move_v)]
64        self.pos = add(self.rect.center, move_vector)
65        self.rect.center = map(int, self.pos)
66
67player1 = Paddle((30,  190), pygame.K_w , pygame.K_s)
68player2 = Paddle((590, 190), pygame.K_UP, pygame.K_DOWN)
69ball = Ball(screen.get_rect().center)
70sprites = pygame.sprite.Group(player1, player2, ball)
71
72while True:
73    for event in pygame.event.get():
74        if event.type == pygame.QUIT: break
75    else:
76        pressed = pygame.key.get_pressed()
77        sprites.update(pressed)
78        screen.fill(pygame.color.Color('black'))
79        sprites.draw(screen)
80        pygame.display.flip()
81        clock.tick(60)
82        continue
83    break
84pygame.quit()
85