Python:猜词游戏

标签 python

我正在尝试用 Python 制作一个猜词游戏,但最后部分让我有点困惑。

这是我到目前为止的代码:

word_tuple = ("c", "o", "d", "e", "c")

word = ""

word = input("Give a word of " +  str(len(word_tuple)) + " characters: ")

while len(word) != len(word_tuple):
    if len(word) != len(word_tuple):
        print("Wrong!")
        word = input("Give a word of " + str(len(word_tuple)) + " characters: ")

for i in range(len(word_tuple)):
    print(word_tuple[i], end="")

基本上,循环会检查您是否插入了 5 个字符的单词,如果插入,它就会将该单词与元组的字符进行比较。如果 1 个或多个字符正确,它将打印正确的字符,而没有猜到的字符会用符号屏蔽,例如“*”。

令人困惑的部分是我必须检查输入的单词是否具有与元组匹配的字符,然后打印出正确的字符。

例如:

Give a word of 5 characters: Python
Wrong!
Give a word of 5 characters: Candy
Almost there! The word is "C*d*c"
Give a word of 5 characters: Denim
Almost there! The word is "C*dec"
Give a word of 5 characters: Codec
You found the word!

任何帮助将不胜感激。

最佳答案

您的问题是您没有正确打印您的单词,并且您的打印超出了时间范围,这是您可以尝试的答案

word_tuple = ("c", "o", "d", "e", "c")

# We use this list to keep in memory the letters found
found = [False] * len(word_tuple)

word = ""

# The `all` method return True only if the list contains only True values
# Which means, while all letters are not found

while not all(found):
    # the `lower` method allows you to not take in account the uppercases
    word = input("Give a word of " +  str(len(word_tuple)) + " characters: ").lower()

    if len(word) == len(word_tuple):
        for charac in word_tuple:
            if charac in word:
                found = [b or word_tuple[index] in word for index, b in enumerate(found)]
        # The `any` method return True only if the list contains at least one True value
        # Which means we print Wrong only if there is no letter found
        if not any(found):
            print('Wrong!')
        else:
            print('Almost there! The word is "', end='')
            for i in range(len(word_tuple)):
                if found[i]:
                    print(word_tuple[i], end="")
                else:
                    print('*', end='')
            print('"')

    else:
        print('Wrong!')
# The method `join` allows you to join every string of an iterable
# Which means it joins every character of your tuple to a printable string
while word != ''.join(word_tuple):
    print('Close, try again')
    word = input("Give a word of " +  str(len(word_tuple)) + " characters: ").lower()

print('You found the word!')

练习可以是用不同的方法重构此代码

关于Python:猜词游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53264574/

相关文章:

javascript - grunt exec 卡住,期待来自 django collectstatic 的 0 状态代码

python - 特定时间戳和前几秒的 df 子集 - python

python - Python-除了ctrl-c外,还可以通过键盘输入安全地关闭终端上的套接字连接吗?

python - 是否可以预先计算要在 renpy 中打印的文本的高度?

python - Django apache 与内置开发服务器相比的显着开销

python - Django 1.7 抛出 django.core.exceptions.AppRegistryNotReady : Models aren't loaded yet

Python按某个词切割列表

python - 将 python 编译为单个 .exe,为什么这么难?

python - 如何访问用户未明确设置的图形属性

python - 如何在 Windows 上使用 Python 获取所有显示器的信息?