0

0

JavaScript 测验游戏:实现所有问题回答完毕后立即结束游戏

碧海醫心

碧海醫心

发布时间:2025-10-25 11:23:01

|

570人浏览过

|

来源于php中文网

原创

JavaScript 测验游戏:实现所有问题回答完毕后立即结束游戏

本文将详细介绍如何在 javascript 测验游戏中,确保当所有问题都被回答完毕时,游戏能够立即结束,而无需等待计时器归零。我们将分析现有代码中的不足,并提供一个简洁有效的解决方案,通过检查当前问题索引与问题总数的逻辑,实现游戏的即时终止,并停止计时器。

JavaScript 测验游戏:实现所有问题回答完毕后立即结束游戏

在开发基于 JavaScript 的测验(Quiz)游戏时,一个常见的需求是游戏不仅要在计时器归零时结束,还应在所有问题都被回答完毕后立即终止。本文将深入探讨如何优雅地实现这一功能,确保用户体验的流畅性。

问题分析

在许多测验游戏的初始实现中,游戏结束的逻辑往往主要依赖于计时器。例如,当计时器倒计时到零时,游戏才进入结束状态。然而,如果玩家在计时器到期之前回答完了所有问题,游戏却仍然停留在最后一个问题界面,等待计时器走完,这会造成不必要的延迟和用户困惑。

我们来看一个典型的 nextquestion 函数实现:

function nextquestion(event) {
  if (event.target.className === "btn") {
    // ... 处理答案逻辑,计算分数或扣除时间 ...

    currentQuestion++; // 移动到下一个问题
    displayQuestion(); // 显示下一个问题
  }
};

这段代码的问题在于,它在 currentQuestion 递增之后,直接调用 displayQuestion() 来显示下一个问题,而没有检查是否已经没有更多问题了。如果 currentQuestion 超出了 questionKey 数组的范围,displayQuestion() 将尝试访问一个不存在的索引,可能导致错误,更重要的是,游戏不会进入结束状态。

立即学习Java免费学习笔记(深入)”;

VWO
VWO

一个A/B测试工具

下载

解决方案:检查问题完成状态

要解决这个问题,我们需要在每次处理完一个问题并准备显示下一个问题之前,增加一个逻辑判断:检查 currentQuestion 是否已经达到了问题数组的总长度。如果达到,则意味着所有问题都已回答完毕,此时应该立即调用 gameOver() 函数来结束游戏,并停止计时器。

以下是修改后的 nextquestion 函数的关键部分:

// ... 其他代码 ...

let timeInterval; // 将 timeInterval 声明为全局变量,以便在任何地方清除

// ... startTimer 函数 ...
function startTimer() {
  timeInterval = setInterval(
    () => {
      timeLeft--;
      document.getElementById("timeSpan").innerHTML = timeLeft;
      if (timeLeft <= 0) {
        clearInterval(timeInterval);
        gameOver();
      }
    }, 1000
  );
};

// ... displayQuestion 函数 ...

function nextquestion(event) {
  if (event.target.className === "btn") {
    // ... 处理答案逻辑,计算分数或扣除时间 ...

    currentQuestion++; // 移动到下一个问题

    // 关键改动:检查是否所有问题都已回答完毕
    if (currentQuestion === questionKey.length) {
      clearInterval(timeInterval); // 停止计时器
      gameOver(); // 结束游戏
    } else {
      displayQuestion(); // 显示下一个问题
    }
  }
};

// ... gameOver 函数 ...

解释:

  1. currentQuestion++: 在玩家选择一个答案后,currentQuestion 递增,指向下一个问题。
  2. if (currentQuestion === questionKey.length): 这是核心判断。questionKey.length 返回问题数组中问题的总数。由于数组索引是从 0 开始的,当 currentQuestion 的值等于 questionKey.length 时,意味着我们已经遍历并回答了所有问题(例如,如果总共有 5 个问题,索引从 0 到 4,那么当 currentQuestion 变为 5 时,所有问题都已回答)。
  3. clearInterval(timeInterval): 在所有问题回答完毕后,计时器就不再需要运行了。调用 clearInterval 函数并传入 setInterval 返回的 ID (timeInterval),可以停止计时器。请确保 timeInterval 是在 startTimer 函数外部声明的,以便 nextquestion 函数可以访问它。
  4. gameOver(): 立即调用 gameOver() 函数,将游戏切换到结束页面,并显示最终分数。
  5. else { displayQuestion(); }: 如果还有未回答的问题,则继续调用 displayQuestion() 来显示下一个问题。

