Pygame Python window stops responding

user9621927

Good day. I am using Pygame with Python 3.6.5. Here's my code:

if event.type == pygame.KEYDOWN:
                if pygame.key == pygame.K_UP:
                    my_change = -15

my += my_change

pygame.display.update()
clock.tick(24)

My problem is, that when I add

running = True
while running: 

To the top of that code, and then run it, my window just stops responding, even though I added just, like, 2 lines of code!

P.S: I have no code to break out of this yet. Could this be one possible reason for this? I do de-indent later on in the code, though, so it only runs for a short period of time. Also: This is all actually in my main game loop. Also: My sprite, Super Mario, just falls right through my ground.

Any help or ideas on this and/or how to fix this issue?

Thanks!!!

Seraph Wedd

I think this is a problem with your loops.

In a pygame loop:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    pygame.display.update()

As you can see, it is an infinite loop. Then, the problem happens in here:

running = True
while running:
    if event.type == pygame.KEYDOWN:
        if pygame.key == pygame.K_UP:
            my_change = -15

With this, you create another infinite loop within the main loop. So, this code will never get to updating you pygame window (as it is stuck in the nested loop).

Remember, updating in pygame should go in a single operation only. As that operation will be repeated for every loop in the main game loop. Try revising your code with this in mind. The way it is now, your code will not work no matter how we arrange it.

Tip: For character motion, creating a class to handle your character, and adding a function for it to update it's position is the most common approach in my opinion.

Possible fix: Move running outside the event loop. Then, add running as another check in your keydown event.

running = True
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

        if running and event.type == pygame.KEYDOWN:
            if pygame.key == pygame.K_UP:
                my_change = -15
    my += my_change
    pygame.display.update()

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related