简体   繁体   English

Python猜谜游戏,用字母替换空格并存储在列表中

[英]Python guessing game, replace blanks with letter and store in a list

Basically I am trying to make a hangman type game. 基本上,我正在尝试制作a子手式游戏。 When a letter is guessed that is in the word I want that letter to stay there during the next round. 当猜到单词中有字母时,我希望该字母在下一轮停留在该位置。 I tried doing this with a list but I couldn't figure out how to get it to replace the specific blank with the letter. 我尝试使用列表来完成此操作,但是我不知道如何用字母替换特定的空白。

And yes I have read the other questions on this topic but could not get them to work for me. 是的,我已经阅读了有关此主题的其他问题,但无法让它们为我工作。

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()

The line where you set the newBlanks variable only worries about the currently entered letter. 设置newBlanks变量的行仅担心当前输入的字母。 There is no storage for the letters that have previously been guessed in the guessing function. 之前在猜测功能中已经猜测过的字母没有存储空间。

You can make a list for the successfully guessed letters and check if each character in randWord matches one of the letters in that list instead of just the last successfully guessed character. 您可以列出成功猜出的字母,并检查randWord中的每个字符是否与该列表中的一个字母匹配,而不仅仅是最后一个成功猜到的字符。

The list is called 'got' in my example. 在我的示例中,该列表称为“获取”。

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 ()

You can use a class to store the previously guessed answer, and have all the functions as methods: 您可以使用一个类来存储先前猜测的答案,并将所有功能用作方法:

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()

The issue is that you do not store your newBlanks, so every time the user guesses a right letter, the program recreates the string. 问题是您不存储newBlanks,因此,每当用户猜测正确的字母时,程序都会重新创建字符串。 So you need to keep track of what letters are guessed correctly. 因此,您需要跟踪正确猜出的字母。 You can do so by replacing every guessed letter in a local variable that's not revalued in the if statement. 您可以通过在if语句中未重定值的局部变量中替换所有猜出的字母来实现。 You can fix that by using the following while loop: 您可以使用以下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, some of your words have blank spaces in them, you might wanna make sure space is not considered as a guess ps,您的某些单词中有空格,您可能想确保不要将空格视为猜测

You can try this: 您可以尝试以下方法:

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)

There are more pytonish way to do it, but judging on your code, I prefer not to show it to you. 还有更多方法可以使用,但是从您的代码来看,我不希望向您展示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM