Typewriter Effect on a list

93 Views Asked by At

I am making the base of a game, and for the intro, I need it to print out like a typewriter. When I call it as multiple, it prints out the whole object, rather than slowly printing it out, like a typewriter would

import random
import sys
from time import sleep

test_list = ['obj 1', 'obj 2']

def writer(text, multi = True):
    if multi == True:
        obj = 0
        for item in text:
            sleep(1)
            sys.stdout.write(text[obj])
            
            obj += 1
            sys.stdout.flush()
    
    else:
        for char in text:
            sleep(0.05)
            sys.stdout.write(char)
            sys.stdout.flush()

writer(test_list)
2

There are 2 best solutions below

3
Ömer Sezer On BEST ANSWER

"for char in item" added, "obj" removed, "sys.stdout.write('\n')" added for pretty printer.

Code:

import random
import sys
from time import sleep

test_list = ['obj 1', 'obj 2']

def writer(text, multi=True):
    if multi:
        for item in text:
            for char in item:
                sleep(0.5)  # <= adjust how many secs to wait for
                sys.stdout.write(char)
                sys.stdout.flush()
            sys.stdout.write('\n')  
    else:
        for char in text:
            sleep(1)   # <= adjust how many secs to wait for
            sys.stdout.write(char)
            sys.stdout.flush()
        sys.stdout.write('\n')  

writer(test_list)
0
Anna Andreeva Rogotulka On

you miss inner for with each symbol in string - for char in item:

import random
import sys
from time import sleep

test_lists = ['obj 1', 'obj 2']


def writer(text, multi = True):
    if multi == True:
        obj = 0
        for item in text:
            for char in item:
                
                sys.stdout.write(char)
                obj += 1
                sys.stdout.flush()
                sleep(1)
                
    
    else:
        for char in text:
            sleep(0.05)
            sys.stdout.write(char)
            sys.stdout.flush()

writer(test_lists)