Reputation: 261
I want to implement bullets into my pong game in which my paddles can shoot out bullets. Right now, I just want to focus on the PlayerPaddle shooting out bullets that travel towards the right. These bullets would originate from the position of the paddle. However, I'm not sure how to approach this. I believe that making a sprite group would overcomplicate my project and I just want my bullets to be able to collide into the pong ball I have eventually. This is what I have so far.
class PlayerPaddle(Image):
def __init__(self, screen_size, width, height, filename, color=(255,0,0)):
# speed and direction have to be before super()
self.speed = 3
self.direction = 0
super().__init__(screen_size, width, height, filename, color=(255, 0, 0))
self.rect.centerx = 40
self.rect.centery = screen_size[1] // 2
self.rect.height = 100
def update(self):
self.rect.centery += self.direction*self.speed # <--- use directly rect.centery
super().update()
#self.rect.center = (self.centerx, self.centery) # <-- don't need it
if self.rect.top < 0:
self.rect.top = 0
if self.rect.bottom > self.screen_size[1]-1:
self.rect.bottom = self.screen_size[1]-1
def handle_event(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.direction = -1
elif event.key == pygame.K_DOWN:
self.direction = 1
elif event.key == pygame.K_LEFT:
self.turnLeft()
elif event.key == pygame.K_RIGHT:
self.turnRight()
elif event.key == pygame.K_u:
bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
bullet.rect.centerx = self.rect.centerx
bullet.rect.centery = self.rect.centery
bullet.draw()
bullet.update()
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP and self.direction == -1:
self.direction = 0
elif event.key == pygame.K_DOWN and self.direction == 1:
self.direction = 0
and Here is my bullet class
class Bullet(Image):
def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):
super().__init__(screen_size, width, height, filename, color = (255, 0, 0))
def update(self):
self.rect.centery -= 3
Upvotes: 0
Views: 43
Reputation: 142651
I would create Group()
outside PlayerPaddle()
self.bullets_group = pygame.sprite.Group()
and use it as argument in PlayerPaddle()
self.player_paddle = PlayerPaddle(..., self.bullets_group)
This way player can easly add bullets to group
elif event.key == pygame.K_u:
bullet = Bullet(screen_size, 5, 5, "naruto.png", color = (255, 0 , 0))
bullet.rect.centerx = self.rect.centerx
bullet.rect.centery = self.rect.centery
self.bullets_group.add(bullet)
and mainloop
can draw and update it
def Update():
self.bullets_group.update()
self.player_paddle.update()
self.ai_paddle.update(..., self.bullets_group)
def Render():
self.bullets_group.draw()
self.player_paddle.draw()
Upvotes: 1