Salamoonder
Salamoonder

Reputation: 25

Why does my pygame window freeze and crash?

Whenever I try to run my program it freezes up and crashes. I'm not a master pygame coder, but I'm almost sure its something to do with my main loop. It's supposed to allow the user to move left and right using arrow keys. I've tried adding a clock and changing the size of the screen but that didn't work. Here is the code:

import pygame
import sys
import random 
import time

pygame.init()
screen = pygame.display.set_mode((500,500))

events = pygame.event.get()
clock = pygame.time.Clock()

x = 50
y = 50

game_over = False
while not game_over:
    for event in events:
        if event.type != pygame.QUIT:

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    x += 5
                elif event.key == pygame.K_LEFT:
                    x -= 5

        else:
            sys.exit()

    
    screen.fill((0,0,0))
    pygame.draw.rect(screen, (255,255,255), (x,y,50,50))
    clock.tick(30)
    pygame.display.update()

Upvotes: 1

Views: 964

Answers (2)

Kingsley
Kingsley

Reputation: 14906

The code needs to process the event queue continuously, otherwise your operating environment will consider your window to be non-responsive (locked up). Your code is almost there, except it only fetches the new events once, but this needs to be done every iteration of the main loop.

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()

x = 50
y = 50

game_over = False
while not game_over:
    events = pygame.event.get()                   # <<-- HERE handle every time
    for event in events:                     
        if event.type != pygame.QUIT:

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    x += 5
                elif event.key == pygame.K_LEFT:
                    x -= 5
        else:
            sys.exit()
    
    screen.fill((0,0,0))
    pygame.draw.rect(screen, (255,255,255), (x,y,50,50))
    clock.tick(30)
    pygame.display.update()

Upvotes: 2

The Big Kahuna
The Big Kahuna

Reputation: 2110

You cant do foe event in events, as when you call pygame.events.get(), you are updating them, you are updating them once and looping over them every frame, you need to use for event in pygame.event.get(): so you are calling the function every frame and updating the events every frame

unless you were trying to do this?

events = pygame.event.get
...
for event in events():

which does the same as above

Upvotes: 1

Related Questions