Advertisement
Guest User

Untitled

a guest
Oct 2nd, 2012
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.73 KB | None | 0 0
  1. import random
  2. import string
  3.  
  4. VOWELS = 'aeiou'
  5. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
  6. HAND_SIZE = 7
  7.  
  8. SCRABBLE_LETTER_VALUES = {
  9.     '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
  10. }
  11.  
  12. # -----------------------------------
  13. # Helper code
  14. # (you don't need to understand this helper code)
  15.  
  16. WORDLIST_FILENAME = "words.txt"
  17.  
  18. def load_words():
  19.     """
  20.    Returns a list of valid words. Words are strings of lowercase letters.
  21.    
  22.    Depending on the size of the word list, this function may
  23.    take a while to finish.
  24.    """
  25.     # inFile: file
  26.     inFile = open(WORDLIST_FILENAME, 'r', 0)
  27.     # wordlist: list of strings
  28.     wordlist = []
  29.     for line in inFile:
  30.         wordlist.append(line.strip().lower())
  31.     return wordlist
  32.  
  33.  
  34. def get_frequency_dict(sequence):
  35.     """
  36.    Returns a dictionary where the keys are elements of the sequence
  37.    and the values are integer counts, for the number of times that
  38.    an element is repeated in the sequence.
  39.  
  40.    sequence: string or list
  41.    return: dictionary
  42.    """
  43.     # freqs: dictionary (element_type -> int)
  44.     freq = {}
  45.     for x in sequence:
  46.         freq[x] = freq.get(x,0) + 1
  47.     return freq
  48.    
  49.  
  50. # (end of helper code)
  51. # -----------------------------------
  52.  
  53. #
  54. # Problem #1: Scoring a word
  55. #
  56.  
  57.  
  58. def get_word_score(word, n):
  59.     """
  60.    Returns the score for a word. Assumes the word is a
  61.    valid word.
  62.  
  63.     The score for a word is the sum of the points for letters
  64.     in the word multiplied by the length of the word, plus 50
  65.     points if all n letters are used on the first go.
  66.  
  67.     Letters are scored as in Scrabble; A is worth 1, B is
  68.     worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.
  69.  
  70.    word: string (lowercase letters)
  71.    returns: int >= 0
  72.    """
  73.     score = 0
  74.     word = string.lower(word)
  75.     for a in word:
  76.         score = score + SCRABBLE_LETTER_VALUES[a]
  77.     score = score * len(word)
  78.     if len(word) == n:
  79.         score = score + 50
  80.     return score
  81.        
  82. #
  83. # Problem 1: Unit Test
  84. #
  85.  
  86. def test_get_word_score():
  87.     """
  88.    Unit test for get_word_score
  89.    """
  90.     failure=0
  91.     # dictionary of words and scores
  92.     words = {("", 7):0, ("it", 7):4, ("was", 7):18, ("scored", 7):54, ("waybill", 7):155, ("outgnaw", 7):127, ("outgnawn", 8):146}
  93.     for (word, n) in words.keys():
  94.         score = get_word_score(word, n)
  95.         if score != words[(word, n)]:
  96.             print "FAILURE: test_get_word_score()"
  97.             print "\tExpected", words[(word, n)], "points but got '" + str(score) + "' for word '" + word + "', n=" + str(n)
  98.             failure=True
  99.     if not failure:
  100.         print "SUCCESS: test_get_word_score()"
  101.        
  102. test_get_word_score()
  103.        
  104.                
  105. # Make sure you understand how this function works and what it does!
  106.  
  107. def display_hand(hand):
  108.     """
  109.    Displays the letters currently in the hand.
  110.  
  111.    For example:
  112.       display_hand({'a':1, 'x':2, 'l':3, 'e':1})
  113.    Should print out something like:
  114.       a x x l l l e
  115.    The order of the letters is unimportant.
  116.  
  117.    hand: dictionary (string -> int)
  118.    """
  119.     for letter in hand.keys():
  120.         for j in range(hand[letter]):
  121.              print letter,              # print all on the same line
  122.     print                               # print an empty line
  123.  
  124. #Make sure you understand how this function works and what it does!
  125.  
  126. def deal_hand(n):
  127.     """
  128.    Returns a random hand containing n lowercase letters.
  129.    At least n/3 the letters in the hand should be VOWELS.
  130.  
  131.    Hands are represented as dictionaries. The keys are
  132.    letters and the values are the number of times the
  133.    particular letter is repeated in that hand.
  134.  
  135.    n: int >= 0
  136.    returns: dictionary (string -> int)
  137.    """
  138.     hand={}
  139.     num_vowels = n / 3
  140.    
  141.     for i in range(num_vowels):
  142.         x = VOWELS[random.randrange(0,len(VOWELS))]
  143.         hand[x] = hand.get(x, 0) + 1
  144.        
  145.     for i in range(num_vowels, n):    
  146.         x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
  147.         hand[x] = hand.get(x, 0) + 1
  148.        
  149.     return hand
  150.  
  151.  
  152. #
  153. #Problem #2: Update a hand by removing letters
  154. #
  155.  
  156. def update_hand(hand, word):
  157.     """
  158.    Assumes that 'hand' has all the letters in word.
  159.     In other words, this assumes that however many times
  160.     a letter appears in 'word', 'hand' has at least as
  161.     many of that letter in it.
  162.  
  163.    Updates the hand: uses up the letters in the given word
  164.    and returns the new hand, without those letters in it.
  165.  
  166.    Has no side effects: does not modify hand.
  167.  
  168.    word: string
  169.    hand: dictionary (string -> int)    
  170.    returns: dictionary (string -> int)
  171.    """
  172.    
  173.     for a in word:
  174.         if hand.get(a, 0) >= 1:
  175.             hand[a] = hand[a] - 1
  176.     return hand    
  177. #
  178. # Problem 2: Unit Test
  179. #
  180.    
  181. def test_update_hand():
  182.     """
  183.    Unit test for update_hand
  184.    """
  185.     # test 1
  186.     hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
  187.     word = "quail"
  188.  
  189.     hand2 = update_hand(hand.copy(), word)
  190.     expected_hand1 = {'l':1, 'm':1}
  191.     expected_hand2 = {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0}
  192.     if hand2 != expected_hand1 and hand2 != expected_hand2:
  193.         print "FAILURE: test_update_hand('"+ word +"', " + str(hand) + ")"
  194.         print "\tReturned: ", hand2, "-- but expected:", expected_hand1, "or", expected_hand2
  195.  
  196.         return # exit function
  197.        
  198.     # test 2
  199.     hand = {'e':1, 'v':2, 'n':1, 'i':1, 'l':2}
  200.     word = "evil"
  201.  
  202.     hand2 = update_hand(hand.copy(), word)
  203.     expected_hand1 = {'v':1, 'n':1, 'l':1}
  204.     expected_hand2 = {'e':0, 'v':1, 'n':1, 'i':0, 'l':1}
  205.     if hand2 != expected_hand1 and hand2 != expected_hand2:
  206.         print "FAILURE: test_update_hand('"+ word +"', " + str(hand) + ")"        
  207.         print "\tReturned: ", hand2, "-- but expected:", expected_hand1, "or", expected_hand2
  208.  
  209.         return # exit function
  210.  
  211.     # test 3
  212.     hand = {'h': 1, 'e': 1, 'l': 2, 'o': 1}
  213.     word = "hello"
  214.  
  215.     hand2 = update_hand(hand.copy(), word)
  216.     expected_hand1 = {}
  217.     expected_hand2 = {'h': 0, 'e': 0, 'l': 0, 'o': 0}
  218.     if hand2 != expected_hand1 and hand2 != expected_hand2:
  219.         print "FAILURE: test_update_hand('"+ word +"', " + str(hand) + ")"                
  220.         print "\tReturned: ", hand2, "-- but expected:", expected_hand1, "or", expected_hand2
  221.        
  222.         return # exit function
  223.  
  224.     print "SUCCESS: test_update_hand()"
  225.  
  226. test_update_hand()     
  227.  
  228. #  
  229. # Problem #3: Test word validity
  230. #
  231.  
  232. word = 'monk'
  233. hand = {'m':1, 'k':1, 'o':1, 'n':1}
  234.  
  235. def is_valid_word(word, hand, word_list):
  236.     """
  237.    Returns True if word is in the word_list and is entirely
  238.    composed of letters in the hand. Otherwise, returns False.
  239.    Does not mutate hand or word_list.
  240.    
  241.    word: string
  242.    hand: dictionary (string -> int)
  243.    word_list: list of lowercase strings
  244.    """
  245.     test1= True
  246.     hand1 = {}
  247.     for a in word:
  248.         if a in hand1:
  249.             hand1[a] = hand1[a] +1
  250.         else:
  251.             hand1[a] = 1
  252.     for b in hand1:
  253.         if (b not in hand):
  254.             test1 = False
  255.             break
  256.         else:
  257.             if hand1[b] > hand[b]:
  258.                 test1 = False
  259.                 break
  260.     return test1
  261.  
  262.  
  263. # print is_valid_word(word, hand, load_words())
  264.          
  265.  
  266.    
  267.  
  268. def test_is_valid_word(word_list):
  269. #     """
  270. #     Unit test for is_valid_word
  271. #     """
  272.     failure=False
  273.     # test 1
  274.     word = "hello"
  275.     hand = get_frequency_dict(word)
  276.  
  277.     if not is_valid_word(word, hand, word_list):
  278.         print "FAILURE: test_is_valid_word()"
  279.         print "\tExpected True, but got False for word: '" + word + "' and hand:", hand
  280.  
  281.         failure = True
  282.  
  283.    # test 2
  284.     hand = {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}
  285.     word = "rapture"
  286.  
  287.     if  is_valid_word(word, hand, word_list):
  288.         print "FAILURE: test_is_valid_word()"
  289.         print "\tExpected False, but got True for word: '" + word + "' and hand:", hand
  290.  
  291.         failure = True        
  292.  
  293.     # test 3
  294.     hand = {'n': 1, 'h': 1, 'o': 1, 'y': 1, 'd':1, 'w':1, 'e': 2}
  295.     word = "honey"
  296.  
  297.     if  not is_valid_word(word, hand, word_list):
  298.         print "FAILURE: test_is_valid_word()"
  299.         print "\tExpected True, but got False for word: '"+ word +"' and hand:", hand
  300.  
  301.         failure = True                        
  302.  
  303.     # test 4
  304.     hand = {'r': 1, 'a': 3, 'p': 2, 't': 1, 'u':2}
  305.     word = "honey"
  306.  
  307.     if  is_valid_word(word, hand, word_list):
  308.         print "FAILURE: test_is_valid_word()"
  309.         print "\tExpected False, but got True for word: '" + word + "' and hand:", hand
  310.        
  311.         failure = True
  312.  
  313.     # test 5
  314.     hand = {'e':1, 'v':2, 'n':1, 'i':1, 'l':2}
  315.     word = "evil"
  316.    
  317.     if  not is_valid_word(word, hand, word_list):
  318.         print "FAILURE: test_is_valid_word()"
  319.         print "\tExpected True, but got False for word: '" + word + "' and hand:", hand
  320.        
  321.         failure = True
  322.        
  323.     # test 6
  324.     word = "even"
  325.  
  326.     if  is_valid_word(word, hand, word_list):
  327.         print "FAILURE: test_is_valid_word()"
  328.         print "\tExpected False, but got True for word: '" + word + "' and hand:", hand
  329.         print "\t(If this is the only failure, make sure is_valid_word() isn't mutating its inputs)"        
  330.        
  331.         failure = True        
  332.  
  333.     if not failure:
  334.         print "SUCCESS: test_is_valid_word()"
  335.  
  336. test_is_valid_word(load_words())
  337.  
  338.  
  339.  
  340. # word_list = load_words()
  341. # print "----------------------------------------------------------------------"
  342. # print "Testing get_word_score..."
  343. # test_get_word_score()
  344. # print "----------------------------------------------------------------------"
  345. # print "Testing update_hand..."
  346. # test_update_hand()
  347. # print "----------------------------------------------------------------------"
  348. # print "Testing is_valid_word..."
  349. # test_is_valid_word(word_list)
  350. # print "----------------------------------------------------------------------"
  351. # print "All done!"
  352. #      
  353.    
  354.  
  355. #
  356. # Problem #4: Playing a hand
  357. #
  358.  
  359.  
  360. def play_hand(hand, word_list):
  361.   # """
  362. #     Allows the user to play the given hand, as follows:
  363. #
  364. #     * The hand is displayed.
  365. #    
  366. #     * The user may input a word.
  367. #
  368. #     * An invalid word is rejected, and a message is displayed asking
  369. #       the user to choose another word.
  370. #
  371. #     * When a valid word is entered, it uses up letters from the hand.
  372. #
  373. #     * After every valid word: the score for that word is displayed,
  374. #       the remaining letters in the hand are displayed, and the user
  375. #       is asked to input another word.
  376. #
  377. #     * The sum of the word scores is displayed when the hand finishes.
  378. #
  379. #     * The hand finishes when there are no more unused letters.
  380. #       The user can also finish playing the hand by inputting a single
  381. #       period (the string '.') instead of a word.
  382. #
  383. #       hand: dictionary (string -> int)
  384. #       word_list: list of lowercase strings
  385. #      
  386. #     """  
  387.     n = 7
  388.     hand = (deal_hand(n))
  389.     guess = ''
  390.     points = 0
  391.     while guess != '.' and len(hand) > 0:
  392.         print "Current Hand: ", display_hand(hand)
  393.         guess = raw_input( "Enter word, or a '.', to indicate that you are finished: ")
  394.         if guess == '.':
  395.             break
  396.         if guess != is_valid_word(guess, hand, load_words()):
  397.             print "Invalid word, please try again."
  398.         else:
  399.             points = points + get_word_score(guess, load_words())
  400.             print guess, " earned ", get_word_score(guess, load_words()), " points. Total: ", points
  401.             hand = update_hand(hand, guess)
  402.         print "Total Score: ", points
  403.  
  404. n =7
  405. def play_game(word_list):
  406.     """Allow the user to play an arbitrary number of hands.
  407.  
  408.    1) Asks the user to input 'n' or 'r' or 'e'.
  409.    * If the user inputs 'n', play a new (random) hand.
  410.    * If the user inputs 'r', play the last hand again.
  411.    * If the user inputs 'e', exit the game.
  412.    * If the user inputs anything else, ask them again.
  413.  
  414.    2) Ask the user to input a 'u' or a 'c'.
  415.    * If the user inputs 'u', let the user play the game as before using play_hand.
  416.    * If the user inputs 'c', let the computer play the game using comp_play_hand (created above).
  417.    * If the user inputs anything else, ask them again.
  418.  
  419.    3) After the computer or user has played the hand, repeat from step 1
  420.  
  421.    word_list: list (string)
  422.    """
  423.     # TO DO...
  424.     choose = ''
  425.     while choose != 'e':
  426.         choose = raw_input("What is your move: ")
  427.         if choose == 'n' or choose == 'r':
  428.             if choose == 'n':
  429.                 handz = deal_hand(7)    
  430.             play_hand(handz, word_list)
  431.         else:
  432.             break
  433.  
  434. play_game(load_words())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement