pygamepong

Is there a way to change the position of the ball to the centre when scored?


  if fireBall.rect.x>=690:
      score_1+=1
      fireBall.ballspeed[0] = -fireBall.ballspeed[0]
  if fireBall.rect.x<=0:
      score_2+=1
      fireBall.ballspeed[0] = -fireBall.ballspeed[0]
  if fireBall.rect.y>490:
      fireBall.ballspeed[1] = -fireBall.ballspeed[1]
  if fireBall.rect.y<0:
      fireBall.ballspeed[1] = -fireBall.ballspeed[1]

I am making a ping pong game, I wanted the ball to restart at the centre when the player scores, but my code allows the ball to carry on moving even after they have scored.


Solution

  • You can get the the center of the window with pygame.display.get_surface().get_rect().center. e.g.:

    if fireBall.rect.x>=690:
        score_1+=1
        fireBall.ballspeed[0] = -fireBall.ballspeed[0]
        fireBall.rect.center = pygame.display.get_surface().get_rect().center
      
    if fireBall.rect.x<=0:
        score_2+=1
        fireBall.ballspeed[0] = -fireBall.ballspeed[0]
        fireBall.rect.center = pygame.display.get_surface().get_rect().center