Increment Python class property and use the incremented property in an infinite while loop

Viewed 27

Hello I am trying to make a circle shape move using pygame. Here is my code

main.py

from src import screen, canvas_background, shapes
import pygame, sys
ball_x = 50
ball_y = 50
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(canvas_background)
    ball = shapes.Ball(ball_x, ball_y)
    ball.deploy()
    ball.addGravity()
    pygame.display.update()

shape.py

class Ball:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def deploy(self):
        pygame.draw.circle(screen, ball_color, [self.x, self.y], ball_r)

    def setGravity(self):
        self.y += 1

Initial window looks like this enter image description here

Problem:

I could use ball_y += 1 to move the ball downwards but I want to do it with setGravity() method. What is the best approach of doing this?

1 Answers

In each frame, a new ball is created at the initial position. You need to create the ball object before the loop and move this object in the loop:

ball = shapes.Ball(ball_x, ball_y)         # <--- INSERT

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(canvas_background)
    # ball = shapes.Ball(ball_x, ball_y)   # <--- DELETE
    ball.deploy()
    ball.addGravity()
    pygame.display.update()
Related