Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

python - how do i make a window quit in pygame?

I want to close the game after was pressed the esc button. how can I do? And where should I place it? I also found some problems that I can't solve, so if you solve them for me I would be happy

This is the code:

#Import Libraries
import pygame
import random

#PyGame Initialization
pygame.init()

#Images Variables
background = pygame.image.load('images/sfondo.png')
bird = pygame.image.load('images/uccello.png')
base = pygame.image.load('images/base.png')
gameover = pygame.image.load('images/gameover.png')
tube1 = pygame.image.load('images/tubo.png')
tube2 = pygame.transform.flip(tube1, False, True)

#Display Create
display = pygame.display.set_mode((288,512))
FPS = 60

#Define Functions
def draw_object():
    display.blit(background, (0,0))
    display.blit(bird, (birdx, birdy))

def display_update():
    pygame.display.update()
    pygame.time.Clock().tick(FPS)

def animations():
    global birdx, birdy, bird_vely
    birdx, birdy = 60, 150
    bird_vely = 0

#Move Control
animations()

while True:
    bird_vely += 1
    birdy += bird_vely
    for event in pygame.event.get():
        if ( event.type == pygame.KEYDOWN
             and event.key == pygame.K_UP):
            bird_vely = -10
        if event.type == pygame.QUIT:
            pygame.quit()
        draw_object()
        display_update()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well you do so by implementing below code snippet in your code:

running = True
while running:
    # other code
    event = pygame.event.wait ()
    if event.type == pygame.QUIT:
         running = False  # Be interpreter friendly
pygame.quit()

Make sure that you call pygame.quit() before you exit your main function

You can also reference this thread Pygame escape key to exit


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...