首页 > 解决方案 > How do I have a list accept lowercase in place of capitalized letters in Hangman for a randomized list in Python 3?

问题描述

I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code.

import random
import urllib.request

wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content- 
type=text/plain"
response = urllib.request.urlopen(wp)
long_txt = response.read().decode()
words = long_txt.splitlines()

###########
# Methods #
###########
def Run():

  dashes1 = "-" * len(word) 
  dashes2 = "-" * len(word2)
  used_letter = []
  dashes = dashes1 + " " + dashes2

  #dashes ="-" * len(secretWord)
  guessesLeft = 6


  while guessesLeft > -1 and not dashes == secretWord:

    print(used_letter)
    print(dashes)
    print (str(guessesLeft))



    guess = input("Guess:")
    used_letter.append(guess)


    if len(guess) != 1:
      print ("Your guess must have exactly one character!")

    elif guess in secretWord:
      print ("That letter is in the secret word!")
      dashes = updateDashes(secretWord, dashes, guess)


    else:
      print ("That letter is not in the secret word!")
      guessesLeft -= 1

  if guessesLeft < 0:
    print ("You lose. The word was: " + str(secretWord))
    print(dashes)

  else:
    print ("Congrats! You win! The word was: " + str(secretWord))
    print(dashes)

 def updateDashes(secret, cur_dash, rec_guess):
  result = ""

  for i in range(len(secret)):
    if secret[i] == rec_guess:
      result = result + rec_guess    

    else:

      result = result + cur_dash[i]

  return result

########
# Main #
########
word = random.choice(words)
word2 = random.choice(words)
#print(word)
#print(word2)
secretWord = word + " " + word2 # can comment out the + word2 to do one 
word or add more above to create and combine more words will have to adjust 
abouve in Run()

splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)])

print (splitw)
Run()

any bit of help is appreciated. The website I'm using has a bunch of words that are being used for the words randomly generated. Some are capitalized, and I need to figure out how to let the input of a letter, say a capital A, accept a lowercase a and count for it.

标签: pythonpython-3.xproject

解决方案


您可以在将所有内容转换为小写后进行比较。例如你可以做

secretWord = word.lower() + " " + word2.lower() # that should make your secret all lowercase

对于输入,您应该执行相同的操作:

guess = input("Guess:").lower()

之后,它是大写还是小写都无关紧要。如果字母是正确的,它应该总是匹配的。希望有帮助


推荐阅读