python - 我在 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 次机会。
解决方案
两个问题:
- 检查字母时,您将扣除每个不匹配字母的机会。只有在根本没有找到这封信的情况下,您才应该扣除机会。
- 在主循环中,检查猜测词是否完整(没有空格),因此循环退出
试试这个代码:
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'。
推荐阅读
- python - 如何在python3中替换has_key?
- php - 使 if 语句更干燥
- tableau-api - Tableau - 如何显示堆积条形图的图例?
- sql-server - SQL Server 代理作业已成功完成,但未执行 SSIS 包中的 (.appref-ms) 文件
- f# - 将列表中每个元素的值与列表中的每个其他元素进行比较并更新它 (f#)
- jquery - 如何使用 symfony 4 用 Jquery 刷新 div?
- angular - 如何从 .ts 文件中捕获 html 元素?
- android - Android 9 崩溃 minifyEnabled 和 multiDexEnabled
- ffmpeg - 如何合并分段的 webvtt 字幕文件并输出单个文件?
- r - 使用 R + DBI 库 + ODBC 连接到 Teradata Database