3
\$\begingroup\$

I just completed Pset 2 about the Hangman game that was issued from OCW MIT. The Pset has no available solution so that any comment regarding code writing best practices would be greatly appreciated (especially about defining functions and linking them to each other). Thank you and have a nice weekend y'all.

# Hangman Game
# -----------------------------------
import random
import string

WORDLIST_FILENAME = "words.txt"


def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist



def choose_word(wordlist):
    """
    wordlist (list): list of words (strings)
    
    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code

# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = load_words()


def is_word_guessed(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    guess = str()
    for char in secret_word:
        for letter in letters_guessed:
            if char == letter:
                guess += char
            else:
                continue
    
    if guess == secret_word:
        return True
    else:
        return False



def get_guessed_word(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    showbox_list = list()
    for char in secret_word:
        showbox_list.append('_ ')
        
    for letter in letters_guessed:
        for count, char in enumerate(secret_word):
            if letter == char:
                showbox_list[count] = letter
            else:
                continue
    
    showbox_str = ''.join(showbox_list)
    
    return showbox_str

    


def get_available_letters(letters_guessed):
    '''
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    english_letters = list(string.ascii_lowercase)
    

    for letter in letters_guessed:
        english_letters.remove(letter)
    
    english_letters_str = ''.join(english_letters)
    print('Available letters:', english_letters_str)
    
    return english_letters_str
    

def hangman(secret_word):
    '''
    secret_word: string, the secret word to guess.
    
    Starts up an interactive game of Hangman.
    
    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.
      
    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.
    
    * Ask the user to supply one guess per round. Remember to make
      sure that the user puts in a letter!
    
    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.
    
    Follows the other limitations detailed in the problem write-up.
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    secret_word = choose_word(wordlist)
    letters_guessed = list()
    warnings_remaining = 3
    guesses_remaining = 6
    good_guess = 0
    print('''
          \n
          OOO-----------------------------------------------OOO
          \n
                         Welcome to the Hangman!,
                       
                       
              I'm thinking of a word that is %d letters long.
          \n
          OOO-----------------------------------------------OOO
          \n
          ''' % len(secret_word))
          
          
    while not is_word_guessed(secret_word, letters_guessed) and guesses_remaining > 0:
        
        print("\nYou have %d guesses left." % guesses_remaining)
        get_available_letters(letters_guessed)
        letter = str.lower(input("Please guess a letter: "))
        
        if not letter or letter not in string.ascii_lowercase:
            if warnings_remaining != 0:
                warnings_remaining -= 1
                print("That is not a valid letter. You have %d warning left." % warnings_remaining)
            else:
                print("That is not a valid letter. You have no warning left, so you lose one guess.")
                guesses_remaining -= 1

        elif letter in letters_guessed:
            if warnings_remaining != 0:
                warnings_remaining -= 1
                print("You've already guessed that letter. You have %d warning left." % warnings_remaining)
            else:
                print("You've already guessed that letter. You have no warning left, so you lose one guess.")
                guesses_remaining -= 1
        
        else:
            letters_guessed.append(letter)
            if letter not in secret_word:
                print("That letter is not in my word.")
                if letter in 'aiueo':
                    guesses_remaining -= 2
                else:
                    guesses_remaining -= 1
            else:
                print("Good guess!")
                good_guess += 1 
                
        print(get_guessed_word(secret_word, letters_guessed)) 
        print("\nOOO-----------------------------------------------------------------------OOO\n")
        
        if is_word_guessed(secret_word, letters_guessed):
            print("Congratulations, you won!")
            print("Your total score for this game is %d." % (good_guess * guesses_remaining))
        
        if guesses_remaining == 0:
            print("Sorry, you ran out of guesses. The word was %s." % secret_word)

# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)


# -----------------------------------



def match_with_gaps(my_word, other_word):
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the 
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise: 
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    my_word_stripped = my_word.replace(" ", "")
    same_char = list()
    blank_stripped = list()
    if len(my_word_stripped) == len(other_word):
        for index, letter in enumerate(my_word_stripped):
            if letter in string.ascii_lowercase:
                same_char.append(index)
            else:
                blank_stripped.append(index)
            
    else:
        return False

    mws = ''
    ow = ''
    for index_same in same_char:
        for index_dif in blank_stripped:
            if other_word[index_dif] == other_word[index_same]:
                return False
            else:
                mws += my_word_stripped[index_same]
                ow += other_word[index_same]
    
    if mws == ow:
        return True
    else:
        return False


def show_possible_matches(my_word):
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    possible_matches = list()
    for i in wordlist:
        if match_with_gaps(my_word, i):
            possible_matches.append(i)
    
    spm = ' '.join(possible_matches)
    
    return spm


def hangman_with_hints(secret_word):
    '''
    secret_word: string, the secret word to guess.
    
    Starts up an interactive game of Hangman.
    
    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.
      
    * The user should start with 6 guesses
    
    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.
    
    * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter
      
    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.
      
    * If the guess is the symbol *, print out all words in wordlist that
      matches the current guessed word. 
    
    Follows the other limitations detailed in the problem write-up.
    '''
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    secret_word = choose_word(wordlist)
    letters_guessed = list()
    warnings_remaining = 3
    guesses_remaining = 6
    good_guess = 0
    print('''
          \n
          OOO-----------------------------------------------OOO
          \n
                         Welcome to the Hangman+!,
                       
                       
              I'm thinking of a word that is %d letters long.
          \n
          OOO-----------------------------------------------OOO
          \n
          ''' % len(secret_word))
          
          
    while not is_word_guessed(secret_word, letters_guessed) and guesses_remaining > 0:
        
        print("\nYou have %d guesses left." % guesses_remaining)
        get_available_letters(letters_guessed)
        letter = str.lower(input("Please guess a letter: "))
        
        if letter == '*':
            print("Possible matches are:", show_possible_matches(get_guessed_word(secret_word, letters_guessed)))
        
        elif not letter or letter not in string.ascii_lowercase:
            if warnings_remaining != 0:
                warnings_remaining -= 1
                print("That is not a valid letter. You have %d warning left." % warnings_remaining)
            else:
                print("That is not a valid letter. You have no warning left, so you lose one guess.")
                guesses_remaining -= 1

        elif letter in letters_guessed:
            if warnings_remaining != 0:
                warnings_remaining -= 1
                print("You've already guessed that letter. You have %d warning left." % warnings_remaining)
            else:
                print("You've already guessed that letter. You have no warning left, so you lose one guess.")
                guesses_remaining -= 1
        
        else:
            letters_guessed.append(letter)
            if letter not in secret_word:
                print("That letter is not in my word.")
                if letter in 'aiueo':
                    guesses_remaining -= 2
                else:
                    guesses_remaining -= 1
            else:
                print("Good guess!")
                good_guess += 1 
                
        print(get_guessed_word(secret_word, letters_guessed)) 
        print("\nOOO-----------------------------------------------------------------------OOO\n")
        
        if is_word_guessed(secret_word, letters_guessed):
            print("Congratulations, you won!")
            print("Your total score for this game is %d." % (good_guess * guesses_remaining))
        
        if guesses_remaining == 0:
            print("Sorry, you ran out of guesses. The word was %s." % secret_word)


# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.


if __name__ == "__main__":
    # pass

    # To test part 2, comment out the pass line above and
    # uncomment the following two lines.
    
    #secret_word = choose_word(wordlist)
    #hangman(secret_word)

###############
    
    # To test part 3 re-comment out the above lines and 
    # uncomment the following two lines. 
    
    secret_word = choose_word(wordlist)
    hangman_with_hints(secret_word)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Just changed it, thanks! \$\endgroup\$ – yfr Feb 20 at 5:51
3
\$\begingroup\$

I'm going to go function by function and explain what I changed and why.

Imports I used:

from typing import List

load_words

def load_words() -> List[str]:
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    with open(WORDLIST_FILENAME, 'r') as file:
        wordlist = [word.strip() for word in file.readlines()]
    return wordlist

I see that you have type hints above every variable. Luckily for you, you can do this inline with the exact same format.

variable: int = 10

Make sure you close files when you open them. If you don't want to worry about that, use a with statement, which will automatically close the file once you exit the context.

You can also use type hints to display what types of parameters you accept, if any, and what types of values you return, if any.

choose_word

def choose_word(wordlist: List[str]) -> str:
    """
    wordlist (list): list of words (strings)
    
    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

