Пример #1
0
def compChooseWordbk(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)  
    bestWord = None
    # For each word in the wordList
    for word in wordList:
        # If you can construct the word from your hand
        if ps4a.isValidWord(word, hand, wordList):
            # find out how much making that word is worth
            score = ps4a.getWordScore(word, n)
            # If the score for that word is higher than your best score
            if (score > bestScore):
                # update your best score, and best word accordingly
                bestScore = score
                bestWord = word
    # return the best word you found.
    return bestWord
Пример #2
0
def word_or_combo(combo_dict, bestWord):    # use bestWord or combo strike
    x = getWordScore(bestWord, HAND_SIZE)
    sort_combo_dict = sorted(combo_dict, reverse=True)  # get highest combo score first
    for p in sort_combo_dict:
        if p > x:
            return combo_dict[p]
    return bestWord
Пример #3
0
def compPlayHand(hand: d_si, wordList: List[str], n: int) -> None:
    """Allows the computer to play the given hand, following the same procedure
    as playHand, except instead of the user choosing a word, the computer
    chooses it.
    
    1) The hand is displayed.
    2) The computer chooses a word.
    3) After every valid word: the word and the score for that word is
    displayed, the remaining letters in the hand are displayed, and the
    computer chooses another word.
    4)  The sum of the word scores is displayed when the hand finishes.
    5)  The hand finishes when the computer has exhausted its possible
    choices (i.e. compChooseWord returns None).
    
    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)

    Args:
        Args:
        hand: dict of letter generate for a func
        wordList: all words acepted
        n: hand size 
    
    Return:
        None:
    """
    # Keep track of the total score
    max_score = 0
    # As long as there are still letters left in the hand:
    while (calculateHandlen(hand) > 0):
        # Display the hand
        print("Current Hand: ", end=' ')
        displayHand(hand)
        # computer's word
        pc_word = compChooseWord(hand, wordList, n)
        # If the input is a single period:
        if pc_word == None:
            # End the game (break out of the loop)
            break
        # Otherwise (the input is not a single period):
        else:
            # If the word is not valid:
            if (not isValidWord(pc_word, hand, wordList)):
                print('This is a terrible error! I need to check my own code!')
                break
            # Otherwise (the word is valid):
            else:
                # Tell the user how many points the word earned, and the
                # updated total score
                score = getWordScore(pc_word, n)
                max_score += score
                print(
                    f'"{pc_word}" earned {score} points. Total: {max_score}' +
                    ' points\n')
                # Update hand and show the updated hand to the user
                hand = updateHand(hand, pc_word)
    # Game is over (user entered a '.' or ran out of letters), so tell user
    # the total score
    print(f'Total score: {max_score} points.')
Пример #4
0
def test_getWordScore():
    """
    Unit test for getWordScore
    """
    failure = False
    # dictionary of words and scores
    words = {
        ("", 7): 0,
        ("it", 7): 4,
        ("was", 7): 18,
        ("scored", 7): 54,
        ("waybill", 7): 155,
        ("outgnaw", 7): 127,
        ("fork", 7): 44,
        ("fork", 4): 94,
    }
    for (word, n) in words.keys():
        score = getWordScore(word, n)
        if score != words[(word, n)]:
            print("FAILURE: test_getWordScore()")
            print(
                "\tExpected",
                words[(word, n)],
                "points but got '" + str(score) + "' for word '" + word +
                "', n=" + str(n),
            )
            failure = True
    if not failure:
        print("SUCCESS: test_getWordScore()")
