python - 回答完所有问题后无法中断游戏

标签 python dictionary

我正在尝试创建一个抽认卡游戏来记住一些 C 语法,正如 Zed Shaw 所著的《Learning C the Hard Way》一书中所建议的(我昨天刚刚收到这本书,非常高兴:)!)。我对制作开始游戏的标志的方式有疑问,并在回答所有问题后将其设置为 False。这是我的代码:

def bordered(text):
    """Creates a border around text"""
    lines = text.splitlines()
    width = max(len(s) for s in lines) 
    res = ['┌' + '-' * width + '┐']
    for s in lines:
        res.append('|' + (s + ' ' * width)[:width] + '|')
    res.append('└' + '-' * width + '┘')

    return '\n'.join(res)

Arithmetic_Operators = {
    '+': 'Add',
    '-': 'Substract',
    '*': 'Multiply',
    '/': 'Divide',
    '%': 'Modulus',
    '++': 'Increment',
    '--': 'Decrement',
}


def start():
    score = 0
    Game_Starts = True
    while Game_Starts:
        for k, v in Arithmetic_Operators.items():
            print(bordered(f"What is the meaning of: {k}?"))
            answer = input()
            if  answer == v:
                print("CORRECT!")
                score = score + 1
            else:
                print("FAILED!")
                correct_answer = bordered(v)
                print(correct_answer)
                score = score - 1
                Game_Starts = False


if __name__ == "__main__":
    start()

我能够完成所有问题,但如果有人得到错误答案,游戏不会停止,并且一旦字典中的所有元素都耗尽,程序也不会停止。有谁可以帮助我理解这一点吗?我认为在 else block 中,通过将 Game_Starts 设置为 false,可以完成第一个任务。我认为到了第二个,我可能必须创建一个额外的字典来插入所有正确的答案,并删除已正确回答的问题。

最佳答案

我更改了 While bool 值,因为额外的变量并不是真正必要的,因为任何循环都可以用 break 结束,或者只是从内部返回结束它。

主要问题是,您从内部循环中中断了外部循环,而内部循环什么也不做,因为外部循环从未真正执行循环

不返回任何内容结束循环

def start():
    score = 0
    while True:
        for k, v in Arithmetic_Operators.items():
            print(bordered(f"What is the meaning of: {k}?"))
            answer = input()
            if  answer == v:
                print("CORRECT!")
                score = score + 1
            else:
                print("FAILED!")
                correct_answer = bordered(v)
                print(correct_answer)
                score = score - 1
                return

替代start()函数

def start():
    score = 0
    while True:
        for k, v in Arithmetic_Operators.items():
            print(bordered(f"What is the meaning of: {k}?"))
            answer = input()
            if  answer == v:
                print("CORRECT!")
                score = score + 1
            else:
                print("FAILED!")
                correct_answer = bordered(v)
                print(correct_answer)
                score = score - 1
                break
        break

但最干净的解决方案是摆脱 while 循环。 (我在写的时候变成了别人的解决方案)

关于python - 回答完所有问题后无法中断游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369983/

相关文章:

python - for 循环内部和外部的 pd.Series 索引 - 理解问题

python - 是什么决定了这个 python 3 代码中集合元素的顺序?

python - 生成随机二进制矩阵

ios - 如何从 NSDictionary 中删除空值

python - 如何在 Python 中拆分字典数组?

Python:将列表字典转换为元组列表

python - 访问hadoop作业跟踪器ui

python - Flask SQLAlchemy 关联表 : error creating backref

python - 将字典转换为 coo_matrix

c - C中具有不同数据类型的键值