You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask猜谜游戏问题:复习页面无法显示用户作答内容

问题分析与解决方案

核心问题

  1. 答题过程中用户答案被意外清空:/路由每次访问都会调用reset_messages(),导致用户答完上一题进入下一题时,之前记录的用户答案被全部清空,最终review页面只能看到最后一题的答案(如果有的话)。
  2. 答对题时未标记状态:答对题目时没有给question['message']赋值为'Correct!',导致review页面的判断逻辑失效,答对的题目会错误显示空的用户答案。

修改步骤

1. 调整reset_messages()的调用时机

仅在重新开始游戏(当前题目索引为0)时重置消息,避免切换题目时清空历史答案:
修改/路由的代码:

@app.route('/')
def index():
    # 仅在重新开始游戏时重置消息
    if current_question == 0:
        reset_messages()
    if current_question < len(questions):
        return render_template('question.html', question=questions[current_question])
    else:
        return render_template('result.html', score=score, total=len(questions), questions=questions)

2. 完善答题结果的标记逻辑

在/answer路由中,答对题目时将message设为'Correct!',确保review页面能正确识别答对状态:
修改/answer路由的代码:

@app.route('/answer', methods=['POST'])
def answer():
    global current_question, score

    user_answer = request.form.get('answer')
    correct_answer = questions[current_question]['correct_answer']

    if user_answer == correct_answer:
        score += 1
        questions[current_question]['message'] = 'Correct!'  # 标记答对状态
    else:
        questions[current_question]['message'] = user_answer  # 记录答错时的用户答案

    current_question += 1

    if current_question < len(questions):
        return redirect(url_for('index'))
    else:
        score = min(score, len(questions))
        current_question = 0
        return redirect(url_for('review', score=score, total=len(questions)))

3. (可选)优化review页面的显示逻辑

可以调整review.html的代码,让答对的情况展示更清晰(原逻辑已能正常工作,此为优化建议):

<!DOCTYPE html>
<html>
<head>
    <title>Review Answers</title>
</head>
<body>
    <h1>Review Answers</h1>
    <p>Your score: {{ score }} out of {{ total }}</p>
    <ul>
        {% for question in questions %}
        <li>
            {{ question['question'] }}<br>
            {% if question['message'] == 'Correct!' %}
                Your answer: {{ question['correct_answer'] }} (Correct)<br>
                Correct answer: {{ question['correct_answer'] }}
            {% else %}
                Your answer: {{ question['message'] }}<br>
                Correct answer: {{ question['correct_answer'] }}
            {% endif %}<br>
        </li>
        {% endfor %}
    </ul>
    <a href="/">Back to Main Page</a>
</body>
</html>

修改完成后,review页面就能正确显示所有题目的用户答案和正确答案,答对的题目会标记为Correct,答错的会展示用户提交的答案和正确答案。

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:38:09