info
Thank you for visiting my website!

Hangman

Python Terminal Game: Hangman

When learning code for the first time, without tutorials, picking where to start can be very daunting, so naturally I went to google and found this website that listed some python projects for beginners.

From this list, I didn’t understand the idea itself for some of the ideas listed, which would make implementing it very hard, or the idea seemed too overwhelming to start. Then I spotted Hangman. This felt like something that was achievable but that I could also add a lot of features to increase difficulty.

At this point I had not started using GitHub, so I edited my code directly in the same document, deleting old code and adding new. I decided it would be best if I put my thought process down on the page. For the step-by-step input/output I used ipython in order to get the results printed directly on the page. Since indentation is important; I write the code and explain it without indentations and then insert a picture of the code (with proper indentation) at the end of each step.

Here you can click to jump to different sections of the project:
Part 1: Welcoming both players to the game
Part 2: Getting word input from user
Part 3: Guessing the letters
Part 4: Updating letters guessed
Part 5: End of game


1: Welcoming both players to the game

The first step is to get input from the players:

username1 = input("Player 1, please enter your name: ")
username2 = input("Player 2, please enter your name: ")

This username1 will store the “input” that the player types on the screen:


As can be seen above, I entered “Anja” when prompted and the second line showed that the username1 has stored Anja.

print(f"") the ‘f’ in the print function allows us to simplify our code and combine strings with variables without having + in between. Rather than writing:

print(“Hello ” + username1 + “ and ” + username2 + “! Welcome to Hangman!”)
It can be simplified to:
print(f"Hello, {username1} and {username2}! Welcome to Hangman!")
print("Let's begin!")

Here is the code so far:

2: Getting word input from user

I made a variable “secretword” to store the word that a player enters as their word to be guessed. Since right now the two players play on the same screen, I wanted the word to be hidden. I found that the library getpass will not display the typed letters. So first we must import getpass (I always import all libraries at the top of the code).

Then we can call on the getpass() function to take the input and store it into our secretword variable:

secretword = getpass.getpass(f”{username1}, enter your word: ").lower()
We must put .lower() function to change the input into lowercase letters to be able to compare letters regardless of the capitalization of the entry.

We want to also have the numbers of letters in the word displayed to the other user. At first what I did was create an empty string variable:

s = ""
Then, create a for-loop for the length of the secret word - len(secretword) - and have the index “i” cycling through the range() of the length. For each iteration it would add (+=) an underscore to the variable s, resulting, at the end of the for-loop, with s have the correct number of underscores as there are letters.
for i in range(len(secretword)):
s+="_"
However, I then found that it could be written a lot easier:
s = '_' * len(secretword)

Last thing for this part would be to print to show other player how many letters:

print(f"{username2} the word to guess is {s}")
So my code for the second part would be:

3: Guessing the letters

We want to ensure we are keeping track of the letters that have already been guessed because we will need to check against that list when we code out errors. I made a list:

guessedletters = []
And I wanted to also keep track of the number of guesses that player has had so I initialized the guesses left variable to be a hard coded 10 guesses:
guessesleft = 10

In order to keep allowing the second player to guess letters, I decided to use a while loop. Meaning that while a condition is met the loop will continue. The way I approached it was as long as there was an underscore in my secret word, then the player would continue to get guesses:

while ("_" in s):
In the while loop, I needed to separate right away into two cases: the first one being if the number of guesses is 10 and under and the second case being if it is over 10 guesses. I did this by creating an if/else statement:
if guessesleft <= 10:

else:
The else case was easy because if the player has had more than 10 guesses the game is over.
print("Sorry you have no more guesses left. Game Over.")
Then we must break out of the while-loop.
break

For the if guessesleft <= 10:
We first must ask the player for their letter guess. When comparing the letters they should all be lowercase in order to be able to compare letters.

letter = input(f"{username2}, what is your letter guess? ").lower()

Now we must break it down into a couple cases to check for errors:

Case 1: is the input a single letter?
We can check if the input is a letter by using the function .isalpha(). We can check that the input is a single input by checking len(letter):

if (not letter.isalpha() or len(letter) != 1):
print("\nNot a valid entry. Please enter a valid single letter.\n")

Case 2: is the letter a new guess?
elif” is used if you have multiple if statements that are connected. It is short for else if. Here we want to check if the letter is in our stored list of guessed letters.

elif (letter in guessedletters):
print("\nYou have already guessed this letter. Please pick a new letter.\n")

Case 3/4: is the letter in the secretword?
Finally, if the letter is a new single letter (checked in case 1) and a new letter (checked in case 2), we want to check if it is in the secretword:

else:
if (letter in secretword):
print(f"\nYou guessed the correct letter {letter}! You still have {guessesleft} guesses left.")
Since the correct letter was guessed we would like to fill in the word in the correct spots. For this we must use a for-loop to cycle through the indices of the secret word.
We must check that we are only looking in the range of the length of the secret word:
for i in range(len(secretword)):
Then check indices:
if (letter == secretword[i]):

We can replace the “s” word with

s = s[:i] + letter + s[i+1:]
: means from the initial location to i, and then i+1 to end location.

However, if the letter is not in the secretword we want to take away a guess (guesses left - 1). We also would like the player to know how many guesses they have left, along with a reminder of what the word looks like thus far with each guess.

else:
guessesleft -= 1 print(f"\nSorry, {letter} is not in the word. You have {guessesleft} guesses left.")

print(f"The word so far is: {s}\n")

The code from step three looks like this:

4: Updating letters guessed

Since we are keeping track of our guessed letters for error tracking, we want to add each letter to our guessedletters[] list.

If we cared about order in a list we can insert it by:

guessedletters.insert(k, letter)
k = k + 1

But in this case we are just keeping track of the letters guessed and not the order so we can use .append() function:

guessedletters.append(letter)

The code from step four looks like this:

5: End of game

We need to consider if the person has guessed the word in under 10 incorrect guesses:

if guessesleft <= 10:
print(f"\nCONGRATULATIONS! You guessed the secret word {secretword}!")
The final code looks like this: