Coding - Python 3

Python – Make a Hangman game part 3: input and display the right picked letters

I enjoy creating inputs. I discovered that creating inputs with while loops in them allowed to create menus that would not need to run inside a while loop. And it makes everything easier. That may sound weird, but my first “big” program with a menu had it in a while loop, so basically it would reload a new menu in the loop, hence costing memory and whatnot. Which was a bad way. I remember it even triggered an error or something fishy at some point. Bear in mind that I’m a junior, and there might be better ways to do that, but so far it’s been working well.

For the game, we need the user to enter ONE letter at a time. And not any letters, one that belongs to the alphabet. It can be entered in lower or uppercase, it’s not relevant as we’ll add something to take care of that conundrum for us. So what we want is the program to accept the input only when it answers the constraints, or else the user must type in again.


INPUT? YES! PUT IT IN!

Or that’s what she said. Yes, apart from being a genius, I also make high-level jokes.
So before we get to the views, in which our inputs will be placed, let’s stay in our first file and create that input and its content there. First, create a variable alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
That variable will be the base of the allowed characters (which is the alphabet). We could have used .isalpha() (that checks if the character belongs to the alphabet a-z A-Z), but for the game I prefer that way in case one would want to use different characters or limit them or whatever.
Then we start a while loop. Why? Because we get out of the loop ONLY if the constraints we set are met. Else, it keeps running that loop. Which also means you need to be careful, or else the program could get stuck in an infinite loop. I like the idea, but it’s not that fun when it happens during a presentation. Which never happened to me. But still, the idea.
In that while loop, we set our input and the conditions to have it right/wrong.
So this is what I’ve got for you (add it after your current code):

1
2
3
4
5
6
7
8
9
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while True:
    letter_input = input("Enter a letter: ").upper()
    if letter_input in alphabet and len(letter_input) == 1:
        break
    elif letter_input == "EXIT":
        exit()
    else:
        continue

Test it. You should get something like:

_ _ _ _ _ _ _
Enter a letter:

The .upper() suffix converts the input into a capital letter. Because “a” does not belong to our string alphabet, it is converted into “A” and does not require anything else.
Adding len(letter_input) == 1 prevents the program from accepting, for example “DE”, which is part of alphabet (so it would work) but is not what we want. We want ONE letter, so we limit the number of accepted characters to 1. If those constraints are met, it gets out of the loop.
If the user enters “exit” (regardless of which character(s) is/are in capital), the program stops.
If none of the above, the loop starts over, so the user must enter something again. So simple, but so powerful. That’s what she… no, I won’t write it.

What to do with that letter? We must check if it is in the chosen word or not, and store it. So I made 2 lists in which the letters will be stored, depending on whether they are right or wrong: wrong_letters and right_letters. Talk about some mysterious variables… To add a letter to a list, we do list.append(letter) (where letter is our validated input).
We’ll also need to move our variable result that will display the new word after validation.
The next step is to check if the right_letters list contains any characters, and go over chosen_word to check if the letter matches. If so, they are added to result, if not, “_” is added. When all letters match, it means we guessed the whole word. That step has to be placed BEFORE the input, so that the user can see the empty word before being asked to enter a letter.
All of that must be put in a while loop, so that the game keeps running.
He is the updated full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import json
import random


language = "english"

def loadWords(language):
    with open("words.json") as file:
        return json.load(file)[language]

words = loadWords(language)

chosen_word = words[random.randrange(len(words))]

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
wrong_letters = []
right_letters = []

while True:
    result = ""

    for c in chosen_word:
        if c in right_letters:
            result += f"{c} "
        else:
            result += "_ "

    print(f"\t{result}")

    while True:
        letter_input = input("Enter a letter: ").upper()
        if letter_input in alphabet and len(letter_input) == 1:
            break
        elif letter_input == "EXIT":
            exit()
        else:
            continue

    if letter_input in chosen_word and letter_input not in right_letters:
        right_letters.append(letter_input)
    elif letter_input not in chosen_word and letter_input not in wrong_letters:
        wrong_letters.append(letter_input)

And testing it:

Enter a letter: e
_ _ A _ _
Enter a letter: r
_ _ A _ R
Enter a letter: h
_ H A _ R
Enter a letter: c
C H A _ R
Enter a letter: i
C H A I R

Yummyyyyy!

We are getting a nice base. In the next episode, we’ll get into the VIEWS, add the health “bar” and render the hanged dude.

Leave a Reply