Flushing strings

Remember those old green-screen terminals that print a character at a time? They are really retro, keep in with the theme of my game and they were certainly present in the movie my game is modelled on.

greenscreen.png

I wanted to emulate this character typing effect on the Terminal to differentiate normal game mode from the computer in the story and to add some atmosphere to the game.

Capturing the text input, creating a list of the characters (using list(arg)) and using a time method was fairly easy. I’ve come across datetime methods before so I was pretty confident Python would have an equivalent.

import time

def print_terminal(str):         
    char = list(str)                                                                                                                                        

    for item in char:                                                           
        print(item, end='')                               
        time.sleep(.1)                                                                                                                                       

The sleep time took a bit of trial and error as the argument is in sec rather than ms which I thought was a bit odd.

However, I kept getting a syntax error for the line:
print(item, end='')

Removing the end=“ statement would correctly print out the text with the time lag but vertically, (a new line for each character). When I included it, output would pause then print as one statement.

After some investigation, I found that it was necessary to flush the buffer. This happens immediately after each message and resolves the issue.

print(item, end'', flush=True)

I also added the sep=‘ ’ argument to manage the empty space between words in the string. So my revised and functioning method became:

import time

def print_flush(str):
    char = list(str)

    for item in char:

        print(item, sep=' ', end='', flush=True)
        time.sleep(.1)

I also added a quick way to clear the Terminal although this will not work cross-platform:

def clear_terminal():                                                           
        print("\033c")

Finally, I added colorama to complete the effect and generate a realistic green-screen terminal emulation.

Screen Shot 2018-06-22 at 22.16.18.png

I’m pretty happy with the way it has worked out and will park these functions for use later in the game later.

 
2
Kudos
 
2
Kudos

Now read this

Understanding the game engine

Whilst I work through the different game elements and features I want to implement, I though I’d revisit the game engine from LPTHW. To be honest, I’ve struggled here a bit. The first time I implemented the game engine I didn’t really... Continue →