
本文将详细介绍如何在 j*ascript 测验游戏中,确保当所有问题都被回答完毕时,游戏能够立即结束,而无需等待计时器归零。我们将分析现有代码中的不足,并提供一个简洁有效的解决方案,通过检查当前问题索引与问题总数的逻辑,实现游戏的即时终止,并停止计时器。
在开发基于 J*aScript 的测验(Quiz)游戏时,一个常见的需求是游戏不仅要在计时器归零时结束,还应在所有问题都被回答完毕后立即终止。本文将深入探讨如何优雅地实现这一功能,确保用户体验的流畅性。
在许多测验游戏的初始实现中,游戏结束的逻辑往往主要依赖于计时器。例如,当计时器倒计时到零时,游戏才进入结束状态。然而,如果玩家在计时器到期之前回答完了所有问题,游戏却仍然停留在最后一个问题界面,等待计时器走完,这会造成不必要的延迟和用户困惑。
我们来看一个典型的 nextquestion 函数实现:
function nextquestion(event) {
if (event.target.className === "btn") {
// ... 处理答案逻辑,计算分数或扣除时间 ...
currentQuestion++; // 移动到下一个问题
displayQuestion(); // 显示下一个问题
}
};这段代码的问题在于,它在 currentQuestion 递增之后,直接调用 displayQuestion() 来显示下一个问题,而没有检查是否已经没有更多问题了。如果 currentQuestion 超出了 questionKey 数组的范围,displayQuestion() 将尝试访问一个不存在的索引,可能导致错误,更重要的是,游戏不会进入结束状态。
要解决这个问题,我们需要在每次处理完一个问题并准备显示下一个问题之前,增加一个逻辑判断:检查 currentQuestion 是否已经达到了问题数组的总长度。如果达到,则意味着所有问题都已回答完毕,此时应该立即调用 gameOver() 函数来结束游戏,并停止计时器。
即梦AI
一站式AI创作平台,免费AI图片和视频生成。
16094
查看详情
以下是修改后的 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 函数 ...解释:
为了更清晰地展示,以下是包含上述修改的完整 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 测验游戏:实现所有问题回答完毕后立即结束游戏的详细内容,更多请关注其它相关文章!
# java
# javascript
# 一个问题
# 双击
# 零时
# 都已
# 完毕后
# 计时器
# 游戏本
# ssl
# html
# seo文案写作技巧
# 沈阳网站建设包括什么
# 房产网站建设的基本步骤
# 抖音互联网营销推广方案
# 小程序怎样营销推广
# 河北大型网站建设检修
# 福州小程序网站建设开发
# 飞翔网站建设美丽中国
# 北京seo seo柯南
# 江门营销推广招聘网站
# 的是
# 自适应
# 全选
# 第三方
相关栏目:
【
Google疑问12 】
【
Facebook疑问10 】
【
优化推广96088 】
【
技术知识133117 】
【
IDC资讯59369 】
【
网络运营7196 】
【
IT资讯61894 】
相关推荐:
《一起考教师》账号注销方法
Flexbox布局实践:实现底部页脚与顶部粘性导航条的完美结合
MySQL多重关联查询:利用别名高效获取同一表的多个关联字段
如何在 WordPress 前端实现内容提交:古腾堡编辑器的替代方案与实践
海外搜索引擎推广效果怎么样,怎么分析效果!
折叠屏手机充不进电是什么问题? 特殊结构带来的维修难点
深入理解随机递归函数的确定性:内部节点、叶节点与时间复杂度分析
《淘宝联盟》推广自己的店铺方法
钉钉任务无法提醒如何处理 钉钉任务提醒优化方法
mysql中如何配置字符集和排序规则_mysql字符集排序配置
键盘保修需要什么_键盘售后维修流程
TikTok视频播放不流畅怎么办 TikTok视频播放优化方法
126手机126邮箱登录_126邮箱手机登录入口官网
哔哩哔哩黑名单怎么查看
Win10如何关闭开机锁屏界面_Windows10跳过锁屏直接登录设置
在Peewee中处理PostgreSQL记录重复:一站式数据摄取教程
POKI小游戏在线免费入口链接 POKI小游戏无下载秒玩玩
126邮箱申请入口官网_126邮箱注册免费登录2025
小红书网页版怎么进 小红书网页版通用入口
《i莞家》修改昵称方法
Composer如何使用composer-plugin-api开发自定义插件
手机雨课堂网页版入口免登录 雨课堂网页版可点击直接进入
电脑开不了机怎么办 电脑无法开机的解决方法
XPath动态元素定位:如何精准选择文本内容变化的元素
感染了幽门螺杆菌一定会导致胃癌吗?蚂蚁庄园今日答案最新11.30
PDF如何批量加注释_PDF多文件批注高亮操作教程
Pandas中基于动态偏移量实现DataFrame列值位移的策略
解决CSS容器溢出问题:使用calc()实现精确布局与边距控制
铁路12306怎么申请退票_铁路12306退票申请操作流程
如何在CSS中使用伪类选择器_hover实现悬停效果
从J*a应用程序中导出MySQL表数据的技术指南
Python对象引用与属性赋值:理解链表中的行为
除了Copilot,还有哪些值得一试的VS Code AI插件?
有道AI翻译入口 智能写作官方网站入口
WooCommerce 购物车:始终显示所有交叉销售商品
基于键值条件高效映射 Pandas DataFrame 多列数据
《东方财富》条件单关闭方法
更换小红书群背景怎么换?小红书群规则怎么设置?
MySQL多重JOIN技巧:高效关联同一表获取多角色信息
海棠阅读网页版_进入海棠网页版在线阅读中心
WPS长文档分栏排版不乱方法_WPS分栏+分节符报纸排版教程
汽水音乐网页端访问 汽水音乐官方网页直达
QQ邮箱注册地址 免费获取QQ邮箱账号
TikTok网页版实时观看入口 TikTok网页版短视频在线浏览
AO3永久镜像入口开放_AO3最新网址兼容所有浏览器
GBA模拟器手柄按键设置
j*a中ArrayBlockingQueue的使用
PHP魔术方法__set与__isset:设计考量、性能权衡与静态分析的视角
多闪电脑版下载_多闪PC端模拟器使用
Word如何将文字快速转成表格 Word文本转换成表格功能使用技巧【效率】
2025-10-25
运城市盐湖区信雨科技有限公司是一家深耕海外推广领域十年的专业服务商,作为谷歌推广与Facebook广告全球合作伙伴,聚焦外贸企业出海痛点,以数字化营销为核心,提供一站式海外营销解决方案。公司凭借十年行业沉淀与平台官方资源加持,打破传统外贸获客壁垒,助力企业高效开拓全球市场,成为中小企业出海的可靠合作伙伴。