我有一个python 3.5.2 hangman代码:
def hangman():
wrongnums =[]
print("what is the word to be guessed?")
global guessnum
guessnum=input('>')
print("how many chances?")
global chances
chances=int(input('>'))
print("game in beginning")
global blanks
blanks = '_ ' * len(guessnum)
print()
print(blanks)
guessing()
def guessing():
global chances
print("guess a letter")
guess=input('>')
for letters in guessnum:
if guess == letters:
letterIndex = guessnum.index(guess)
global newBlanks
newBlanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
print ("Guess is correct!")
check()
elif guess != letters:
chances -=1
print ("Guess is wrong! ", chances, " more failed attempts allowed.")
guessing()
def check():
print()
print("Word: ",newBlanks)
guessing()

当我去猜测这个词时,例如" car"," c"很好,它说的正确。但对于" a"和" r"它说错了。为什么是这样?结果如下:
答案 0 :(得分:1)
你没有检查猜测的字母和单词,你正在检查vs由于for循环导致的单词中的每一个字母所以它检查与第一个字母相比,认为它不是wight和答案,然后才能检查其余部分。试试这个:
def hangman():
wrongnums =[]
print("what is the word to be guessed?")
global guessnum
guessnum=input('>')
print("how many chances?")
global chances
chances=int(input('>'))
print("game in beginning")
global blanks
blanks = '_ ' * len(guessnum)
print()
print(blanks)
guessing()
def guessing():
global chances
print("guess a letter")
guess=input('>')
if guess in guessnum:
letterIndex = guessnum.index(guess)
global newBlanks
newBlanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
print ("Guess is correct!")
check()
else:
chances -=1
print ("Guess is wrong! ", chances, " more failed attempts allowed.")
guessing()
def check():
print()
print("Word: ",newBlanks)
guessing()