Reputation: 2782
I am trying to move a paddle in a game of Pong by using the up and down arrows. I am doing this through an event handling loop. Here is the code for the event handling loop:
for event in PE.get():
if event.type == PG.KEYDOWN:
keystate = PG.key.get_pressed()
if event.key == PG.K_ESCAPE:
done = True
if keystate[PL.K_UP]:
rightPaddle.update(-10)
if keystate[PL.K_DOWN]:
rightPaddle.update(10)
if event.type == PG.QUIT:
done = True
The update function is shown below:
def update(self, move):
self.toplefty += move
And here is the PaddleSprite Class:
def __init__(self, x, y):
PG.sprite.Sprite.__init__(self)
self.image = PG.Surface([15,100])
self.topleftx = x
self.toplefty = y
self.rect = self.image.get_rect
self.rect.move_ip(self.topleftx, self.toplefty)
def draw(self, surface):
surface.fill(PINK, self.rect)
def update(self, move):
self.toplefty += move
Simply put, the update function for the paddle (which is essentially a rectangle) moves the top left corner of the rectangle to a new y position based on how many times the up or down arrow is clicked. Each up or down arrow increments the paddle a distance of 10 in either the positive or negative direction. However, in my program, the paddle is not moving at all when I press up or down. Can anyone tell me why? Furthermore, is it possible to move the paddles while I hold down the up or down key rather than me pressing it multiple times to move it?
Upvotes: 0
Views: 326
Reputation: 11170
It looks like you have combined 2 ways of checking for input. They seem to be conflicting. Let us take a look:
for event in PE.get():
this is called a event loop, what pygame does, is stores an input queue of all the events that have happened, and a get(), pops the value from the queue.
The other method is PG.key.get_pressed()
.
This is a more of a hardware approach, since it returns an array of button states.
To fix this, I recommend removing the get_pressed()
call along with the keystate[] checks and replace them with event.key == PG.K_UP
.
EDIT:
It seems that your error is setting a variable of self.toplefty, but using a self.rect to draw. You should use self.rect.move_ip to update, so that it moves the actual rect.
Upvotes: 1
Reputation: 2782
Here's how I got it to work:
def update(self, move):
self.rect.centerx += 0
self.rect.centery += move
Essentially, the problem had to be with update because the event driven loop recognized I was pressing up or down. So I just got the Rect object of the sprite and moved its center in the vertical axis. Thanks to everyone who commented or answered!
Upvotes: 0