Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.16 KB | None | 0 0
  1. # CS 111 Problem Set 3A
  2. # The CS 111 Word Game
  3. #
  4.  
  5. import random
  6. import string
  7.  
  8. VOWELS = 'aeiou'
  9. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
  10. HAND_SIZE = 7
  11.  
  12. SCRABBLE_LETTER_VALUES = {
  13.     '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
  14. }
  15.  
  16.  
  17. # -----------------------------------
  18. # Helper code
  19. # (you don't need to understand this helper code)
  20.  
  21. WORDLIST_FILENAME = "words.txt"
  22.  
  23. def load_words():
  24.     """
  25.    Returns a list of valid words. Words are strings of lowercase letters.
  26.    
  27.    Depending on the size of the word list, this function may
  28.    take a while to finish.
  29.    """
  30.     print("Loading word list from file...")
  31.     # inFile: file
  32.     inFile = open(WORDLIST_FILENAME, 'r')
  33.     # wordlist: list of strings
  34.     wordlist = []
  35.     for line in inFile:
  36.         wordlist.append(line.strip().lower())
  37.     print("  ", len(wordlist), "words loaded.")
  38.     return wordlist
  39.  
  40. def get_frequency_dict(sequence):
  41.     """
  42.    Returns a dictionary where the keys are elements of the sequence
  43.    and the values are integer counts, for the number of times that
  44.    an element is repeated in the sequence.
  45.  
  46.    sequence: string or list
  47.    return: dictionary
  48.    """
  49.     # freqs: dictionary (element_type -> int)
  50.     freq = {}
  51.     for x in sequence:
  52.         freq[x] = freq.get(x,0) + 1
  53.     return freq
  54.    
  55.  
  56. # (end of helper code)
  57. # -----------------------------------
  58.  
  59. #
  60. # Problem #1: Scoring a word
  61. #
  62. def get_word_score(word, n):
  63.     #Changing word to list to use proper list functions
  64.     L = list(word)
  65.     #defining word_score that we will use later. Setting it to default value 0
  66.     word_score = 0
  67.     #Goes thru the list
  68.     for x in range(0,len(L)-1):
  69.         #Look up what the dictionary function .get() does to understand this
  70.         #for clarification L[x] is the letter at index x of the list L
  71.         word_score = word_score + SCRABBLE_LETTER_VALUES.get(L[x])
  72.  
  73.     #multiplying the score * the length
  74.     word_score = word_score * len(word)
  75.  
  76.     #If we use all the letter add 50
  77.     if(len(word) == n):
  78.         word_score = word_score + 50
  79.        
  80.     return word_score
  81.    
  82.     """
  83.    Returns the score for a word. Assumes the word is a
  84.    valid word.
  85.  
  86.     The score for a word is the sum of the points for letters
  87.     in the word multiplied by the length of the word, plus 50
  88.     points if all n letters are used on the first go.
  89.  
  90.     Letters are scored as in Scrabble; A is worth 1, B is
  91.     worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.
  92.  
  93.    word: string (lowercase letters)
  94.    returns: int >= 0
  95.    """
  96.     # TO DO...
  97.    
  98. #
  99. # Make sure you understand how this function works and what it does!
  100. #
  101. def display_hand(hand):
  102.     """
  103.    Displays the letters currently in the hand.
  104.  
  105.    For example:
  106.       display_hand({'a':1, 'x':2, 'l':3, 'e':1})
  107.    Should print out something like:
  108.       a x x l l l e
  109.    The order of the letters is unimportant.
  110.  
  111.    hand: dictionary (string -> int)
  112.    """
  113.     for letter in hand.keys():
  114.         for j in range(hand[letter]):    
  115.              print(letter,)              # print all on the same line
  116.     print()                              # print an empty line
  117.  
  118. #
  119. # Make sure you understand how this function works and what it does!
  120. #
  121. def deal_hand(n):
  122.     """
  123.    Returns a random hand containing n lowercase letters.
  124.    At least n/3 the letters in the hand should be VOWELS.
  125.  
  126.    Hands are represented as dictionaries. The keys are
  127.    letters and the values are the number of times the
  128.    particular letter is repeated in that hand.
  129.  
  130.    n: int >= 0
  131.    returns: dictionary (string -> int)
  132.    """
  133.     hand={}
  134.     num_vowels = n / 3
  135.    
  136.     for i in range(num_vowels):
  137.         x = VOWELS[random.randrange(0,len(VOWELS))]
  138.         hand[x] = hand.get(x, 0) + 1
  139.        
  140.     for i in range(num_vowels, n):    
  141.         x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
  142.         hand[x] = hand.get(x, 0) + 1
  143.        
  144.     return hand
  145.  
  146. #
  147. # Problem #2: Update a hand by removing letters
  148. #
  149. def update_hand(hand, word):
  150.     """
  151.    Assumes that 'hand' has all the letters in word.
  152.     In other words, this assumes that however many times
  153.     a letter appears in 'word', 'hand' has at least as
  154.     many of that letter in it.
  155.  
  156.    Updates the hand: uses up the letters in the given word
  157.    and returns the new hand, without those letters in it.
  158.  
  159.    Has no side effects: does not modify hand.
  160.  
  161.    word: string
  162.    hand: dictionary (string -> int)    
  163.    returns: dictionary (string -> int)
  164.    """
  165.     #take every letter from word out of hand
  166.     #return the new updated hand
  167.     #make all this a new dictionary do not use hand
  168.  
  169.     #creates a copy of the dictionary hand because he said not to mutate...
  170.     #the original hand dictionary
  171.     updatedHand = hand.copy()
  172.     #changes the string word to a list named L
  173.     L = list(word)
  174.  
  175.     #for loop of the length of the list L
  176.     for x in range(0,len(L)-1):
  177.         #google how to delete a element from a dictionary
  178.         del updatedHand[L[x]]
  179.  
  180.     #returning updated hand
  181.     return updatedHand
  182.  
  183. #
  184. # Problem #3: Test word validity
  185. #
  186. def is_valid_word(word, hand, word_list):
  187.     """
  188.    Returns True if word is in the word_list and is entirely
  189.    composed of letters in the hand. Otherwise, returns False.
  190.    Does not mutate hand or word_list.
  191.    
  192.    word: string
  193.    hand: dictionary (string -> int)
  194.    word_list: list of lowercase strings
  195.    """
  196.     if word not in word_list:
  197.         return False
  198.  
  199.     word_Freq = get_frequency_dict(word)
  200.  
  201.     for letter in word_Freq.keys():
  202.         if word_Freq[letter] > hand.get(letter, 0):
  203.             return False
  204.     return True
  205.            
  206.    
  207.  
  208.    
  209.  
  210.  
  211.    
  212.    
  213. def calculate_handlen(hand):
  214.     handlen = 0
  215.     for v in hand.values():
  216.         handlen += v
  217.     return handlen
  218.  
  219. #
  220. # Problem #4: Playing a hand
  221. #
  222. def play_hand(hand, word_list):
  223.  
  224.     """
  225.    Allows the user to play the given hand, as follows:
  226.  
  227.    * The hand is displayed.
  228.    
  229.    * The user may input a word.
  230.  
  231.    * An invalid word is rejected, and a message is displayed asking
  232.      the user to choose another word.
  233.  
  234.    * When a valid word is entered, it uses up letters from the hand.
  235.  
  236.    * After every valid word: the score for that word is displayed,
  237.      the remaining letters in the hand are displayed, and the user
  238.      is asked to input another word.
  239.  
  240.    * The sum of the word scores is displayed when the hand finishes.
  241.  
  242.    * The hand finishes when there are no more unused letters.
  243.      The user can also finish playing the hand by inputing a single
  244.      period (the string '.') instead of a word.
  245.  
  246.      hand: dictionary (string -> int)
  247.      word_list: list of lowercase strings
  248.      
  249.    """
  250.     hand_copy = hand.copy()
  251.     word_score = 0
  252.    
  253.     while(True):
  254.         if bool(hand.copy):
  255.             print("Total score: ", word_score," points.")
  256.             break
  257.                  
  258.         print("Current Hand: ", hand_copy)
  259.         word = str(input('Enter word, or a "." to indicate that you are finished: ')
  260.         if(is_valid_word(word, hand_copy, word_list)):
  261.             hand_copy = update_hand(hand_copy, word)
  262.             word_score = word_score + get_word_score(word, HAND_SIZE))
  263.  
  264.             print('"',word, '"earned ', get_word_score(word, HAND_SIZE)),". Total: ", word_score ," points")
  265.        
  266.         elif word == ".":
  267.             print("Total score: ",
  268.             break
  269.         else:
  270.             print("Invalid word, please try again")
  271.  
  272. #
  273. # Problem #5: Playing a game
  274. # Make sure you understand how this code works!
  275. #
  276. def play_game(word_list):
  277.     """
  278.    Allow the user to play an arbitrary number of hands.
  279.  
  280.    * Asks the user to input 'n' or 'r' or 'e'.
  281.  
  282.    * If the user inputs 'n', let the user play a new (random) hand.
  283.      When done playing the hand, ask the 'n' or 'e' question again.
  284.  
  285.    * If the user inputs 'r', let the user play the last hand again.
  286.  
  287.    * If the user inputs 'e', exit the game.
  288.  
  289.    * If the user inputs anything else, ask them again.
  290.    """
  291.     # TO DO...
  292.     lastHand = {}
  293.     while(True)
  294.         if(bool(lastHand)):
  295.             print("'n' to play a new hand")
  296.             print("'r' to play the last hand again")
  297.             print("'e' to exit the game"
  298.             nre = str(input("Please input 'n', 'r', or 'e': ")
  299.                 if nre == 'n':
  300.                     play_hand(deal_hand(HAND_SIZE), load_words())
  301.                 elif nre == 'r':
  302.                     play_hand(lastHand, load_words())
  303.                 elif nre == 'e':
  304.                     break
  305.                 else:
  306.                     print("That is not a valid input")
  307.                      
  308.         else:
  309.             print("This is your first hand")
  310.             lastHand= deal_hand(HAND_SIZE)
  311.             play_hand(deal_hand(HAND_SIZE), load_words())
  312.  
  313.                      
  314.  
  315.        
  316.  
  317.    
  318.  
  319. #
  320. # Build data structures used for entire session and play game
  321. #
  322. if __name__ == '__main__':
  323.     word_list = load_words()
  324.     play_game(word_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement