как очистить текст в окне в pygame

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

проблема в том, что когда вы умираете, он говорит: «Вы умерли», тогда я нажимаю «Воспроизвести снова» или «Выйти». Если вы нажмете «Выход», очевидно, игра выйдет из игры, но если вы снова нажмете «Играть», я хочу, чтобы она перезапустила программу.

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

def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic, (x, y, w, h))
    smallText = pygame.font.SysFont("comicsansms", 20)
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w / 2)), (y + (h / 2)))
    screen.blit(textSurf, textRect)



def quitgame():
    pygame.quit()
    quit()

def dead():
    global dead
    dead = True
    
    while dead:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        largeText = pygame.font.SysFont("comicsansms", 115)
        TextSurf, TextRect = text_objects("You Died", largeText)
        TextRect.center = ((display_width / 2), (display_height / 2))
        screen.blit(TextSurf, TextRect)

        button("Play Again", 20, 450, 115, 50, green, bright_green, respawn)
        button("Quit", 250, 450, 100, 50, red, bright_red, quitgame)

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

для моей функции возрождения. Кто-то сказал мне скопировать и вставить все в мой цикл while true и поместить все это в мою функцию возрождения, и я заметил, что когда вы снова нажимаете кнопку воспроизведения, музыка и звуковые эффекты играют, и все, кроме экрана окончания игры, все еще играю

если вам это нужно, вот код функции возрождения

