graphics=['''------------''',
'''------------
| | ''',
'''------------
| |
| O''',
'''------------
| |
| O
| / |''',
'''------------
| |
| O
| / |
| | ''',
'''------------
| |
| O
| / |
| |
| / |
|
| ''']
print('Welcome to Hangman! Guess the mystery word with less than 6 mistakes!')
while True:
words=['table','chair','pencil','stapler','penney','computer','printer','cable','america','shelf']
alphabet=['a','b','c','d','e','f','g,','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
number=input('Please enter an integer number (0<=number<10) to choose the word in the list:')
if number=='':
print('Empty input!')
continue
elif number in alphabet:
print('Input must be an integer!')
continue
number=int(number)
if number<0 or number>9:
print('Index is out of range!')
continue
elif 0<=number<10:
break
words2=[]
words2.extend(words[number])
print('The length of the word is: ',len(words2))
i=0
j=0
x='_'*len(words2)
blankword=[]
blankword.extend(x)
while j<6 and i!=len(words2):
print('')
letter=input('Please enter the letter you guess: ')
if letter in words2:
increment=0
print('The letter is in the word.')
i=i+1
while words2.count(letter)!=blankword.count(letter):
place=words2.index(letter,increment)
blankword[place]=letter
blankword2=''.join(blankword)
i=i+1
increment=increment+1
if i==len(words2):
print('You have found the mystery word. You win!')
print('Letters matched so far:',blankword2)
print('Goodbye!')
break
else:
print('Letters matched so far: ',blankword2)
continue
elif letter not in words2:
if letter not in alphabet:
print('You need to input a single alphabetic character!')
elif letter not in words2:
blankword2=''.join(blankword)
print('The letter is not in the word.')
print('Letters matched so far: ',blankword2)
print(graphics[j])
j=j+1
if j==6:
print('Too many incorrect guesses. You lost!')
print('The word was:',words[number])
print('Goodbye!')
break
我得到的结果是。
Welcome to Hangman! Guess the mystery word with less than 6 mistakes!
Please enter an integer number (0<=number<10) to choose the word in the list:4
The length of the word is: 6
Please enter the letter you guess: p
The letter is in the word.
Letters matched so far: p_____
Please enter the letter you guess: e
The letter is in the word.
You have found the mystery word. You win!
Letters matched so far: pe__e_
Goodbye!
您好。这是我制作的蟒蛇刽子手游戏,但每次运行时我都会收到此错误。我不知道这个错误意味着什么。有谁知道导致此错误的原因是什么?否则它工作正常。 谢谢!
PS
答案 0 :(得分:0)
这可能不是唯一的问题,但是你在你发布的例子中得到ValueError
的原因即使'n'是'penney'的一部分也是因为你从未重置increment
并且它被使用了当你在字符串上调用index
时作为搜索的开始。
由于你在第二次尝试时输入'e',增量将等于3并从那里开始,它将永远不会找到'n'。
这是我修改的原始代码的一小部分,以使其有效。我摆脱了增量。
if letter in words2:
print('The letter is in the word.')
place = -1
while words2.count(letter)!=blankword.count(letter):
place=words2.index(letter, place+1)
blankword[place]=letter
blankword2=''.join(blankword)
i=i+1