简体   繁体   中英

Display Surface quit error when quitting

I made a pygame program what is working fine, but when I try to quit it, error occurs: pygame.error: display Surface quit, and show the code part: DS.blit(bg, (back_x - bg.get_rect().width, 0)). I use quit() command in my events and also at the end of the loop. Can't figure out where is the problem.

import pygame, os, random

pygame.init()
pygame.mixer.init()

W, H = 800,600
HW, HH = W/2,H/2

WHITE = (255,255,255)
PURPLE = (139,34,82)

FPS = 60
DS = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Purpleman')

clock = pygame.time.Clock()

#Allalaadimised
bg = pygame.image.load(os.path.join('Pildid', 'Taust3.png'))
bg = pygame.transform.scale(bg, (2000, 600))
startscreen = pygame.image.load(os.path.join('Pildid', 'Start.png'))
startscreen = pygame.transform.scale(startscreen, (800, 600))
endscreen = pygame.image.load(os.path.join('Pildid', 'dead.png'))
endscreen = pygame.transform.scale(endscreen, (800, 600))
PLAYER_SHEET =  pygame.image.load(os.path.join('Pildid', 'karakter.png')).convert_alpha()

menuu = pygame.mixer.Sound(os.path.join('Helid', 'Taust_laul.ogg'))
ohno = pygame.mixer.Sound(os.path.join('Helid', 'ohno.ogg'))
sad = pygame.mixer.Sound(os.path.join('Helid', 'sad.ogg'))
pygame.mixer.music.load(os.path.join('Helid', 'taustalaul.ogg'))

pygame.display.set_icon(bg)


# Sprite sheeti loikamine ja lisamine listi
PLAYER_IMAGES = []
width = PLAYER_SHEET.get_width() / 4
height = PLAYER_SHEET.get_height()
for x in range(4):
    PLAYER_IMAGES.append(PLAYER_SHEET.subsurface(x*width, 0, width, height))


class Player(pygame.sprite.Sprite):
    '''Mangija'''
    def __init__(self, x, y, py):
        super(Player,self).__init__()
        self.x = x
        self.y = y

        self.jumping = False
        self.platform_y = py
        self.velocity_index = 0
        self.velocity = list([(i/ 1.5)-25 for i in range (0,60)]) #huppe ulatus ja kiirus

        self.frame_index = 0
        self.image = PLAYER_IMAGES[self.frame_index] #kaadri valimine
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image) #hitbox

    def do_jump(self):
        '''Huppemehaanika'''
        if self.jumping:
            self.y += self.velocity[self.velocity_index]
            self.velocity_index += 2
            if self.velocity_index >= len(self.velocity) - 1: #huppe aeglustus (nagu gravitatsioon)
                self.velocity_index = len(self.velocity) - 1
            if self.y > self.platform_y: #platvormi tagades ei huppa
                self.y = self.platform_y
                self.jumping = False
                self.velocity_index = 0


    def update(self):
        '''Kaadrite vahetus ja huppamine'''
        self.rect.center = self.x, self.y
        self.do_jump()
        # Animatsiooni kaadri uuendamine.
        self.frame_index += 1
        self.frame_index %= len(PLAYER_IMAGES) * 7
        # Pildi vahetamine.
        self.image = PLAYER_IMAGES[self.frame_index//7]


def keys(player):
    '''Mangija inputi saamine'''
    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE] or keys[pygame.K_UP] and player.jumping == False:
        player.jumping = True


class Obstacle(pygame.sprite.Sprite):
    '''Mangu takistused'''
    def __init__(self, x, y):
        super(Obstacle,self).__init__()
        self.image = pygame.image.load(os.path.join('Pildid', 'kivi.png')).convert_alpha()
        self.image = pygame.transform.scale(self.image, (90,90))
        self.rect = self.image.get_rect(center=(x, y))
        self.x = x
        self.y = y
        self.mask = pygame.mask.from_surface(self.image)

    def update(self):
        '''Takistuse kustutamine'''
        if self.x < -64:
            self.kill()
        self.x += speed
        self.rect.center = self.x, self.y


