我的Hangman游戏问题(Python)

时间:2014-07-23 17:42:49

标签: python regex python-3.x

我知道这很长,请耐心等待。我正在参加这个在线课程,我们的大项目是为Hangman游戏编写代码。在网上寻找并找到一些例子以帮助我了解从哪里开始以及如何解决这个问题后,我几乎完成了游戏。我只有一些需要清理的小问题,我无法弄清楚如何修复。第一个涉及不与字母排列的空格。因此,假设计算机选择单词BASEBALL它将显示_ _ _ _ _ _ _ _,它似乎正确排列。因此,如果我猜B然后它将显示B _ _ _ B _ _ _等等,所以第四,但随着我添加越来越多的字母,他们不会排队。例如,当只剩下一个字母(S)时,我将BA_EBALL _ _ _ _。我不知道为什么或如何在最后添加额外的空白。我遇到麻烦的另一件事是重复猜测。我编写了游戏程序以显示一条消息,告诉您如果猜不止一个字母或者不是一封字母的话,请再试一次。我有办法跟踪猜测的字母,但由于某种原因它仍然允许重复猜测。任何帮助将不胜感激。我很抱歉这个问题太久了,而且代码更长了。

import random
hangManPics = ['''<hangman art omitted>''']

words = 'AMERICAN NATIONAL BASEBALL BASE BALL STRIKE FOUL OUT\
 SINGLE DOUBLE TRIPLE HOMERUN PITCHER CATCHER OUTFIELD INFIELD\
 DIAMOND STADIUM CARDINALS DIAMONDBACKS BRAVES ORIOLES CUBS REDS\
 INDIANS ROCKIES TIGERS ASTROS ROYALS ANGELS DODGERS MARLINS\
 BREWER TWINS METS YANKEES ATHLETICS PHILLIES PIRATES PADRES\
 GIANTS MARINERS RAYS RANGERS NATIONALS STRIKEOUT RUNS FASTBALL\
 SLIDER CURVEBALL STEAL'

##  Select a random word from a word list
def getRandomWord(wordList):
    newWords = words.split()    ##  split the word list
    word = newWords[random.randint(0, len(newWords) - 1)]
    return word

def displayBoard(hangManPics, missedLetters, correctLetters, secretWord):
    print(hangManPics[len(missedLetters)])
    print()

    print("Missed letters:", end = '')
    for letter in missedLetters:
        print(letter, end = '')
    print()

    blanks = '_ ' * len(secretWord)

    for i in range(len(secretWord)):
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i + 1:]

    for letter in blanks:
        print(letter, end = '')
    print()

def getGuess(alreadyGuessed):
    while True:
        guess = input("Please guess a letter. ")
        upperGuess = guess.upper()
        if len(upperGuess) != 1:
            print("Please enter a single letter.\n")
        elif guess in alreadyGuessed:
            print("You have already guessed that letter. Please select another one.\n")
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print("Your guess must be a letter.\n")
        else:
            return upperGuess

def playAgain():
    print("Would you like to play again? (yes or no)")
    return input().upper().startswith('Y')

print("H A N G M A N")
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
endGame = False

while True:
    displayBoard(hangManPics, missedLetters, correctLetters, secretWord)

    guess = getGuess(missedLetters + correctLetters)

    if guess in secretWord:
        correctLetters = correctLetters + guess

        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if foundAllLetters:
            print('''\<ascii art omitted>\n''')
            print("The secret word is", secretWord, ". You have won!\n")
            endGame = True
    else:
        missedLetters = missedLetters + guess

        if len(missedLetters) == len(hangManPics) - 1:
            displayBoard(hangManPics, missedLetters, correctLetters, secretWord)
            print('''<ascii art omitted>''')
            print("You have run out of guesses. The secret word is",\
                  secretWord, ". You lose.\n")
            endGame = True

    if endGame:
        if playAgain():
            missedLetters = ''
            correctLetters = ''
            endGame = False
            secretWord = getRandomWord(words)
        else:
            break

playAgain()

1 个答案:

答案 0 :(得分:2)

你的两个问题都被隔离到一个功能。将来,您应该单独调试每个函数:

  1. 将每个函数复制到一个单独的python文件中,而不需要程序的其余部分(除了使函数工作所需的极小的函数)
  2. 使用各种示例数据调用该函数,直到您确定该函数是否正常工作
  3. 如果函数不起作用,请删除函数内与问题无关的任何内容。你拥有的代码越少,就越容易找出错误的内容
  4. 如果您无法自行解决问题,请使用您创建的最少代码询问有关每个隔离问题的问题。
  5. 如果你已经解决了这个问题,那么你可能会遇到两个问题的答案:

    问题1:displayBoard功能:

    问题是您忘记了blanks的长度加倍,因为您为每个字母添加了一个空格:blanks = '_ ' * len(secretWord)。对于i的每个索引secretWordi*2的索引为blanks。此外,无需逐个字母地打印单词。固定版本是:

    def displayBoard(hangManPics, missedLetters, correctLetters, secretWord):
        blanks = '_ ' * len(secretWord)
    
        for i in range(len(secretWord)):
            if secretWord[i] in correctLetters:
                blanks = blanks[:i*2] + secretWord[i] + blanks[i*2 + 1:]
    
        print(blanks)
    
    displayBoard([], ['Z', 'K', 'C'], ['B', 'A', 'E', 'L'], 'BASEBALL')
    

    无索引的方法是用下划线替换所有未猜到的字母,然后在字母之间插入空格:

    from string import ascii_uppercase
    
    def displayBoard(hangManPics, missedLetters, correctLetters, secretWord):
        # print(hangManPics[len(missedLetters)])
        print()
    
        print("Missed letters: " + ''.join(missedLetters))
    
        # copy secretWord to blanked
        blanked = secretWord
    
        # Replace missing letters with blanks
        for letter in ascii_uppercase:
            if letter not in correctLetters:
                blanked = blanked.replace(letter, '_')
    
        # Add spaces between letters
        blanked = ' '.join(list(blanked))
    
        print(blanked)
    
    displayBoard([], ['Z', 'K', 'C'], ['B', 'A', 'E', 'L'], 'BASEBALL')
    

    问题2:getGuess功能:

    您使用upperGuess = guess.upper()将输入字母设为大写,但随后继续使用小写guess。更正版本:

    def getGuess(alreadyGuessed):
        while True:
            guess = input("Please guess a letter. ")
            upperGuess = guess.upper()
            if len(upperGuess) != 1:
                print("Please enter a single letter.\n")
            elif upperGuess in alreadyGuessed:
                print("You have already guessed that letter. Please select another one.\n")
            elif upperGuess not in 'abcdefghijklmnopqrstuvwxyz'.upper():
                print("Your guess must be a letter.\n")
            else:
                return upperGuess
    
    getGuess(['A', 'B', 'C'])  # Guessing "a" should produce error