完整示例代码

为了更清晰地展示,以下是包含上述修改的完整 JavaScript 代码片段:

// calling in id/class from HTML 
const questionEl = document.getElementById("question");
// checkers 元素在原始HTML中没有对应的ID,如果不需要可移除或根据实际情况添加ID
// const checkers = document.getElementById("right-wrong"); 
const timerEl = document.getElementById("timeSpan"); // 更正为getElementById,因为只有一个timeSpan
const answerOne = document.getElementById("answer1");
const answerTwo = document.getElementById("answer2");
const answerThree = document.getElementById("answer3");
const answerFour = document.getElementById("answer4");
const finalScoreEl = document.getElementById("pointScore");
const nameEl = document.getElementById("initials");
const highScoreEl = document.getElementById("highScoreList");

var questionKey = [
  {
    question: "which variable has the value of a string.",
    choiceOne: "x = 6",
    choiceTwo: "x = \"87\"",
    choiceThree: "x = true",
    choiceFour: "x;",
    answer: "x = \"87\""
  },
  {
    question: "choose the operator that checks for value and type.",
    choiceOne: "=",
    choiceTwo: "+=",
    choiceThree: "===",
    choiceFour: "<=;",
    answer: "==="
  },
  {
    question: "choose the true statement.",
    choiceOne: "4 != 4",
    choiceTwo: "4 > 85",
    choiceThree: "7 === \"7\"",
    choiceFour: "7.6 == \"7.6\"",
    answer: "7.6 == \"7.6\""
  },
  {
    question: "which data type is not primitive.",
    choiceOne: "boolean",
    choiceTwo: "array",
    choiceThree: "number",
    choiceFour: "string",
    answer: "array"
  },
  {
    question: "Which one is the Increment operator.",
    choiceOne: "**",
    choiceTwo: "/",
    choiceThree: "++",
    choiceFour: "+=",
    answer: "++"
  }
];

// starting positions
let timeLeft = 60;
let score = 0;
let currentQuestion = -1;
let finalScore;
let timeInterval; // 声明 timeInterval 以便在任何函数中访问

// change div to start the test
function changeDiv(curr, next) {
  document.getElementById(curr).classList.add('hide');
  document.getElementById(next).removeAttribute('class');
}

// button to start the game
document.querySelector('#startButton').addEventListener('click', gameStart);

function gameStart() {
  changeDiv('start', 'questionHolder');
  currentQuestion = 0;
  displayQuestion();
  startTimer();
}

// timer function/Count down
function startTimer() {
  timeInterval = setInterval(
    () => {
      timeLeft--;
      document.getElementById("timeSpan").innerHTML = timeLeft;
      if (timeLeft <= 0) {
        clearInterval(timeInterval);
        gameOver();
      }
    }, 1000
  );
}

function displayQuestion() {
  questionEl.textContent = questionKey[currentQuestion].question;
  answerOne.textContent = questionKey[currentQuestion].choiceOne;
  answerTwo.textContent = questionKey[currentQuestion].choiceTwo;
  answerThree.textContent = questionKey[currentQuestion].choiceThree;
  answerFour.textContent = questionKey[currentQuestion].choiceFour;
}

// will end game when all questions are completed as well as populate the next question
document.querySelector('#questionHolder').addEventListener('click', nextquestion);

