开发者

How to "style" a text based hangman game

开发者 https://www.devze.com 2023-03-09 03:27 出处:网络
My question is simple, the hangman game looks like this: I\'m doing the indentation in a way I don\'t think is very good.

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

How to "style" a text based hangman game

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

I just ha开发者_开发问答ve 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!


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(...)
    )
)


Templates aren't just for HTML.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消