Конечный экран в python с использованием pygame

Я создаю свой первый проект Pygame в виде птички, но я хочу отобразить конечный экран, на котором будет отображаться счет, как только игрок выйдет. Я работаю со следующим кодом.

import pygame
import pygame.freetype
import random
import sys
pygame.init()
pygame.font.init()
GAME_FONT = pygame.freetype.Font("OpenSans-Bold.ttf", 24)
surface = pygame.display.set_mode((320, 568))
end_screen = pygame.display.set_mode((320, 568))
bg = pygame.image.load('bg.png')
bird = pygame.image.load('player.png')
text = pygame.font.Font(None, 50)
pole_width = 70
pole_gap = 100
pole_x = 350 - pole_width
top_pole_height = random.randint(100, 200)
pole_color = (220, 85, 57)
bird_x = 0
bird_y = 0
score = 0
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():

        # if event object type is QUIT
        # then quitting the pygame
        # and program both.
        if event.type == pygame.QUIT:
            # deactivates the pygame library
            pygame.quit()

            # quit the program.
            sys.exit()
    pygame.event.get()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_DOWN]:
        bird_y = bird_y + 6
    elif keys[pygame.K_UP]:
        bird_y = bird_y - 6
    if pole_x <= -pole_width:
        pole_x = 320
        top_pole_height = random.randint(100, 400)
        score = score+20
    surface.blit(bg, (0, 0))
    surface.blit(bird, (bird_x, bird_y))
    pygame.draw.rect(surface, pole_color, pygame.Rect(pole_x, 0, pole_width, top_pole_height))  # upper pole
    pygame.draw.rect(surface, pole_color, (pole_x, top_pole_height + pole_gap, pole_width, 568))  # lower pole
    if pole_x <= bird_x + 50 and bird_x <= pole_x + pole_width:
        # In the video you will see the line below
        # if bird_y <= top_pole_height or bird_y >= top_pole_height + pole_gap:
        # However, the bird bottom has to more than the top pole height and gap to
        # hit the bottom pole.
        if bird_y <= top_pole_height or bird_y + 50 >= top_pole_height + pole_gap:
            # score = score - 5
            print(score)
            pygame.quit()
            sys.exit()
        # if score<0:
            # pygame.quit()
            # sys.exit()
    GAME_FONT.render_to(surface, (0, 0), f"score:{score}", (0, 0, 0))
    pole_x = pole_x - 5
    pygame.display.flip()
    pygame.display.update()
    clock.tick(60)


person Devansha    schedule 25.05.2021    source источник
comment
Отвечает ли это на ваш вопрос? Закрытие окна Pygame   -  person itprorh66    schedule 25.05.2021


Ответы (2)


Добавьте переменную gameover, установите для нее значение True, когда игрок умирает, и проверьте ее в цикле:

gameover = False
score = 0
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():

        # if event object type is QUIT
        # then quitting the pygame
        # and program both.
        if event.type == pygame.QUIT:
            # deactivates the pygame library
            pygame.quit()

            # quit the program.
            sys.exit()
    pygame.event.get()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_DOWN]:
        bird_y = bird_y + 6
    elif keys[pygame.K_UP]:
        bird_y = bird_y - 6
    if gameover:
       if keys[pygame.K_SPACE]:
          sys.exit()
    if not gameover:
        if pole_x <= -pole_width:
            pole_x = 320
            top_pole_height = random.randint(100, 400)
            score = score+20
        surface.blit(bg, (0, 0))
        surface.blit(bird, (bird_x, bird_y))
        pygame.draw.rect(surface, pole_color, pygame.Rect(pole_x, 0, pole_width, top_pole_height))  # upper pole
        pygame.draw.rect(surface, pole_color, (pole_x, top_pole_height + pole_gap, pole_width, 568))  # lower pole
        if pole_x <= bird_x + 50 and bird_x <= pole_x + pole_width:
            # In the video you will see the line below
        # if bird_y <= top_pole_height or bird_y >= top_pole_height + pole_gap:
        # However, the bird bottom has to more than the top pole height and gap to
        # hit the bottom pole.
            if bird_y <= top_pole_height or bird_y + 50 >= top_pole_height + pole_gap:
            # score = score - 5
            gameover = True
       
        GAME_FONT.render_to(surface, (0, 0), f"score:{score}", (0, 0, 0))
        pole_x = pole_x - 5
    else:
        GAME_FONT.render_to(surface, (0, 0), f"score:{score}", (0, 0, 0))

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

Также вам не нужны как display.flip(), так и display.update().

person marienbad    schedule 25.05.2021
comment
Я попробовал ваш код, но он не показывает конечный экран - person Devansha; 25.05.2021

здесь эта версия делает, она ждет в конце нажатия клавиши. Мне пришлось изменить некоторые изображения поверхностей, так как у меня их нет, и шрифт, так как он не мог найти этот шрифт на моем компьютере.

import pygame
import pygame.freetype
import random
import sys
pygame.init()
pygame.font.init()
GAME_FONT = pygame.freetype.SysFont("arial", 24)
surface = pygame.display.set_mode((320, 568))
end_screen = pygame.display.set_mode((320, 568))
#bg = pygame.Surface((30,30)) #image.load('bg.png')
bird = pygame.Surface((30,30)) #image.load('player.png')
bird.fill((255,255,0))
text = pygame.font.Font(None, 50)
pole_width = 70
pole_gap = 100
pole_x = 350 - pole_width
top_pole_height = random.randint(100, 200)
pole_color = (220, 85, 57)
bird_x = 0
bird_y = 0
score = 0
gameover = False
clock = pygame.time.Clock()

def wait_for_key():
    pygame.event.wait()
    waiting = True
    while waiting:
        clock.tick(60)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
        
            if event.type == pg.KEYUP:
                waiting = False
        
while True:
    for event in pygame.event.get():

        # if event object type is QUIT
        # then quitting the pygame
        # and program both.
        if event.type == pygame.QUIT:
            # deactivates the pygame library
            pygame.quit()

            # quit the program.
            sys.exit()
    pygame.event.get()
    keys = pygame.key.get_pressed()
    if keys[pygame.K_DOWN]:
        bird_y = bird_y + 6
    elif keys[pygame.K_UP]:
        bird_y = bird_y - 6
    if pole_x <= -pole_width:
        pole_x = 320
        top_pole_height = random.randint(100, 400)
        score = score+20
    
    if not gameover:
        #surface.blit(bg, (0, 0))
        surface.blit(bird, (bird_x, bird_y))
        pygame.draw.rect(surface, pole_color, pygame.Rect(pole_x, 0, pole_width, top_pole_height))  # upper pole
        pygame.draw.rect(surface, pole_color, (pole_x, top_pole_height + pole_gap, pole_width, 568))  # lower pole
        if pole_x <= bird_x + 50 and bird_x <= pole_x + pole_width:
            # In the video you will see the line below
            # if bird_y <= top_pole_height or bird_y >= top_pole_height + pole_gap:
            # However, the bird bottom has to more than the top pole height and gap to
            # hit the bottom pole.
            if bird_y <= top_pole_height or bird_y + 50 >= top_pole_height + pole_gap:
                # score = score - 5
                gameover = True
            # if score<0:
                # pygame.quit()
                # sys.exit()
        GAME_FONT.render_to(surface, (0, 0), f"score:{score}", (0, 0, 0))
        pole_x = pole_x - 5
    else:
        GAME_FONT.render_to(surface, (0, 0), f"score:{score}", (0, 0, 0))
        wait_for_key()
        
    pygame.display.flip()
    pygame.display.update()
        clock.tick(60)
person marienbad    schedule 25.05.2021