function nextquestion(event) {
  if (event.target.className === "btn") {
    console.log(event.target.textContent, questionKey[currentQuestion].answer);
    if (event.target.textContent === questionKey[currentQuestion].answer) {
      score += 10;
      console.log("correct");
      console.log(score);
    } else {
      if (timeLeft >= 10) {
        console.log(timeLeft);
        timeLeft = timeLeft - 10;
        document.getElementById("timeSpan").innerHTML = timeLeft;
        console.log("not correct");
      } else {
        timeLeft = 0;
        gameOver(); // 如果时间不足10秒,直接结束游戏
      }
    }
    currentQuestion++;

    // IF THERE ARE NO MORE QUESTIONS, CALL gameOver
    if (currentQuestion === questionKey.length) {
      clearInterval(timeInterval); // 停止计时器
      gameOver(); // 结束游戏
    } else {
      displayQuestion(); // 显示下一个问题
    }
  }
}

// the game is over and logs your current score
function gameOver() {
  document.getElementById("timeSpan").textContent = 0; // 直接设置span的文本
  changeDiv('questionHolder', 'finishedPage');
  finalScore = score;
  finalScoreEl.textContent = finalScore;
}

注意事项与最佳实践

相关专题

更多
js获取数组长度的方法
js获取数组长度的方法

在js中,可以利用array对象的length属性来获取数组长度,该属性可设置或返回数组中元素的数目,只需要使用“array.length”语句即可返回表示数组对象的元素个数的数值,也就是长度值。php中文网还提供JavaScript数组的相关下载、相关课程等内容,供大家免费下载使用。

557

2023.06.20

js刷新当前页面
js刷新当前页面

js刷新当前页面的方法:1、reload方法,该方法强迫浏览器刷新当前页面,语法为“location.reload([bForceGet]) ”;2、replace方法,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL,语法为“location.replace(URL) ”。php中文网为大家带来了js刷新当前页面的相关知识、以及相关文章等内容

394

2023.07.04

js四舍五入
js四舍五入

js四舍五入的方法:1、tofixed方法,可把 Number 四舍五入为指定小数位数的数字;2、round() 方法,可把一个数字舍入为最接近的整数。php中文网为大家带来了js四舍五入的相关知识、以及相关文章等内容

754

2023.07.04

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

478

2023.09.01

JavaScript转义字符
JavaScript转义字符

JavaScript中的转义字符是反斜杠和引号,可以在字符串中表示特殊字符或改变字符的含义。本专题为大家提供转义字符相关的文章、下载、课程内容,供大家免费下载体验。

454

2023.09.04

js生成随机数的方法
js生成随机数的方法

js生成随机数的方法有:1、使用random函数生成0-1之间的随机数;2、使用random函数和特定范围来生成随机整数;3、使用random函数和round函数生成0-99之间的随机整数;4、使用random函数和其他函数生成更复杂的随机数;5、使用random函数和其他函数生成范围内的随机小数;6、使用random函数和其他函数生成范围内的随机整数或小数。

1031

2023.09.04

如何启用JavaScript
如何启用JavaScript

JavaScript启用方法有内联脚本、内部脚本、外部脚本和异步加载。详细介绍:1、内联脚本是将JavaScript代码直接嵌入到HTML标签中;2、内部脚本是将JavaScript代码放置在HTML文件的`<script>`标签中;3、外部脚本是将JavaScript代码放置在一个独立的文件;4、外部脚本是将JavaScript代码放置在一个独立的文件。

658

2023.09.12

Js中Symbol类详解
Js中Symbol类详解

javascript中的Symbol数据类型是一种基本数据类型,用于表示独一无二的值。Symbol的特点:1、独一无二,每个Symbol值都是唯一的,不会与其他任何值相等;2、不可变性,Symbol值一旦创建,就不能修改或者重新赋值;3、隐藏性,Symbol值不会被隐式转换为其他类型;4、无法枚举,Symbol值作为对象的属性名时,默认是不可枚举的。

553

2023.09.20

AO3中文版入口地址大全
AO3中文版入口地址大全

本专题整合了AO3中文版入口地址大全,阅读专题下面的的文章了解更多详细内容。

1

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 3.9万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 2.3万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号