n.alha
n.alha

Reputation: 9

Paddles in pong aren't moving

I want to move the left paddle using W and S, but whenever I click the keys the paddle doesn't move. I've only been learning python for a few months and pygame a few weeks, so if its a really obvious mistake then that's why.

Here's the main game loop:

while not x:
  for event in pygame.event.get():
    if event.type == pygame.QUIT: 
      x = True #quits the game when you press X
    if event.type == pygame.KEYUP: #makes start screen go away
      if event.key == pygame.K_RETURN:
        gamescreen() 
  
      ball = Ball(window, white, 350, 220, 7)
      p1Paddle = Paddle(window, blue, 50, 180, 10, 60)
      p2Paddle = Paddle(window, red, 630, 180, 11, 60)
  #moves the paddles
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_w: #supposed to make the paddle go up
        p1Paddle.state = 'up'
        print('up')
        
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_s: #supposed to make the paddle go down
        p1Paddle.state = 'down'
        p1Paddle.move()
        print('down')

    
    pygame.display.update()
    clock.tick(45)

and here's the paddle function/class.

class Paddle:
  def __init__(self, screen, colour, posX, posY, width, height):
    self.screen = screen
    self.colour = colour
    self.posX = posX
    self.posY = posY
    self.width = width
    self.height = height
    self.state = 'stopped'
    self.show()

  def show(self):
    pygame.draw.rect(self.screen, self.colour, (self.posX, self.posY, self.width, self.height))

  def move(self):
    if self.state == 'up':
      self.posY -= 10

    elif self.state == 'down':
      self.posY += 10

(I haven't gotten the chance to add the controls for the second paddle; I'll get there once I figure this one out.) It prints 'up' and 'down', so I know it works to some extent.

Upvotes: 1

Views: 249

Answers (1)

Rabbid76
Rabbid76

Reputation: 210948

You need to create the objects before the application loop instead of in the application loop. But you have to draw the objects in each frame at their new position in the application loop:

p1Paddle = Paddle(window, blue, 50, 180, 10, 60)
p2Paddle = Paddle(window, red, 630, 180, 11, 60)
ball = Ball(window, white, 350, 220, 7)
 
while not x:
    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            x = True
        # [...] more events


    # clear screen
    window.fill(0)

    # draw objects
    p1Paddle.show()
    p2Paddle.show()
    ball.show()

    # update display
    pygame.display.update()
    clock.tick(45)

The typical PyGame application loop has to:

Upvotes: 2

Related Questions