【问题标题】:Python: Guessing game gone wrongPython:猜谜游戏出错了
【发布时间】:2015-03-11 16:21:32
【问题描述】:

我正在尝试在 python 中创建一个小型的基本猜谜游戏,例如 Text Twist。代码如下:

while game_running == True:
    if (tries_left != 0):
        print "Tries left: " + str(tries_left)
        chosen_text = text_list[picker(text_length)]
        scrambled_text = scrambler(chosen_text)
        print "Guess the word/s: " + scrambled_text
        guess_text = raw_input("Your answer (space included): ")
        if (chosen_text == guess_text):
            print "Congratulations! You guessed correctly!"
            game_running = False
        else:
            tries_left-=1
    else:
        print "LOL. You dun goofed son. Terminating like SkyNet..."
        game_running = False

看不见的功能:

  • picker - 基本上是一个随机化器
  • 加扰器 - 加扰单词。正在进行中,尚未实施。

您有 3 次尝试正确猜测,否则应用程序将终止。如果您猜对了,应用程序会显示一条消息,然后终止。听起来很简单。

问题:

我无法让它工作:

if (chosen_text == guess_text):

尽管我 100% 确定(通过 print chosen_text)我猜对了。

我尝试了什么:

我尝试颠倒顺序,将str() 放在它们周围,甚至颠倒if 和else 的流程,使用is 而不是==,并删除try 函数,fwiw。

没有什么可以让它成为现实...
...除非我硬编码chosen_text,然后猜对了。

我错过了什么吗?

【问题讨论】:

  • 尝试检查每个字符串的长度,它们是否相同?它可能包含换行符或空格。

标签: python


【解决方案1】:

你可能想插入一些调试代码:

print repr(chosen_text)
print repr(guess_text)

这将准确地显示您正在处理的两个字符串。 repr 函数会在字符串周围加上引号,并让您确定字符串是否存在意外空格或其他难以发现的问题。

如果有,您可以尝试以下方法:

if chosen_text.strip() == guess_text.strip():
    print "Congratulations! You guessed correctly!"

或者如果有不同的大小写:

if chosen_text.strip().lower() == guess_text.strip().lower():
    print "Congratulations! You guessed correctly!"

您还可以做一些其他的事情来使您的代码更符合 Python 风格/更符合 Python 习语。例如:

while game_running == True:

最好表述为:

while game_running:

但是其他一些清理是风格上的,与您的比较难度无关。

【讨论】:

  • .strip() 工作,谢谢。也感谢 repr() 的提示。永远不会猜到。
  • 在很多情况下不直接测试A == B 而是测试func(A) == func(B) 很有用,其中func 是一个执行某种清理、“折叠”或散列操作的函数.在这种情况下,通过.strip() 和/或.lower() 方法运行比较的双方等效于func
  • repr() btw 的意思是“代表”。它为您提供了数据的“程序员视图”,而str() 提供了更多的“用于普通用户输入/输出”的数据视图。
猜你喜欢
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多