When I run this sample pygame code DOS window appears and suddenly disappears without waiting any user input

Viewed 51

When I run this sample PyGame code, a command window appears and suddenly disappears without waiting any user input. What is wrong? I am a newbie and trying to learn python. I have only VBA experiance previously.

The Python version is: Python 3.8.

import pygame
import sys
pygame.init() 

win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game") 

x = 50
y = 50
width = 40
height = 60
vel = 5 

run = True 

while run:
    pygame.time.delay(100) 

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x -= vel 

    if keys[pygame.K_RIGHT]:
        x += vel 

    if keys[pygame.K_UP]:
        y -= vel 

    if keys[pygame.K_DOWN]:
        y += vel 
    win.fill((0,0,0))  # Fills the screen with black
    pygame.draw.rect(win, (255,0,0), (x, y, width, height))
    pygame.display.update()
    pygame.quit()
    sys.exit()
1 Answers

Both your pygame.quit() and sys.exit() should be outside of the run loop, so that they execute only when the loop exits.

What you have now will run a single iteration, because it exits at the end of that iteration. Some people say a short game is a good game but you can take that too far :-)

What I see when I run your code is that the window with the red square appears briefly, then the whole program exits. When I fix your indentation, the window stays there and I can move the red square with the arrow keys:

enter image description here

In other words, this is the form you need:

run = True
while run:
    do_stuff()
pygame.quit()
sys.exit() # Probably not needed since you'll exit anyway.

It also sounds like you're running it from an IDE, given that the window disappears. I always like to run it from the command line so that, should an exception occur (or important output shows up), I can see it after the program has finished.

Related