如何为问答游戏添加得分统计与结束结算功能?
问答游戏得分统计与结束逻辑修改方案
1. HTML结构补充
在现有页面里新增得分显示区和结果面板(初始隐藏):
<!-- 新增:当前得分展示,放在答题区顶部 --> <div class="score">当前得分:<span id="currentScore">0</span></div> <!-- 新增:游戏结束后的结果面板 --> <div id="resultPanel" style="display:none;"> <h2>游戏结束!</h2> <p>你的最终得分:<span id="finalScore">0</span>/10</p> <button id="restartBtn">重新开始游戏</button> <button id="homeBtn">返回主页</button> </div> <!-- 保留你原有的答题容器 --> <div id="quizContainer"> <div id="question"></div> <div id="options"></div> </div>
2. 基础样式调整(可选)
给新增元素加些样式,让界面更清晰:
.score { font-size: 1.2rem; margin-bottom: 1rem; font-weight: bold; } #resultPanel { text-align: center; padding: 2rem; border: 1px solid #ddd; border-radius: 8px; margin-top: 2rem; } #resultPanel button { margin: 0 0.5rem; padding: 0.8rem 1.5rem; cursor: pointer; }
3. JavaScript核心逻辑修改
在原有代码基础上添加得分跟踪、进度判断和结束逻辑:
// 新增全局变量:记录得分和当前题目索引 let score = 0; let currentQuestionIndex = 0; // 假设你的题目数组是questions,包含10道题 const questions = [ // 这里放你原有的题目数据,格式比如: // { question: "题目内容", options: ["选项1", "选项2", "选项3"], correct: "正确选项" } ]; // 初始化/重置游戏状态 function initGame() { score = 0; currentQuestionIndex = 0; document.getElementById("currentScore").textContent = score; document.getElementById("resultPanel").style.display = "none"; document.getElementById("quizContainer").style.display = "block"; loadQuestion(); // 加载第一题 } // 加载题目(修改原有逻辑,增加完成判断) function loadQuestion() { // 10道题做完,显示结果 if (currentQuestionIndex >= questions.length) { showResult(); return; } const question = questions[currentQuestionIndex]; // 保留你原有的渲染题目和选项的代码 document.getElementById("question").textContent = question.question; const optionsContainer = document.getElementById("options"); optionsContainer.innerHTML = ""; question.options.forEach(option => { const btn = document.createElement("button"); btn.textContent = option; btn.addEventListener("click", () => checkAnswer(option)); optionsContainer.appendChild(btn); }); } // 检查答案(修改原有逻辑,增加得分更新) function checkAnswer(selectedOption) { const currentQuestion = questions[currentQuestionIndex]; // 答对就加分并更新显示 if (selectedOption === currentQuestion.correct) { score++; document.getElementById("currentScore").textContent = score; } currentQuestionIndex++; loadQuestion(); // 加载下一题 } // 显示最终结果 function showResult() { document.getElementById("quizContainer").style.display = "none"; document.getElementById("finalScore").textContent = score; document.getElementById("resultPanel").style.display = "block"; } // 绑定按钮事件 document.getElementById("restartBtn").addEventListener("click", initGame); document.getElementById("homeBtn").addEventListener("click", () => { // 替换成你的主页路径,比如根目录"/" window.location.href = "/"; }); // 页面加载完成后启动游戏 window.addEventListener("DOMContentLoaded", initGame);
关键修改说明
- 用
score和currentQuestionIndex跟踪得分与答题进度 - 每道题答对后立即更新得分显示
- 做完10题后自动切换到结果面板,隐藏答题区
- 重新开始按钮重置所有状态并重启游戏,返回主页按钮直接跳转
内容的提问来源于stack exchange,提问作者levani
相关产品推荐
相关产品推荐

