我在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")

从评论编辑:

如果要猜测的单词是CCD_ 1,那么如果我输入CCD__"由CCD_ 3代替。

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

两个问题:

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

试试这个代码:

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"。

尝试一下:

guess_word = input("Enter the word to be guess: ")
guess_word_list = ['_']*len(guess_word)
guess_chances = 6
print("You can now guess letters")
while guess_chances > 0 and '_' in guess_word_list:
guess_letter = input()
correct_guess = False
for i, letter in enumerate(guess_word):
if letter == guess_letter:
guess_word_list[i] = guess_letter
correct_guess = True
if not correct_guess:
guess_chances = guess_chances - 1
print("Chances remaining {}".format(guess_chances))
else:
print(''.join(guess_word_list))
if '_' not in guess_word_list:
print('winner')
else:
print('looser')

最新更新