Advertisement
Guest User

Untitled

a guest
Mar 9th, 2013
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.23 KB | None | 0 0
  1. import random
  2. import string
  3.  
  4. VOWELS = 'aeiou'
  5. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
  6. HAND_SIZE = 10
  7. n = HAND_SIZE
  8.  
  9. SCRABBLE_LETTER_VALUES = {
  10.     '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
  11. }
  12.  
  13. # -----------------------------------
  14. # Helper code
  15. # (you don't need to understand this helper code)
  16.  
  17. WORDLIST_FILENAME = "words.txt"
  18.  
  19. def loadWords():
  20.     """
  21.    Returns a list of valid words. Words are strings of lowercase letters.
  22.  
  23.    Depending on the size of the word list, this function may
  24.    take a while to finish.
  25.    """
  26.     print "Loading word list from file..."
  27.     # inFile: file
  28.     inFile = open(WORDLIST_FILENAME, 'r', 0)
  29.     # wordList: list of strings
  30.     wordList = []
  31.     for line in inFile:
  32.         wordList.append(line.strip().lower())
  33.     print "  ", len(wordList), "words loaded."
  34.     return wordList
  35.  
  36. def getFrequencyDict(sequence):
  37.     """
  38.    Returns a dictionary where the keys are elements of the sequence
  39.    and the values are integer counts, for the number of times that
  40.    an element is repeated in the sequence.
  41.  
  42.    sequence: string or list
  43.    return: dictionary
  44.    """
  45.     # freqs: dictionary (element_type -> int)
  46.     freq = {}
  47.     for x in sequence:
  48.         freq[x] = freq.get(x,0) + 1
  49.     return freq
  50.  
  51.  
  52. # (end of helper code)
  53. # -----------------------------------
  54.  
  55. #
  56. # Problem #1: Scoring a word
  57. #
  58.  
  59.  
  60.  
  61.  
  62.  
  63. def scoreW(word):
  64.     scrab = SCRABBLE_LETTER_VALUES
  65.     return sum([scrab[i] for i in word])  # get sum of word
  66.  
  67.  
  68.  
  69. def wordL(word):    #get len of word
  70.     lenW = ''
  71.     for i in word:
  72.         lenW += i
  73.     return len(lenW)
  74.  
  75. def getWordScore(word, n):
  76.     """
  77.   Returns the score for a word. Assumes the word is a valid word.
  78.  
  79.   The score for a word is the sum of the points for letters in the
  80.   word, multiplied by the length of the word, PLUS 50 points if all n
  81.   letters are used on the first turn.
  82.  
  83.   Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
  84.   worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
  85.  
  86.   word: string (lowercase letters)
  87.   n: integer (HAND_SIZE; i.e., hand size required for additional points)
  88.   returns: int >= 0
  89.   """
  90.     score = 0
  91.     for i in word:
  92.         score += SCRABBLE_LETTER_VALUES[i]
  93.     if len(word) == n:
  94.         return (score * len(word)) + 50
  95.     else:
  96.         return score * len(word
  97. #
  98. # Problem #2: Make sure you understand how this function works and what it does!
  99. #
  100. def displayHand(hand):
  101.     """
  102.    Displays the letters currently in the hand.
  103.  
  104.    For example:
  105.    >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
  106.    Should print out something like:
  107.       a x x l l l e
  108.    The order of the letters is unimportant.
  109.  
  110.    hand: dictionary (string -> int)
  111.  
  112.    """
  113.     ans = []
  114.     for letter in hand.keys():
  115.         for j in range(hand[letter]):
  116.             ans.append(letter)
  117.             print letter, # print all on the same line
  118.     print                               # print an empty line
  119.  
  120.  
  121. #
  122. # Problem #2: Make sure you understand how this function works and what it does!
  123. #
  124. def dealHand(n):
  125.     """
  126.    Returns a random hand containing n lowercase letters.
  127.    At least n/3 the letters in the hand should be VOWELS.
  128.  
  129.    Hands are represented as dictionaries. The keys are
  130.    letters and the values are the number of times the
  131.    particular letter is repeated in that hand.
  132.  
  133.    n: int >= 0
  134.    returns: dictionary (string -> int)
  135.    """
  136.     hand={}
  137.     numVowels = n / 3
  138.  
  139.     for i in range(numVowels):
  140.         x = VOWELS[random.randrange(0,len(VOWELS))]
  141.         hand[x] = hand.get(x, 0) + 1
  142.  
  143.     for i in range(numVowels, n):
  144.         x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
  145.         hand[x] = hand.get(x, 0) + 1
  146.  
  147.     return hand
  148.  
  149. #
  150. # Problem #2: Update a hand by removing letters
  151. #
  152.  
  153. def updateHand(hand, word):
  154.     """
  155.    Assumes that 'hand' has all the letters in word.
  156.    In other words, this assumes that however many times
  157.    a letter appears in 'word', 'hand' has at least as
  158.    many of that letter in it.
  159.  
  160.    Updates the hand: uses up the letters in the given word
  161.    and returns the new hand, without those letters in it.
  162.  
  163.    Has no side effects: does not modify hand.
  164.  
  165.    word: string
  166.    hand: dictionary (string -> int)
  167.    returns: dictionary (string -> int)
  168.    """
  169.     # TO DO ... <-- Remove this comment when you code this function
  170.     hand2 = dict.copy(hand)
  171.     for l in word:
  172.         hand2[l] -= 1
  173.     return hand2
  174.  
  175. #
  176. # Problem #3: Test word validity
  177. #
  178.  
  179. def isValidWord(word,hand,wordList):
  180.     hand_cp = dict.copy(hand)
  181.     for letter in word:
  182.         if hand_cp.get(letter):
  183.             # The letter is in our hand, so "use it up".
  184.             hand_cp[letter] = hand_cp[letter] - 1
  185.         else:
  186.             # The letter isn't in our hand, so the word isn't valid.
  187.             return False
  188.  
  189.     # If we can make the word, now make sure it's a real word:
  190.     # (If wordlist is long, you might want to sort it and do a real search)
  191.     if word not in wordList:
  192.         return False
  193.  
  194.     # We haven't found any reason to return False, so this is a valid word.
  195.     return True
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203. # Problem #4: Playing a hand
  204. #
  205.  
  206.  
  207. def calculateHandlen(hand):
  208.     """
  209.    Returns the length (number of letters) in the current hand.
  210.  
  211.    hand: dictionary (string int)
  212.    returns: integer
  213.    """
  214.     return sum(hand.itervalues())
  215.  
  216. hand = {'a':1}
  217.  
  218. wordList = loadWords()
  219. def playHand(hand, wordList, n):
  220.     """
  221.    Allows the user to play the given hand, as follows:
  222.  
  223.    * The hand is displayed.
  224.    * The user may input a word or a single period (the string ".")
  225.      to indicate they're done playing
  226.    * Invalid words are rejected, and a message is displayed asking
  227.      the user to choose another word until they enter a valid word or "."
  228.    * When a valid word is entered, it uses up letters from the hand.
  229.    * After every valid word: the score for that word is displayed,
  230.      the remaining letters in the hand are displayed, and the user
  231.      is asked to input another word.
  232.    * The sum of the word scores is displayed when the hand finishes.
  233.    * The hand finishes when there are no more unused letters or the user
  234.      inputs a "."
  235.  
  236.      hand: dictionary (string -> int)
  237.      wordList: list of lowercase strings
  238.      n: integer (HAND_SIZE; i.e., hand size required for additional points)
  239.  
  240.    """
  241.  
  242.  
  243.     #  Keep track of the total score
  244.     totalScore = 0
  245.  
  246.     gameOver = False
  247.     c = calculateHandlen(hand)
  248.     # As long as there are still letters left in the hand:
  249.  
  250.     while not gameOver:
  251.         if c == 0:
  252.             print "Run out of letters. Total score: " + str(totalScore) + " points."
  253.             break
  254.             # Game is over if ran out of letters), so tell user the total score
  255.  
  256.  
  257.         # Display the hand
  258.  
  259.  
  260.         print displayHand(hand), #print hand on screen
  261.  
  262.         word = raw_input("Enter word, or a " + '"."' +  " to indicate that you are finished: ") # Ask user for input
  263.         word = word.lower()
  264.  
  265.  
  266.  
  267.         # If the input is a single period:
  268.         if word == '.':
  269.         # End the game (break out of the loop)
  270.             print   "Goodbye! Total score: " +  str(totalScore) + " points."
  271.             break
  272.  
  273.             # Otherwise (the input is not a single period):
  274.         else:
  275.  
  276.             # If the word is not valid:
  277.             if word != '.' and  isValidWord(word,hand,wordList)  == False:
  278.  
  279.  
  280.                 # Reject invalid word (print a message followed by a blank line)
  281.                 print  "Invalid word, please try again."
  282.  
  283.             # Otherwise (the word is valid):
  284.             elif isValidWord(word,hand,wordList)  == True:
  285.                 hand = updateHand(hand,word)
  286.                 # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
  287.                 getWordScore(word,n)
  288.                 totalScore += getWordScore(word,n)
  289.                 print   '"'+str(word)+'"'  + " earned " + str(getWordScore(word,n)) +' points.' " Total:  " + str(totalScore) + " points."
  290.                 print
  291.  
  292.                 # Update the hand
  293.                 c = calculateHandlen(hand)
  294.  
  295.  
  296.  
  297.  
  298.  
  299.  
  300.  
  301.  
  302.  
  303.  
  304.  
  305.  
  306. wordList = loadWords()
  307. hand = {'a': 1, 'p': 2, 's': 1, 'e': 1, 'l': 1}
  308. def playGame(wordList):
  309.  
  310.     """
  311.    Allow the user to play an arbitrary number of hands.
  312.  
  313.    1) Asks the user to input 'n' or 'r' or 'e'.
  314.      * If the user inputs 'n', let the user play a new (random) hand.
  315.      * If the user inputs 'r', let the user play the last hand again.
  316.      * If the user inputs 'e', exit the game.
  317.      * If the user inputs anything else, tell them their input was invalid.
  318.  
  319.    2) When done playing the hand, repeat from step 1
  320.    """
  321.  
  322.     user = None
  323.     pHand = None
  324.     while user != 'e':
  325.  
  326.  
  327.         user = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
  328.         user = user.lower()
  329.         legalIn = ['r','e','n'] #legal input characters
  330.  
  331.         if user == 'e': #exit game if player inputs e.
  332.             return None
  333.         if user not in legalIn:
  334.             print "Invalid command."
  335.  
  336.  
  337.         if user == 'n': #if user wants to play a new hand
  338.             pHand = dealHand(HAND_SIZE)
  339.             print "Hand passed to playHand: ",
  340.             playHand(pHand.copy(),wordList,HAND_SIZE)
  341.  
  342.         elif user == 'r' and pHand != None:  #if user inputs r and hand2 is  not empty, hand will be replayed
  343.             print "Hand passed to playHand: ",
  344.             playHand(pHand.copy(),wordList,HAND_SIZE)
  345.  
  346.         else:
  347.             if user == 'r' and pHand == None: #if user inputs r but there have been no hands played yet
  348.                print "You have not played a hand yet. Please play a new hand first!"
  349.                print
  350.  
  351.  
  352.  
  353.  
  354. from ps4a import *
  355. import time
  356.  
  357.  
  358. #
  359. #
  360. # Problem #6: Computer chooses a word
  361. #
  362. #
  363.  
  364. def validWord(word,hand):
  365.     """
  366.  
  367.    :param word:
  368.    :param hand:
  369.    :return:
  370.    """
  371.     hand_cp = dict.copy(hand)
  372.     for letter in word:
  373.         if hand_cp.get(letter):
  374.  
  375.             hand_cp[letter] -= 1  # The letter is in our hand, so "use it up".
  376.         else:                        # The letter isn't in our hand, so the word isn't valid.
  377.             return False
  378.     return True        # We haven't found any reason to return False, so this is a valid word.
  379.  
  380. #
  381. #
  382. # Problem #6: Computer chooses a word
  383. #
  384.  
  385.  
  386. def compChooseWord(hand, wordList, n):
  387.     """
  388.    Given a hand and a wordList, find the word that gives
  389.    the maximum value score, and return it.
  390.  
  391.    This word should be calculated by considering all the words
  392.    in the wordList.
  393.  
  394.    If no words in the wordList can be made from the hand, return None.
  395.  
  396.    hand: dictionary (string -> int)
  397.    wordList: list (string)
  398.    n: integer (HAND_SIZE; i.e., hand size required for additional points)
  399.  
  400.    returns: string or None
  401.    """
  402.  
  403.     # Create a new variable to store the maximum score seen so far (initially 0)
  404.     bestScore = 0  # Create a new variable to store the best word seen so far (initially None)
  405.     score = 0
  406.  
  407.     bestWord = None
  408.                      # For each word in the wordList
  409.  
  410.     for word in wordList:
  411.                          # If you can construct the word from your hand
  412.         if len(hand) <=1:
  413.             return None
  414.  
  415.         if validWord(word, hand):
  416.  
  417.             score = getWordScore(word,n)  # Find out how much making that word is worth
  418.  
  419.         if score > bestScore:    # If the score for that word is higher than your best score
  420.  
  421.             bestWord = word                   # Update your best score, and best word accordingly
  422.             bestScore = score
  423.  
  424.     return bestWord  # return the best word  found.
  425.  
  426.  
  427. #
  428. # Problem #7: Computer plays a hand
  429.  
  430. def compPlayHand(hand, wordList, n):
  431.  
  432.  
  433.     totalScore = 0    #  Keep track of the total score
  434.  
  435.     while compChooseWord(hand,wordList,n) is not None:     # As long as there are still usable letters left in the hand:
  436.  
  437.  
  438.         print "Current Hand: ",                 # Display the hand
  439.         displayHand(hand)
  440.  
  441.         word = compChooseWord(hand,wordList,n)  # comp chooses word
  442.  
  443.         hand = updateHand(hand,word)            #update hand
  444.  
  445.         getWordScore(word,n)                #get word score
  446.         totalScore += getWordScore(word,n)
  447.  
  448.         c = calculateHandlen(hand)           #recalculate hand length
  449.  
  450.         print   '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total:  " + str(totalScore) + " points."
  451.         print
  452.  
  453.         if calculateHandlen(hand) == 0:                      #if all letters used
  454.             print "Total score: " + str(totalScore) + " points."
  455.             break
  456.  
  457.         if compChooseWord(hand,wordList,n) is None:         #if no  more words can be made
  458.  
  459.             print  "Current Hand: ",
  460.             displayHand(hand)
  461.             print "Total score: " + str(totalScore) + " points."
  462.             brea
  463. print compPlayHand(hand,wordList,n)
  464.  
  465.  
  466.  
  467. wordList = loadWords()
  468. hand = {'b': 1, 'i': 1, 'j': 1, 'o': 1, 'q': 1, 'u': 1, 'y': 1, 'x': 1}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement