Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import string
- VOWELS = 'aeiou'
- CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
- HAND_SIZE = 7
- 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.
- """
- # inFile: file
- inFile = open(WORDLIST_FILENAME, 'r', 0)
- # wordlist: list of strings
- wordlist = []
- for line in inFile:
- wordlist.append(line.strip().lower())
- 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
- #
- 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
- """
- score = 0
- word = string.lower(word)
- for a in word:
- score = score + SCRABBLE_LETTER_VALUES[a]
- score = score * len(word)
- if len(word) == n:
- score = score + 50
- return score
- #
- # Problem 1: Unit Test
- #
- def test_get_word_score():
- """
- Unit test for get_word_score
- """
- failure=0
- # dictionary of words and scores
- words = {("", 7):0, ("it", 7):4, ("was", 7):18, ("scored", 7):54, ("waybill", 7):155, ("outgnaw", 7):127, ("outgnawn", 8):146}
- for (word, n) in words.keys():
- score = get_word_score(word, n)
- if score != words[(word, n)]:
- print "FAILURE: test_get_word_score()"
- print "\tExpected", words[(word, n)], "points but got '" + str(score) + "' for word '" + word + "', n=" + str(n)
- failure=True
- if not failure:
- print "SUCCESS: test_get_word_score()"
- test_get_word_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
- #
- 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)
- """
- for a in word:
- if hand.get(a, 0) >= 1:
- hand[a] = hand[a] - 1
- return hand
- #
- # Problem 2: Unit Test
- #
- def test_update_hand():
- """
- Unit test for update_hand
- """
- # test 1
- hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
- word = "quail"
- hand2 = update_hand(hand.copy(), word)
- expected_hand1 = {'l':1, 'm':1}
- expected_hand2 = {'a':0, 'q':0, 'l':1, 'm':1, 'u':0, 'i':0}
- if hand2 != expected_hand1 and hand2 != expected_hand2:
- print "FAILURE: test_update_hand('"+ word +"', " + str(hand) + ")"
- print "\tReturned: ", hand2, "-- but expected:", expected_hand1, "or", expected_hand2
- return # exit function
- # test 2
- hand = {'e':1, 'v':2, 'n':1, 'i':1, 'l':2}
- word = "evil"
- hand2 = update_hand(hand.copy(), word)
- expected_hand1 = {'v':1, 'n':1, 'l':1}
- expected_hand2 = {'e':0, 'v':1, 'n':1, 'i':0, 'l':1}
- if hand2 != expected_hand1 and hand2 != expected_hand2:
- print "FAILURE: test_update_hand('"+ word +"', " + str(hand) + ")"
- print "\tReturned: ", hand2, "-- but expected:", expected_hand1, "or", expected_hand2
- return # exit function
- # test 3
- hand = {'h': 1, 'e': 1, 'l': 2, 'o': 1}
- word = "hello"
- hand2 = update_hand(hand.copy(), word)
- expected_hand1 = {}
- expected_hand2 = {'h': 0, 'e': 0, 'l': 0, 'o': 0}
- if hand2 != expected_hand1 and hand2 != expected_hand2:
- print "FAILURE: test_update_hand('"+ word +"', " + str(hand) + ")"
- print "\tReturned: ", hand2, "-- but expected:", expected_hand1, "or", expected_hand2
- return # exit function
- print "SUCCESS: test_update_hand()"
- test_update_hand()
- #
- # Problem #3: Test word validity
- #
- word = 'monk'
- hand = {'m':1, 'k':1, 'o':1, 'n':1}
- 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
- """
- test1= True
- hand1 = {}
- for a in word:
- if a in hand1:
- hand1[a] = hand1[a] +1
- else:
- hand1[a] = 1
- for b in hand1:
- if (b not in hand):
- test1 = False
- break
- else:
- if hand1[b] > hand[b]:
- test1 = False
- break
- return test1
- # print is_valid_word(word, hand, load_words())
- def test_is_valid_word(word_list):
- # """
- # Unit test for is_valid_word
- # """
- failure=False
- # test 1
- word = "hello"
- hand = get_frequency_dict(word)
- if not is_valid_word(word, hand, word_list):
- print "FAILURE: test_is_valid_word()"
- print "\tExpected True, but got False for word: '" + word + "' and hand:", hand
- failure = True
- # test 2
- hand = {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}
- word = "rapture"
- if is_valid_word(word, hand, word_list):
- print "FAILURE: test_is_valid_word()"
- print "\tExpected False, but got True for word: '" + word + "' and hand:", hand
- failure = True
- # test 3
- hand = {'n': 1, 'h': 1, 'o': 1, 'y': 1, 'd':1, 'w':1, 'e': 2}
- word = "honey"
- if not is_valid_word(word, hand, word_list):
- print "FAILURE: test_is_valid_word()"
- print "\tExpected True, but got False for word: '"+ word +"' and hand:", hand
- failure = True
- # test 4
- hand = {'r': 1, 'a': 3, 'p': 2, 't': 1, 'u':2}
- word = "honey"
- if is_valid_word(word, hand, word_list):
- print "FAILURE: test_is_valid_word()"
- print "\tExpected False, but got True for word: '" + word + "' and hand:", hand
- failure = True
- # test 5
- hand = {'e':1, 'v':2, 'n':1, 'i':1, 'l':2}
- word = "evil"
- if not is_valid_word(word, hand, word_list):
- print "FAILURE: test_is_valid_word()"
- print "\tExpected True, but got False for word: '" + word + "' and hand:", hand
- failure = True
- # test 6
- word = "even"
- if is_valid_word(word, hand, word_list):
- print "FAILURE: test_is_valid_word()"
- print "\tExpected False, but got True for word: '" + word + "' and hand:", hand
- print "\t(If this is the only failure, make sure is_valid_word() isn't mutating its inputs)"
- failure = True
- if not failure:
- print "SUCCESS: test_is_valid_word()"
- test_is_valid_word(load_words())
- # word_list = load_words()
- # print "----------------------------------------------------------------------"
- # print "Testing get_word_score..."
- # test_get_word_score()
- # print "----------------------------------------------------------------------"
- # print "Testing update_hand..."
- # test_update_hand()
- # print "----------------------------------------------------------------------"
- # print "Testing is_valid_word..."
- # test_is_valid_word(word_list)
- # print "----------------------------------------------------------------------"
- # print "All done!"
- #
- #
- # Problem #4: Playing a hand
- #
- 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 inputting a single
- # period (the string '.') instead of a word.
- #
- # hand: dictionary (string -> int)
- # word_list: list of lowercase strings
- #
- # """
- n = 7
- hand = (deal_hand(n))
- guess = ''
- points = 0
- while guess != '.' and len(hand) > 0:
- print "Current Hand: ", display_hand(hand)
- guess = raw_input( "Enter word, or a '.', to indicate that you are finished: ")
- if guess == '.':
- break
- if guess != is_valid_word(guess, hand, load_words()):
- print "Invalid word, please try again."
- else:
- points = points + get_word_score(guess, load_words())
- print guess, " earned ", get_word_score(guess, load_words()), " points. Total: ", points
- hand = update_hand(hand, guess)
- print "Total Score: ", points
- n =7
- 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...
- choose = ''
- while choose != 'e':
- choose = raw_input("What is your move: ")
- if choose == 'n' or choose == 'r':
- if choose == 'n':
- handz = deal_hand(7)
- play_hand(handz, word_list)
- else:
- break
- play_game(load_words())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement