Reputation: 145
When I run the code below, the pygame rect wont move. It is set to move -7 in the x direction at each left arrow press, but nothing happens. I tried to print the position of the rect, and it seems like it's position is updated once, from the initial position 300, to 293, although there is no movement on screen. Any help is much appreciated!
import sys
import pygame
PINK = (255, 102, 255)
BLACK = (0, 0, 0)
pygame.init()
clock = pygame.time.Clock()
pygame.display.init()
font = pygame.font.SysFont("impact", 20)
screen = pygame.display.set_mode(750, 550)
class Paddle:
def __init__(self):
self.paddle = pygame.Rect(300, 730,
10,
52)
def draw_paddle(self):
# Draw paddle
pygame.draw.rect(screen, PINK,
self.paddle)
def move_paddle_left(self):
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.paddle.left -= 7
if self.paddle.left < 0:
self.paddle.left = 0
print(self.paddle)
class Game:
def __init__(self):
self.run()
Paddle()
# Levels().draw_level_one()
def run(self):
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# fps lock, screen fill and method call for input
clock.tick(60)
screen.fill(BLACK)
Paddle().draw_paddle()
Paddle().move_paddle_left()
pygame.display.flip()
# Creates instance of the game class, and runs it
if __name__ == "__main__":
Game()
Game().run()
Upvotes: 0
Views: 860
Reputation: 655
While I can't get your code to actually draw a paddle, I do notice that you create a new Paddle instance in every iteration of the loop, so the position resets to 300 each time.
Try this instead:
def run(self):
paddle = Paddle()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# fps lock, screen fill and method call for input
clock.tick(60)
screen.fill(BLACK)
paddle.draw_paddle()
paddle.move_paddle_left()
pygame.display.flip()
That way you create a paddle object and then re-use its values in each iteration and it'll keep moving left until it hits 0.
Upvotes: 1