如何在python游戏中隐藏/显示字母?

时间:2013-11-04 01:00:32

标签: python string python-3.x

我是编码的新手,我正在尝试使用Python 3制作一个简化的Hangman游戏。在大多数情况下,我把它弄下来,除了最重要的部分,如何隐藏字母的随机的单词,然后一旦猜到如何揭示它们。主要是,我只需要快速回答。任何帮助将不胜感激。这是我的代码到目前为止(对不起,如果它很长,就像我说的那样,我相对较新,再次感谢!):

import random

#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")

#randomizes the word chosen for game
index = random.randint(0,len(hangmanWords)-1)

#assigns radomized word to variable
randomWord = hangmanWords[index]


'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
   print("""
Welcome to Hangman!

Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)

4. Exit Game
""")
   selection = int(input("What difficulty do you pick (1-4)?: "))
   return selection

'''
the function for easy mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 9 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def easyMode():
   wrongGuesses = 0
   listOfGuesses = []
   print(randomWord)
   while(wrongGuesses != 9):
      x = input("Enter a letter: ")
      if x.lower() in randomWord.lower():
         print(x,"is in the word!")
         listOfGuesses.append(x)
         print("Letters guessed so far: ",listOfGuesses)
         print()
      else:
         print(x,"is not in the word.")
         wrongGuesses += 1
         print(wrongGuesses, "wrong guesses.")
         listOfGuesses.append(x)
         print("Letters guessed so far: ",listOfGuesses)
         print()

   print("You lost the game!")
   return x

'''
the function for medium mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 7 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def medium():
   wrongGuesses = 0
   listOfGuesses = []
   print(randomWord)
   while(wrongGuesses != 7):
      x = input("Enter a letter: ")
      if x.lower() in randomWord.lower():
         print(x,"is in the word!")
         listOfGuesses.append(x)
         print("Letters guessed so far: ",listOfGuesses)
         print()
      else:
         print(x,"is not in the word.")
         wrongGuesses += 1
         print(wrongGuesses, "wrong guesses.")
         listOfGuesses.append(x)
         print("Letters guessed so far: ",listOfGuesses)
         print()

   print("You lost the game!")
   return x

'''
the function for advanced mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 5 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def advanced():
   wrongGuesses = 0
   listOfGuesses = []
   print(randomWord)
   while(wrongGuesses != 5):
      x = input("Enter a letter: ")
      if x.lower() in randomWord.lower():
         print(x,"is in the word!")
         listOfGuesses.append(x)
         print("Letters guessed so far: ",listOfGuesses)
         print()
      else:
         print(x,"is not in the word.")
         wrongGuesses += 1
         print(wrongGuesses, "wrong guesses.")
         listOfGuesses.append(x)
         print("Letters guessed so far: ",listOfGuesses)
         print()

   print("You lost the game!")
   return x

'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
   select = menu()
   while(select != 4):
      if(select == 1):
         easyMode()
      elif(select == 2):
         medium()
      elif(select == 3):
         advanced()

      select = menu()

   print("You don't want to play today? :'(")

main()

2 个答案:

答案 0 :(得分:0)

如果你想亲自尝试一下,那么请不要看代码。就像在hangman中一样,我们可以看到我们的进度(部分猜测的单词),你应该创建另一个包含这样一个字符串的变量。并且,每次正确猜测,您都应该相应地更新此字符串。根据要猜测的单词的长度,字符串显然以#####或*****开头。

经过多次改进,我向你们展示了Hangman!

当然,所有学分都归你所有!

import random

#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")

#assigns radomized word to variable
randomWord = random.choice(hangmanWords)


'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
   print("""
Welcome to Hangman!

Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)

4. Exit Game
""")
   selection = int(input("What difficulty do you pick (1-4)?: "))
   return selection

def game(mode):
    '''
    the game function, prints the word chosen by randomizer
    asks the player to enter a letter that they guess is in the word
    player gets guesses according to value passed as per mode,
    to figure out the word, correct guesses don't count,
    returns player to main menu when they lose
    '''
    modes = {1:9, 2:7, 3:5} # Matches mode to guesses
    guesses = modes[mode]
    wrongGuesses = 0
    listOfGuesses = []
    # print(randomWord) Dont't print the solution!!

    # Get a random word which would be guessed by the user
    to_guess = random.choice(hangmanWords)
    to_guess = to_guess.lower()

    # The correctly guessed part of the word that we print after every guess
    guessed  = "#"*len(to_guess) # e.g. "Hangman" --> "#######"
    while(wrongGuesses != guesses):
        x = input("Word - %s . Guess a letter: "%guessed).lower()
        if x in to_guess:
            print(x,"is in the word!")
            listOfGuesses.append(x)
            # Now replace the '#' in 'guessed' to 'x' as per our word 'to_guess'
            new_guessed = ""
            for index, char in enumerate(to_guess):
                if char == x:
                    new_guessed += x
                else:
                    new_guessed += guessed[index]
            guessed = new_guessed # Change the guessed word according to new guess
            # If user has guessed full word correct, then he has won!
            if guessed == to_guess:
                print("You have guessed the word! You win!")
                print("The word was %s"%to_guess)
                return True # return true on winning
            else:
                print("Letters guessed so far:", listOfGuesses, "\n")

        else:
            print(x,"is not in the word.")
            wrongGuesses += 1
            print("Wrong guesses:", wrongGuesses)
            listOfGuesses.append(x)
            print("Letters guessed so far:", listOfGuesses, "\n")

    print("You lost the game!")
    print("The word was %s"%to_guess)
    return False # return false on loosing

'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
   select = menu()
   while(select != 4):
      game(select)
      select = menu()

   print("You don't want to play today? :'(")

main()

无论你在哪里看到复制粘贴或代码重复,都不是Pythonic!尽量避免重复,特别是在功能方面。 (例如您的easymediumhard功能)

答案 1 :(得分:0)

另一个答案是为您实现的,但我将引导您完成该方法,以便您可以作为程序员进行改进。

您将需要两个列表,一个包含完整单词,另一个包含您要显示的列表。您可以创建与单词长度相同的二进制列表,也可以创建一个充满下划线的“显示列表”,直到猜到正确的字母为止。

显示列表方法看起来应该像这样,更容易实现:

初始化displaylist:

for _ in range(len(randomword)):
    displaylist.append("_")

然后在if语句中:

for i in range(len(randomword)):
    if x == randomword[i]:
        displaylist[i] = x

然后打印,你需要这样的东西:

print(''.join(displaylist))

您可以做的另一项改进是创建一个单独的函数来检查您的单词,以便您可以最有效地使用模块化编程。这将减少代码复杂性,冗余,并使实现更改变得更容易。