新闻中心
J*aScript 测验游戏:实现所有问题回答完毕后立即结束游戏

本文将详细介绍如何在 j*ascript 测验游戏中,确保当所有问题都被回答完毕时,游戏能够立即结束,而无需等待计时器归零。我们将分析现有代码中的不足,并提供一个简洁有效的解决方案,通过检查当前问题索引与问题总数的逻辑,实现游戏的即时终止,并停止计时器。
J*aScript 测验游戏:实现所有问题回答完毕后立即结束游戏
在开发基于 J*aScript 的测验(Quiz)游戏时,一个常见的需求是游戏不仅要在计时器归零时结束,还应在所有问题都被回答完毕后立即终止。本文将深入探讨如何优雅地实现这一功能,确保用户体验的流畅性。
问题分析
在许多测验游戏的初始实现中,游戏结束的逻辑往往主要依赖于计时器。例如,当计时器倒计时到零时,游戏才进入结束状态。然而,如果玩家在计时器到期之前回答完了所有问题,游戏却仍然停留在最后一个问题界面,等待计时器走完,这会造成不必要的延迟和用户困惑。
我们来看一个典型的 nextquestion 函数实现:
function nextquestion(event) {
if (event.target.className === "btn") {
// ... 处理答案逻辑,计算分数或扣除时间 ...
currentQuestion++; // 移动到下一个问题
displayQuestion(); // 显示下一个问题
}
};这段代码的问题在于,它在 currentQuestion 递增之后,直接调用 displayQuestion() 来显示下一个问题,而没有检查是否已经没有更多问题了。如果 currentQuestion 超出了 questionKey 数组的范围,displayQuestion() 将尝试访问一个不存在的索引,可能导致错误,更重要的是,游戏不会进入结束状态。
解决方案:检查问题完成状态
要解决这个问题,我们需要在每次处理完一个问题并准备显示下一个问题之前,增加一个逻辑判断:检查 currentQuestion 是否已经达到了问题数组的总长度。如果达到,则意味着所有问题都已回答完毕,此时应该立即调用 gameOver() 函数来结束游戏,并停止计时器。
小爱开放平台
小米旗下小爱开放平台
291
查看详情
以下是修改后的 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 函数 ...解释:
- currentQuestion++: 在玩家选择一个答案后,currentQuestion 递增,指向下一个问题。
- if (currentQuestion === questionKey.length): 这是核心判断。questionKey.length 返回问题数组中问题的总数。由于数组索引是从 0 开始的,当 currentQuestion 的值等于 questionKey.length 时,意味着我们已经遍历并回答了所有问题(例如,如果总共有 5 个问题,索引从 0 到 4,那么当 currentQuestion 变为 5 时,所有问题都已回答)。
- clearInterval(timeInterval): 在所有问题回答完毕后,计时器就不再需要运行了。调用 clearInterval 函数并传入 setInterval 返回的 ID (timeInterval),可以停止计时器。请确保 timeInterval 是在 startTimer 函数外部声明的,以便 nextquestion 函数可以访问它。
- gameOver(): 立即调用 gameOver() 函数,将游戏切换到结束页面,并显示最终分数。
- else { displayQuestion(); }: 如果还有未回答的问题,则继续调用 displayQuestion() 来显示下一个问题。
完整示例代码
为了更清晰地展示,以下是包含上述修改的完整 J*aScript 代码片段:
// 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;
}注意事项与最佳实践
以上就是J*aScript 测验游戏:实现所有问题回答完毕后立即结束游戏的详细内容,更多请关注其它相关文章!
# 连接到
# 品牌seo招商加盟项目
# 黔南州营销推广网站推广
# 惠阳家装网站建设项目
# seo快速金手指下拉五
# 关键词排名退后怎么解决
# 谷歌seo优化公司安丘
# 仁怀探店推广员招聘网站
# 短视频seo河南
# 数字营销技术应用初级app推广
# 邢台旅游网站建设
# 这是
# 的是
# javascript
# 一个问题
# 零时
# 都已
# 完毕后
# 小爱
# 置顶
# 计时器
# 游戏本
# ssl
# html
# java
相关栏目:
【
科技资讯46185 】
【
网络学院92790 】
相关推荐:
b站如何看历史记录_b站观看历史找回方法
Adobe PDF表单中利用J*aScript解析与格式化日期组件的教程
LocoySpider如何部署到云服务器_LocoySpider云部署的远程配置
处理嵌套交互式控件:前端可访问性指南
绝地鸭卫平a核爆刀流玩法攻略
淘宝网网页版登录入口 淘宝官方网页版快捷登录
解决 MongoDB 聚合查询中对象数组 _id 匹配问题
深入理解Go语言中Map值与方法接收器的交互:为什么需要临时变量
深入理解J*a链表中的IPosition接口与使用
从J*aScript对象中精确提取指定属性的教程
在python-socketio事件处理器中安全访问Flask应用上下文
必由学登录入口 必由学官方网站在线访问链接
没有大陆身份证/银行卡如何实名微信? 亲测有效的几种方法分享
QQ网页版官方账号入口 QQ网页版网页版登录指南
LINQ to XML为何解析失败? 深入理解C# XDocument的异常处理
C++如何实现单例模式_C++设计模式之线程安全的单例写法
Pygame教程:解决用户输入与游戏状态更新不同步问题
怎么在html里运行vbs脚本_html中运行vbs脚本方法【教程】
Win11怎么关闭触摸屏_Windows 11禁用HID符合标准触摸屏
一加手机拍照效果不好怎么办 一加哈苏影像调校与专业模式使用教程【高手篇】
抖音商城签到领现金是真的吗_抖音商城签到奖励与提现说明
夸克AO3官网入口_AO3镜像网站2025推荐
响应式CSS Grid布局:优化网格项在小屏幕下的堆叠与宽度适配
2025俄罗斯Yandex最新入口 官方网站地址及浏览器下载指南
163邮箱登录密码 163邮箱忘记密码找回
顺丰快递查询系统 官方正版查询入口
利用5118提升短视频内容效果_5118短视频关键词优化方法
CSS自定义字体样式被系统字体替换怎么办_font-face方式指定font-display控制渲染策略
批改网学生版PC登录 批改网官网登录系统入口
Golang如何优化内存分配与垃圾回收_Golang内存管理与GC优化实践
Go语言中Map值调用指针接收器方法的限制与应对
C++ typeid如何获取类型信息_C++ RTTI运行时类型识别用法
Lar*el表单中优雅地处理“返回”按钮以规避验证:最佳实践指南
Angular响应式表单:实现提交后表单及按钮的禁用与只读化
高德地图沿途添加点失败如何解决 高德多点规划方法
今日头条怎么同步内容到抖音_今日头条内容同步到抖音教程
CSS实现侧边栏导航项全宽圆角悬停背景效果
Go调试环境为何无法启动_Go调试器启动失败原因与解决策略
J*aScript Promise链中如何正确终止后续.then执行并处理错误
CSS布局中意外空白:解决padding-top导致的顶部间距问题
Golang如何实现状态模式管理对象状态_Golang State模式实现技巧
海棠电脑版入口_通过电脑访问海棠官网阅读
sublime怎么覆盖插件的默认快捷键_sublime快捷键优先级与设置
1688商家版怎样分析买家画像精准供货_1688商家版分析买家画像精准供货【供货策略】
qq游戏手机版下载安装_qq游戏移动端入口
MAC怎么让Dock栏只显示当前运行的应用_MAC终端命令实现极简Dock栏
解决Python单元测试中Mock异常方法调用计数为零的问题
天猫双十一预售商品怎么退款_天猫双十一预售退款操作指南
Golang如何实现容器化日志收集与分析_Golang容器日志收集分析方法
抓大鹅解压小游戏 抓大鹅摸鱼解压入口


2025-10-25
浏览次数:次
返回列表
"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;
}