EDIT NO. 2
I did a second event loop within the function to check if there is a KEYUP event, and it works now. Thanks everyone who commented!
EDIT
So I've separated the display part from the moving thing and realised that it actually wasn't taking any new inputs from the keyboard, so it didn't know that pg.K_s wasn't pressed anymore, but now I don't know how to get the key_up event from within my function. Should I use event.get again?
I'm trying to make a game in Pygame where you use WASD to control the character. I wanted everything to be contained in different classes and functions, so I moved the character moving out of the main loop and into a function. Unfortunately, now whenever I press any WASD key, the sprite just goes in that direction infinitely and creates a runtime error.
def moving(self):
counter = 0
loop = pg.key.get_pressed()
for i in range(0, len(loop)):
if loop[i] == 1:
counter += 1
else:
continue
while counter == 1:
pressed = pg.key.get_pressed()
if pressed[pg.K_w]:
if (self.y - 3) >= 0:
self.y -= 3
elif pressed[pg.K_a]:
if (self.x - 3) >= 0:
self.x -= 3
elif pressed[pg.K_s]:
if (self.y + 3) <= 238:
self.y += 3
elif pressed[pg.K_d]:
if (self.x + 3) <= 360:
self.x += 3
self.display.fill((0, 0, 0))
self.display.blit(self.justin, (self.x, self.y))
pg.display.flip()
clock = pg.time.Clock()
clock.tick(100)
counter = 0
loop = pg.key.get_pressed()
for i in range(0, len(loop)):
if loop[i] == 1:
counter += 1
else:
continue
Here's the code where the moving function is called:
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.display.quit()
pg.quit()
elif event.type == pg.KEYDOWN:
if (event.key == pg.K_w or event.key == pg.K_a
or event.key == pg.K_s or event.key == pg.K_d):
self.moving()
I just honestly don't know where to go from this - as soon as a button stops being pressed, counter should stay at 0, and so the while loop would close, but it just infintely sends the sprite to the edge of the screen.
print()lines in intervals in your code to debug your code. You can see where the the game is getting caught up in some loop or an if statement that isn't working correctly. Also, take @Bradley Robinson's advice on cleaning up your code.