def respawn():
    global dead
    global run
    global velotimeser 
    global timeForLevel 
    global font 
    global man 
    global zombie 
    global zombie1 

    global randomside 
    global gunCapacity 
    global points
    global powerMeter 
    global bullets 
    global intro 
    dead = False
    velotimeser = 1
    timeForLevel = 0
    font = pygame.font.SysFont('comicsans', 30, True)
    man = Player(300, 508, 64, 64)
    zombie = Enemy(100, 508, 64, 64, 450)
    zombie1 = Enemy1(100, 508, 64, 64, 450)

    randomside = 0
    gunCapacity = 1
    points = 0
    powerMeter = 0
    bullets = []
    intro = False

    pygame.mixer.music.play(-1)

    run = True
    while run and dead == False:

        clock.tick(27)
        #this is the hitbox for when the zombie collides with the player and the player hasnt shot a bullet or has launched a punch that it should deduct a peice of health and 5 points and move the player back depending on where the zombie is facing


        timeForLevel += 0.05
        
        
        


        if man.hitbox[1] < zombie.hitbox[1] + zombie.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie.hitbox[0] and man.hitbox[0] < zombie.hitbox[0] + zombie.hitbox[2] and man.punchislaunched == False and zombie.visible == True and zombie.velo > 0 and man.x > zombie.x:
                man.x += 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        if man.hitbox[1] < zombie.hitbox[1] + zombie.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie.hitbox[0] and man.hitbox[0] < zombie.hitbox[0] + zombie.hitbox[2] and man.punchislaunched == False and zombie.visible == True and zombie.velo > 0 and man.x < zombie.x:
                man.x -= 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        if man.hitbox[1] < zombie.hitbox[1] + zombie.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie.hitbox[0] and man.hitbox[0] < zombie.hitbox[0] + zombie.hitbox[2] and man.punchislaunched == False and zombie.visible == True and zombie.velo < 0 and man.x <= zombie.x:
                man.x -= 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        if man.hitbox[1] < zombie.hitbox[1] + zombie.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie.hitbox[0] and man.hitbox[0] < zombie.hitbox[0] + zombie.hitbox[2] and man.punchislaunched == False and zombie.visible == True and zombie.velo < 0 and man.x > zombie.x:
                man.x += 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        

        #this hitbox detects if the player is touching the zombie whilst punching it
        if man.hitbox[1] < zombie.hitbox[1] + zombie.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie.hitbox[0] and man.hitbox[0] < zombie.hitbox[0] + zombie.hitbox[2] and man.punchislaunched == True and zombie.visible == True:
                if zombie.velo < 0 and zombie.x < man.x:
                    zombie.x = zombie.x - 15
                    zombie.hit()
                    points += 5
                if zombie.velo < 0 and zombie.x > man.x:
                    zombie.x = zombie.x + 15
                    zombie.hit()
                    points += 5
                if zombie.velo > 0 and zombie.x > man.x:
                    zombie.x = zombie.x + 15
                    zombie.hit()
                    points += 5
                if zombie.velo > 0 and zombie.x < man.x:
                    zombie.x = zombie.x - 15
                    zombie.hit()
                    points += 5

        #this is the hitbox for when the zombie collides with the player and the player hasnt shot a bullet or has launched a punch that it should deduct a peice of health and 5 points and move the player back depending on where the zombie is facing
        if man.hitbox[1] < zombie1.hitbox[1] + zombie1.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie1.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie1.hitbox[0] and man.hitbox[0] < zombie1.hitbox[0] + zombie1.hitbox[2] and man.punchislaunched == False and zombie1.visible == True and zombie.velo > 0 and man.x > zombie1.x:
                man.x += 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        if man.hitbox[1] < zombie1.hitbox[1] + zombie1.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie1.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie1.hitbox[0] and man.hitbox[0] < zombie1.hitbox[0] + zombie1.hitbox[2] and man.punchislaunched == False and zombie1.visible == True and zombie.velo > 0 and man.x < zombie1.x:
                man.x += 15
                pygame.time.delay(10)
                points -= 5
                man.hit()
                
        #same thing here expet its for when the zombie is facing left       
        if man.hitbox[1] < zombie1.hitbox[1] + zombie1.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie1.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie1.hitbox[0] and man.hitbox[0] < zombie1.hitbox[0] + zombie1.hitbox[2] and man.punchislaunched == False and zombie1.visible == True and zombie1.velo < 0 and man.x < zombie1.x:
                man.x -= 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        if man.hitbox[1] < zombie1.hitbox[1] + zombie1.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie1.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie1.hitbox[0] and man.hitbox[0] < zombie1.hitbox[0] + zombie1.hitbox[2] and man.punchislaunched == False and zombie1.visible == True and zombie1.velo < 0 and man.x > zombie1.x:
                man.x -= 15
                pygame.time.delay(10)
                points -= 5
                man.hit()

        #this hitbox detects if the player is touching the zombie whilst punching it
        if man.hitbox[1] < zombie1.hitbox[1] + zombie1.hitbox[3] and man.hitbox[1] + man.hitbox[3] > zombie1.hitbox[1]:
            if man.hitbox[0] + man.hitbox[2] > zombie1.hitbox[0] and man.hitbox[0] < zombie1.hitbox[0] + zombie1.hitbox[2] and man.punchislaunched == True and zombie1.visible == True:
                    if zombie1.velo < 0 and zombie1.x < man.x:
                        zombie1.x = zombie1.x - 15
                        zombie1.hit()
                        points += 1
                    if zombie1.velo < 0 and zombie1.x > man.x:
                        zombie1.x = zombie1.x + 15
                        zombie1.hit()
                        points += 1
                    if zombie1.velo > 0 and zombie1.x > man.x:
                        zombie1.x = zombie1.x + 15
                        zombie1.hit()
                        points += 1
                    if zombie1.velo > 0 and zombie1.x < man.x:
                        zombie1.x = zombie1.x - 15
                        zombie1.hit()
                        points += 1
                        

        #this tels it to shoot one bullet at a time instead of sending a group of bullets to the zombie
        if gunCapacity > 0:
            gunCapacity += 1
        if gunCapacity> 10:
            gunCapacity = 0

        #this tels it to close the programe if you press the big red cross at the top right
        for event in pygame.event.get():


            if event.type == pygame.QUIT:
                run = False
           
        #this sets the collision for when the zombie  touches the bullet
        for bullet in bullets:
            if bullet.y - bullet.radius < zombie.hitbox[1] + zombie.hitbox[3] and bullet.y + bullet.radius > zombie.hitbox[1]:
                if bullet.x + bullet.radius > zombie.hitbox[0] and bullet.x - bullet.radius < zombie.hitbox[0] + zombie.hitbox[2] and zombie.visible == True:
                    if zombie.velo < 0 and zombie.x < man.x:
                        zombie.x = zombie.x - 15
                        zombie.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
                    if zombie.velo < 0 and zombie.x > man.x:
                        zombie.x = zombie.x + 15
                        zombie.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
                    if zombie.velo > 0 and zombie.x > man.x:
                        zombie.x = zombie.x + 15
                        zombie.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
                    if zombie.velo > 0 and zombie.x < man.x:
                        zombie.x = zombie.x - 15
                        zombie.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))

                    
                    
                        

            #this tells the bullet to delete itself if it touches the the end of the screen
            if bullet.x < 600 and bullet.x > 0:
                bullet.x += bullet.velo
            else:
                bullets.pop(bullets.index(bullet))

        
        #this sets the collision for when the zombie  touches the bullet
        for bullet in bullets:
            if bullet.y - bullet.radius < zombie1.hitbox[1] + zombie1.hitbox[3] and bullet.y + bullet.radius > zombie1.hitbox[1]:
                if bullet.x + bullet.radius > zombie1.hitbox[0] and bullet.x - bullet.radius < zombie1.hitbox[0] + zombie1.hitbox[2] and zombie1.visible == True:
                    if zombie1.velo < 0 and zombie1.x < man.x:
                        zombie1.x = zombie1.x - 15
                        zombie1.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
                    if zombie1.velo < 0 and zombie1.x > man.x:
                        zombie1.x = zombie1.x + 15
                        zombie1.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
                    if zombie1.velo > 0 and zombie1.x > man.x:
                        zombie1.x = zombie1.x + 15
                        zombie1.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
                    if zombie1.velo > 0 and zombie1.x < man.x:
                        zombie1.x = zombie1.x - 15
                        zombie1.hit()
                        points += 1
                        bullets.pop(bullets.index(bullet))
            #this tells the bullet to delete itself if it touches the the end of the screen
            if bullet.x < 600 and bullet.x > 0:
                bullet.x += bullet.velo
            else:
                bullets.pop(bullets.index(bullet))

        
        if timeForLevel > 20:
            velotimeser = 1.0002
            zombie.velo = zombie.velo * velotimeser
            zombie1.velo = zombie1.velo * velotimeser


        

        keys = pygame.key.get_pressed()

        #these are the keaboard bings for all the functions
        if keys[pygame.K_LEFT] and man.x > man.velo:
            man.x -= man.velo
            man.right = False
            man.left = True
            man.Idlecount = 0
            man.guncount = 0
            man.gunisfired = False
            man.standing = False
        elif keys[pygame.K_RIGHT] and man.x < 600 - man.width - man.velo:
            man.x += man.velo
            man.right = True
            man.left = False
            man.Idlecount = 0
            man.guncount = 0
            man.gunisfired = False
            man.standing = False
        elif keys[pygame.K_SPACE]:
            man.gunisfired = True
            man.isIdle = False
            man.standing = True
            man.Idlecount = 0
            man.punchislaunched = False
            man.walkcount = 0
        
        elif keys[pygame.K_x]:
            man.gunisfired = False
            man.isIdle = False
            man.standing = True
            man.Idlecount = 0
            man.guncount = 0
            man.punchislaunched = True
        else:
            man.walkcount = 0
            man.isIdle = True
            man.guncount = 0
            man.gunisfired = False
            man.standing = True
            man.punchislaunched = False
            man.punchcount = 0
        if keys[pygame.K_SPACE] and gunCapacity == 0:
            
            if man.left:
                facing = -1
            else:
                facing = 1
            if len(bullets) < 5:
                bullets.append(Projectile(round(man.x + man.width //2), round(man.y + man.height//2), 6, (0,0,0), facing))
                bulletSound.play()
            gunCapacity = 1

        #this tells the zombie to respawn when it is dead
        if zombie.visible == False:
            randomside = random.randint(1,4)
            if randomside == 1:
                zombie.x = 20
            if randomside ==2:
                zombie.x = 580
            if randomside ==3:
                zombie.x = 580
                zombie1.x = 520
                zombie1.visible = True
                zombie1.health = 10
                zombie1.draw(screen)
            if randomside == 4:
                zombie.x = 20
                zombie1.x = 80
                zombie1.visible = True
                zombie1.health = 10
                zombie1.draw(screen)

            zombie.visible = True
            zombie.health = 10
            zombie.draw(screen)
        print(randomside)

 

    
    
       
    redrawGameWindow()
    Timetext = font.render('Time elapsed:' + str(round(timeForLevel,1)), 1, (255,251,0))
    screen.blit(Timetext, (20, 10))
    

    pygame.display.update()

если этого кода достаточно для показа, проверьте мой Git hub

могу получить объяснение, как это происходит или как я могу это исправить


person Zina    schedule 04.01.2021    source источник
comment
Кто-то сказал мне скопировать и вставить все в мой цикл while true и поместить все это в мою функцию возрождения Скорее всего, они сказали вам поместить все, что находится до в цикле while, в функция respawn. Это так, что вы можете сбросить все переменные.   -  person Ted Klein Bergman    schedule 04.01.2021
comment
Не копируйте и не вставляйте весь цикл while True. Это не разумное решение. Вместо этого попробуйте установить все переменные в вашей игре в начальное состояние.   -  person    schedule 04.01.2021


Ответы (1)


Спасибо, ребята, за советы, как вы сказали, я должен был просто установить переменные в их исходные условия. Как это

def respawn():
    global dead
    global run
    global velotimeser 
    global timeForLevel 
    global font 
    global man 
    global zombie 
    global zombie1 

    global randomside 
    global gunCapacity 
    global points
    global powerMeter 
    global bullets 
    global intro 
    dead = False
    velotimeser = 1
    timeForLevel = 0
    font = pygame.font.SysFont('comicsans', 30, True)
    man = Player(300, 508, 64, 64)
    zombie = Enemy(100, 508, 64, 64, 450)
    zombie1 = Enemy1(100, 508, 64, 64, 450)

    randomside = 0
    gunCapacity = 1
    points = 0
    powerMeter = 0
    bullets = []
    intro = False

    pygame.mixer.music.play(-1)

    run = True
person Zina    schedule 04.01.2021