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

MIT6_0001F16_ProblemSet3.pdf

Assignment sets:

ps3.py test_ps3.py words.txt


My mindmap for the game codes:

Detail version:

  • The arrow with words are small functions that need to be implemented first
The arrow with words are small functions that need to be implemented first
The arrow with words are small functions that need to be implemented first

Download original PDF: - The arrow with words are small functions that need to be implemented first

Mindmap.pdf

General version:

General version:
General version:

My Codes:

import math
import random
import string

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7

SCRABBLE_LETTER_VALUES = {'*': 0,
    'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}

# -----------------------------------
# Helper code
# (you don't need to understand this helper code)

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')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.append(line.strip().lower())
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def get_frequency_dict(sequence):
    """
    Returns a dictionary where the keys are elements of the sequence
    and the values are integer counts, for the number of times that
    an element is repeated in the sequence.

    sequence: string or list
    return: dictionary
    """
    
    # freqs: dictionary (element_type -> int)
    freq = {}
    for x in sequence:
        freq[x] = freq.get(x,0) + 1
    return freq
	

# (end of helper code)
# -----------------------------------

Problem #1: Scoring a word

def get_word_score(word, n):
    """
    Returns the score for a word. Assumes the word is a
    valid word.

    You may assume that the input word is always either a string of letters, 
    or the empty string "". You may not assume that the string will only contain 
    lowercase letters, so you will have to handle uppercase and mixed case strings 
    appropriately. 

	The score for a word is the product of two components:

	The first component is the sum of the points for letters in the word.
	The second component is the larger of:
            1, or
            7*wordlen - 3*(n-wordlen), where wordlen is the length of the word
            and n is the hand length when the word was played

	Letters are scored as in Scrabble; A is worth 1, B is
	worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.

    word: string
    n: int >= 0
    returns: int >= 0
    """
    
    word = word.lower()
    # 1st component
    score_1 = 0  # Initialize total score
    for char in word:
        # Add the score of the character if it exists in the dictionary
        score_1 = score_1 + SCRABBLE_LETTER_VALUES.get(char, 0)  # Default to 0 if char not in dict
    # 2nd component
    score_2 = 7*len(word) - 3*(n-len(word))
    if score_2 < 1:
        score_2 = 1
    
    score = score_1 * score_2
    return score
    
    

#
# Make sure you understand how this function works and what it does!
#
def display_hand(hand):
    """
    Displays the letters currently in the hand.

    For example:
       display_hand({'a':1, 'x':2, 'l':3, 'e':1})
    Should print out something like:
       a x x l l l e
    The order of the letters is unimportant.

    hand: dictionary (string -> int)
    """
    
    for letter in hand.keys():
        for j in range(hand[letter]):
             print(letter, end=' ')      # print all on the same line
    print()                              # print an empty line
     

#
# Make sure you understand how this function works and what it does!
# You will need to modify this for Problem #4.
#
def deal_hand(n):
    """
    Returns a random hand containing n lowercase letters.
    ceil(n/3) letters in the hand should be VOWELS 
    (note, ceil(n/3) means the smallest integer not less than n/3).
    ( ex: ceil(4.3) = 5; ceil(-4.2) = -4 )

    Hands are represented as dictionaries. The keys are
    letters and the values are the number of times the
    particular letter is repeated in that hand.

    n: int >= 0
    returns: dictionary (string -> int)
    """
    
    hand={}
    num_vowels = int(math.ceil(n / 3))
    
    # CONSONANTS
    for i in range(num_vowels, n):    
        x = random.choice(CONSONANTS)
        hand[x] = hand.get(x, 0) + 1

    # VOWELS & wildcard
    num_vowels = num_vowels - 1 # at least 1 space for the wildcard
    if num_vowels > 0:

        for i in range(num_vowels):
            x = random.choice(VOWELS) # choose random VOWELS
            # add the chosen VOWELS in the "hand" dictionary, if it doesn't exist in the dic => 
            # hand.get(x, 0) will become 0 => hand[x] = 1.
            # if it already exists in the dic => hand.get(x, 0) will become its previous value =>
            # hand[x] = previous value + 1 (how many times it was chosen to be in the dic)
            hand[x] = hand.get(x, 0) + 1
        hand["*"] = 1
        return hand
        
    elif num_vowels == 0:
        hand["*"] = 1
        return hand
        
    else:
        return hand

Problem #2: Update a hand by removing letters

def update_hand(hand, word):
    """
    Does NOT assume that hand contains every letter in word at least as
    many times as the letter appears in word. 
    Letters in word that don't appear in hand should be ignored. 
    Letters that appear in word more times than in hand should never result in a negative count; 
    instead, set the count in the returned hand to 0 (or remove the letter from the
    dictionary, depending on how your code is structured). 

    Updates the hand: uses up the letters in the given word
    and returns the new hand, without those letters in it.

    Has no side effects: does not modify hand.

    word: string
    hand: dictionary (string -> int)    
    returns: dictionary (string -> int)
    """
    word = word.lower()
    new_hand = dict(hand)
    for char in word:
        if new_hand.get(char, 0) != 0:
            new_hand[char] = new_hand[char] - 1
    return new_hand

Problem #3: Test word validity

def is_valid_word(word, hand, word_list):
    """
    Returns True if word is in the word_list and is entirely
    composed of letters in the hand. Otherwise, returns False.
    Does not mutate hand or word_list.
   
    word: string
    hand: dictionary (string -> int)
    word_list: list of lowercase strings
    returns: boolean
    """
    
    word = word.lower()
    new_hand = dict(hand)
    
    # define a function to check if the word is entirely composed of letters in the hand          
    def is_word_composed_of_hand(word, hand):
        not_in_hand_counts = 0
        
        for char in word:
            if hand.get(char, 0) != 0:
                hand[char] = hand[char] - 1
            else:
                not_in_hand_counts = not_in_hand_counts + 1
            
        # return results
        if not_in_hand_counts == 0:
            return True
        else:
            return False  
    
    # if the word is entirely composed of letters in the hand...then
    if is_word_composed_of_hand(word, new_hand):
        
        not_in_wordlist_counts = 0
        # test if the word is included in word_list after replacing wildcard
        # replace the wildcard with 5 vowels one by one
        for vowel in VOWELS:
            word_replaced_wildcard = word.replace("*",vowel)
            if word_replaced_wildcard not in word_list:
                not_in_wordlist_counts = not_in_wordlist_counts + 1
        
        # if all 5 vowels do not exist...
        if not_in_wordlist_counts == 5:
            return False
        else:
            return True

    
    else:
        print("The word is not entirely composed of letters in the hand")
        return False

Problem #5: Playing a hand

def calculate_handlen(hand):
    """ 
    Returns the length (number of letters) in the current hand.
    
    hand: dictionary (string-> int)
    returns: integer
    """
    
    hand_len = sum(hand.values())    
    return hand_len
    

def play_hand(hand, word_list):

    """
    Allows the user to play the given hand, as follows:

    * The hand is displayed.
    
    * The user may input a word.

    * When any word is entered (valid or invalid), it uses up letters
      from the hand.

    * An invalid word is rejected, and a message is displayed asking
      the user to choose another word.

    * After every valid word: the score for that word is displayed,
      the remaining letters in the hand are displayed, and the user
      is asked to input another word.

    * The sum of the word scores is displayed when the hand finishes.

    * The hand finishes when there are no more unused letters.
      The user can also finish playing the hand by inputing two 
      exclamation points (the string '!!') instead of a word.

      hand: dictionary (string -> int)
      word_list: list of lowercase strings
      returns: the total score for the hand
      
    """
    
    # BEGIN PSEUDOCODE <-- Remove this comment when you implement this function
    # Keep track of the total score
    total_score = 0
    
    
    while calculate_handlen(hand) > 0:
    # As long as there are still letters left in the hand:
    
        # Display the hand
        print("Current hand:") 
        display_hand(hand)
        
        # Ask user for input
        word = input('Enter word, or "!!" to indicate that you are finished:').lower()
        
        # If the input is two exclamation points -> break
        if word == "!!":
            break
            
        # Otherwise
        else:
            # If the word is valid:
            if is_valid_word(word, hand, word_list):
                score = get_word_score(word, calculate_handlen(hand))
                total_score = total_score + score
                print(f'"{word}" earned {score} points. Total: {total_score} points')
                print()
            
            else:
                print("That is not a valid word. Please choose another word.")
                print()

            # update the user's hand by removing the letters of their inputted word
            hand = update_hand(hand, word)
           
    # Game is over (user entered '!!' or ran out of letters),
    # so tell user the total score
    if calculate_handlen(hand) > 0:
        print("Total score:", total_score, "points")
        return total_score
    else:
        print("Ran out of letters. Total score:" , total_score, "points")
        return total_score
        

Problem #6: Playing a game

#
# procedure you will use to substitute a letter in a hand
#

def substitute_hand(hand, letter):
    """ 
    Allow the user to replace all copies of one letter in the hand (chosen by user)
    with a new letter chosen from the VOWELS and CONSONANTS at random. The new letter
    should be different from user's choice, and should not be any of the letters
    already in the hand.

    If user provide a letter not in the hand, the hand should be the same.

    Has no side effects: does not mutate hand.

    For example:
        substitute_hand({'h':1, 'e':1, 'l':2, 'o':1}, 'l')
    might return:
        {'h':1, 'e':1, 'o':1, 'x':2} -> if the new letter is 'x'
    The new letter should not be 'h', 'e', 'l', or 'o' since those letters were
    already in the hand.
    
    hand: dictionary (string -> int)
    letter: string
    returns: dictionary (string -> int)
    """
    
    replaced_hand = dict(hand)
    
    # the substitute letter specified by player should not be the wildcard
    if letter != "*":
        # the substitute letter specified by player is indeed in the hand
        if letter in replaced_hand.keys():
    
            
            # Modified CONSONANTS and VOWELS
            exclude_letters = replaced_hand.keys()
            modified_consonants = ""
    
            # Loop through each letter in CONSONANTS
            for char in CONSONANTS:
                # If the letter is not in the exclude_letters string, add it to modified_consonants
                if char not in exclude_letters:
                    modified_consonants = modified_consonants + char
            # Loop through each letter in VOWELS
            for char in VOWELS:
                if char not in exclude_letters:
                    modified_consonants = modified_consonants + char
            
            # choose random letter to replaced the letter
            x = random.choice(modified_consonants)
            replaced_hand[x] = hand.get(letter)
            del replaced_hand[letter]
            return replaced_hand
            
        else:
            print("The letter is not detected in the hand.")
            print()
            return replaced_hand

    else:
        print("The substitute letter can not be the wildcard.")
        print()
        return replaced_hand

    
    
    
    
    
       
    
def play_game(word_list):
    """
    Allow the user to play a series of hands

    * Asks the user to input a total number of hands

    * Accumulates the score for each hand into a total score for the 
      entire series
 
    * For each hand, before playing, ask the user if they want to substitute
      one letter for another. If the user inputs 'yes', prompt them for their
      desired letter. This can only be done once during the game. Once the
      substitue option is used, the user should not be asked if they want to
      substitute letters in the future.

    * For each hand, ask the user if they would like to replay the hand.
      If the user inputs 'yes', they will replay the hand and keep 
      the better of the two scores for that hand.  This can only be done once 
      during the game. Once the replay option is used, the user should not
      be asked if they want to replay future hands. Replaying the hand does
      not count as one of the total number of hands the user initially
      wanted to play.

            * Note: if you replay a hand, you do not get the option to substitute
                    a letter - you must play whatever hand you just had.
      
    * Returns the total score for the series of hands

    word_list: list of lowercase strings
    """
    
    num_of_hands = int(input("Enter total number of hands:"))
    total_overall_score = 0
    
    # play multiple hands
    for i in range(num_of_hands):
        hand = deal_hand(HAND_SIZE)
        
        # Display the hand and ask for substitute (loop to make sure only input YES/NO)
        print("----------")
        print("Current hand:") 
        display_hand(hand)
        while True:
            substitute_or_not = input("Would you like to substitute a letter? (YES/NO)")
            if substitute_or_not == "YES":
                letter = input("Which letter would you like to replace:")
                new_hand = substitute_hand(hand, letter)
                break
            elif substitute_or_not == "NO":
                new_hand = dict(hand)
                break
            else:
                print("Please type 'YES' or 'NO'.")
                print()
        
        score_in_this_hand = play_hand(new_hand, word_list)
        print("----------")
        while True:
            replay_or_not = input("Would you like to replay the hand? (YES/NO)")
            if replay_or_not == "YES":
                score_in_this_hand = play_hand(new_hand, word_list)
                break
            elif replay_or_not == "NO":
                break
            else:
                print("Please type 'YES' or 'NO'.")
                print()
        total_overall_score = total_overall_score + score_in_this_hand
    
    print("----------")
    print("Total score over all hands:", total_overall_score)
    return total_overall_score






    


#
# Build data structures used for entire session and play game
# Do not remove the "if __name__ == '__main__':" line - this code is executed
# when the program is run directly, instead of through an import statement
#
if __name__ == '__main__':
    word_list = load_words()
    play_game(word_list)
← Back to all posts