Skip to content
Advertisement

Create a typewriter-effect animation for strings in Python

Just like in the movies and in games, the location of a place comes up on screen as if it’s being typed live. I want to make a game about escaping a maze in python. At the start of the game it gives the background information of 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 do a for loop for each line similar to this:

from time import sleep

for x in line_1:
    print (x)
    sleep(0.1)

The only problem with this is that it print one letter per line. The timing of it is ok, but how can I get it to go on one line?

Advertisement

Answer

Because you tagged your question with python 3 I will provide a python 3 solution:

  1. Change your end character of print to an empty string: print(..., end='')
  2. Add sys.stdout.flush() to make it print instantly (because the output is buffered)

Final 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.

  1. Add this import:

    from random import uniform
    
  2. Change your sleep call to the following:

    sleep(uniform(0, 0.3))  # random sleep from 0 to 0.3 seconds
    
Advertisement