patternpythonMinor
Simple game of Hangman
Viewed 0 times
gamesimplehangman
Problem
On my quest to become a master programmer I have created a simple game of Hangman, and so I thought I would upload it here and see how it could be refined.
One question I had was my use of exception handling. I tried to utilise it here, but I get the sense it might have been overkill. Should I only be using try/except if I know there will be exceptions, or is it good practice to use them regardless?
```
"""Hangman
Standard game of Hangman. A word is chosen at random from a list and the
user must guess the word letter by letter before running out of attempts."""
import random
def main():
welcome = ['Welcome to Hangman! A word will be chosen at random and',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts. Good luck!'
]
for line in welcome:
print(line, sep='\n')
# setting up the play_again loop
play_again = True
while play_again:
# set up the game loop
words = ["hangman", "chairs", "backpack", "bodywash", "clothing",
"computer", "python", "program", "glasses", "sweatshirt",
"sweatpants", "mattress", "friends", "clocks", "biology",
"algebra", "suitcase", "knives", "ninjas", "shampoo"
]
chosen_word = random.choice(words).lower()
player_guess = None # will hold the players guess
guessed_letters = [] # a list of letters guessed so far
word_guessed = []
for letter in chosen_word:
word_guessed.append("-") # create an unguessed, blank version of the word
joined_word = None # joins the words in the list word_guessed
HANGMAN = (
"""
-----
| |
|
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| -+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /
One question I had was my use of exception handling. I tried to utilise it here, but I get the sense it might have been overkill. Should I only be using try/except if I know there will be exceptions, or is it good practice to use them regardless?
```
"""Hangman
Standard game of Hangman. A word is chosen at random from a list and the
user must guess the word letter by letter before running out of attempts."""
import random
def main():
welcome = ['Welcome to Hangman! A word will be chosen at random and',
'you must try to guess the word correctly letter by letter',
'before you run out of attempts. Good luck!'
]
for line in welcome:
print(line, sep='\n')
# setting up the play_again loop
play_again = True
while play_again:
# set up the game loop
words = ["hangman", "chairs", "backpack", "bodywash", "clothing",
"computer", "python", "program", "glasses", "sweatshirt",
"sweatpants", "mattress", "friends", "clocks", "biology",
"algebra", "suitcase", "knives", "ninjas", "shampoo"
]
chosen_word = random.choice(words).lower()
player_guess = None # will hold the players guess
guessed_letters = [] # a list of letters guessed so far
word_guessed = []
for letter in chosen_word:
word_guessed.append("-") # create an unguessed, blank version of the word
joined_word = None # joins the words in the list word_guessed
HANGMAN = (
"""
-----
| |
|
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
|
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| -+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /-+-\
|
|
|
|
|
--------
""",
"""
-----
| |
| 0
| /
Solution
You have a bare except clause; i.e.,
The problem with a bare except is that it will catch all exceptions, including ones you really don’t want to be ignoring (like KeyboardInterrupt and SystemExit). It would be much better if your except block only caught the specific exception you expect, and let all others bubble up as normal.
A few other general comments on your code:
-
In line 200, you have this construction:
You’re looping over the index variable, but also using the list element. It would be better to write:
-
Rather than using the flag value
That’s a bit cleaner and easier to follow, because I don’t have to follow the
-
Your main() function is huge. Most of this code is not reusable, because it’s tied up in a single monolithic function. You’d be much better off breaking it into small, distinct units of code: those are easier to test and debug, and it would be more reusable to boot.
try:
some_code()
except:
clean_up()The problem with a bare except is that it will catch all exceptions, including ones you really don’t want to be ignoring (like KeyboardInterrupt and SystemExit). It would be much better if your except block only caught the specific exception you expect, and let all others bubble up as normal.
A few other general comments on your code:
-
In line 200, you have this construction:
for letter in range(len(chosen_word)):
if player_guess == chosen_word[letter]:
word_guessed[letter] = player_guessYou’re looping over the index variable, but also using the list element. It would be better to write:
for idx, letter in enumerate(chosen_word):
if player_guess == letter:
word_guessed[idx] = player_guess-
Rather than using the flag value
play_again, you could use a break statement. That is, structure your code as follows:while True:
# play the game
if not player_response_is_play_again():
breakThat’s a bit cleaner and easier to follow, because I don’t have to follow the
play_again variable around.-
Your main() function is huge. Most of this code is not reusable, because it’s tied up in a single monolithic function. You’d be much better off breaking it into small, distinct units of code: those are easier to test and debug, and it would be more reusable to boot.
Code Snippets
try:
some_code()
except:
clean_up()for letter in range(len(chosen_word)):
if player_guess == chosen_word[letter]:
word_guessed[letter] = player_guessfor idx, letter in enumerate(chosen_word):
if player_guess == letter:
word_guessed[idx] = player_guesswhile True:
# play the game
if not player_response_is_play_again():
breakContext
StackExchange Code Review Q#95997, answer score: 9
Revisions (0)
No revisions yet.