我想创建一个程序,从列表中随机取出一个单词,并要求用户输入一个字母,如果该字母在单词中,则将其添加或直接显示到称为“找到的字母”的行中,如果不在单词中,则将其显示在单词中。添加到名为“错过的字母”的行中,如果用户输入已经输入过的字母,则会显示一条消息,告诉他已经输入了该字母并邀请他尝试新的字母,如果他输入了字母旁边的任何内容程序停止。
import random
words = ['cat', 'why', 'car', 'dress', 'apple', 'orange']
word = random.choice(words)
displaylist = []
found_letters = []
missed_letters = []
for _ in range(len(word)):
displaylist.append('_')
repeater = True
while repeater:
print(f"Word: {' '.join(displaylist)}")
print(f"found letters: {' '.join(found_letters)}")
print(f"missed letters: {' '.join(missed_letters)}")
letter = input("Enter a letter:")
if letter in word:
if letter in displaylist:
print("you have already entered that letter:")
continue
for i in range(len(word)):
if letter == word[i]:
displaylist[i] = letter
found_letters.append(letter)
continue
elif letter.isalpha():
missed_letters.append(letter)
continue
else:
print("you have to enter a letter:")
repeater = False
问题是每次用户输入一个字母时, 它显示到新发现的字母行或丢失的字母行, 但我希望它们能够被修复,唯一改变的是字母, 当用户输入一些字母,并且它们在单词中时, 它们被直接添加到一个找到的字母行和一个丢失的字母行 如果它们不在单词中,则每次都不要重复找到的字母和遗漏的字母行。 有谁知道我该怎么做
我的输出:
预期输出:
我观察了您想要的输出,并考虑到有关“ncurses”的良好评论,如果由于某种原因您不想走这条路,另一种选择是利用一些操作系统功能来清除屏幕。考虑到这一点,以下是代码的重构版本,具有简化的屏幕清除功能。我对其长度表示歉意,但增强功能已遍布您的整个程序。
import random
import time # Provide functionality for sleep/delay
from os import system, name # Provide functionality to clear the screen
def clx(): # Generic screen clear
if name == 'nt': # Windows screen clear
system('cls')
else:
system('clear') # Linux/Posix clear
words = ['cat', 'why', 'car', 'dress', 'apple', 'orange']
word = random.choice(words)
displaylist = []
found_letters = []
missed_letters = []
for _ in range(len(word)):
displaylist.append('_')
repeater = True
clx()
while repeater:
print(f"Word: {' '.join(displaylist)}")
print(f"found letters: {' '.join(found_letters)}")
print(f"missed letters: {' '.join(missed_letters)}")
print("\n\n")
letter = input("Enter a letter:")
if letter in word:
if letter in displaylist:
print("You have already entered that letter")
time.sleep(2)
clx()
continue
for i in range(len(word)):
if letter == word[i]:
displaylist[i] = letter
found_letters.append(letter)
if '_' not in displaylist: # Check to see if the word has been guessed
clx()
print(f"Word: {' '.join(displaylist)}")
print(f"found letters: {' '.join(found_letters)}")
print(f"missed letters: {' '.join(missed_letters)}")
print("\n\n")
print("You have guessed the word")
print(f"Word: {''.join(displaylist)}")
break
else:
clx()
continue
elif letter.isalpha():
if letter in missed_letters:
print("You have already tried that letter and it is not in the word")
time.sleep(2)
clx()
continue
missed_letters.append(letter)
clx()
continue
else:
print("you have to enter a letter:")
repeater = False
以下是重点。
在终端上进行测试似乎模仿了您想要的功能。
Word: o r a n g e
found letters: a o r n g e
missed letters: h j k l w q
You have guessed the word
Word: orange
这种可能的路线/解决方案(这可能只是众多解决方案之一)的主要收获是,您可能想深入研究 Python 教程,特别是因为它与函数使用有关,而循环使用“继续”和“中断”语句。