Python 不知道如何在乒乓球游戏中使用子弹
我想在我的乒乓球游戏中使用子弹,我的球拍可以射出子弹。现在,我只想把重点放在PlayerPaddle向右边发射子弹上。这些子弹将从桨的位置产生。然而,我不知道如何处理这个问题。我相信组建一个精灵小组会使我的项目过于复杂,我只希望我的子弹能够撞到我最终拥有的乒乓球上。这就是我目前所拥有的Python 不知道如何在乒乓球游戏中使用子弹,python,pygame,pong,Python,Pygame,Pong,我想在我的乒乓球游戏中使用子弹,我的球拍可以射出子弹。现在,我只想把重点放在PlayerPaddle向右边发射子弹上。这些子弹将从桨的位置产生。然而,我不知道如何处理这个问题。我相信组建一个精灵小组会使我的项目过于复杂,我只希望我的子弹能够撞到我最终拥有的乒乓球上。这就是我目前所拥有的 class PlayerPaddle(Image): def __init__(self, screen_size, width, height, filename, color=(255,0,0)):
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
我将在PlayerPaddle()外部创建Group()
并将其用作PlayerPaddle()中的参数
这样,玩家可以轻松地将子弹添加到组中
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)
而mainloop
可以绘制并更新它
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()
使用Group()
或至少使用普通列表保存所有项目符号。组是为分组元素创建的,运行Group.draw()
,Group.update()
并检查冲突-因此它可以是更好的选择。
self.player_paddle = PlayerPaddle(..., self.bullets_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)
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()