Отображение условия выигрыша - PullRequest
0 голосов
/ 21 апреля 2019

Итак, я делаю 2-мерную игру и хочу отображать выигрышный текст, каждый раз, когда я достигаю нижней части экрана (именно так я выигрываю игру), игра просто зависает и не показывает мой текст. Хотя он будет сброшен и вернется к началу, как я хочу

#this is where I set up my text and font

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

#def message_dissplay(text):
  #  largeText = pygame.font.Font("freesansbold.ttf", 115)
   # TextSurf, TextRect = text_objects(text, largeText)
   # TextRect.center = ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2))
   # gameDisplay.blit(TextSurf, TextRect)

    #time.sleep(2)

   # main()

#def GameWon():
 #   message_dissplay("You Won")

  #this is the mainloop I use for my game
#def main():
   # pygame.init()

    # Set the height and width of the screen
   # size = [SCREEN_WIDTH, SCREEN_HEIGHT]
   # screen = pygame.display.set_mode(size)


    # Main Loop
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

          #I set up my code so if the player reached 750 pixles he gets 
           #reset to 
           #the top and 

         #I want it to display a win text

        if player.rect.y > 750:
            GameWon()

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

1 Ответ

0 голосов
/ 21 апреля 2019

draw() blit() отправляет только в буфер.Вы забыли pygame.screen.update() или pygame.screen.flip() для отправки графики из буфера на видеокарту, которая будет отображать ее.

Вы GameWon() используете sleep(), поэтому игра не может запустить цикл for event и получить движение / щелчок мышью или нажатую клавишу.Он также не может запустить pygame.screen.update() для отправки графики на экран, а затем выглядит так, как будто он зависает.

В примере я использую state для запуска другого кода в основном цикле - intro, game, gameover,и т.д. Я также использую таймер для управления вместо sleep, чтобы он не останавливал цикл.

Вместо того, чтобы снова запускать main(), я использую внешний loop, чтобы игра могла выйти из старого цикла, сбросить настройки и снова запустить старый цикл.Таким образом, мне не нужно снова запускать main ().

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

def message_dissplay(text):
    largeText = pygame.font.Font("freesansbold.ttf", 115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((SCREEN_WIDTH/2), (SCREEN_HEIGHT/2))
    #TextRect.center = screen.get_rect().center
    gameDisplay.blit(TextSurf, TextRect)

def main():
    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    # Main Loop
    repeate_game = True:

    while repeate_game:

        reset_game() # set default values again
        state = 'game' #'intro'

        done = False
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True

            current_time = pygame.time.get_ticks()

            if state = 'intro'
                # here code for intro

            elif state = 'game'
                # here code for game

                if player.rect.y > 750:
                    state = 'gameover'
                    state_end = current_time + 2000 #2000ms = 2s

            elif state = 'pause'
                # here code for pause

                message_dissplay("Pause")

            elif state = 'gameover'
                # here code for Game Over

                message_dissplay("You Won")

                if current_time > state_end:
                    done = True # to exit `while done` after 2000 ms

            # send buffer to video card and on screen 
            pygame.screen.flip() # or pygame.screen.update()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...