'Calling class methods inside main game loop
im trying to learn pygame by creating a pong game and defining methods for movement in a 'Paddle' class, how can i call that method in my game loop so the paddles' position is updated when the associtaed keys (s,w,up arrow, down arrow)
class Paddle:
def __init__(self, x, y, width, heigth) -> None:
self.x = x
self.y = y
self.width = width
self.height = heigth
def draw(self, win):
pygame.draw.rect(win, WHITE, (
self.x, self.y, self.width, self.height
))
def move_up(self):
self.y - 10
def move_down(self):
self.y + 10
game loop:
def main():
run = True
clock = pygame.time.Clock()
left_paddle = Paddle(10, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = Paddle(WIDTH - 10 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
while(run):
clock.tick(FPS)
draw(WIN, [left_paddle, right_paddle])
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
keys = pygame.key.get_pressed()
#this is part of my attempts to accomplish movement, didnt work
for key in keys:
if key == pygame.K_w:
left_paddle.move_up
if key == pygame.K_s:
left_paddle.move_down
if key == pygame.K_UP:
right_paddle.move_up
if key == pygame.K_DOWN:
right_paddle.move_down
pygame.quit()
Solution 1:[1]
You got it almost correct.left_paddle.move_up returns the method 'move_up' but it does not call it. Just add () to call the method instead:
for key in keys:
if key == pygame.K_w:
left_paddle.move_up()
if key == pygame.K_s:
left_paddle.move_down()
if key == pygame.K_UP:
right_paddle.move_up()
if key == pygame.K_DOWN:
right_paddle.move_down()
Solution 2:[2]
While calling the functions adding the parenthesis was needed, the main issue was that I was trying to check if the keys were pressed inside a for loop iterating over the 'keys' map. I don't exactly why it didn't work at all but the gist is that after getting the list instead of iterating over it I just checked for specific key inside keys and then called the appropriate methods.
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
left_paddle.move_up()
if keys[pygame.K_s]:
left_paddle.move_down()
if keys[pygame.K_y]:
right_paddle.move_up()
if keys[pygame.K_h]:
right_paddle.move_down()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Blupper |
| Solution 2 | yonatan goldin |
