【问题标题】:Python guessing game, replace blanks with letter and store in a listPython猜谜游戏,用字母替换空格并存储在列表中
【发布时间】:2017-10-14 09:29:58
【问题描述】:

基本上我正在尝试制作一个刽子手类型的游戏。当猜到一个字母时,我希望该字母在下一轮中保留在那里。我试着用一个列表来做这个,但我不知道如何让它用字母替换特定的空白。

是的,我已阅读有关此主题的其他问题,但无法让它们为我工作。

import random
import time

def intro():
    print ('''Welcome to the word guessing game!
    You will have 6 letter guesses to figure out my word!
    First you must choose a topic.
    Choose from the following: (1) Cars , (2) Diseases ,
    (3) Animals , or (4) Mathematical Words''')

def optionSelect():
    choice = ''
    while choice != '1' and choice != '2' and choice !='3' and choice !='4':
        choice = input()
    return choice

def checkChoice(chosenOption):
    if chosenOption == '1':
        sectionOne()
    elif chosenOption == '2':
        sectionTwo()
    elif chosenOption == '3':
        sectionThree()
    elif chosenOption == '4':
        sectionFour()
    else:
        print('You didnt choose an option...')

def sectionOne():
    words = ['mclaren ', 'bugatti ', 'aston martin ', 'mitsubishi ']
    randWord = random.choice(words)
    blanks = '_ ' * len(randWord)
    guessing(blanks, randWord)


def sectionTwo():
    words = ['gonorrhea ', 'nasopharyngeal carcinoma ', 'ependymoma ', 'tuberculosis ']
    randWord = random.choice(words)
    blanks = '_ ' * len(randWord)
    guessing(blanks, randWord)



def sectionThree():
    words = ['tardigrade ', 'komodo dragon ', 'bontebok ', 'ferruginous hawk ']
    randWord = random.choice(words)
    blanks = '_ ' * len(randWord)
    guessing(blanks, randWord)


def sectionFour():
    words = ['pythagorean ', 'differentiation ', 'polyhedron ', 'googolplex ']
    randWord = random.choice(words)
    blanks = '_ ' * len(randWord)
    guessing(blanks, randWord)


def guessing(blanks, randWord):
    missed = []
    print ()
    print ("Word: ",blanks)
    attempts = 15
    while attempts != 0:
        attempts = attempts - 1
        print ('Guess a letter, you have ' + str(attempts) + ' attempts left.')
        guessLetter = input()
        if guessLetter in randWord:
            newBlanks = " ".join(c if c in guessLetter else "_" for c in randWord)
            print ('Correct!')
            print ()
            print ("Word: ",newBlanks)
        else:
                  missed.append(guessLetter)
                  print ('That letter is not in the word, you have guessed the following letters:')
                  print (', '.join(missed))
                  print ()


playAgain = ''
while playAgain != 'yes' and playAgain!= 'no':
    intro()
    optionNumber = optionSelect()
    checkChoice(optionNumber)
    print('Do you want to play again? (yes or no)')
    #Play again or not
    playAgain = input()
    if playAgain == 'yes':
        played = 1
        playAgain =''
    else:
        print('Thanks for Playing! Bye!')
        time.sleep(2)
        quit()

【问题讨论】:

  • 您的代码中究竟有什么问题?或者至少你认为它在哪里有问题?
  • 您究竟想存储什么?随机词,还是用户尝试?

标签: python


【解决方案1】:

问题是您没有存储 newBlanks,因此每次用户猜对一个字母时,程序都会重新创建该字符串。因此,您需要跟踪正确猜到的字母。您可以通过替换局部变量中的每个猜测的字母来做到这一点,这些字母在 if 语句中没有重新赋值。您可以使用以下 while 循环来解决此问题:

while attempts != 0:
    attempts = attempts - 1
    print ('Guess a letter, you have ' + str(attempts) + ' attempts left.')
    guessLetter = input()
    if guessLetter in randWord:
        newBlanks = " ".join(c if c in guessLetter else "_" for c in randWord)
        index = 0
        for letter in newBlanks:
            if letter != '_' and letter != ' ':
                blanks= blanks[:index] + letter + blanks[index+1:]
            index += 1
        print ('Correct!')
        print ()
        print ("Word: ",blanks)

ps,您的某些单词中有空格,您可能想确保空格不被视为猜测

