why the window of this program closes immediately after opening

Question:

I ran this code for testing if it works and continue but I saw this closes immediately after opening why what is the problem here I checked many different things
What is wrong in this code? How to fix that?

import pygame
import random
pygame.init()
x=480
y=680
tick=pygame.time.Clock()
x_change=0
red=(0,0,255)
green=(0,255,0)
white=(255,255,255)
graphic=pygame.display.set_mode((700,700))
graphic.fill(green)
noexit=True
while noexit:
    pygame.draw.rect(graphic,white,(x,y,20,20))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            noexit=False
        elif event.type==pygame.KEYDOWN:
            if event.key==K_RIGHT:
                x_change=+2
            elif event.key==K_LEFT:
                x_change=-2
        elif event.type==pygame.KEYUP:
            if event.key==K_RIGHT or event.key==K_LEFT:
                x_change=0
    tick.tick(60)

pygame.quit()
quit()

Asked By: Supergamer

||

Answers:

Suggestions:

  1. You should use sys.
import sys

...

sys.quit()
  1. Like as https://stackoverflow.com/users/14531062/matiiss said, you should add pygame. to all the consonants that come from pygame.

  2. You might consider use pgzero (pygame zero) because it is easier.

Errors:

  1. There is a syntax error in lines 22 and 27 where it’s += and -= not =+ and =-.

  2. Just remove quit.

Here’s what your converted code might look like from all the suggestions and errors:

import pgzrun #this line imports pygame zero
import random
import pygame

pygame.init()

x=480
y=680

rect1 = Rect(x, y, 20, 20)

tick=pygame.time.Clock()

def draw(): #you don't have to call draw or update in pygame zero
    screen.clear()
    screen.fill("green")
    screen.draw.filled_rect(rect1, "white")

def update():
    global rect1
    if keyboard.right:
        rect1.x += 2
    elif keyboard.left:
        rect1.x -= 2

    tick.tick(60)

pgzrun.go()

NOTES:

Since pygame zero is a third-party program, install it in the command terminal.

Windows: pip install pgzero
Mac: pip3 install pgzero

You might need to learn pygame zero to understand the code. Go to https://pygame-zero.readthedocs.io/en/stable/ to learn more about pygame zero.

Answered By: Samuel Jeung
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.