【问题标题】:Creating a Hangman game创建一个刽子手游戏
【发布时间】:2020-06-10 16:48:02
【问题描述】:

我正在创建一个刽子手游戏,但遇到了一个我似乎无法解决的问题。以下是我正确输入字母的代码:

            for i, l in enumerate(answer):
                if l == attempt:
                    temp += attempt
                else:
                    temp += hidden[i]
            print(F"Correct! You have {lives} lives left")
            print(temp)

返回:(答案是双工的)

            duplex
            Guess a letter: x
            Correct! You have 5 lives left
            -----x

但是,当添加第二个输入时,它会打印第二个连接的字符串而不是更新的字符串。

            Guess a letter: e
            Correct! You have 5 lives left
            -----x----e-
            Guess a letter: 

我哪里错了?谢谢!

【问题讨论】:

  • 这是因为您在 if 语句 temp += attempttemp += hidden[i] 的两个分支中连接。您可能想研究某种列表理解
  • 欢迎堆栈溢出!不幸的是,这段代码的可重复性不足以生成minimal reproducible exampleattempt 是什么? temp 是什么? hidden 是什么?第一个想法是你每次都用temp += 一遍又一遍地连接temp

标签: python python-3.x loops


【解决方案1】:

问题是隐藏的。在代码中,您发布的内容并未将用户输入添加到此数组中。所以隐藏是永远不会改变的。在正确的尝试范围内尝试 hidden[i]=attempt。它应该是这样的。

   for i, l in enumerate(answer):
                if l == attempt:
                    temp += attempt
                    hidden[i]=attempt
                else:
                    temp += hidden[i]
            print(F"Correct! You have {lives} lives left")
            print(temp)

在python中,字符串有find函数,它返回字符串中子字符串的索引。它可以让你的代码更干净。

index = answer.find(attempt,0)
if(index>0):
   hidden[index] = attempt
print(hidden)

【讨论】:

    【解决方案2】:

    而不是不断地附加到temp 字符串,我认为你想在猜测时替换它的特定字母。我还建议给它一个比temp更好的名字!

    visible = ["-"] * len(answer)
    
    # now for each attempt, do:
    
        if attempt in answer and attempt not in visible:
            print(f"Correct! You have {lives} lives left")
    
        for i, l in enumerate(answer):
            if l == attempt:
                visible[i] = attempt
    
        print("".join(visible))
    

    【讨论】:

    • 您好,非常感谢您花时间回答这个问题。我曾尝试使用“visible[i] = attempt”,但收到以下错误:TypeError: 'str' object does not support item assignment
    • 啊抱歉,让我更新一下以使其真正起作用:P 我有时忘记了字符串在 Python 中是不可变的;简单的解决方法是将其列在列表中,然后在需要打印时使用join
    猜你喜欢
    • 2015-05-29
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 2012-10-26
    • 2014-10-19
    相关资源
    最近更新 更多