vaboro

ps5.py

Apr 28th, 2012
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.10 KB | None | 0 0
  1. # Problem Set 5: 6.00 Word Game
  2. # Name: vaboro
  3. # Collaborators: none
  4. # Time: n/a
  5. #
  6.  
  7. import random
  8. import string
  9.  
  10. VOWELS = 'aeiou'
  11. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
  12. HAND_SIZE = 10
  13.  
  14. SCRABBLE_LETTER_VALUES = {
  15.     '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
  16. }
  17.  
  18. # -----------------------------------
  19. # Helper code
  20. # (you don't need to understand this helper code)
  21.  
  22. WORDLIST_FILENAME = "words.txt"
  23.  
  24. def load_words():
  25.     """
  26.    Returns a list of valid words. Words are strings of lowercase letters.
  27.    
  28.    Depending on the size of the word list, this function may
  29.    take a while to finish.
  30.    """
  31.     print "Loading word list from file..."
  32.     # inFile: file
  33.     inFile = open(WORDLIST_FILENAME, 'r', 0)
  34.     # wordlist: list of strings
  35.     wordlist = []
  36.     for line in inFile:
  37.         wordlist.append(line.strip().lower())#I see some string formatting used here...
  38.     print "  ", len(wordlist), "words loaded."
  39.     return wordlist
  40.  
  41. def get_frequency_dict(sequence):
  42.     """
  43.    Returns a dictionary where the keys are elements of the sequence
  44.    and the values are integer counts, for the number of times that
  45.    an element is repeated in the sequence.
  46.  
  47.    sequence: string or list
  48.    return: dictionary
  49.    """
  50.     # freqs: dictionary (element_type -> int)
  51.     freq = {}
  52.     for x in sequence:
  53.         freq[x] = freq.get(x,0) + 1
  54.     return freq
  55.  
  56.  
  57. # (end of helper code)
  58. # -----------------------------------
  59.  
  60. #
  61. # Problem #1: Scoring a word
  62. #
  63. def get_word_score(word, n):
  64.     """
  65.    Returns the score for a word. Assumes the word is a
  66.    valid word.
  67.  
  68.    The score for a word is the sum of the points for letters
  69.    in the word, plus 50 points if all n letters are used on
  70.    the first go.
  71.  
  72.    Letters are scored as in Scrabble; A is worth 1, B is
  73.    worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.
  74.  
  75.    word: string (lowercase letters)
  76.    returns: int >= 0
  77.    """
  78.     # TO DO ...
  79.     # Since the function assumes the word is a valid word, it doesn't check the word for validity. All it is supposed to do is to score the word.
  80.     # The number of letters in a word can be less or equal to the maximum number of letters in the hand n
  81.     # The means of counting letters in the word is needed. Then then number of letters in the word is compared to n and if they are equal
  82.     # additional 50 points are added to the score.
  83.     # score is an integer since scores of letters are integers
  84.  
  85.     score = 0 #initialize the score
  86.    
  87.     for letter in word:
  88.         score = score + SCRABBLE_LETTER_VALUES[letter]
  89.        
  90.     if len(word) == n:
  91.         score = score + 50
  92.  
  93.     return score
  94. #
  95. # Make sure you understand how this function works and what it does!
  96. #
  97. def display_hand(hand):
  98.     """
  99.    Displays the letters currently in the hand.
  100.  
  101.    For example:
  102.       display_hand({'a':1, 'x':2, 'l':3, 'e':1})
  103.    Should print out something like:
  104.       a x x l l l e
  105.    The order of the letters is unimportant.
  106.  
  107.    hand: dictionary (string -> int)
  108.    """
  109.     for letter in hand.keys():
  110.         for j in range(hand[letter]):
  111.             print letter,              # print all on the same line
  112.     print                              # print an empty line
  113.  
  114. #
  115. # Make sure you understand how this function works and what it does!
  116. #
  117. def deal_hand(n):
  118.     """
  119.    Returns a random hand containing n lowercase letters.
  120.    At least n/3 the letters in the hand should be VOWELS.
  121.  
  122.    Hands are represented as dictionaries. The keys are
  123.    letters and the values are the number of times the
  124.    particular letter is repeated in that hand.
  125.  
  126.    n: int >= 0
  127.    returns: dictionary (string -> int)
  128.    """
  129.     hand={}
  130.     num_vowels = n / 3
  131.    
  132.     for i in range(num_vowels):
  133.         x = VOWELS[random.randrange(0,len(VOWELS))]
  134.         hand[x] = hand.get(x, 0) + 1
  135.        
  136.     for i in range(num_vowels, n):    
  137.         x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
  138.         hand[x] = hand.get(x, 0) + 1
  139.        
  140.     return hand
  141.  
  142. #
  143. # Problem #2: Update a hand by removing letters
  144. #
  145. def update_hand(hand, word):
  146.     """
  147.    Assumes that 'hand' has all the letters in word.
  148.    In other words, this assumes that however many times
  149.    a letter appears in 'word', 'hand' has at least as
  150.    many of that letter in it.
  151.  
  152.    Updates the hand: uses up the letters in the given word
  153.    and returns the new hand, without those letters in it.
  154.  
  155.    Has no side effects: does not mutate hand.
  156.  
  157.    word: string
  158.    hand: dictionary (string -> int)    
  159.    returns: dictionary (string -> int)
  160.    """
  161.     # TO DO ...
  162.  
  163.     #Since it is assumed that 'hand' has all the letters in 'word' this check is performed somewhere else in the program.
  164.     #At least I need to keep in mind that somewhere in the program when the user inputs words it has to be checked if
  165.     #'hand' actually has the necessary letter to compose the inputed 'word'
  166.     #Not to mutate 'hand' the function has to create a new 'hand' that it returns. This new hand is a dictionary.
  167.     #I will call it updated_hand
  168.     #I assume that neither 'hand' nor 'word' are empty
  169.  
  170.     updated_hand = {} #declare the updated hand
  171.  
  172.     #first, I need to copy all values from hand to updated_hand
  173.     #since dictionaries are muntable assigment creates a new reference to the same object, so, I cannot assign hand{} to updated_hand{} like
  174.     #this: updated_hand = hand. This will create a new reference to values in 'hand'
  175.  
  176.     #create a deep copy of the 'hand'
  177.    
  178.     for key in hand.keys():
  179.         updated_hand[key] = hand[key]
  180.  
  181.     for letter in word:
  182.         if letter in updated_hand.keys():
  183.             updated_hand[letter] -= 1
  184. ##            if updated_hand[letter] == 0:
  185. ##                updated_hand.pop(letter)
  186.     return updated_hand
  187.            
  188.  
  189. #
  190. # Problem #3: Test word validity
  191. #
  192. def is_valid_word(word, hand, word_list):
  193.     """
  194.    Returns True if word is in the word_list and is entirely
  195.    composed of letters in the hand. Otherwise, returns False.
  196.    Does not mutate hand or word_list.
  197.    
  198.    word: string
  199.    hand: dictionary (string -> int)
  200.    word_list: list of lowercase strings
  201.    """
  202.     # TO DO ...
  203.  
  204.     #First, check if 'word' is in 'word_list', if not then 'word' is not a valid word
  205.     #Second, convert 'word' into 'hand' format with get_frequency_dict() function
  206.     #Then make a deep copy of the 'hand' and compare keys in the two dictionaries
  207.     #'dict_word' and 'dict_hand' reducting the corresponding values if keys match
  208.  
  209.     is_valid = False
  210.  
  211.     dict_word = {}
  212.  
  213.     dict_hand = {}
  214.  
  215.     if word in word_list:
  216.        
  217.         dict_word = get_frequency_dict(word)
  218.      
  219.     else:
  220.  
  221.         return is_valid
  222.  
  223.     for key in hand.keys():
  224.         dict_hand[key] = hand[key]
  225.  
  226.     #for each key in dict_word
  227.  
  228.     for word_key in dict_word.keys():
  229.  
  230.         #check if dict_hand contains word_key
  231.        
  232.         if dict_hand.has_key(word_key):
  233.  
  234.             #and if dict_hand doesn't have enough letters for dict_word
  235.            
  236.             if dict_hand[word_key] - dict_word[word_key] < 0:
  237.  
  238.                 #the word is not valid
  239.                
  240.                 return is_valid
  241.                
  242.             else:
  243.  
  244.                 #otherwide decrease values of corresponding keys in dict_hand and dict_word
  245.                
  246.                 dict_hand[word_key] -= dict_word[word_key]
  247.                 dict_word[word_key] -= dict_word[word_key]
  248.                
  249.         else:
  250.            
  251.             return is_valid
  252.        
  253.     #this is a debug print statement
  254.  
  255.     #print 'Word:', word, 'Dict_word:', dict_word, 'Hand:', hand, 'Dict_hand:', dict_hand
  256.  
  257.     is_valid = True
  258.  
  259.     return is_valid
  260.              
  261. #
  262. # Problem #4: Playing a hand
  263. #
  264. def play_hand(hand, word_list):
  265.     """
  266.    Allows the user to play the given hand, as follows:
  267.  
  268.    * The hand is displayed.
  269.    
  270.    * The user may input a word.
  271.  
  272.    * An invalid word is rejected, and a message is displayed asking
  273.      the user to choose another word.
  274.  
  275.    * When a valid word is entered, it uses up letters from the hand.
  276.  
  277.    * After every valid word: the score for that word and the total
  278.      score so far are displayed, the remaining letters in the hand
  279.      are displayed, and the user is asked to input another word.
  280.  
  281.    * The sum of the word scores is displayed when the hand finishes.
  282.  
  283.    * The hand finishes when there are no more unused letters.
  284.      The user can also finish playing the hand by inputing a single
  285.      period (the string '.') instead of a word.
  286.  
  287.    * The final score is displayed.
  288.  
  289.      hand: dictionary (string -> int)
  290.      word_list: list of lowercase strings
  291.    """
  292.     # TO DO ...
  293.    
  294.     word = ''
  295.     total_score = 0
  296.     letters_left = HAND_SIZE
  297.    
  298.     while word <> '.':
  299.         if letters_left == 0:
  300.             return
  301.         print 'Current Hand:',
  302.         display_hand(hand)
  303.         print 'Enter word, or (.) to indicate that you are finished:',
  304.         word = raw_input().lower()
  305.         if word == '.':
  306.             print 'Total score:', total_score, 'points.',
  307.             return
  308.         elif not is_valid_word(word, hand, word_list):
  309.                 print 'Invalid word, please try again.'
  310.         else:
  311.             score = get_word_score(word, HAND_SIZE)
  312.             total_score += score
  313.             print word, 'earned', score, 'points. Total:', total_score, 'points'
  314.             hand = update_hand(hand, word)
  315.             letters_left -= len(word)
  316.  
  317. #
  318. # Problem #5: Playing a game
  319. # Make sure you understand how this code works!
  320. #
  321. def play_game(word_list):
  322.     """
  323.    Allow the user to play an arbitrary number of hands.
  324.  
  325.    * Asks the user to input 'n' or 'r' or 'e'.
  326.  
  327.    * If the user inputs 'n', let the user play a new (random) hand.
  328.      When done playing the hand, ask the 'n' or 'e' question again.
  329.  
  330.    * If the user inputs 'r', let the user play the last hand again.
  331.  
  332.    * If the user inputs 'e', exit the game.
  333.  
  334.    * If the user inputs anything else, ask them again.
  335.    """
  336.     # TO DO ...
  337.     #print "play_game not implemented."         # delete this once you've completed Problem #4
  338.     #play_hand(deal_hand(HAND_SIZE), word_list) # delete this once you've completed Problem #4
  339.    
  340.     ## uncomment the following block of code once you've completed Problem #4
  341.     hand = deal_hand(HAND_SIZE) # random init
  342.     while True:
  343.         cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
  344.         if cmd == 'n':
  345.             hand = deal_hand(HAND_SIZE)
  346.             play_hand(hand.copy(), word_list)
  347.             print
  348.         elif cmd == 'r':
  349.             play_hand(hand.copy(), word_list)
  350.             print
  351.         elif cmd == 'e':
  352.             break
  353.         else:
  354.             print "Invalid command."
  355.  
  356. #
  357. # Build data structures used for entire session and play game
  358. #
  359. if __name__ == '__main__':
  360.     word_list = load_words()
  361.     play_game(word_list)
Advertisement
Add Comment
Please, Sign In to add comment