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


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

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

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

问题分析

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

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

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

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

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

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

要解决这个问题,我们需要在每次处理完一个问题并准备显示下一个问题之前,增加一个逻辑判断:检查 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;
}

注意事项与最佳实践


# javascript  # java  # html  # ssl  # 游戏本 


相关栏目: 【 Google疑问12 】 【 Facebook疑问10 】 【 网络优化76771 】 【 技术知识130152 】 【 IDC云计算60162 】 【 营销推广131313 】 【 AI优化88182 】 【 百度推广37138 】 【 网站推荐60173 】 【 精选阅读31334


相关推荐: 如何开启Windows的远程服务器管理工具(RSAT)?(管理服务器)  Win11怎么开启自动HDR画质_Windows11显示设置HDR选项  如何使用Golang反射创建map对象_动态生成键值映射  windows如何测试网速_windows系统网络速度测试方法  win11如何清理传递优化文件 Win11为C盘瘦身删除更新缓存【技巧】  如何使用Golang处理网络超时错误_Golang请求超时异常处理方法  如何在 Django 中安全修改用户密码而不使会话失效  Win11怎么设置默认图片查看器_Windows11照片应用关联设置  Go 中 defer 语句在 goroutine 内部不返回时不会执行  mac怎么退出id_MAC退出iCloud账号与Apple ID切换【指南】  PythonFastAPI项目实战教程_API接口与异步处理实践  c# 如何用c#实现一个支持优先级的任务队列  Windows10怎样连接蓝牙设备_Windows10蓝牙连接步骤【教程】  Win11任务栏怎么放到顶部_Win11修改任务栏位置方法【详细】  如何使用Golang优化模块引入路径_Golanggo mod tidy清理与优化方法  c# Task.Yield 的作用是什么 它和Task.Delay(1)有区别吗  Python安全爬虫设计_IP代理池与验证码识别策略解析  php485函数执行慢怎么优化_php485性能提升小技巧【技巧】  php下载安装包太大怎么下载_分卷压缩下载方法【教程】  VSC里PHP变量未定义报错怎么解决_错误抑制技巧【解答】  Python高性能计算项目教程_NumPyCythonGPU并行加速  Win11色盲模式怎么开_Win11屏幕颜色滤镜设置【关怀】  Windows10蓝屏SYSTEM_SERVICE_EXCEPTION_Win10驱动冲突排查  C++如何使用std::async进行异步编程?(future用法)  如何使用Golang实现错误包装与传递_Golangfmt.Errorf%w使用实践  MAC怎么在照片中添加水印_MAC自带编辑工具文字水印叠加【方法】  Linux如何挂载新硬盘_Linux磁盘分区格式化与开机自动挂载【指南】  Win10怎样安装Excel数据分析工具_Win10安装分析工具包步骤【教程】  php控制舵机角度怎么调_php发送pwm信号控制舵机转动【解答】  Win11怎么更改鼠标指针方案_Windows11自定义鼠标光标样式与大小  Windows10怎么备份注册表_Windows10注册表备份步骤【教程】  如何使用Golang encoding/json解析JSON_Golang encoding/json解析与序列化示例  windows 10应用商店区域怎么改_windows 10微软商店切换地区方法  php命令行怎么运行_通过CLI模式执行PHP脚本的步骤【说明】  Win11怎么设置任务栏透明_Windows11使用工具美化任务栏  php怎么连接数据库_MySQL数据库连接的基础代码编写【说明】  Win11怎么关闭系统提示音_Windows11声音方案设为无声教程  Win11怎么设置触控板手势_Windows11三指四指操作自定义  如何在Golang中理解指针比较_Golang地址比较与相等判断  php报错怎么查看_定位PHP致命错误与警告的方法【教程】  c++的mutex和lock_guard如何使用 互斥锁保护共享资源【多线程】  Win11怎么开启上帝模式_创建Windows 11 God Mode全能文件夹【技巧】  C++如何编写函数模板?(泛型编程入门)  如何使用Golang实现容器健康检查_监控和自动重启  Win11怎么连接蓝牙耳机_Win11蓝牙设备配对与连接教程【步骤】  c++如何用AFL++进行模糊测试 c++ Fuzzing入门【安全】  c++怎么调用nana库开发GUI_c++ 现代风格窗口组件与事件处理【实战】  Windows服务持续崩溃怎样修复_系统服务保护机制解析  c++怎么实现高并发下的无锁队列_c++ std::atomic原子变量与CAS操作【详解】  Win11怎样激活系统密钥_Win11系统密钥激活步骤【攻略】 

 2025-10-25

了解您产品搜索量及市场趋势,制定营销计划

同行竞争及网站分析保障您的广告效果

点击免费数据支持

提交您的需求,1小时内享受我们的专业解答。

致胜网络推广营销网


致胜网络推广营销网

致胜网络推广营销网专注海外推广十年,是谷歌推广.Facebook广告全球合作伙伴,我们精英化的技术团队为企业提供谷歌海外推广+外贸网站建设+网站维护运营+Google SEO优化+社交营销为您提供一站式海外营销服务。

 915688610

 17370845950

 915688610@qq.com

Notice

We and selected third parties use cookies or similar technologies for technical purposes and, with your consent, for other purposes as specified in the cookie policy.
You can consent to the use of such technologies by closing this notice, by interacting with any link or button outside of this notice or by continuing to browse otherwise.