Пример #5
0
def compPlayHand(hand, wordList, n):
    """
    Allows the computer to play the given hand, following the same procedure
    as playHand, except instead of the user choosing a word, the computer 
    chooses it.

    1) The hand is displayed.
    2) The computer chooses a word.
    3) After every valid word: the word and the score for that word is 
    displayed, the remaining letters in the hand are displayed, and the 
    computer chooses another word.
    4)  The sum of the word scores is displayed when the hand finishes.
    5)  The hand finishes when the computer has exhausted its possible
    choices (i.e. compChooseWord returns None).
 
    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)
    """
    # Keep track of the total score
    totalScore = 0
    # As long as there are still letters left in the hand:
    while (ps4a.calculateHandlen(hand) > 0) :
        # Display the hand
        print("Current Hand: ", end=' ')
        ps4a.displayHand(hand)
        # computer's word
        word = compChooseWord(hand, wordList, n)
        # If the input is a single period:
        if word == None:
            # End the game (break out of the loop)
            break
            
        # Otherwise (the input is not a single period):
        else :
            # If the word is not valid:
            if (not ps4a.isValidWord(word, hand, wordList)) :
                print('This is a terrible error! I need to check my own code!')
                break
            # Otherwise (the word is valid):
            else :
                # Tell the user how many points the word earned, and the updated total score 
                score = ps4a.getWordScore(word, n)
                totalScore += score
                print('"' + word + '" earned ' + str(score) + ' points. Total: ' + str(totalScore) + ' points')              
                # Update hand and show the updated hand to the user
                hand = ps4a.updateHand(hand, word)
                print()
    # Game is over (user entered a '.' or ran out of letters), so tell user the total score
    print('Total score: ' + str(totalScore) + ' points.')
