Create a typewriter effects animation for strings in Python

As in movies and games, the location of the place appears on the screen as if it were being typed in live. I want to make a game about shielding a maze in python. At the beginning of the game, he gives background information about the game:

line_1 = "You have woken up in a mysterious maze" line_2 = "The building has 5 levels" line_3 = "Scans show that the floors increase in size as you go down" 

Under the variables, I tried to make a for loop for each line like this:

 from time import sleep for x in line_1: print (x) sleep(0.1) 

The only problem is that it prints one letter per line. The timing of this is fine, but how can I get him to follow the same line?

+6
source share
4 answers

Since you tagged your question with python 3, I provided a python 3 solution:

  • Change the ending print character to an empty string: print(..., end='')
  • Add sys.stdout.flush() to print instantly (because the output is buffered)

End Code:

 from time import sleep import sys for x in line_1: print(x, end='') sys.stdout.flush() sleep(0.1) 

Making it random is also very simple.

  • Add this import:

     from random import uniform 
  • Change the sleep call to the following:

     sleep(uniform(0, 0.3)) # random sleep from 0 to 0.3 seconds 
+8
source
 lines = ["You have woken up in a mysterious maze", "The building has 5 levels", "Scans show that the floors increase in size as you go down"] from time import sleep import sys for line in lines: # for each line of text (or each message) for c in line: # for each character in each line print(c, end='') # print a single character, and keep the cursor there. sys.stdout.flush() # flush the buffer sleep(0.1) # wait a little to make the effect look good. print('') # line break (optional, could also be part of the message) 
+7
source

To loop over the lines, change the loop to:

 for x in (line_1, line_2, line_3): 
+1
source

You can change the end-of-line character, which is automatically added by printing with print("", end="") . To print foobar , you can do this:

 print("foo", end="") print("bar", end="") 

From the documentation :

All non-keyword arguments are converted to strings, such as str (), and written to the stream, separated by sep, and then terminated. Both sep and end must be strings; they can also be None, which means using default values.

+1
source

Source: https://habr.com/ru/post/957845/


All Articles