我正在用python编写一个猜字游戏,但是我在guess()函数中遇到了一些问题
当用户猜到一个正确的字母并用该字符替换时,空格(u3;)应该相应地消失。然而,仍然有一些徘徊甚至用户猜对了单词。如何调整格式以使其被猜测的字符替换
另一个问题是,程序给了我10次尝试,无论我得到的字是对还是错。我猜测在尝试时使用if语句或for循环。在我说对了词之后我该怎么让它停下来
谢谢
def pick():
print()
f = open('words.txt', 'r')
wlist = f.readlines()
f.close()
chosenword = random.choice(wlist)
return(chosenword)
def guess():
#Determine length of chosen word and display number of blanks
chosenword = pick()
pH = '_ ' * (len(chosenword)-1)
print()
print (pH)
print()
#Number of failed attempts
attempt = 0
count = 10
#Receive guess
for i in range (0, 10):
attempt += 1
guess = input("Enter a letter for a guess : ")
guess = guess.upper()
#Check if guess is found in random word
if guess in chosenword:
for i in range (0,len(chosenword)):
if guess == chosenword[i]:
pH = pH[:i] + guess + pH[i+1:]
print(pH)
if guess not in chosenword:
print(pH)
if pH == chosenword:
print ("You guessed the word - congrats!")
else:
print ("The word was ",chosenword)
print ("Sorry - bettter luck next time.")
guess()
pick()
下面是一个使用指定列表的版本。您可以将其更改为从文件读取。我在代码中添加了注释以显示对代码的更正
相关问题 更多 >
编程相关推荐