这是我的代码,我认为所有的东西都能工作,除了它不需要任何超过一个的值。请帮帮我。你知道吗
word = input("What's your word?\n").upper()
forguess = " ".join(word)
char = "_"
for index in range(len(word)):
word = word[:index] + char + word[index+1:]
spacedwords = " ".join(word)
print(spacedwords)
chances = 5
while chances != 0:
print("You have " + str(chances) + " chances left\n")
letter = input("Guess the letters: \n").upper()
if letter in forguess: #check if the input letter is in original word
pos = forguess.index(letter) #gets the letter position from forguess original word
spacedwords = spacedwords[:pos] + letter + spacedwords[pos+1:] #replace word in the blank ones
print(spacedwords)
if spacedwords == forguess:
print("YOU WON!!!")
break
else:
chances -= 1
if chances == 0:
print("YOU LOOSE!!!")
代码不起作用的主要原因是,虽然猜字母时
spacedwords
会改变,但forguess
不会。这样,您的index
调用总是只找到第一个出现的letter
。尽可能少地修改代码(有更有效的方法),下面是一个如何实现所需的示例:编辑:
我第一次误解了OP的意图,这里又是一个试图尽可能少地修改原始代码的示例。我引入了一个新变量
original
,它在开头与forguess
相同。现在,每次正确猜测一个字母时,forguess
都会被修改(猜测的字母会变成NULL
字符),这样在下一次搜索中它就不会再出现了。最后,将spaceedwords
与original
而不是forguess
进行比较。你知道吗注意:
如果将
forguess
转换为单个字符的列表,整个问题将更容易处理。你知道吗相关问题 更多 >
编程相关推荐