Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import string
- VOWELS = 'aeiou'
- CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
- HAND_SIZE = 10
- n = HAND_SIZE
- 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 loadWords():
- """
- 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 getFrequencyDict(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 scoreW(word):
- scrab = SCRABBLE_LETTER_VALUES
- return sum([scrab[i] for i in word]) # get sum of word
- def wordL(word): #get len of word
- lenW = ''
- for i in word:
- lenW += i
- return len(lenW)
- def getWordScore(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 turn.
- 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 (see SCRABBLE_LETTER_VALUES)
- word: string (lowercase letters)
- n: integer (HAND_SIZE; i.e., hand size required for additional points)
- returns: int >= 0
- """
- score = 0
- for i in word:
- score += SCRABBLE_LETTER_VALUES[i]
- if len(word) == n:
- return (score * len(word)) + 50
- else:
- return score * len(word
- #
- # Problem #2: Make sure you understand how this function works and what it does!
- #
- def displayHand(hand):
- """
- Displays the letters currently in the hand.
- For example:
- >>> displayHand({'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)
- """
- ans = []
- for letter in hand.keys():
- for j in range(hand[letter]):
- ans.append(letter)
- print letter, # print all on the same line
- print # print an empty line
- #
- # Problem #2: Make sure you understand how this function works and what it does!
- #
- def dealHand(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={}
- numVowels = n / 3
- for i in range(numVowels):
- x = VOWELS[random.randrange(0,len(VOWELS))]
- hand[x] = hand.get(x, 0) + 1
- for i in range(numVowels, 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 updateHand(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 ... <-- Remove this comment when you code this function
- hand2 = dict.copy(hand)
- for l in word:
- hand2[l] -= 1
- return hand2
- #
- # Problem #3: Test word validity
- #
- def isValidWord(word,hand,wordList):
- hand_cp = dict.copy(hand)
- for letter in word:
- if hand_cp.get(letter):
- # The letter is in our hand, so "use it up".
- hand_cp[letter] = hand_cp[letter] - 1
- else:
- # The letter isn't in our hand, so the word isn't valid.
- return False
- # If we can make the word, now make sure it's a real word:
- # (If wordlist is long, you might want to sort it and do a real search)
- if word not in wordList:
- return False
- # We haven't found any reason to return False, so this is a valid word.
- return True
- # Problem #4: Playing a hand
- #
- def calculateHandlen(hand):
- """
- Returns the length (number of letters) in the current hand.
- hand: dictionary (string int)
- returns: integer
- """
- return sum(hand.itervalues())
- hand = {'a':1}
- wordList = loadWords()
- def playHand(hand, wordList, n):
- """
- Allows the user to play the given hand, as follows:
- * The hand is displayed.
- * The user may input a word or a single period (the string ".")
- to indicate they're done playing
- * Invalid words are rejected, and a message is displayed asking
- the user to choose another word until they enter a valid word or "."
- * 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 or the user
- inputs a "."
- hand: dictionary (string -> int)
- wordList: list of lowercase strings
- n: integer (HAND_SIZE; i.e., hand size required for additional points)
- """
- # Keep track of the total score
- totalScore = 0
- gameOver = False
- c = calculateHandlen(hand)
- # As long as there are still letters left in the hand:
- while not gameOver:
- if c == 0:
- print "Run out of letters. Total score: " + str(totalScore) + " points."
- break
- # Game is over if ran out of letters), so tell user the total score
- # Display the hand
- print displayHand(hand), #print hand on screen
- word = raw_input("Enter word, or a " + '"."' + " to indicate that you are finished: ") # Ask user for input
- word = word.lower()
- # If the input is a single period:
- if word == '.':
- # End the game (break out of the loop)
- print "Goodbye! Total score: " + str(totalScore) + " points."
- break
- # Otherwise (the input is not a single period):
- else:
- # If the word is not valid:
- if word != '.' and isValidWord(word,hand,wordList) == False:
- # Reject invalid word (print a message followed by a blank line)
- print "Invalid word, please try again."
- # Otherwise (the word is valid):
- elif isValidWord(word,hand,wordList) == True:
- hand = updateHand(hand,word)
- # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
- getWordScore(word,n)
- totalScore += getWordScore(word,n)
- print '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total: " + str(totalScore) + " points."
- print
- # Update the hand
- c = calculateHandlen(hand)
- wordList = loadWords()
- hand = {'a': 1, 'p': 2, 's': 1, 'e': 1, 'l': 1}
- def playGame(wordList):
- """
- 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', let the user play a new (random) hand.
- * 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, tell them their input was invalid.
- 2) When done playing the hand, repeat from step 1
- """
- user = None
- pHand = None
- while user != 'e':
- user = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
- user = user.lower()
- legalIn = ['r','e','n'] #legal input characters
- if user == 'e': #exit game if player inputs e.
- return None
- if user not in legalIn:
- print "Invalid command."
- if user == 'n': #if user wants to play a new hand
- pHand = dealHand(HAND_SIZE)
- print "Hand passed to playHand: ",
- playHand(pHand.copy(),wordList,HAND_SIZE)
- elif user == 'r' and pHand != None: #if user inputs r and hand2 is not empty, hand will be replayed
- print "Hand passed to playHand: ",
- playHand(pHand.copy(),wordList,HAND_SIZE)
- else:
- if user == 'r' and pHand == None: #if user inputs r but there have been no hands played yet
- print "You have not played a hand yet. Please play a new hand first!"
- print
- from ps4a import *
- import time
- #
- #
- # Problem #6: Computer chooses a word
- #
- #
- def validWord(word,hand):
- """
- :param word:
- :param hand:
- :return:
- """
- hand_cp = dict.copy(hand)
- for letter in word:
- if hand_cp.get(letter):
- hand_cp[letter] -= 1 # The letter is in our hand, so "use it up".
- else: # The letter isn't in our hand, so the word isn't valid.
- return False
- return True # We haven't found any reason to return False, so this is a valid word.
- #
- #
- # Problem #6: Computer chooses a word
- #
- def compChooseWord(hand, wordList, n):
- """
- Given a hand and a wordList, find the word that gives
- the maximum value score, and return it.
- This word should be calculated by considering all the words
- in the wordList.
- If no words in the wordList can be made from the hand, return None.
- hand: dictionary (string -> int)
- wordList: list (string)
- n: integer (HAND_SIZE; i.e., hand size required for additional points)
- returns: string or None
- """
- # Create a new variable to store the maximum score seen so far (initially 0)
- bestScore = 0 # Create a new variable to store the best word seen so far (initially None)
- score = 0
- bestWord = None
- # For each word in the wordList
- for word in wordList:
- # If you can construct the word from your hand
- if len(hand) <=1:
- return None
- if validWord(word, hand):
- score = getWordScore(word,n) # Find out how much making that word is worth
- if score > bestScore: # If the score for that word is higher than your best score
- bestWord = word # Update your best score, and best word accordingly
- bestScore = score
- return bestWord # return the best word found.
- #
- # Problem #7: Computer plays a hand
- def compPlayHand(hand, wordList, n):
- totalScore = 0 # Keep track of the total score
- while compChooseWord(hand,wordList,n) is not None: # As long as there are still usable letters left in the hand:
- print "Current Hand: ", # Display the hand
- displayHand(hand)
- word = compChooseWord(hand,wordList,n) # comp chooses word
- hand = updateHand(hand,word) #update hand
- getWordScore(word,n) #get word score
- totalScore += getWordScore(word,n)
- c = calculateHandlen(hand) #recalculate hand length
- print '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total: " + str(totalScore) + " points."
- print
- if calculateHandlen(hand) == 0: #if all letters used
- print "Total score: " + str(totalScore) + " points."
- break
- if compChooseWord(hand,wordList,n) is None: #if no more words can be made
- print "Current Hand: ",
- displayHand(hand)
- print "Total score: " + str(totalScore) + " points."
- brea
- print compPlayHand(hand,wordList,n)
- wordList = loadWords()
- 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