Creating a Text Figure for the Word Game

There are a number of ways to tackle this creativity option. I will show two potential approaches below for creating “hangman”-style figures using multi-line strings and the format method.

The triple quotes we use to create docstrings actually create multi-line strings. Thus we can write the figure directly into our program without any additional formatting, e.g.

FIGURES = [
r"""
|-----|
|     O
|    \|/
|     |
|    / 
""",
r"""
|-----|
|     O
|    \|/
|     |
|    / \
"""
]

Here I have created a constant list with two steps in the figure drawing. I can then print these stages out via list indexing, e.g.

>>> print(FIGURES[1])

|-----|
|     O
|    \|/
|     |
|    / \

A couple of notes:

The above approach is very effective (and totally OK for the lab, despite being not very DRY). The one caveat is that it only works for games with specific numbers of allowed wrong guesses. You should include a fallback (i.e., just show stars) if more wrong guesses are allowed and start with some of the drawing already filled if there are fewer than the number of guesses assumed in your drawing.

If you want to DRY up your implementation, one way to do so is with the string format method. format makes it easier to insert characters within strings. For example:

FIGURE = r"""
|-----|
|     {0[0]}
|    {0[1]}{0[2]}/
|     |
|    / \
"""

When I invoke the format method on this string, {0[0]} will be replaced with the item at the 0 index of the first positional argument to format. For example:

>>> print(FIGURE.format(r"O\ "))

|-----|
|     O
|    \ /
|     |
|    / \

The curly braces are replaced by “O”, “" and “ “, respectively. You could carefully construct the argument to format depending on the number of wrong guesses the player had made.