This problem set involves a word game somewhat like Scrabble. In Part A, the player is dealt a hand of semi-random letters and has to make as many valid words as she can. Some letters are weighted higher or lower when it comes to scoring. Some aspects of the game code are provided to begin with. The rest of the functions are left up to us to complete, then put together into a looping game where you can choose to start a New Game, Replay, or Exit. In Part B, a computer player is added, which will pick one or more valid words until no more can be made with the remaining letters.
Key take-aways from lecture:
- floats are dangerous, e.g. 0.1 can only be approximated in binary
- print(num) may show ‘0.1’ but use repr(num) to see what is actually being stored
- When debugging, ask, “How could it have done what it did?”
- It’s a better starting point than, “Why didn’t it do what I want?”
- Use print statements in a manner similar to bisection search. Check here, then there.
- Try to test against small input values and make tests repeatable
Part A
- Scoring Words
- Dealing with Hands
- Word Validation
- Playing a Hand
- Playing a Game
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# 6.00 Problem Set 3A Solutions # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 6 SCRABBLE_LETTER_VALUES = { '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 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print " ", len(wordlist), "words loaded." return wordlist def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x,0) + 1 return freq # (end of helper code) # ----------------------------------- # # Problem #1: Scoring a word # # Casey Brown # caseycodes@gmail.com # begin: 20h35 # end: 21h00 # test_ps3a.py passing # def get_word_score(word, n): """ Returns the score for a word. Assumes the word is a valid word. The score for a word is the sum of the points for letters in the word multiplied by the length of the word, plus 50 points if all n letters are used on the first go. Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is worth 3, D is worth 2, E is worth 1, and so on. word: string (lowercase letters) returns: int >= 0 """ # TO DO... # n is not the length of the word, it is the length of the dealt hand if len(word) == 0: return 0 else: # start with a counter at zero score = 0 # for each letter, add them to the score for letter in word: score += SCRABBLE_LETTER_VALUES[letter] # how long is the word? That's our multiplier score *= len(word) # bonus score if len(word) == n: score += 50 # return something return score # # Make sure you understand how this function works and what it does! # def display_hand(hand): """ Displays the letters currently in the hand. For example: display_hand({'a':1, 'x':2, 'l':3, 'e':1}) Should print out something like: a x x l l l e The order of the letters is unimportant. hand: dictionary (string -> int) """ for letter in hand.keys(): for j in range(hand[letter]): print letter, # print all on the same line print # print an empty line # # Make sure you understand how this function works and what it does! # def deal_hand(n): """ Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. n: int >= 0 returns: dictionary (string -> int) """ hand={} num_vowels = n / 3 for i in range(num_vowels): x = VOWELS[random.randrange(0,len(VOWELS))] hand[x] = hand.get(x, 0) + 1 for i in range(num_vowels, n): x = CONSONANTS[random.randrange(0,len(CONSONANTS))] hand[x] = hand.get(x, 0) + 1 return hand # # Problem #2: Update a hand by removing letters # # Casey Brown # caseycodes@gmail.com # begin: 21h30 # end: 21h35 # test_ps3a.py passing # def update_hand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new hand, without those letters in it. Has no side effects: does not modify hand. word: string hand: dictionary (string -> int) returns: dictionary (string -> int) """ # TO DO ... # for each letter in word for i in word: # subtract 1 of that letter from hand hand[i] -= 1 return hand # # Problem #3: Test word validity # # Casey Brown # caseycodes@gmail.com # 15 min, sleep, start over, 20 min # def is_valid_word(word, hand, word_list): """ Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. word: string hand: dictionary (string -> int) word_list: list of lowercase strings """ # TO DO... # copy hand to not modify it when checking for letters this_hand = dict(hand) if word in word_list: is_a_word = True else: is_a_word = False # True until proven False word_in_hand = True for letter in word: # will return KeyError if check hand[letter] and letter not in hand if this_hand.get(letter, 0) > 0: this_hand[letter] -= 1 else: word_in_hand = False if is_a_word and word_in_hand: return True else: return False def calculate_handlen(hand): handlen = 0 for v in hand.values(): handlen += v return handlen # # Problem #4: Playing a hand # # Casey Brown # caseycodes@gmail.com # 18h55 # def play_hand(hand, word_list): """ Allows the user to play the given hand, as follows: * The hand is displayed. * The user may input a word. * An invalid word is rejected, and a message is displayed asking the user to choose another word. * When a valid word is entered, it uses up letters from the hand. * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the user is asked to input another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when there are no more unused letters. The user can also finish playing the hand by inputing a single period (the string '.') instead of a word. hand: dictionary (string -> int) word_list: list of lowercase strings """ # TO DO ... word = "" total_score = 0 while word != ".": display_hand(hand) word = raw_input("Enter a word using letters in your hand.\n>>>") if is_valid_word(word, hand, word_list): print "Your word is valid!" update_hand(hand, word) print get_word_score(word, HAND_SIZE) total_score += get_word_score(word, HAND_SIZE) elif word == ".": break else: print "Sorry, that's not a word or you don't have all the letters." # 17h20 print "Your final score was ", total_score, "!" # 17h10 # # Problem #5: Playing a game # Make sure you understand how this code works! # def play_game(word_list): """ Allow the user to play an arbitrary number of hands. * Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', let the user play a new (random) hand. When done playing the hand, ask the 'n' or 'e' question again. * If the user inputs 'r', let the user play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. """ # TO DO... game_on = True while game_on == True: user_choice = raw_input("N: New Game\nR: Replay\nE: Exit\n>>>") if user_choice.lower() == "n": hand = deal_hand(HAND_SIZE) mod_hand = dict(hand) play_hand(mod_hand, load_words()) elif user_choice.lower() == "e": game_on = False elif user_choice.lower() == "r": # figure out how to do if(hand, deal_hand(HAND_SIZE)) try: hand except NameError: hand = deal_hand(HAND_SIZE) mod_hand = dict(hand) play_hand(mod_hand, load_words()) else: mod_hand = dict(hand) play_hand(mod_hand, load_words()) else: print "Enter either 'n', 'r', or 'e' without quotes" # # Build data structures used for entire session and play game # if __name__ == '__main__': word_list = load_words() play_game(word_list) |
Part B
- Computer Chooses (best scoring first word and so on)
- Computer’s Turn to Play
- You or the Computer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
from ps3a import * import time from perm import * # # # Problem #6A: Computer chooses a word # # def comp_choose_word(hand, word_list): """ Given a hand and a word_dict, find the word that gives the maximum value score, and return it. This word should be calculated by considering all possible permutations of lengths 1 to HAND_SIZE. hand: dictionary (string -> int) word_list: list (string) """ # TO DO... all_perms = get_perms(hand, HAND_SIZE) # store best words here valid_words = set() best_words = {} for i in all_perms: # check if there is a word that uses full HAND_SIZE if i in word_list: # testing # print i return i # walk backwards from end of word, checking if it's in word_list j = 1 while j < HAND_SIZE: word = i[:-j] # watch it work with time.sleep(1) # print word if word in word_list: valid_words.add(word) # print word, get_word_score(word, len(word)) j += 1 if len(valid_words) == 0: return None for i in valid_words: best_words[get_word_score(i, len(word))] = i # testing # print best_words # for i in sorted(best_words): # print i return best_words[max(best_words.keys())] # # Problem #6B: Computer plays a hand # def comp_play_hand(hand, word_list): """ Allows the computer to play the given hand, as follows: * The hand is displayed. * The computer chooses a word using comp_choose_words(hand, word_dict). * After every valid word: the score for that word is displayed, the remaining letters in the hand are displayed, and the computer chooses another word. * The sum of the word scores is displayed when the hand finishes. * The hand finishes when the computer has exhausted its possible choices (i.e. comp_play_hand returns None). hand: dictionary (string -> int) word_list: list (string) """ # TO DO ... # keep score score = 0 while True: # The hand is displayed. display_hand(hand) # The computer chooses a word using comp_choose_words(hand, word_dict). chosen_word = comp_choose_word(hand, word_list) print chosen_word # The hand finishes when the computer has exhausted its possible choices # (i.e. comp_play_hand returns None). if chosen_word == None: print score return None # After every valid word: the score for that word is displayed, # the remaining letters in the hand are displayed, and the computer # chooses another word. score += get_word_score(chosen_word, len(hand)) print score update_hand(hand, chosen_word) # # Problem #6C: Playing a game # # def play_game(word_list): """Allow the user to play an arbitrary number of hands. 1) Asks the user to input 'n' or 'r' or 'e'. * If the user inputs 'n', play a new (random) hand. * If the user inputs 'r', play the last hand again. * If the user inputs 'e', exit the game. * If the user inputs anything else, ask them again. 2) Ask the user to input a 'u' or a 'c'. * If the user inputs 'u', let the user play the game as before using play_hand. * If the user inputs 'c', let the computer play the game using comp_play_hand (created above). * If the user inputs anything else, ask them again. 3) After the computer or user has played the hand, repeat from step 1 word_list: list (string) """ # TO DO... game_on = True user_choice = "" while game_on == True: while user_choice.lower() != "r" and user_choice.lower() != "n": user_choice = raw_input("N: New Game\nR: Replay\nE: Exit\n>>>") if user_choice.lower() == "n": hand = deal_hand(HAND_SIZE) mod_hand = dict(hand) player_choice = "" while player_choice.lower() != "c" and player_choice.lower() != "u": player_choice = raw_input("U: You play\nC: Computer plays\n>>>") if player_choice.lower() == "u": play_hand(mod_hand, load_words()) # remove choice and start over user_choice = "" elif player_choice.lower() == "c": comp_play_hand(mod_hand, load_words()) # remove choice and start over user_choice = "" elif user_choice.lower() == "r": player_choice = "" mod_hand = dict(hand) while player_choice.lower() != "c" and player_choice.lower() != "u": player_choice = raw_input("U: You play\nC: Computer plays\n>>>") if player_choice.lower() == "u": play_hand(mod_hand, load_words()) # remove choice and start over user_choice = "" elif player_choice.lower() == "c": comp_play_hand(mod_hand, load_words()) # remove choice and start over user_choice = "" elif user_choice.lower() == "e": print "thanks for playing" game_on = False return # # Build data structures used for entire session and play game # # Ya, I think I just built them as I went, oops if __name__ == '__main__': word_list = load_words() play_game(word_list) |