class Scoring():
    '''Punktide lugemine ja menuud'''
    def __init__(self):
        with open('highscore.txt', 'w') as f: #high score salvestamine
            try:
                self.highscore = int(f.read())
            except:
                self.highscore = 0

    def score(self,points):
        self.font = pygame.font.Font('freesansbold.ttf',30)
        self.text = self.font.render('Score: ' + str(points) , True, PURPLE)
        DS.blit(self.text, (0,0))

    def text_objects(self,text, font):
        self.textSurface = font.render(text, True, PURPLE)
        return self.textSurface, self.textSurface.get_rect()

    def message_display(self,text):
        self.largeText = pygame.font.Font('freesansbold.ttf',60)
        self.TextSurf, self.TextRect = self.text_objects(text, self.largeText)
        self.TextRect.center = ((W/2),(H/4))
        DS.blit(self.TextSurf, self.TextRect)
        pygame.display.update()
        self.waiting = True

    def startscreen(self):
        '''Algusaken'''
        menuu.play(-1)
        DS.blit(startscreen, [0,0])
        self.draw_text('Purpleman', 48, PURPLE, W/2, H/4)
        self.draw_text('Space to jump', 22, PURPLE, W/2, H*3/7)
        self.draw_text('Press key to play', 22, PURPLE, W/2, H*5/9)
        self.draw_text('High score: ' + str(self.highscore), 22, PURPLE, W/2, 15)
        self.draw_text('All made by TaaviR', 14, WHITE, W/2, 570)
        pygame.display.update()
        self.wait_for_key()

    def pause_endscreen(self):
        '''Lopuaken'''
        sad.play()
        DS.blit(endscreen, [0,0])
        self.draw_text('GAME OVER', 48, PURPLE, W/2, H/4)
        self.draw_text('You ran ' + str(points), 22, PURPLE, W/2, H/2)
        self.draw_text('Press key to play again', 22, WHITE, W/2, H*5/6)
        if points > self.highscore: #high score mehhanism
            self.highscore = points
            self.draw_text('NEW HIGH SCORE!', 22, PURPLE, W/2, H/2 + 40)
            with open('highscore.txt', 'w') as f:
                f.write(str(points))
        else:
            self.draw_text('Highscore ' + str(self.highscore), 22, PURPLE, W/2, H/2 + 40)

        pygame.display.update()

        self.wait_for_key()
        self.waiting = True

    def wait_for_key(self):
        '''Mangija input menuu jaoks'''
        self.waiting = True
        while self.waiting:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    self.waiting = False
                    pygame.mixer.quit()

                elif event.type == pygame.KEYUP:
                    self.waiting = False
                    menuu.stop()
                    pygame.mixer.music.play(-1)
                    sad.stop()

    def draw_text(self,text, size, color, x, y):
        self.font = pygame.font.Font('freesansbold.ttf', size)
        self.text_surface = self.font.render(text, True, color)
        self.text_rect = self.text_surface.get_rect()
        self.text_rect.midtop = (x, y)
        DS.blit(self.text_surface, self.text_rect)

    def crash(self):
        self.message_display('Purpleman got hurt')
        self.waiting = True

def background():
    '''Liikuv taust'''
    back_x = x % bg.get_rect().width
    # ---Draw everything.---
    DS.blit(bg, (back_x - bg.get_rect().width, 0))
    if back_x < W:
        DS.blit(bg, (back_x, 0))


pygame.time.set_timer(pygame.USEREVENT+2, random.choice([2500, 3000, 1500,1000])) #valjastamaks suvaliselt takistusi

#klassid
obstacle = Obstacle(832, 412)
player = Player(190, 359, 359)

#sprite grupid
all_sprites = pygame.sprite.Group(player, obstacle)
obstacles = pygame.sprite.Group(obstacle)

#vajalikud vaartused
index = 3
points = 0
x = 0
x -= 1
speed = -5

start = Scoring()
start.startscreen()
pygame.mixer.music.play(-1)

running = True
while running:
    # ---Mangumootor.---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.mixer.quit()
            pygame.quit()
        elif event.type == pygame.USEREVENT+2:
            r = random.randrange(0, 2)
            if r == 0:
                obstacle = Obstacle(832, 412)
                # Lisamaks takistuse gruppidesse
                obstacles.add(obstacle)
                all_sprites.add(obstacle)



    # ---Mangu loogika---
    all_sprites.update()

    collided = pygame.sprite.spritecollide(player, obstacles, True, pygame.sprite.collide_mask) #kokkupuutumine

    if collided:
        ohno.play()
        pygame.mixer.music.stop()
        start.crash()
        pygame.time.delay(3000)
        pygame.event.clear()
        obstacles.empty()
        start.pause_endscreen()
        points = 0
        speed = -5

    else:
        points += 1

    #vajalikud vaartused
    index += 1
    x -= 2
    speed += -0.008

    #funktsioonid
    background()
    start.score(points)
    all_sprites.draw(DS)
    keys(player)

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

pygame.mixer.quit()
pygame.quit()

Don't call pygame.mixer.quit() and pygame.quit() in the event loop when a pygame.QUIT event occurs. When you call pygame.quit() , you can't use some pygame functions like pygame.display.update anymore because all modules have been uninitialized, and since the while loop is still running, this exception gets raised.

So just remove the pygame.quit and pygame.mixer.quit() in the event loop and call them at the end of the program (as you already do).

Actually, you don't even have to call these functions and can just let the program finish as any other program. I think pygame.quit is only needed to close the window if you run your game with the IDLE IDE (and maybe with other tkinter based applications).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM