编写一个简单的刽子手游戏,寻找填补空白的方法

2024-06-17 13:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在编写一个非常简单的刽子手游戏,以便了解Python和一般编程。下面你可以找到我已经做了什么。在这个阶段,我的代码能够从名为“word\u pool”的列表中随机选择一个单词,然后用空格而不是字母显示它(例如,“kitty”变成“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。这已经行得通了

我遇到的问题是,如果猜测正确,就替换空格。假设单词是“kitty”,用户猜到了“t”,我想把编码的单词改成“uu_uu_u_u_u_u_u”。这就是我试图对for循环所做的;我让我迭代单词的每个字符,如果它匹配,应该在编码单词中替换它。在编码字中是i*2-1的原因是下划线之间有空格。然后我尝试打印编码的单词,看看它是否有效,但它只打印下划线,中间有空格。为什么什么都没有被取代

import random

word_pool = ["kitty", "dog", "teeth", "sitting"]

print("Guess the word!")
word = word_pool[random.randint(0, len(word_pool)-1)].upper()
print(word)
encoded_word = "_ "*len(word)
print(encoded_word)
guess = input("Which letter do you want to guess? ").upper()

if guess in word:
    print(f"Yes, {guess} is correct!")
    for i in range(0, len(word)):
        if word[i] == guess:
            encoded_word.replace(encoded_word[i*2-1], guess, 1)
            print(encoded_word)
else:
    print(f"No, {guess} isn't correct!")

1条回答
网友
1楼 · 发布于 2024-06-17 13:23:10

Changing one character in a string in Python的启发,我将编码的string更改为列表,因为python中的字符串是不可变的。有关更多详细信息,请参见上述问题。现在我可以简单地在他们的位置修改字母

此外,我用一个enumerate替换了range,因为它更好,更像python。我不确定您是否真的想在每次替换后或在替换所有字母后打印结果

我注释掉了随机部分和用户输入,以便更快地执行和测试

import random

word_pool = ["kitty", "dog", "teeth", "sitting"]

print("Guess the word!")
word = word_pool[0]  # word_pool[random.randint(0, len(word_pool)-1)].upper()
print(word)
encoded_word = ["_"] * len(word)
print(" ".join(encoded_word))
guess = "t"  # input("Which letter do you want to guess? ").upper()

if guess in word:
    print(f"Yes, {guess} is correct!")
    for i, letter in enumerate(word):
        if letter == guess:
            encoded_word[i] = guess

    print(" ".join(encoded_word))
else:
    print(f"No, {guess} isn't correct!")

输出:

Guess the word!
kitty
_ _ _ _ _
Yes, t is correct!
_ _ t t _

相关问题 更多 >