Pygame Surface обновляется не последовательно - программирование
Подтвердить что ты не робот

Pygame Surface обновляется не последовательно

Я пытаюсь реализовать простой сценарий Pygame, который должен:

  1. Сначала проверьте, когда пользователь нажимает клавишу Space;
  2. На Space нажмите, покажите текст; затем
  3. Пауза в течение 2 секунд, а затем обновление экрана до исходного состояния.

Обратите внимание, что все перечисленные выше события должны происходить последовательно и не могут быть выведены из строя.

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

Кажется, что программа пропустила шаг 2 и продолжила паузу на шаге 3 перед отображением текста. Мой код выглядит следующим образом:

import pygame
import sys
from pygame.locals import *

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

pygame.init()
wS = pygame.display.set_mode((500, 500), 0, 32)


# Method works as intended by itself
def create_text(x, y, phrase, color):
    """
    Create and displays text onto the globally-defined 'wS' Surface
    (params in docstring omitted)
    """
    # Assume that the font file exists and is successfully found
    font_obj = pygame.font.Font("./roboto_mono.ttf", 32)
    text_surface_obj = font_obj.render(phrase, True, color)
    text_rect_obj = text_surface_obj.get_rect()
    text_rect_obj.center = (x, y)
    wS.blit(text_surface_obj, text_rect_obj)


while True:
    wS.fill(BLACK)
    for event in pygame.event.get():
        if event.type == KEYDOWN and event.key == K_SPACE:

            # Snippet containing unexpected behavior
            create_text(250, 250, "Hello world!", WHITE)
            pygame.display.update()
            pygame.time.delay(2000)
            # Snippet end

        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
    pygame.display.update()

Заранее спасибо!

4b9b3361

Ответ 1

По какой-то причине программа работала для меня, и единственное, что я изменил, это шрифт. Это то же самое, что делает @Omega0x013, но у вас есть неограниченная частота кадров. Это работает, потому что FPS.tick() возвращает количество времени с момента последнего FPS.tick(), если вы не указали частоту кадров, она не поддерживает программу.

import pygame
import sys
from pygame.locals import *
displayText = False
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

pygame.init()
wS = pygame.display.set_mode((500, 500), 0, 32)


# Method works as intended by itself
def create_text(x, y, phrase, color):
    """
    Create and displays text onto the globally-defined 'wS' Surface
    (params in docstring omitted)
    """
    # Assume that the font file exists and is successfully found

    font_obj = pygame.font.Font(None,30)
    text_surface_obj = font_obj.render(phrase, True, color)
    text_rect_obj = text_surface_obj.get_rect()
    text_rect_obj.center = (x, y)
    wS.blit(text_surface_obj, text_rect_obj)

FPS = pygame.time.Clock()
while True:
    wS.fill(BLACK)
    for event in pygame.event.get():
        if event.type == KEYDOWN and event.key == K_SPACE:
            totalTime = 0
            FPS.tick()
            displayText = True

        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
    if displayText:
        totalTime += FPS.tick()
        create_text(250, 250, "Hello world!", WHITE)
        if totalTime >= 2000:
            displayText = False
    pygame.display.update()

Ответ 2

вы должны попробовать следующее:

import pygame
import sys
from pygame.locals import *

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

pygame.init()
wS = pygame.display.set_mode((500, 500), 0, 32)
clock = pygame.time.Clock()

showing = False
timer = 0
# Method works as intended by itself
def create_text(x, y, phrase, color):
    """
    Create and displays text onto the globally-defined 'wS' Surface
    (params in docstring omitted)
    """
    # Assume that the font file exists and is successfully found
    font_obj = pygame.font.Font("./roboto_mono.ttf", 32)
    text_surface_obj = font_obj.render(phrase, True, color)
    text_rect_obj = text_surface_obj.get_rect()
    text_rect_obj.center = (x, y)
    wS.blit(text_surface_obj, text_rect_obj)


while True:
    wS.fill(BLACK)
    for event in pygame.event.get():
        if event.type == KEYDOWN and event.key == K_SPACE:
            showing = True
            timer = 0

        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)

    if showing:
        timer += 1
        create_text(250, 250, "Hello world!", WHITE)

    if timer == 20:
        timer = 0
        showing = False

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

что это делает каждый раз, когда вы нажимаете пробел, он показывает текст для 2-х, показывая его, считая 2000 мс, а затем не показывая его.