Пример #6
0
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
    """
    bestscore = 0
    bestword = None
    for word in wordList:
        if ps4a.isValidWord(word, hand, wordList):
            if ps4a.getWordScore(word, n) > bestscore:
                bestscore = ps4a.getWordScore(word, n)
                bestword = word
    return bestword
Пример #7
0
def compChooseWord(hand, wordList, n):
    bestScore = 0
    bestWord = None
    letters = []
    for l in hand:
        count = hand[l]
        for i in range(count):
            letters.append(l)
    for i in range(len(letters)):
        myWordList = getPermutations(letters, i+1)
        for word in myWordList:
            if word in wordList:
                score = ps4a.getWordScore(word, n)
                if score > bestScore:
                    bestScore = score
                    bestWord = word
    return bestWord
Пример #8
0
def compPlayHand(hand, wordList, n):
    """
    Allows the computer to play the given hand, following the same procedure
    as playHand, except instead of the user choosing a word, the computer 
    chooses it.

    1) The hand is displayed.
    2) The computer chooses a word.
    3) After every valid word: the word and the score for that word is 
    displayed, the remaining letters in the hand are displayed, and the 
    computer chooses another word.
    4)  The sum of the word scores is displayed when the hand finishes.
    5)  The hand finishes when the computer has exhausted its possible
    choices (i.e. compChooseWord returns None).
 
    hand: dictionary (string -> int)
    wordList: list (string)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)
    """
    total = 0

    while True:

        if not ps4a.calculateHandlen(hand) or not compChooseWord(
                hand, wordList, n):
            print("Total score: {} points.".format(total))
            return

        print("Current Hand: ", end="")
        ps4a.displayHand(hand)
        for word in wordList:
            if ps4a.isValidWord(word, hand, wordList):
                score = ps4a.getWordScore(word, n)
                total += score
                print('"{}" earned {}  points. Total:  {}  points'.format(
                    word, score, total))
                hand = ps4a.updateHand(hand, word)
Пример #9
0
def compChooseWord(hand: d_si, wordList: List[str], n: int) -> Optional[str]:
    """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.
    
    returns: string or None

    Args:
        hand: dict of letter generate for a func
        wordList: all words acepted
        n: hand size 

    Returns:
        string or None
    """
    # Create a new variable to store the maximum score seen so far(initially 0)
    max_score = 0
    # Create a new variable to store the best word seen so far (initially None)
    best_word = None
    # For each word in the wordList
    for word in wordList:
        # If you can construct the word from your hand
        if isValidWord(word, hand, wordList):
            # find out how much making that word is worth
            score = getWordScore(word, n)
            # If the score for that word is higher than your best score
            if (score > max_score):
                # update your best score, and best word accordingly
                max_score = score
                best_word = word
    # return the best word you found.
    return best_word
Пример #10
0
def compPlayHand(hand, wordList, n):
    """
    Allows the computer to play the given hand, as follows:

    * The hand is passed as a parameter to a procedure.
    * The computer may return a word or None to indicate she's done playing.
    * Invalid words are rejected, and the hand is terminated.
    * 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 computer 
      procedure is called again 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 
    * computer procedure returns no words.

      hand: dictionary (string -> int)
      wordList: list of lowercase strings
      n: integer (HAND_SIZE; i.e., hand size required for additional points)
      
    """ 
       
    strHand = ''
    handPoints = 0    
    wordPoints = 0
    handLen = 0
    currentWord = ''

    def prtLine1(cH):
        outputLine = 'Current Hand: ' + cH 
        print(outputLine)
    # end of code 
    
    def prtLine2(cw, wpts, hpts):
        outputLine = '"'+ cw + '"' + ' earned ' + str(wpts) + ' points. Total: ' + str(hpts) + ' points'
        print(outputLine)
    # end of code 
        
    outputLine3 = 'Invalid word, hand terminated.'

    def prtLine4(hpts):
        outputLine = 'Run out of letters. Total score: ' + str(hpts) + ' points.'
        print(outputLine)
    # end of code 

    def prtLine5(hpts):
        outputLine = 'Total score: '+ str(hpts) + ' points.'   
        print(outputLine)
    # end of code 
    
    inputLine1 = 'Calling procedure to enter word. If no word is returned hand is finished.'

    # Main loop
    while True:

    # Keep track of the total score
        
    # As long as there are still letters left in the hand    
        handLen = calculateHandlen(hand)             # see if hand still valid
        if handLen == 0:
            prtLine4(handPoints)                     # no more words 
            return                                  # end of game

    # Display the hand
        strHand = ''        
        for letter in hand.keys():      # get hand in display format
            for i in range(hand[letter]):
                strHand += letter + ' '      
        prtLine1(strHand)              # display current hand
           
    # Ask user for input            
        # currentWord = raw_input(inputLine1)      # get new word
        # print(inputLine1)                         # get new word
        currentWord = compChooseWord(hand, wordList, n)
        
    # If there is no input:
        if currentWord == None:                   # computer has no more words 
            # End the game (break out of the loop)
           break                                # get out of loop

        # Otherwise (the input is not a single period):     
        # If the word is not valid:
        if not isValidWord(currentWord, hand, wordList):       # check if word is valid
            # Reject invalid word (print a message and end hand)
            print(outputLine3)                     # tell the user
            break 
        else:

            # Otherwise (the word is valid):
            # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
            wordPoints = getWordScore(currentWord, n)    # get points earned
            handPoints += wordPoints                     # accumulate hand points
            prtLine2(currentWord, wordPoints, handPoints) # tell user points earned
            print('')                                   # additional line             
 
            # Update the hand 
            hand = updateHand(hand, currentWord)         # update hand
   
    # Game is over (user entered a '.' or ran out of letters), so tell user the total score
    prtLine5(handPoints)
    return None
Пример #11
0
                h[i] -= 1           # remove letters used in word
                if h[i] < 0:        # test if using more letters than held 
                    return False
            return True
        except KeyError, e:         # letter not in hand. exception thrown.
            return False

    if flag == (1,):                # flag for combination. 
        comboWordList=[]
        combo_dict = {}
        for a in wordList:          # cross matrix of all words.
            for b in wordList:
                if (len(a + b) <= n): 
                    if canHandConstruct(a + b, hand):   # can combo be made?
                        comboWordList.append(a + b)     # build combo dictionary [overwrite duplicates]
                        combo_dict[getWordScore(a, n) + getWordScore(b, n)] = [a, b] # combo_dict = {score:[a,b]} 
        
        if len(combo_dict) >= 1:
            print "%s Viable Combinations from Word List:" % len(combo_dict),
            print combo_dict
            print ""    
        return combo_dict
        
    handWordList =[]                # create word list based on hand only.
    for word in wordList:
        if (len(word) <= n):        # eliminate all words larger than hand ***optimization***
            if canHandConstruct(word, hand):
                handWordList.append(word)   # compile custom word list
    if len(handWordList) >= 1:
        print "\n%s Words in Word List:" % len(handWordList),
        print handWordList