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:

<span style="color: #ff9900;">import</span> time<br /> <span style="color: #ff9900;">import</span> sys

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


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.

<span style="color: #ff9900;">for</span> c <span style="color: #ff9900;">in</span> text:<br /> sys.stdout.write(c)<br /> sys.stdout.flush()<br /> 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:

<span style="color: #ff9900;">from</span> random <span style="color: #ff9900;">import</span> randrange<br /> <span style="color: #ff9900;">for</span> c <span style="color: #ff9900;">in</span> text:<br />     sys.stdout.write(c)<br />     sys.stdout.flush()<br />     seconds = <span style="color: #ff9900;">"0."</span> + <span style="color: #ff9900;">str</span>(randrange(1, 4, 1))<br />     seconds = <span style="color: #ff9900;">float</span>(seconds)<br />     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 time import sys from random import randrange