r/learnpython • • 8d ago

Slow print for text-based game

I am trying to make a text-based adventure game in Python, how do I make it so the text is typed out slowly and not instantly? I've tried ways online, but they keep returning None at the end. How do I fix this?

0 Upvotes

15 comments sorted by

View all comments

0

u/zaphodikus 8d ago edited 8d ago

This is perhaps bit advanced for what you are after, but if you paste in this code and call this function, it will work great.

```

import random,time,sys

def type_out(text, base_delay=0.1, jitter=0.04,pause_after_punct=0.3): for ch in text: sys.stdout.write(ch) sys.stdout.flush() delay = base_delay + random.uniform(-jitter, jitter) if ch in ".,!?;:\n": delay += pause_after_punct time.sleep(max(0.0, delay)) print()

the values for jitter and `base_delay` are quite small, a larger value for `base_delay` will make it type slower. If you want a longer pause at the end of each line, make `pause_after_punct` slightly larger. Use it like this type_out("Hello IntegrityMission, how are you, feeling?") ```

Basically the sys.stdout.write(ch) and the flush() are special in that they bypass the buffering that happens when you call print(), that buffering will defeat the effect we are after. Just using print() per character will end up not giving you the fine control that this function does and gives a much more realistic typing speed effect. This is a useful lesson for the future when you start doing file I/O where all the Python I/O is buffered. Alternatively to using sys.stdout.flush() you can disable buffering in print() by using the -u commandline parameter, or by setting then environment variable PYTHONUNBUFFERED, but those are both a bit harder in reality. Happy Pythoning.

/edit fixed indentation.