所以我一直在用Python修改Hangman,但遇到了一个问题。
输出完全没有更新。尽管代码的其他部分(例如尝试次数减少或已使用的字母添加到used
列表中)的功能似乎完美无缺,但它始终保持着下划线网格。
代码如下:
# IMPORT GUARDS
from random import choice
from os import system
from time import sleep
# DECLARATIONS
wordList = ["apple", "pear"]
gameWord = choice(wordList)
strList = list(gameWord)
strOut = "_" * len(gameWord)
tries = 5
used = []
alphabet = "abcdefghijklmnopqrstuvwxyz"
while True:
system ("cls")
print (strOut + "\n")
print ("Tries Left:", str(tries))
print ("Letters Used:", used)
Ltr = input ("Letter: ")
# INPUT CHECK
if len(Ltr) != 1 and Ltr.lower() in alphabet:
print ("Input is of incorect size.")
sleep(0.5)
elif len(Ltr) == 0 and Ltr.lower() in alphabet:
print ("No input value given.")
sleep(0.5)
if len(Ltr) == 1 and Ltr.lower() not in alphabet:
print ("Invalid character input.")
sleep(0.5)
if len(Ltr) != 1 and Ltr.lower() not in alphabet:
print ("Input is both too large and contains invalid characters.")
sleep(0.5)
# CORRECT INPUT
if len(Ltr) == 1 and Ltr.lower() in alphabet:
ltrPos = ( [pos for pos, char in enumerate(gameWord) if char == Ltr.lower])
# DECLARATIONS
Counter = 0
strcounter = 0
# CHECKING THE NUM OF TIMES THE INPUT APPEARS IN THE WORD
while Counter < len(strList):
if gameWord[Counter].lower() == Ltr.lower():
strcounter += 1
Counter += 1
# INPUT DOES APPEAR
if strcounter != 0:
strcounter -= 1
strOut = list(strOut)
for i in ltrPos:
strOut[ltrPos[strcounter]] = Ltr.upper()
strcounter += 1
strOut = "".join(strOut)
# INPUT DOES NOT APPEAR AND/OR IS USED
elif strcounter == 0:
if Ltr not in used:
print ("Letter not in word.")
used.append(Ltr.lower())
tries -= 1
else:
print ("Letter Already Used.")
sleep(0.5)
# OUT OF TRIES
if tries == 0:
system("cls")
print ("Game Over. \nWord: " + gameWord)
break
# VICTORY
if "_" not in strOut:
system("cls")
print ("Congratulations!")
break
system ("pause")
感谢所有建议。预先感谢。
答案 0 :(得分:1)
主要问题是您忘记在一个地方调用lower
函数:
ltrPos = [pos for pos, char in enumerate(gameWord) if char == Ltr.lower()]
但是还有更多。首先,您可以将strCounter
简化为
strcounter = len(ltrPos)
或者只检查if ltrPos:
而不是if strcounter != 0:
。另外,您可以使用else
代替elif
。
下一个问题是strOut[ltrPos[strcounter]]
。在这里,您尝试访问lrtPos[strcounter]
,当您将strcounter
递减一次时会产生索引错误,而不是将其设置回零。相反,只需直接迭代ltrPos
中的索引:
for i in ltrPos:
strOut[i] = Ltr.upper()
此外,请注意,如果单词中的字母不是 ,则仅将字母添加到used
列表中。