[我刚刚编写了一个可运行的程序来执行Hangman游戏,但有一个困扰我的问题,我一直无法弄清。
程序正确评估所选字符是否在要猜测的单词中以及单词在单词中的位置(即使该字符出现多次)。尽管如此,在玩游戏时,需要比估计多转一圈来评估您是否完全猜出了这个单词,或者您是否还没有生命。
例如,您必须猜测单词“ hello”。我希望程序可以像这样运行:
转向1:“ h”。转弯2:“ e”。转3:“ l”。转4:'o'。该程序应在此处停止,但需要另一个字符(任意)来识别游戏已完成。
这是我的代码:
def play_game():
# Pick word randomly from list
random_num = random.randint(0, (len(words_list) - 1))
current_word = list(words_list[random_num].upper())
print(current_word)
print('The word has', str(len(current_word)), 'characters')
current_letter = input('Pick a letter: ').upper() #User input
picked_letters = []
correct_ones = []
for i in range(len(current_word)):
correct_ones.append('_ ')
lifes = 3
while lifes != 0:
# Check if all characters have been already guessed
if current_word == correct_ones:
print('You won!')
break
# Check if character has already been chosen
elif current_letter in picked_letters:
print('You already chose this letter!')
current_letter = input('Pick another letter: ').upper()
continue
# Check if character is in word
if current_letter in current_word:
index_list = []
for i in range(len(current_word)): #Get indexes of character in word
if current_word[i] == current_letter:
index_list.append(i)
picked_letters.append(current_letter) #Append to keep track of chosen characters
for i in index_list:
correct_ones[i] = current_letter.upper() #Append to correct position
print('Correct!')
for i in correct_ones:
print(i + ' ', end='')
current_letter = input('Pick another letter: ').upper()
# Incorrect character
else:
picked_letters.append(current_letter)
lifes -= 1
print('Incorrect')
print('You have', str(lifes), 'lifes left')
current_letter = input('Pick another letter: ').upper()
continue
play_game()
如果您发现我的代码中有任何不良做法,请随时告诉我!
提前感谢!
您在循环结束时要求用户输入。因此,当您输入最后一个正确的字符时,您要求用户再次输入:
print('Correct!')
for i in correct_ones:
print(i + ' ', end='')
current_letter = input('Pick another letter: ').upper()
要解决此问题,您可以将循环开始时所做的检查移到那里。自游戏开始以来,没有提供任何输入,因此,切勿正确猜出该单词(除非真实单词为空,但不应发生!)。而且,因为只有猜测正确的角色才能赢得胜利,所以在那里进行检查是有意义的。希望这对您有所帮助:)