在循环中生成字典并在另一个循环中假设其存在而重用

0 投票
2 回答
660 浏览
提问于 2025-04-18 13:03

我的任务是制作一个文字游戏。

代码其实很简单,定义如下(忽略未定义的辅助函数,为了简洁起见):

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    
    """
    choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
    n=7
    previous_hand={}
    hand=dealHand(n)

    while choice!= False:

                    previous_hand=hand.copy()


                    if choice=='n':

                        playHand(hand, wordList, n)


                        choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))

                    elif choice=='r':

                                if len(previous_hand)==0:
                                    print 'You have not played a hand yet. Please play a new hand first!'
                                    choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))

                                else:

                                    playHand(previous_hand, wordList,n)
                                    choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))

                    elif choice=='e':
                            break
                    else:
                        print 'Invalid command.'
                    choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))

除了 'r' 这一部分,其他都运行得很好。这个游戏的主要特点是,玩家可以通过输入 'r' 来重玩之前的回合。比如说,玩家开始了一局游戏,玩了一次回合,然后想要完全重复这一回合(所有发出的字母和之前的一样),如果玩家输入 'r',游戏就会允许他/她这样做。

大概是这样的:

Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: tot
"tot" earned 9 points. Total: 9 points

Current Hand: p z u t
Enter word, or a "." to indicate that you are finished: .
Goodbye! Total score: 9 points.

Enter n to deal a new hand, r to replay the last hand, or e to end game: r
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: top
"top" earned 15 points. Total: 15 points

不过,我的代码在这一部分没有正常工作。其他的都没问题,就是这一块。我不太明白怎么才能保存最开始的手牌和故事,然后在玩家选择 'r' 时重新使用它。

2 个回答

0

我会这样做。这里只有一个变量,叫做 hand,这个变量只有在我们开始新一局的时候才会被修改。如果我们是在重新玩上一局,那就不需要动它(除非它是 None,在这种情况下我们就会拒绝这个输入):

hand = None

while True:
    choice = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
    if choice == "n":    # deal a new hand
        hand = dealHand(n)
    elif choice == "r":  # reuse the old hand, if there was one
        if hand is None:
            print 'You have not played a hand yet. Please play a new hand first!'
            continue
    elif choice == "e":  # exit
        break
    else:                # any other input
        print 'Invalid command.'
        continue

    playHand(hand)       # actually play here
1

这段内容来自很久以前,但应该适用于你的麻省理工学院的作业:

def playGame(wordList):
    hand = None
    legalIn = ['r','e','n']
    while True:
            user = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
            if user not in legalIn:
                print "Invalid word."
                continue
                #if user inputs r but there have been no hands played yet
            elif user == 'r' and hand is None:
                   print "You have not played a hand yet. Please play a new hand first!"

            elif user == 'n':
                hand = dealHand(n)
                playHand(hand,wordList,n)
            elif user == 'e': # exit game if player inputs e.
                break
            else:
                playHand(hand,wordList, n)




def playHand(hand, wordList, n):
    #  Keep track of the total score
    totalScore = 0
    c = calculateHandlen(hand)
    # As long as there are still letters left in the hand:
    while True:
        if c == 0:
            print "Run out of letters. Total score: {} points.".format(totalScore)
            break
            # Game is over if ran out of letters), so tell user the total score
        # Display the hand
        displayHand(hand)
        # Ask user for input
        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: {} points.".format(totalScore)
            break
            # Otherwise (the input is not a single period):
        # If the word is not valid:
        elif  not isValidWord(word,hand,wordList):
            # Reject invalid word (print a message followed by a blank line)
            print  "Invalid word, please try again."
            print
        # Otherwise (the word is valid):
        else:
            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  "{} earned {} points.: {}.".format(word,getWordScore(word,n),totalScore)
            # Update the hand
            c = calculateHandlen(hand)

撰写回答