Only thing I changed here was adding type hints. Now it's clear wordlist is a List of string, and the function returns a string.

is_word_guessed

def is_word_guessed(secret_word: str, letters_guessed: List[str]) -> bool:
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    guess = ""
    for char in secret_word:
        for letter in letters_guessed:
            if char == letter:
                guess += char
            else:
                continue
    
    return guess == secret_word

Personally, I would just use "" when creating an empty string. Again, note the type hints.

Instead of return True else return False, you can return the boolean condition that is being evaluated. It does the same exact thing, but it's shorter and looks a lot nicer.

get_guessed_word

def get_guessed_word(secret_word: str, letters_guessed: List[str]) -> str:
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    showbox_list = ['_ ' for _ in secret_word]
    for letter in letters_guessed:
        for count, char in enumerate(secret_word):
            if letter == char:
                showbox_list[count] = letter
            else:
                continue
    
    return ''.join(showbox_list)

Instead of using a traditional for loop, I would use list comprehension to construct your showbox list. The _ variable just indicates that the variable used in the loop should be ignored. Instead of creating a variable, then returning that variable, just return the value you would have assigned to that variable. Again, type hints.

get_available_letters

def get_available_letters(letters_guessed: List[str]) -> str:
    '''
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    english_letters = [char for char in string.ascii_lowercase if char not in letters_guessed]
    
    english_letters_str = ''.join(english_letters)
    print('Available letters:', english_letters_str)
    
    return english_letters_str

Again, you can use list comprehension to construct your initial list. This adds every character in the string.ascii_lowercase list, but ONLY if the character is not in the letters_guessed list. Obligatory type hints point.

match_with_gaps

def match_with_gaps(my_word: str, other_word: str) -> bool:
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the 
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise: 
    '''
    my_word_stripped = my_word.replace(" ", "")
    same_char = []
    blank_stripped = []
    if len(my_word_stripped) != len(other_word):
        return False
    for index, letter in enumerate(my_word_stripped):
        if letter in string.ascii_lowercase:
            same_char.append(index)
        else:
            blank_stripped.append(index)

    mws = ''
    ow = ''
    for index_same in same_char:
        for index_dif in blank_stripped:
            if other_word[index_dif] == other_word[index_same]:
                return False
            mws += my_word_stripped[index_same]
            ow += other_word[index_same]
    
    return mws == ow

The most important thing I want to stress here is guard clauses. These prevent you from having to indent into another context space. It makes your code look nicer, and is a good thing to practice.

You don't need an else if the if returns from the function. Again, type hints and returning boolean expressions.

show_possible_matches

def show_possible_matches(my_word: str) -> str:
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    possible_matches = [i for i in wordlist if match_with_gaps(my_word, i)]
    return ' '.join(possible_matches)

Using list comprehension reduces the need for the for loop, allowing you to accomplish the same task in one line. Again, type hints.


One more thing I'd like to add. You said that you initially didn't want to post the entire program because "it was too long". Most of the length of your program comes down to docstrings. Now, this isn't inherently a bad thing. Looking through them, this looks like a problem set, and these are instructions. Thats fine. But keep in mind that docstrings should really only display what the function does, what parameters it accepts (if any), and what it returns. I personally think the hangman_with_hints docstring goes a little over the top (25 lines!), but that's just me.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.