Back to Everyone Can Use English

Digits Short Term Memory Raining

1000-hours/public/jupyter-notebooks/digits-short-term-memory-raining.ipynb

0.7.91.9 KB
Original Source
python
%pip install edge_tts playsound
python
import random
import edge_tts
import datetime
from playsound import playsound

def generate_digits(n):
    """
    Generates a string of n random digits.
    """
    return ''.join([str(random.randint(0, 9)) for _ in range(n)])

async def speak_digits(digits):
    """
    Speaks every digit in the string to the user with a pause in between.
    """
    VOICE = "en-US-GuyNeural"
    # VOICE = "zh-CN-YunjianNeural"

    # generate voice over file
    OUTPUT_FILE = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.mp3'
    communicate = edge_tts.Communicate(digits, VOICE)
    await communicate.save(OUTPUT_FILE)
    
    # play the OUTPUT_FILE
    playsound(OUTPUT_FILE)

async def play_game(n):
    """
    Plays the memory game.
    """
    num_digits = n
    while True:
        # Generate a string of random digits
        digits = generate_digits(num_digits)

        # a decoration to have edge_tts pronounce with breaks
        voice_string = f"{', '.join(d for d in digits)}, .. over!"

        # Speak the digits to the user|
        print(f"You'll challenge {num_digits} digits to remember, please listen carefully...")
        await speak_digits(voice_string)

        # Ask the user to input what they heard
        guess = input("Please enter what you heard: ")

        # Check if the guess is correct
        if guess == digits:
            num_digits += 1
            print("Congratulations! You got it right!")            
        else:
            num_digits -= 1
            print("Sorry, that's not correct. Keep trying! Let's hold back a little...")
            if num_digits < 1:
                num_digits = 1

        # Ask the user if they want to continue playing
        play_again = input("Do you want to play again? (y/n) ")
        if play_again.lower() != 'y':
            break

    print("Thanks for playing!")

start_length = 5
await play_game(start_length)