MCPcopy Create free account
hub / github.com/Mrinank-Bhowmick/python-beginner-projects / Ball

Class Ball

projects/PONG/main.py:58–126  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

56
57
58class Ball(Block):
59 def __init__(self, path, x_pos, y_pos, speed_x, speed_y, paddles):
60 super().__init__(path, x_pos, y_pos)
61 self.speed_x = speed_x * random.choice((-1, 1))
62 self.speed_y = speed_y * random.choice((-1, 1))
63 self.paddles = paddles
64 self.active = False
65 self.score_time = 0
66
67 def update(self):
68 if self.active:
69 self.rect.x += self.speed_x
70 self.rect.y += self.speed_y
71 self.collisions()
72 else:
73 self.restart_counter()
74
75 def collisions(self):
76 if self.rect.top <= 0 or self.rect.bottom >= HEIGHT:
77 pygame.mixer.Sound.play(hit_sound)
78 self.speed_y *= -1
79
80 if pygame.sprite.spritecollide(self, self.paddles, False):
81 pygame.mixer.Sound.play(hit_sound)
82 collision_paddle = pygame.sprite.spritecollide(self, self.paddles, False)[
83 0
84 ].rect
85 if abs(self.rect.right - collision_paddle.left) < 10 and self.speed_x > 0:
86 self.speed_x *= -1
87 if abs(self.rect.left - collision_paddle.right) < 10 and self.speed_x < 0:
88 self.speed_x *= -1
89 if abs(self.rect.top - collision_paddle.bottom) < 10 and self.speed_y < 0:
90 self.rect.top = collision_paddle.bottom
91 self.speed_y *= -1
92 if abs(self.rect.bottom - collision_paddle.top) < 10 and self.speed_x > 0:
93 self.rect.bottom = collision_paddle.top
94 self.speed_y *= -1
95
96 def reset_ball(self):
97 for paddle in self.paddles:
98 if paddle.x == 20:
99 paddle.rect.center = (20, HEIGHT / 2)
100 else:
101 paddle.rect.center = (WIDTH - 20, HEIGHT / 2)
102 self.active = False
103 self.speed_x *= random.choice((-1, 1))
104 self.speed_y *= random.choice((-1, 1))
105 self.score_time = pygame.time.get_ticks()
106 self.rect.center = (WIDTH / 2, HEIGHT / 2)
107 if started > 1:
108 pygame.mixer.Sound.play(score_sound)
109
110 def restart_counter(self):
111 current_time = pygame.time.get_ticks()
112 countdown_number = 3
113
114 if current_time - self.score_time <= 700:
115 countdown_number = 3

Callers 1

create_ballFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected