Trufa
Trufa

Reputation: 40717

How to "style" a text based hangman game

My question is simple, the hangman game looks like this:

enter image description here

I'm doing the indentation in a way I don't think is very good.

I just have var = "\t" and add it at the begging of every print, this seem impractical and hard to maintain.

Would you have it any other way? How is this generally managed?

Thanks in advance!

Upvotes: 0

Views: 9671

Answers (4)

Tom Shaw
Tom Shaw

Reputation: 660

I'd probably fix the typo in "You word looks like this". Then look at printf style formatting, as described here.

Upvotes: 0

ninjagecko
ninjagecko

Reputation: 91094

problem:

print('\tthis')
print('\tis')
print('\tan')
print('\texample')

solution = abstraction!:

def echo(string, indent=1):  # name it whatever you want, e.g. p
    print('\t'*indent + string)

echo('this')
echo('is')
echo('an')
echo('abstraction')

better solution = templates:

template = """
{partial}
 ______
{hangman}
|_________

Your points so far: {points}
You've entered (wrong): {wrong}

Choose a letter:
"""

print(
    template.format(
        partial=..., 
        hangman='\n'.join('|'+line for line in hangmanAscii(wrong=2).splitlines()), 
        points=..., 
        wrong=', '.join(...)
    )
)

Upvotes: 1

DS.
DS.

Reputation: 24110

A quick solution to your immediate problem is a helper function:

def put(text): print "\t" + text

For more interesting stuff, there is a library for terminal-based "graphical"-like applications. It is called "curses", and is available in python too: http://docs.python.org/library/curses.html. There is a tutorial here http://docs.python.org/howto/curses.html, and you can find more online.

Curses makes it possible to do more interesting text-based UI without too much effort. To just replicate what you have, you would probably create a window with the correct size and position (using newwin), and then print text to it without any indent (using addstr). Curses offers a lot of options and several modes of operation. It's not quick to learn, so only makes sense if you plan to do more with terminal based applications.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

Templates aren't just for HTML.

Upvotes: 0

Related Questions