首页 > 解决方案 > 我在 python 中的刽子手游戏代码没有给出正确的输出

问题描述

我试图在 python 中创建一个刽子手游戏,但我的输出很奇怪。它没有像我想要的那样给出输出。请帮我。

guess_word = input("Enter the word to be guess")
guess_word_list = []
for i in range(0, len(guess_word)):
    guess_word_list.append("_")
guess_chances = 6
print("You can now guess letters")
while guess_chances > 0:
    guess_letter = input()
    for letter in guess_word:
        if letter == guess_letter:
            guess_word_list[guess_word.index(letter)] = guess_letter
            print(guess_word_list)
        else:
            guess_chances = guess_chances - 1
            print("Chances remaining {}".format(guess_chances))
count = 0
for letter in guess_word_list:
    if letter == "_":
        count += 1
if count == 0:
    print("Winner")
else:
    print("Looser")

从评论中编辑:

如果要猜的词是'mm.......'这样,如果我输入了'm',那么也只有第一个“_”被替换为'm'

如果输入错误的字符,则一次减少 2 次机会。

标签: pythonpython-3.xalgorithmloopsdata-structures

解决方案


两个问题:

  • 检查字母时,您将扣除每个不匹配字母的机会。只有在根本没有找到这封信的情况下,您才应该扣除机会。
  • 在主循环中,检查猜测词是否完整(没有空格),因此循环退出

试试这个代码:

guess_word = input("Enter the word to be guess")
guess_word_list = []
for i in range(0, len(guess_word)):
    guess_word_list.append("_")
guess_chances = 6
print("You can now guess letters")
while guess_chances > 0 and '_' in guess_word_list:
    guess_letter = input()
    found = False
    for letter in guess_word:  # check all letters
        if letter == guess_letter:
            guess_word_list[guess_word.index(letter)] = guess_letter
            print(guess_word_list)
            found = True  # found letter in word
    if not found: # guess letter not in word
            guess_chances = guess_chances - 1
            print("Chances remaining {}".format(guess_chances))
count = 0
for letter in guess_word_list:
    if letter == "_":
        count += 1
if count == 0:
    print("Winner")
else:
    print("Looser")

仍然存在的一个逻辑问题是单词必须具有唯一的字母。如果单词是'zoom',游戏永远不会结束,因为循环总是找到第一个'o'。


推荐阅读