View difference between Paste ID: 1KD5Nxdf and 0fB1mgMB
SHOW: | | - or go back to the newest paste.
1
import pygame
2
import random
3
4
SCREEN_WIDTH = 1024
5
SCREEN_HEIGHT = 800
6
vec = pygame.math.Vector2
7
8
9
class Ball(pygame.sprite.Sprite):
10
    def __init__(self):
11
        super(Ball, self).__init__()
12
        self.image = pygame.image.load("images/ball.png")
13
        self.reset_position()
14
        self.r = 16
15
        self.lost = False
16
17
    # resetting position
18
    def reset_position(self):
19
        self.coordinates = vec(SCREEN_WIDTH/2, SCREEN_HEIGHT-140)
20
        self.rect = self.image.get_rect(center=self.coordinates)
21
        self.vector = vec(0, -10)
22
        self.incline_angle = random.randrange(-30, 30)
23
        self.vector.rotate_ip(self.incline_angle)
24
        self.lost = False
25
26
    # update
27
    def update(self, platform, bricks):
28
        self.coordinates += self.vector
29
        self.rect.center = self.coordinates
30
        self.check_collision(platform, bricks)
31
32
    # check all possible collisions
33
    def check_collision(self, paddle, bricks):
34
        # screen edges
35
        if self.rect.x <= 0:
36
            self.vector.x *= -1
37
        if self.rect.right >= SCREEN_WIDTH:
38
            self.vector.x *= -1
39
        if self.rect.top <= 0:
40
            self.vector.y *= -1
41
        if self.rect.bottom >= SCREEN_HEIGHT:
42
            self.lost = True
43
44
        # paddle
45
        if self.rect.colliderect(paddle.rect):
46
            self.vector.y *= -1
47
            self.vector.x += paddle.moving*5
48
            if self.vector.x < -10:
49
                self.vector.x = -10
50
            if self.vector.x > 10:
51
                self.vector.x = 10
52
53
        # bricks
54
        for brick in bricks:
55
            # collision detected
56
            if self.brick_collision(self, brick):
57
                brick.hit()
58
                break
59
60
    # auxiliary method for brick collision
61
    def brick_collision(self, ball, brick):
62
        distance_x = abs(ball.rect.centerx -
63
                         brick.rect.centerx) - brick.rect.w / 2
64
        distance_y = abs(ball.rect.centery -
65
                         brick.rect.centery) - brick.rect.h / 2
66
67
        if distance_x < ball.r and distance_y < ball.r:
68
            if distance_x < distance_y:
69
                self.vector.y *= -1
70
            else:
71
                self.vector.x *= -1
72
            return True
73
        return False
74