• API
• FAQ
• Tools
• Trends
• Archive
SHARE
TWEET

# Untitled

a guest May 11th, 2014 147 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # 6.00 Problem Set 3A Solutions
2. #
3. # The 6.00 Word Game
4. # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
5. #
6. #
7.
8. import random
9. import string
10. import sys
11.
12. VOWELS = 'aeiou'
13. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
14. HAND_SIZE = 7
15.
16. SCRABBLE_LETTER_VALUES = {
17.     '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
18. }
19.
20. # -----------------------------------
21. # Helper code
22. # (you don't need to understand this helper code)
23.
24. WORDLIST_FILENAME = "words.txt"
25.
27.     """
28.    Returns a list of valid words. Words are strings of lowercase letters.
29.
30.    Depending on the size of the word list, this function may
31.    take a while to finish.
32.    """
33.     print "Loading word list from file..."
34.     # inFile: file
35.     inFile = open(WORDLIST_FILENAME, 'r', 0)
36.     # wordlist: list of strings
37.     wordlist = []
38.     for line in inFile:
39.         wordlist.append(line.strip().lower())
40.     print "  ", len(wordlist), "words loaded."
41.     return wordlist
42.
43.
44. # We dont need this -Nix
45. #word_list = load_words()
46.
47. def get_frequency_dict(sequence):
48.     """
49.    Returns a dictionary where the keys are elements of the sequence
50.    and the values are integer counts, for the number of times that
51.    an element is repeated in the sequence.
52.
53.    sequence: string or list
54.    return: dictionary
55.    """
56.     # freqs: dictionary (element_type -> int)
57.     freq = {}
58.     for x in sequence:
59.         freq[x] = freq.get(x,0) + 1
60.     return freq
61.
62.
63. # (end of helper code)
64. # -----------------------------------
65.
66. #
67. # Problem #1: Scoring a word
68. #
69. def get_word_score(word, n):
70.     """
71.     Returns the score for a word. Assumes the word is a
72.     valid word.
73.
74.         The score for a word is the sum of the points for letters
75.         in the word multiplied by the length of the word, plus 50
76.         points if all n letters are used on the first go.
77.
78.         Letters are scored as in Scrabble; A is worth 1, B is
79.         worth 3, C is worth 3, D is worth 2, E is worth 1, and so on.
80.
81.     word: string (lowercase letters)
82.     returns: int >= 0
83.     """
84.     sum = 0
85.     #if is_valid_word is true
86.     for e in word:
87.         sum += SCRABBLE_LETTER_VALUES[e]
88.     score = len(word)*sum
89.     if len(word) == n:
90.         score += 50
91.     return score
92.     # TO DO...
93. #
94. # Make sure you understand how this function works and what it does!
95. #
96. def display_hand(hand):
97.     """
98.    Displays the letters currently in the hand.
99.
100.    For example:
101.       display_hand({'a':1, 'x':2, 'l':3, 'e':1})
102.    Should print out something like:
103.       a x x l l l e
104.    The order of the letters is unimportant.
105.
106.    hand: dictionary (string -> int)
107.    """
108.     for letter in hand.keys():
109.         for j in range(hand[letter]):
110.              print letter,              # print all on the same line
111.     print                               # print an empty line
112.
113. #
114. # Make sure you understand how this function works and what it does!
115. #
116. def deal_hand(n):
117.     """
118.    Returns a random hand containing n lowercase letters.
119.    At least n/3 the letters in the hand should be VOWELS.
120.
121.    Hands are represented as dictionaries. The keys are
122.    letters and the values are the number of times the
123.    particular letter is repeated in that hand.
124.
125.    n: int >= 0
126.    returns: dictionary (string -> int)
127.    """
128.     hand={}
129.     num_vowels = n / 3
130.
131.     for i in range(num_vowels):
132.         x = VOWELS[random.randrange(0,len(VOWELS))]
133.         hand[x] = hand.get(x, 0) + 1
134.
135.     for i in range(num_vowels, n):
136.         x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
137.         hand[x] = hand.get(x, 0) + 1
138.
139.     return hand
140.
141. #
142. # Problem #2: Update a hand by removing letters
143. #
144. def update_hand(hand, word):
145.     """
146.    Assumes that 'hand' has all the letters in word.
147.         In other words, this assumes that however many times
148.         a letter appears in 'word', 'hand' has at least as
149.         many of that letter in it.
150.
151.    Updates the hand: uses up the letters in the given word
152.    and returns the new hand, without those letters in it.
153.
154.    Has no side effects: does not modify hand.
155.
156.    word: string
157.    hand: dictionary (string -> int)
158.    returns: dictionary (string -> int)
159.    """
160.
161. #   The update_hand() isn't working quite as intended.
162. #   It will remove all instances of a letter in the players hand, no matter
163. #   how many of those letters the player uses.
164. #   E.g.:-
165. #   My hand: l u c k y y x
166. #   I play: lucky
167. #   Leftover letters: x
168. #
169. #   - Nix
170.
171. #    for letter in word:
172. #        hand[letter] -= 1
173. #    for letter in hand.keys():
174. #        if hand[letter] == 0:
175. #            hand.pop(letter, 0)
176. #    return hand
177.
178.     for letter in word:
179.        hand[letter] -= 1
180.        if hand[letter] < 1:
181.            hand.pop(letter)
182.     return hand
183.
184.
185. #
186. # Problem #3: Test word validity
187. #
188. def is_valid_word(word, hand, word_list):
189.     """
190.    Returns True if word is in the word_list and is entirely
191.    composed of letters in the hand. Otherwise, returns False.
192.    Does not mutate hand or word_list.
193.
194.    word: string
195.    hand: dictionary (string -> int)
196.    word_list: list of lowercase strings
197.    """
198.     hand1 = hand
199.     if word in word_list:
200.         for letter in word:
201.             if letter in hand1 and hand1[letter] > 0:
202.                 hand1[letter] -= 1
203.             else:
204.                 return False
205.         return True
206.     else:
207.         return False
208.
209. def calculate_handlen(hand):
210.     handlen = 0
211.     for v in hand.values():
212.         handlen += v
213.     return handlen
214.
215. #
216. # Problem #4: Playing a hand
217. #
218. def play_hand(hand, word_list):
219.     '''Allows the user to play a single, randomnly generated hand'''
220.     total = 0
221.     while True:
222.         display_hand(hand)
223.         word = raw_input('Enter a word compiled from the characters above or a period to end the hand:')
224.         if word == '.':
225.             break
226.         else:
227.             if is_valid_word(word, hand, word_list) == False:
228.                 print 'Invalid word, please enter another word.'
229.             else:
230.                 score = get_word_score(word, len(hand))
231.                 total += score
232.                 print '"'+word+'"','earned',score,'points. Total:',total,'points.'
233.                 update_hand(hand, word)
234.     print "Total score:",total
235.
236. #play_hand(word_list, 7)
237. #
238. # Problem #5: Playing a game
239. # Make sure you understand how this code works!
240. #
241.
242. #   I've re-written your play_game();
243. #   we don't need to take in 'hand' or 'n' in the function
244. #
245. #   'n' is just the number of characters you have in your hand, and is only
246. #   really useful to us when we want to add the bonus 50pts. So, I've just left
247. #   it local to the scoring function, instead of being passed around like a cheap
248. #   hooker.
249. #   play_game() is the "main" game function, so we don't want to take hand in
250. #   as a variable, we want to create the hand inside! I like to think of this
251. #   function as the "conductor" to the whole game, if that makes sense?
252. #
253. #   Also, be careful with variable contents over the conditional loops.
254. #   You had it so the current player hand wasn't refreshed if they decided to
255. #   play with the same hand again.
256. #
257. #   -Nix
258.
259.
260. #def play_game(hand, word_list, n):
261. #    hand1 = hand.copy()
262. #    while True:
263. #        play_hand(hand, word_list, n)
264. #        print 'Input "n" to play a new hand, "r" to play the last hand again, "e" to exit the game.'
265. #        choice = raw_input('')
266. #        if choice != 'n' and choice != 'r' and choice != 'e':
267. #            print 'Entry invalid, try again.'
268. #        elif choice == 'n':
269. #            play_game(deal_hand(n), word_list, n)
270. #        elif choice == 'r':
271. #            play_game(hand1, word_list, n)
272. #        else:
273. #            sys.exit()
274. def play_game(word_list):
275.     delt_hand = deal_hand(7)
276.     current_hand = delt_hand.copy()
277.     while True:
278.         display_hand(current_hand)
279.         choice = raw_input('Input "n" to play a new hand, "r" to play the last hand again, "e" to exit the game: ')
280.         if choice.lower() == 'n':
281.             delt_hand = deal_hand(7)
282.             current_hand = delt_hand.copy()
283.             play_hand(current_hand, word_list)
284.         elif choice.lower() == 'r':
285.             current_hand = delt_hand.copy()
286.             play_hand(current_hand, word_list)
287.         elif choice.lower() == 'e':
288.             sys.exit()
289.         else:
290.             print 'Entry invalid, try again.'
291.
292. #play_game(deal_hand(7), word_list, 7)
293. #
294. # Build data structures used for entire session and play game
295. #
296. if __name__ == '__main__':
297.     word_list = load_words()
298.     play_game(word_list)
RAW Paste Data
Top