Python刽子手替换字母

2024-03-28 20:48:00 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,这是我到目前为止的刽子手游戏代码。我需要一些帮助。首先,如果可能的话,有人可以通过添加一些东西来修改我的代码。1) 我不知道如何用下划线代替字母。因此,每当用户输入正确的字母时,它应该替换正确的下划线/s。2)如果用户猜错了字母,我不知道如何减少生命。注意:我已经打印了用于测试的实际单词,稍后将删除该单词。

import time
import random

#words

simpWords = ['triskaidekaphobia', 'spaghettification', 'sesquipedalian', 'floccinaucinihilipilification', 'deipnosophist']
medWords = ['erubescent', 'entomophogy', 'noctambulist', 'parapente', 'umbriferous']
hardWords = ['cat', 'house', 'degust', 'glaikit', 'otalgia']

simpWordsR = random.choice(simpWords)
medWordsR = random.choice(medWords)
hardWordsR = random.choice(hardWords)


#welcome the user

name = input("What is your name?")
print ("Hello! " + name + ". Time to play Hangman")

#wait for 1 second
time.sleep(1)

print ("")

correctLetters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

#picking levels

gameMode = input('Choose a level - Easy (10 Guesses), Medium (8 Guesses) or Hard (7 Guesses)')
if gameMode == str('easy'):
  numberOfGuesses1 = 11
  print ('')
  print (list(simpWordsR))
  blanks = '_ ' * len(simpWordsR)
  correctLetters = ''
  for i in range(len(simpWordsR)): # replace blanks with correctly guessed letters
    if simpWordsR[i] in correctLetters:
      blanks = blanks[:i] + simpWordsR[i] + blanks[i+1:]
  print (blanks)

elif gameMode == str('medium'):
  numberOfGuesses2 = 8
  print ('')
  print (list(medWordsR))
  blanks = '_ ' * len(medWordsR)
  correctLetters = ''
  for i in range(len(medWordsR)): # replace blanks with correctly guessed letters
    if medWordsR[i] in correctLetters:
      blanks = blanks[:i] + medWordsR[i] + blanks[i+1:]
  print (blanks)

elif gameMode == str('hard'):
  numberOfGuesses3 = 7
  print ('')
  print (list(hardWordsR))
  blanks = '_ ' * len(hardWordsR)
  correctLetters = ''
  for i in range(len(hardWordsR)): # replace blanks with correctly guessed letters
    if hardWordsR[i] in correctLetters:
      blanks = blanks[:i] + hardWordsR[i] + blanks[i+1:]
  print (blanks)

time.sleep(1)

print ("")

numberOfGuesses1 -= 1
print (numberOfGuesses1)

while numberOfGuesses1 == 10:
  guess = input("Guess a Character!")

  if (guess in simpWordsR):
   print ("Well Done! You Guessed it right!")

  else:
    print ("The letter is not in the word. Try Again!")


if numberOfGuesses1 == 0:
  print ("Game Finished. Maybe Try Again y/n.")

非常感谢你的帮助。我实际上是python编程的初学者。我也试过其他的例子,但由于某种原因,它不能与我的代码一起工作,我确实改变了变量。你知道吗


Tags: 代码inforlenif字母randomprint
1条回答
网友
1楼 · 发布于 2024-03-28 20:48:00

参见代码中的注释:

import time
import random

#words

simpWords = ['triskaidekaphobia', 'spaghettification', 'sesquipedalian', 'floccinaucinihilipilification', 'deipnosophist']
medWords = ['erubescent', 'entomophogy', 'noctambulist', 'parapente', 'umbriferous']
hardWords = ['cat', 'house', 'degust', 'glaikit', 'otalgia']

# Just use one word, which will be set after user selects difficulty
#simpWordsR = random.choice(simpWords)
#medWordsR = random.choice(medWords)
#hardWordsR = random.choice(hardWords)


#welcome the user

name = input("What is your name?")
print ("Hello! " + name + ". Time to play Hangman")

#wait for 1 second
time.sleep(1)

print ("")

# Removed uppercase. We will only use lower case
alphabet = 'abcdefghijklmnopqrstuvwxyz'

#picking levels

gameMode = input('Choose a level - Easy (10 Guesses), Medium (8 Guesses) or Hard (7 Guesses)').lower()
if gameMode == 'easy':
    numberOfGuesses = 11
    theWord = random.choice(simpWords)
    # Not sure what this is for....deleted
    #correctLetters = ''
    #for i in range(len(simpWordsR)): # replace blanks with correctly guessed letters
    #  if simpWordsR[i] in correctLetters:
    #    blanks = blanks[:i] + simpWordsR[i] + blanks[i+1:]
    #print (blanks)

elif gameMode == 'medium':
    numberOfGuesses = 8
    theWord = random.choice(medWords)

else:
    numberOfGuesses = 7
    theWord = random.choice(hardWords)

print(gameMode)
print(theWord)  # For debugging purposes

# Since python strings are immutable, use a list
blanks = ['_'] * len(theWord)

# Need to keep a list of already guessed letters
used_letters = []

time.sleep(1)

print ("")

# Move this to the loop
#numberOfGuesses1 -= 1
#print (numberOfGuesses1)

#while numberOfGuesses1 == 10:
while numberOfGuesses > 0:
    print (numberOfGuesses)
    print (' '.join(blanks))

    # get user input and convert to lower case
    guess = input("Guess a Character!").lower()

    # Make sure it's a letter
    if not guess in alphabet:
        print("Enter a letter...")
    # Make sure not already guessed
    elif guess in used_letters:
        print("Already guessed that....")
    # Valid guess. Check it
    else:
        used_letters.append(guess)
        if (guess in theWord):
            print ("Well Done! You Guessed it right!")
            # Loop through and replace
            for x in range(0, len(theWord)):
                if theWord[x] == guess:
                    # Note: this works since theWord and blanks have the same length
                    blanks[x] = guess
            # Check for success
            if not '_' in blanks:
                print("You win")
                # End the loop
                break
        else:
            print ("The letter is not in the word. Try Again!")
            # Only decrement if incorrect
            numberOfGuesses -= 1

print ("Game Finished. Maybe Try Again y/n.")

相关问题 更多 >