import timeit
import time
start = timeit.default_timer()
username = input('Enter your username:')
print("Hello,", username, ", do you want to play a game of Hangman?")
question = input("[Y]/[N]?\n")
if question == "Y":
print("Great, let's start!\n_________")
else:
print(username, "left the game!")
time.sleep(2)
quit()
print('Initializing Game...\nPlease wait...')
time.sleep(5)
game_word = input("Enter the game word:")
list_gw = list(game_word)
word_length = len(list_gw)
print("The word is", word_length, "characters long")
lives = 7
guesses = 0
player_guess = []
while lives > 0:
letter = input("Enter your guess(lowercase only):\n")
if letter not in list_gw:
print("False")
lives -= 1
print('You have', lives, 'more lives')
guesses += 1
if letter in list_gw:
print('True')
print(list_gw.index(letter))
guesses += 1
player_guess.insert(list_gw.index(letter), letter)
if player_guess == list_gw:
print("You WON!")
print("It took you only", guesses, "guesses!")
stop = timeit.default_timer()
print("This game took", round(stop - start), "seconds")
quit()
在介绍出现在“ game_word”中的相同角色的概念时,我似乎有问题。我很难找到正确的方法来处理用户输入的“字母”在“ game_word”中出现2次或更多次的情况。 帮助将不胜感激。
答案 0 :(得分:0)
您的问题可能是list_gw.index(letter)仅返回第一个索引,而不是所有索引!
代替使用索引,您可以遍历单词,逐个检查每个字符并相应地更新player_guess。
答案 1 :(得分:0)
答案 2 :(得分:0)
您的问题是.index()
仅返回字母的 first 出现。就像@schwobaseggl在评论中所说的那样,您需要获取所有事件的 all 索引。
您可以通过列表理解来做到这一点:
indices = [i for i in range(len(list_gw)) if list_gw[i] == letter]