Advertisement
ArCiGo

ps4a.py

Jan 10th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.50 KB | None | 0 0
  1. # 6.00x Problem Set 4A Template
  2. #
  3. # The 6.00 Word Game
  4. # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
  5. # Modified by: Sarina Canelake <sarina>
  6. #
  7.  
  8. import random
  9. import string
  10.  
  11. VOWELS = 'aeiou'
  12. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
  13. HAND_SIZE = 7
  14.  
  15. SCRABBLE_LETTER_VALUES = {
  16.     '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
  17. }
  18.  
  19. # -----------------------------------
  20. # Helper code
  21. # (you don't need to understand this helper code)
  22.  
  23. WORDLIST_FILENAME = "C:\Users\Armando\Documents\Online Courses\MITx 6.00.1x Introduction to Computer Science and Programming Using Python\Week 4\words.txt"
  24.  
  25. def loadWords():
  26.     """
  27.    Returns a list of valid words. Words are strings of lowercase letters.
  28.    
  29.    Depending on the size of the word list, this function may
  30.    take a while to finish.
  31.    """
  32.     print "Loading word list from file..."
  33.     # inFile: file
  34.     inFile = open(WORDLIST_FILENAME, 'r', 0)
  35.     # wordList: list of strings
  36.     wordList = []
  37.     for line in inFile:
  38.         wordList.append(line.strip().lower())
  39.     print "  ", len(wordList), "words loaded."
  40.     return wordList
  41.  
  42. def getFrequencyDict(sequence):
  43.     """
  44.    Returns a dictionary where the keys are elements of the sequence
  45.    and the values are integer counts, for the number of times that
  46.    an element is repeated in the sequence.
  47.  
  48.    sequence: string or list
  49.    return: dictionary
  50.    """
  51.     # freqs: dictionary (element_type -> int)
  52.     freq = {}
  53.     for x in sequence:
  54.         freq[x] = freq.get(x,0) + 1
  55.     return freq
  56.    
  57.  
  58. # (end of helper code)
  59. # -----------------------------------
  60.  
  61. #
  62. # Problem #1: Scoring a word
  63. #
  64. def getWordScore(word, n):
  65.     """
  66.    Returns the score for a word. Assumes the word is a valid word.
  67.  
  68.    The score for a word is the sum of the points for letters in the
  69.    word, multiplied by the length of the word, PLUS 50 points if all n
  70.    letters are used on the first turn.
  71.  
  72.    Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
  73.    worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
  74.  
  75.    word: string (lowercase letters)
  76.    n: integer (HAND_SIZE; i.e., hand size required for additional points)
  77.    returns: int >= 0
  78.    """
  79.     score = 0
  80.    
  81.     for char in word :
  82.         score += SCRABBLE_LETTER_VALUES[char]
  83.    
  84.     score *= len(word)
  85.    
  86.     if len(word) == n :
  87.         score += 50
  88.  
  89.     return score
  90.  
  91.  
  92. #
  93. # Problem #2: Make sure you understand how this function works and what it does!
  94. #
  95. def displayHand(hand):
  96.     """
  97.    Displays the letters currently in the hand.
  98.  
  99.    For example:
  100.    >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
  101.    Should print out something like:
  102.       a x x l l l e
  103.    The order of the letters is unimportant.
  104.  
  105.    hand: dictionary (string -> int)
  106.    """
  107.     for letter in hand.keys():
  108.         for j in range(hand[letter]):
  109.              print letter,              # print all on the same line
  110.     print                               # print an empty line
  111.  
  112. #
  113. # Problem #2: Make sure you understand how this function works and what it does!
  114. #
  115. def dealHand(n):
  116.     """
  117.    Returns a random hand containing n lowercase letters.
  118.    At least n/3 the letters in the hand should be VOWELS.
  119.  
  120.    Hands are represented as dictionaries. The keys are
  121.    letters and the values are the number of times the
  122.    particular letter is repeated in that hand.
  123.  
  124.    n: int >= 0
  125.    returns: dictionary (string -> int)
  126.    """
  127.     hand={}
  128.     numVowels = n / 3
  129.    
  130.     for i in range(numVowels):
  131.         x = VOWELS[random.randrange(0,len(VOWELS))]
  132.         hand[x] = hand.get(x, 0) + 1
  133.        
  134.     for i in range(numVowels, n):    
  135.         x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
  136.         hand[x] = hand.get(x, 0) + 1
  137.        
  138.     return hand
  139.  
  140. #
  141. # Problem #2: Update a hand by removing letters
  142. #
  143. def updateHand(hand, word):
  144.     """
  145.    Assumes that 'hand' has all the letters in word.
  146.    In other words, this assumes that however many times
  147.    a letter appears in 'word', 'hand' has at least as
  148.    many of that letter in it.
  149.  
  150.    Updates the hand: uses up the letters in the given word
  151.    and returns the new hand, without those letters in it.
  152.  
  153.    Has no side effects: does not modify hand.
  154.  
  155.    word: string
  156.    hand: dictionary (string -> int)    
  157.    returns: dictionary (string -> int)
  158.    """
  159.     copyHand = hand.copy()
  160.    
  161.     for char in word :
  162.         copyHand[char] -= 1
  163.     return copyHand
  164.  
  165. #
  166. # Problem #3: Test word validity
  167. #
  168. def isValidWord(word, hand, wordList):
  169.     """
  170.    Returns True if word is in the wordList and is entirely
  171.    composed of letters in the hand. Otherwise, returns False.
  172.  
  173.    Does not mutate hand or wordList.
  174.  
  175.    word: string
  176.    hand: dictionary (string -> int)
  177.    wordList: list of lowercase strings
  178.    """
  179.     auxWord = ''
  180.     copyHand = hand.copy()
  181.    
  182.     for char in word :
  183.         if char in copyHand.keys() and copyHand[char] > 0 :
  184.             auxWord += char
  185.             copyHand[char] -= 1
  186.            
  187.     if auxWord.lower() in wordList :
  188.         return True
  189.     else :
  190.         return False
  191. #
  192. # Problem #4: Playing a hand
  193. #
  194.  
  195. def calculateHandlen(hand):
  196.     """
  197.    Returns the length (number of letters) in the current hand.
  198.    
  199.    hand: dictionary (string-> int)
  200.    returns: integer
  201.    """
  202.     count = 0
  203.    
  204.     for char in hand.keys() :
  205.         count += hand[char]
  206.    
  207.     return count
  208.        
  209.  
  210. def playHand(hand, wordList, n):
  211.     """
  212.    Allows the user to play the given hand, as follows:
  213.  
  214.    * The hand is displayed.
  215.    * The user may input a word or a single period (the string ".")
  216.      to indicate they're done playing
  217.    * Invalid words are rejected, and a message is displayed asking
  218.      the user to choose another word until they enter a valid word or "."
  219.    * When a valid word is entered, it uses up letters from the hand.
  220.    * After every valid word: the score for that word is displayed,
  221.      the remaining letters in the hand are displayed, and the user
  222.      is asked to input another word.
  223.    * The sum of the word scores is displayed when the hand finishes.
  224.    * The hand finishes when there are no more unused letters or the user
  225.      inputs a "."
  226.  
  227.      hand: dictionary (string -> int)
  228.      wordList: list of lowercase strings
  229.      n: integer (HAND_SIZE; i.e., hand size required for additional points)
  230.      
  231.    """
  232.     # BEGIN PSEUDOCODE <-- Remove this comment when you code this function; do your coding within the pseudocode (leaving those comments in-place!)
  233.     # Keep track of the total score
  234.     totalScore = 0
  235.    
  236.     # As long as there are still letters left in the hand:
  237.     while calculateHandlen(hand) >= 0 :
  238.         # Display the hand
  239.         print('Current Hand:'), displayHand(hand)
  240.         # Ask user for input
  241.         userInput = raw_input(str("Enter word, or a \".\" to indicate that you are finished: "))
  242.         # If the input is a single period:
  243.         if userInput == "." :
  244.             # End the game (break out of the loop)
  245.             print("Goodbye! Total score: "+str(totalScore)+" points.")
  246.             break
  247.         # Otherwise (the input is not a single period):
  248.         elif not isValidWord(userInput, hand, wordList) :
  249.             # If the word is not valid:
  250.             # Reject invalid word (print a message followed by a blank line)
  251.             print("Invalid word, please try again.")
  252.             print("")
  253.         # Otherwise (the word is valid):
  254.         else :
  255.             # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
  256.             totalScore += getWordScore(userInput, n)
  257.             print("\""+str(userInput)+"\" earned "+str(getWordScore(userInput, n))+". Total: "+str(totalScore))
  258.             print("")
  259.             # Update the hand
  260.             hand = updateHand(hand, userInput)
  261.  
  262.         # Game is over (user entered a '.' or ran out of letters), so tell user the total score
  263.         if calculateHandlen(hand) == 0 :
  264.             print("Run out of letters. Total score: "+str(totalScore)+" points.")
  265.             break
  266.  
  267. #
  268. # Problem #5: Playing a game
  269. #
  270.  
  271. def playGame(wordList):
  272.     """
  273.    Allow the user to play an arbitrary number of hands.
  274.  
  275.    1) Asks the user to input 'n' or 'r' or 'e'.
  276.      * If the user inputs 'n', let the user play a new (random) hand.
  277.      * If the user inputs 'r', let the user play the last hand again.
  278.      * If the user inputs 'e', exit the game.
  279.      * If the user inputs anything else, tell them their input was invalid.
  280.  
  281.    2) When done playing the hand, repeat from step 1    
  282.    """
  283.     while True :
  284.         userInput = raw_input(str("Enter n to deal a new hand, r to replay the last hand, or e to end game: "))
  285.        
  286.         if userInput == "n" :
  287.             n = HAND_SIZE
  288.             hand = dealHand(n)
  289.             playHand(hand, wordList, n)
  290.         elif userInput == "r" :
  291.             try :
  292.                 playHand(hand, wordList, n)
  293.             except :
  294.                 print("You have not played a hand yet. Please play a new hand first!")
  295.         elif userInput == "e" :
  296.             break
  297.         else :
  298.             print("Invalid command.")
  299.  
  300. #
  301. # Build data structures used for entire session and play game
  302. #
  303. if __name__ == '__main__':
  304.     wordList = loadWords()
  305.     playGame(wordList)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement