2

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

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

2 回答 2

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!尽量避免重复,尤其是在函数中。(比如你的easy, medium&hard函数)

于 2013-11-04T01:34:45.490 回答
0

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

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

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

初始化显示列表:

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

然后在 if 语句中:

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

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

print(''.join(displaylist))

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

于 2013-11-04T02:31:55.497 回答