Nine weeks. I have completed nine whole weeks of my software engineering bootcamp. During the first two phases, we studied JavaScript and React, along with a little HTML and CSS.
Tomorrow will mark the end of Phase 3, which was all about Python. To show off what we learned, my cohort was split into groups and tasked with creating a command-line interface (CLI) application.
My partner and I chose to create a text-based adventure game, which we titled Cave Crawler. While thinking about the presentation of the game, I decided that I wanted the text in our app to appear in the terminal as if it were being typed.
Thus, the slow_text method was born.
This function takes two arguments:
text
: This is the input text that you want to slowly display.delay
: This is an optional argument that determines the delay, in seconds, between the display of each character. As a default, I set it to 0.03 seconds (30 milliseconds).
Here's a step-by-step explanation of what the above code does:
print()
: This line adds an empty line at the beginning to create some space before displaying the text.sentences = re.split(r"(?<=[.!?])\s+", text)
: This line uses a regular expression (aka RegEx) to split the input text into sentences. It looks for sentence-ending punctuation (periods, exclamation points, or question marks) that is followed by one or more whitespace characters (spaces, tabs, or newlines). The result is a list of sentences, which I tied to a variable.We then encounter some nested loops. The outer loop iterates through each sentence in the
sentences
list, while the inner loop iterates through each character in the sentence.print(char, end="", flush=True)
: Inside the inner loop, the code prints each character (char) of the sentence. Theend=""
argument ensures that a newline character is not added at the end of each print statement, so the characters are printed on the same line. Theflush=True
argument forces the output to be immediately displayed on the screen.time.sleep(delay)
: After printing each character, there is a delay of 0.03 seconds (the default delay). This is what creates the slow text display effect.print()
: Finally, after printing all the characters of a sentence, a newline character is added to move to the next line and start displaying the next sentence.
This method was a simple yet powerful way to add depth and engagement to our game. It has to be one of my favorite parts of the project (along with the ASCII art!). If you happen to be building terminal-based games, feel free to use and alter the code to fit your project's needs.
Good luck and happy coding!