python - 我只能输入 1 个字母,如何让代码知道 2 个或更多字母也可以?
问题描述
import random
from typing import List
words = [ 'apple', 'tree', 'python', 'bench', 'float' ]
word = random.choice(words)
guesses= []
letter_storage = []
f = "Do you want to play?"
a = ["yes","no"]
max_fails = []
def print_word_to_guess(letters: List):
print("{0}".format(" ".join(letters))) # need to display _ _ _ _ instead of ['_', '_', '_', '_', '_']
def input_choice(f:str,a:list[str])->str:
if f in a:
if f == "yes":
a = "yes"
elif f == "no":
print("ok no")
elif f not in a:
while f not in a:
f = input("Invalid answer. Try again")
if f in a:
if f == "yes":
a = "yes"
elif f == "no":
print("ok no")
def shape(word:str,guesses:str)->str:
for letter in word:
guesses.append("_ ")
def hangman(word:str,max_fails:int):
max_fails = int(input("Number of allowed mistakes: "))
while max_fails> 0:
guess = input("make a guess:")
if guess in letter_storage:
print("mistakes left:",max_fails,",you already guessed that letter!")
else:
letter_storage.append(guess)
if guess in word :
for x in range(0, len(word)):
if word[x] == guess:
guesses[x] = guess
print_word_to_guess(guesses)
if not '_ ' in guesses:
print("You won!","The word was:",word)
break
else:
max_fails -= 1
print(max_fails,"mistakes left")
if max_fails == 0:
print("You lost :( The word was",word)
input_choice(input("Do you want to play? [yes / no]"),("yes","no"))
shape(word,guesses)
hangman(word,max_fails)
这是我的小刽子手游戏。该代码识别出单词中有多个字母,但不会将它们添加到空格中。我希望多个字母也被接受,所以当你已经猜到应用程序时,你也可以添加 le 来完成游戏。如何在我的代码中实现这一点?
解决方案
您可以将猜测保存到变量guess_str
中,然后遍历猜测的所有字母for guess in guess_str
并再次运行您的代码逻辑:
def hangman(word: str, max_fails: int):
max_fails = int(input("Number of allowed mistakes: "))
while max_fails > 0:
guess_str = input("make a guess:")
for guess in guess_str:
if guess in letter_storage:
print("mistakes left:", max_fails, ",you already guessed that letter!")
else:
letter_storage.append(guess)
if guess in word:
for x in range(0, len(word)):
if word[x] == guess:
guesses[x] = guess
print_word_to_guess(guesses)
if not "_ " in guesses:
print("You won!", "The word was:", word)
break
else:
max_fails -= 1
print(max_fails, "mistakes left")
if max_fails == 0:
print("You lost :( The word was", word)
推荐阅读
- postgresql - 为什么在 Postgresql 文档的 LTree 示例中,作者在 ltree 列上创建了两个索引?
- sql - 没有日期和主键的表
- reactjs - Redux-Thunk Action 将 action 设置为 Promise
- python - 将 Pandas DataFrame 作为 Pickle 写入 S3
- typescript - 打字稿反应列表
- react-native - 如何在不删除/安装 npm 包的情况下解决捆绑模块解析问题?
- php - Wordpress:块元素内的关系字段
- python - 可调用在python标准库中返回一个常量
- python - Snakemake 使用不同文件夹中的输入文件按名称汇总
- c# - 将指针数据复制到字节数组并写入 MemoryStream 会导致 LOH 中的大量分配