I started to work on a Python text adventure game. I will split the working progress into several parts. This is the first one.

With “displaying the text slowly” I mean that, for example the introduction text, should appear like it is just being typed.

 

To do this, you must first import some things:

import time
import sys

The next step is to set the text you want to be “written”.

text = "This is the introduction text."

Now you have to make a for loop to print the text not as a single string, but character by character with a little delay between.

for c in text:
    sys.stdout.write(c)
    sys.stdout.flush()
    time.sleep(0.2)

The “c” stands for character. So the for loop is continuing until it passed every character from the string.

sys.stdout.write(c) writes the actual character.

sys.stdout.flush() actually I’m not sure what this means, I think it just clears the buffer.

time.sleep(0.2) makes the loop wait 0.2 seconds before it writes the next character.

You can set this to any value you feel comfortable with, you can even make it a random number, for example between 0.1 and 0.4.

 

This can be done the following way:

from random import randrange
for c in text:
    sys.stdout.write(c)
    sys.stdout.flush()
    seconds = "0." + str(randrange(1, 4, 1))
    seconds = float(seconds)
    time.sleep(seconds)

seconds = “0.” + str(randrange(1, 4, 1)) generates a random integer between 1 and 4 in the step of 1 and converts it into a string. As we need a number between 0.1 and 0.4 we have to add the 0. manually because randrange does only support integer values.

seconds = float(seconds) converts the string to float, so we can use it with the time.sleep function.

 

This is the whole code again, with the random time.sleep function:

import</span> time
import</span> sys
from</span> random import randrange
text = "This is the introduction text."

for c in text:
    sys.stdout.write(c)
    sys.stdout.flush()
    seconds = "0." + str(randrange(1, 4, 1))
    seconds = float(seconds)
    time.sleep(seconds)