Tinko
Tinko

Reputation: 59

How to add a function with if statements (key movement) in a class (python/pygame)?

I need to program a game in pygame similar to pong, but with 1 player. Although there is one paddle and one ball, I'm required to make a class for the paddle and for the ball. I created the paddle class, drawn it, but I have problem with implementing the if statements for movement. Here's what I tried:

class Paddle():

    def __init__(self,x,y,width,height,color):
        self.x = x
        self.y = y
        self.width  = width
        self.height = height
        self.color  = color
    
    
    
    def Draw(self, screen,):
        pygame.draw.rect(window, self.color, [self.x,self.y,self.width,self.height])

    def Keys(self, y, height):
        keys = pygame.key.get_pressed()

        if keys [pygame.K_UP]: 
            self.y -= 1
        if keys [pygame.K_DOWN]:
            self.y += 1

and then I added a separate function for the objects from the classes:

def Objects():
    paddle = Paddle(1150,250,20,100,black)
    paddle.Draw(window)
    paddle.Keys(250,100)

Again I want to add key movement in the class (since all paddles should have the same function). I should also mention that I'm not getting any error, but it doesn't work.

Upvotes: 1

Views: 112

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

You must create the instance of Paddle before the application loop. Pass the object to the Objects function:

def Objects(surf, paddle):
    paddle.Draw(surf)
    paddle.Keys(250,100)
my_paddle = Paddle(1150,250,20,100,black)

while True:

    # [...]

    Objects(window, my_paddle)

    # [...]

Upvotes: 1

Related Questions