【讨论】:

    【解决方案2】:

    设置 newBlanks 变量的行只关心当前输入的字母。之前在猜测函数中猜测的字母没有存储空间。

    您可以为成功猜出的字母制作一个列表,并检查 randWord 中的每个字符是否与该列表中的一个字母匹配,而不仅仅是最后一个成功猜到的字符。

    在我的示例中,该列表称为“得到”。

    def guessing(blanks, randWord):
        missed = []
        got = [] #successful letters
        print ()
        print ("Word: ",blanks)
        attempts = 15
        while attempts != 0:
            attempts = attempts - 1
            print ('Guess a letter, you have ' + str(attempts) + ' attempts left.')
            guessLetter = input()
            if guessLetter in randWord:
                #add the letter to the 'got' list
                got.append(guessLetter)
                #newBlanks now adds in all successful letters
                newBlanks = " ".join(c if c in got else '_' for c in randWord)
                print ('Correct!')
                print ()
                print ("Word: ",newBlanks)
            else:
                missed.append(guessLetter)
                print ('That letter is not in the word, you have guessed the following letters:')
                print (', '.join(missed))
                print ()
    

    【讨论】:

      【解决方案3】:

      您可以使用一个类来存储之前猜到的答案,并将所有功能都作为方法:

      class Hangman:
          def __main__(self):
             self.last_word = ''
      
          def intro(self):
             print ('''Welcome to the word guessing game!
             You will have 6 letter guesses to figure out my word!
             First you must choose a topic.
             Choose from the following: (1) Cars , (2) Diseases ,
             (3) Animals , or (4) Mathematical Words''')
      
          def optionSelect(self):
             self.choice = ''
             while choice != '1' and choice != '2' and choice !='3' and choice !='4':
             self.choice = input()
             return self.choice
      
          def checkChoice(self, chosenOption):
              if chosenOption == '1':
                 self.sectionOne()
              elif chosenOption == '2':
                  self.sectionTwo()
              elif chosenOption == '3':
                 self.sectionThree()
              elif chosenOption == '4':
                 self.sectionFour()
              else:
                  print('You didnt choose an option...')
      
            def sectionOne(self):
               self.words = ['mclaren ', 'bugatti ', 'aston martin ', 'mitsubishi ']
               randWord = random.choice(words)
               self.blanks = '_ ' * len(randWord)
               self.guessing(blanks, randWord)
           #the rest of the sections have been omitted for brevity
      
            def guessing(self, blanks, randWord):
                 self.missed = []
                print ()
                print ("Word: ",blanks)
                self.attempts = 15
                while self.attempts != 0:
                self.attempts -= 1
                print ('Guess a letter, you have ' + str(self.attempts) + '   attempts left.')
                self.guessLetter = input()
                if guessLetter in randWord:
                    newBlanks = " ".join(c if c in guessLetter else "_" for c in randWord)
                    print ('Correct!')
                    print ()
                    print ("Word: ",self.newBlanks)
                    self.last_word = self.newBlanks #here, we are storing the word that is correct
                 else:
                    missed.append(self.guessLetter)
                    print ('That letter is not in the word, you have guessed the following letters:')
                    print (', '.join(self.missed))
                    self.last_word = self.missed
                    print ()
      
      playAgain = ''
      the_game = Hangman()
      while playAgain != 'yes' and playAgain!= 'no':
      
           the_game.intro()
           optionNumber = the_game.optionSelect()
           the_game.checkChoice(optionNumber)
           print('Do you want to play again? (yes or no)')
           #Play again or not
           playAgain = input()
           if playAgain == 'yes':
              played = 1
              playAgain =''
           else:
               print('Thanks for Playing! Bye!')
               time.sleep(2)
               quit()
      

      【讨论】:

        【解决方案4】:

        你可以试试这个:

        randWord = "something"
        blanks = len("something")*"_ "
        guessLetter = "t"
        
        print(blanks)
        if guessLetter in randWord:
            for index, letter in enumerate(randWord, 0):
                if guessLetter == randWord[index]:
                    temp = list(blanks)
                    temp[2*index] = guessLetter
                    blanks = "".join(temp)
        print(blanks)
        

        还有更多的 pytonish 方法可以做到这一点,但从你的代码来看,我不想向你展示它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-01
          • 2013-03-24
          • 1970-01-01
          • 2013-03-27
          • 1970-01-01
          • 1970-01-01
          • 2015-11-20
          • 1970-01-01
          相关资源
          最近更新 更多