Description

Description — page 1
Description — page 1

Download original PDF: ## Description — page 1

Description — page 2
Description — page 2
Description — page 3
Description — page 3
Description — page 4
Description — page 4
Description — page 5
Description — page 5
Description — page 6
Description — page 6
Description — page 7
Description — page 7
Description — page 8
Description — page 8
Description — page 9
Description — page 9
Description — page 10
Description — page 10
Description — page 11
Description — page 11
Description — page 12
Description — page 12
Description — page 13
Description — page 13

MIT6_0001F16_Pset2.pdf


My Python code:

# Problem Set 2, hangman.py
# Name: 
# Collaborators:
# Time spent:

# Hangman Game
# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)
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

Problem 2: Hangman Part 1: Three helper functions

# 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
    '''
    secret_word_list = list(secret_word)
    if len(letters_guessed) == len(secret_word_list):
            if ''.join(letters_guessed) == secret_word:
                return True
            else:
                return False
    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"
    secret_word_list = list(secret_word)
    secret_word_list_copy = secret_word_list[:]
    
    for letter in secret_word_list_copy:
        if letter not in letters_guessed:
            index_letter = secret_word_list.index(letter)
            secret_word_list[index_letter] = "_"
    return ' '.join(secret_word_list)



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"
    ascii_lowercase_list = list(string.ascii_lowercase)
    ascii_lowercase_list_copy = ascii_lowercase_list[:]
    for letter in ascii_lowercase_list_copy:
        if letter in letters_guessed:
            ascii_lowercase_list.remove(letter)
    return ''.join(ascii_lowercase_list)

Problem 3
Hangman Part 2: The Game

def generate_hint(test):
    # Create a hint with underscores and whitespaces
    hint = "_ " * len(test)

    # Remove the trailing whitespace
    hint = hint.rstrip()

    return hint

Problem 4 Hangman Part 3: The Game with Hints

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"
    match_score = 0
    my_word_list = my_word.split(" ")
    other_word_list = list(other_word)
    if len(my_word_list) == len(other_word_list):
        
        for index in range(len(my_word_list)):
            if my_word_list[index] != "_":
                if my_word_list[index] != other_word_list[index]:
                    match_score = match_score - 1
        if match_score < 0:
            return False
        else:
            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"
    all_other_word = list()

    for other_word in wordlist:
        if match_with_gaps(my_word, other_word):
            all_other_word.append(other_word)
            
    if len(all_other_word) != 0:
        print("Possible words are:", ' '.join(all_other_word))
    else:
        print("No matches found")



#################################################################################    
def hangman_with_hints(secret_word):

    # 一些前置的參數
    guess_num = 6
    letters_guessed = []
    hint = generate_hint(secret_word)
    warning_num = 3
    vowels = ["a","e","i","o","u"]
    
    
    # Welcome message
    print("Welcome to the game Hangman!") 
    print("I am thinking of a word that is", len(secret_word) ,"letters long.")
    print("You can ask for hint by typing *")
    print("---------------------------")
    
    while guess_num > 0: # 遊戲繼續的條件就是剩餘猜測次數
        print("You have", warning_num,"warnings left.")
        print("You have", guess_num,"guesses left.")
            
        # 顯示剩餘可以猜的字母,每次都會更新顯示
        print("Available letters:", get_available_letters(letters_guessed))
        letters_guess_this_time = input("Please guess a letter:").lower()  # 請猜測字母,並強制小寫
        
        # 設計提示單字的功能,輸入 * 會提示,但會扣剩餘猜測次數
        if letters_guess_this_time == "*":
            guess_num = guess_num - 1
            show_possible_matches(hint)                                    # 出現提示:可能的單字

        # 如果輸入的不是 * 也不是字母,會扣剩餘警告次數,甚至是剩餘猜測次數
        elif letters_guess_this_time.isalpha() == False:
            print("Oops! That is not a valid letter.")
            if warning_num > 0:
                warning_num = warning_num - 1
            else:
                guess_num = guess_num - 1
            print("You now have", warning_num,"warnings left:", hint)
            print("---------------------------")
        
        # 如果輸入的字母早就出現過,一樣,會扣剩餘警告次數,甚至是剩餘猜測次數
        elif letters_guess_this_time in letters_guessed:
            print("Oops! You've already guessed that letter.")
            if warning_num > 0:
                warning_num = warning_num - 1
            else:
                guess_num = guess_num - 1
            print("You now have", warning_num,"warnings left:", hint)
            print("---------------------------")
        
        # 輸入的是字母,遊戲順利進行
        else:
            letters_guessed.append(letters_guess_this_time)             # 先收集猜測過的字母
            
            # 如果你猜的字母有出現在 secret_word 中
            if letters_guess_this_time in list(secret_word):            
                hint = get_guessed_word(secret_word, letters_guessed)
                print("Good guess:", hint)                              # 出現提示:字母的位置
                print("---------------------------")
                
                # 勝利條件
                ans = hint.split(" ")
                if is_word_guessed(secret_word, ans) == True:
                    score = guess_num*len(set(secret_word))
                    print("Congratulations, you won! Your total score for this game is:", score)
                    break
            
            # 如果你猜的字母「沒有」出現在 secret_word 中,會有兩種狀況
            else:
                print("Oops! That letter is not in my word:", hint)     # 出現提示:舊的提示
                print("---------------------------")
                
                # 是母音,扣兩次剩餘猜測次數
                if letters_guess_this_time in vowels:
                    guess_num = guess_num - 2
                # 不是母音,正常扣一次剩餘猜測次數
                else:
                    guess_num = guess_num - 1
    
    # 遊戲結束條件,確認剩餘猜測次數為 0
    if guess_num == 0:
        print("Sorry, you ran out of guesses. The word was", secret_word)


#################################################################################    
secret_word = choose_word(wordlist)
hangman_with_hints(secret_word)
← Back to all posts