1

The conditional operator checks "if answer_code == NumberX" then the code starts the sound, but due to the fact that it's all in the loop, the sound is played every frame. How do I make the sound play 1 time?

while run:
        timer.tick(fps)  # Контроль времени (обновление игры)
        left_click = False
        events = pygame.event.get()
        for event in events:  # Обработка ввода (события)
            if event.type == pygame.QUIT:  # Проверить закрытие окна
                run = False  # Завершаем игровой цикл
            if event.type == pygame.MOUSEBUTTONDOWN:
                left_click = event.button = 1
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_BACKSPACE:
                    answer_code = answer_code[:-1]
                else:
                    answer_code += event.unicode

        # Рендеринг (прорисовка)

        screen.fill(WHITE)  # Заливка заднего фона
        screen.blit(BackGround.image, BackGround.rect)

        if answer_code == NumberX:
            print_text('Правильно', width // 2 - 400, height // 2 -500, font_color=(0, 255, 0), font_size=200)
            print(answer_code)
            print(valueOne, valueTwo, (valueOne * valueTwo))

            pygame.mixer.Sound.play(win_sound)

        pygame.display.update()  # Переворачиваем экран
Neytron
  • 23
  • 2

1 Answers1

1

You don't have to call pygame.mixer.Sound.play frame. pygame.mixer.Sound.play only plays the sound in the background. The sound is played only when the response is received:

while run:
    timer.tick(fps)  # Контроль времени (обновление игры)
    left_click = False
    events = pygame.event.get()
    for event in events:  # Обработка ввода (события)
        # [...]
            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                answer_code = answer_code[:-1]
            else:
                answer_code += event.unicode

            if answer_code == NumberX:
                pygame.mixer.Sound.play(win_sound)

    # [...]

    if answer_code == NumberX:
        print_text('Правильно', width // 2 - 400, height // 2 -500, font_color=(0, 255, 0), font_size=200)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174