JavaScript案例(乘法答题游戏)

项目概述

使用原生JavaScript实现一个乘法答题游戏,随机生成乘法题目,判断答案正误并记录分数,通过localStorage实现分数持久化存储。

核心功能需求

  1. 随机题目生成:动态生成1-10之间的乘法题
  2. 答题交互:输入答案并提交,支持回车提交
  3. 正误判定:判断答案正确性并给出视觉反馈
  4. 积分系统:答对加分,记录当前分数和历史最高分
  5. 分数持久化:使用localStorage保存分数数据
  6. 游戏控制:支持重新开始游戏

技术栈

  • HTML5:页面结构
  • CSS3:样式设计,包括答题状态反馈
  • JavaScript:题目生成、答案验证、分数管理、本地存储
  • 本地存储:localStorage API

项目结构

multiplication-game/
├── index.html      # 游戏主页面
├── css/
│   └── style.css   # 样式文件
├── js/└── game.js     # 游戏核心逻辑

实现思路

1. 数据结构设计

// 游戏状态对象
const gameState = {currentScore: 0,       // 当前分数highScore: 0,          // 历史最高分num1: 0,               // 第一个乘数num2: 0,               // 第二个乘数currentAnswer: 0,      // 当前题目正确答案streak: 0,             // 连续答对次数maxStreak: 0           // 最大连续答对次数
};

2. 核心功能模块

  • 题目生成模块:使用Math.random()生成随机乘数
  • 答案验证模块:比较用户输入与正确答案
  • 分数管理模块:更新分数、记录最高分
  • 本地存储模块:保存和读取分数数据
  • UI交互模块:更新界面、反馈答题结果

3. 关键技术点实现

  • 随机数生成Math.floor(Math.random() * 10) + 1生成1-10的随机数
  • 本地存储localStorage.setItem()localStorage.getItem()实现数据持久化
  • 事件处理:监听表单提交和键盘事件
  • 状态反馈:通过CSS类切换实现正确/错误状态样式

代码:

  • index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>乘法答题游戏 | Math Multiplication Game</title><link rel="stylesheet" href="css/style.css"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body><div class="game-container"><header><h1>乘法答题挑战 <i class="fas fa-calculator"></i></h1><p>测试你的乘法计算能力,挑战最高分!</p></header><div class="score-board"><div class="score-item"><span class="label">当前分数</span><span id="currentScore" class="score">0</span></div><div class="score-item"><span class="label">历史最高分</span><span id="highScore" class="score">0</span></div></div><div class="game-card"><div class="problem"><span id="num1">?</span><span class="operator">×</span><span id="num2">?</span><span class="equal">=</span><form id="answerForm"><input type="number" id="answerInput" placeholder="输入答案" autocomplete="off" required><button type="submit" id="submitBtn">提交 <i class="fas fa-paper-plane"></i></button></form></div><div id="feedback" class="feedback hidden"></div><div class="controls"><button id="restartBtn"><i class="fas fa-sync-alt"></i> 重新开始</button></div></div><div class="game-stats"><div class="stat-item"><i class="fas fa-fire"></i><span>当前连击: <span id="currentStreak">0</span></span></div><div class="stat-item"><i class="fas fa-trophy"></i><span>最大连击: <span id="maxStreak">0</span></span></div></div></div><script src="js/game.js"></script>
</body>
</html>
  • style.css
* {margin: 0;padding: 0;box-sizing: border-box;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}body {background-color: #f0f4f8;color: #333;line-height: 1.6;min-height: 100vh;display: flex;justify-content: center;align-items: center;padding: 20px;
}.game-container {width: 100%;max-width: 600px;margin: 0 auto;
}header {text-align: center;margin-bottom: 30px;
}header h1 {font-size: 2.2rem;color: #2c3e50;margin-bottom: 10px;display: flex;align-items: center;justify-content: center;gap: 15px;
}header p {color: #7f8c8d;font-size: 1.1rem;
}/* 分数面板 */
.score-board {display: flex;justify-content: space-around;margin-bottom: 25px;background-color: white;border-radius: 12px;padding: 15px;box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}.score-item {text-align: center;
}.label {display: block;font-size: 0.9rem;color: #7f8c8d;margin-bottom: 5px;
}.score {font-size: 1.8rem;font-weight: bold;color: #2c3e50;
}/* 游戏卡片 */
.game-card {background-color: white;border-radius: 15px;padding: 30px;box-shadow: 0 6px 20px rgba(0,0,0,0.08);margin-bottom: 25px;
}/* 题目区域 */
.problem {display: flex;align-items: center;justify-content: center;flex-wrap: wrap;gap: 15px;margin-bottom: 25px;
}.problem span {font-size: 2.5rem;font-weight: bold;color: #2c3e50;
}.operator, .equal {color: #7f8c8d;
}#answerForm {display: flex;gap: 10px;flex: 0 0 180px;
}#answerInput {width: 100%;padding: 12px 15px;border: 2px solid #ddd;border-radius: 8px;font-size: 1.2rem;text-align: center;transition: all 0.3s ease;
}#answerInput:focus {outline: none;border-color: #3498db;box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}#submitBtn {padding: 12px 20px;background-color: #3498db;color: white;border: none;border-radius: 8px;cursor: pointer;font-size: 1rem;transition: background-color 0.3s ease;display: flex;align-items: center;gap: 8px;
}#submitBtn:hover {background-color: #2980b9;
}/* 反馈区域 */
.feedback {padding: 15px;border-radius: 8px;text-align: center;font-size: 1.1rem;margin-bottom: 20px;transition: all 0.3s ease;
}.correct {background-color: rgba(46, 204, 113, 0.1);color: #27ae60;border: 1px solid #2ecc71;
}.incorrect {background-color: rgba(231, 76, 60, 0.1);color: #e74c3c;border: 1px solid #e74c3c;
}.hidden {display: none;
}/* 控制按钮 */
.controls {text-align: center;
}#restartBtn {padding: 10px 20px;background-color: #95a5a6;color: white;border: none;border-radius: 8px;cursor: pointer;font-size: 1rem;transition: all 0.3s ease;display: flex;align-items: center;gap: 8px;justify-content: center;
}#restartBtn:hover {background-color: #7f8c8d;
}/* 游戏统计 */
.game-stats {display: flex;justify-content: space-around;background-color: white;border-radius: 12px;padding: 15px;box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}.stat-item {display: flex;align-items: center;gap: 8px;color: #7f8c8d;font-size: 0.95rem;
}.stat-item i {color: #f39c12;
}.stat-item span {font-weight: 500;
}/* 响应式设计 */
@media (max-width: 500px) {.problem {flex-direction: column;gap: 10px;}.problem span {font-size: 2rem;}#answerForm {flex: 0 0 100%;}.score-board {flex-direction: column;gap: 15px;}.game-stats {flex-direction: column;gap: 10px;text-align: center;}.stat-item {justify-content: center;}
}
  • game.js
const gameState = {currentScore: 0,highScore: 0,num1: 0,num2: 0,currentAnswer: 0,streak: 0,maxStreak: 0
};// DOM元素
const num1El = document.getElementById('num1');
const num2El = document.getElementById('num2');
const answerInput = document.getElementById('answerInput');
const answerForm = document.getElementById('answerForm');
const feedbackEl = document.getElementById('feedback');
const currentScoreEl = document.getElementById('currentScore');
const highScoreEl = document.getElementById('highScore');
const restartBtn = document.getElementById('restartBtn');
const currentStreakEl = document.getElementById('currentStreak');
const maxStreakEl = document.getElementById('maxStreak');// 初始化游戏
function initGame() {// 从本地存储加载分数loadScores();// 生成第一题generateProblem();// 绑定事件监听器bindEvents();// 更新UI显示updateStats();
}// 从本地存储加载分数
function loadScores() {const savedScores = localStorage.getItem('multiplicationGameScores');if (savedScores) {const scores = JSON.parse(savedScores);gameState.highScore = scores.highScore || 0;gameState.maxStreak = scores.maxStreak || 0;}
}// 保存分数到本地存储
function saveScores() {const scoresToSave = {highScore: gameState.highScore,maxStreak: gameState.maxStreak};localStorage.setItem('multiplicationGameScores', JSON.stringify(scoresToSave));
}// 生成新题目
function generateProblem() {// 生成1-10之间的随机数gameState.num1 = Math.floor(Math.random() * 10) + 1;gameState.num2 = Math.floor(Math.random() * 10) + 1;gameState.currentAnswer = gameState.num1 * gameState.num2;// 更新UI显示题目num1El.textContent = gameState.num1;num2El.textContent = gameState.num2;// 清空输入框并聚焦answerInput.value = '';answerInput.focus();// 隐藏反馈feedbackEl.classList.add('hidden');
}// 检查答案
function checkAnswer(userAnswer) {const isCorrect = userAnswer === gameState.currentAnswer;// 显示反馈showFeedback(isCorrect);if (isCorrect) {// 答对处理handleCorrectAnswer();} else {// 答错处理handleWrongAnswer();}// 短暂延迟后生成新题目setTimeout(generateProblem, 1500);
}// 显示答题反馈
function showFeedback(isCorrect) {feedbackEl.classList.remove('hidden', 'correct', 'incorrect');if (isCorrect) {feedbackEl.classList.add('correct');feedbackEl.innerHTML = `<i class="fas fa-check-circle"></i> 正确!答案是 ${gameState.currentAnswer}`;} else {feedbackEl.classList.add('incorrect');feedbackEl.innerHTML = `<i class="fas fa-times-circle"></i> 错误,正确答案是 ${gameState.currentAnswer}`;}
}// 处理正确答案
function handleCorrectAnswer() {// 增加分数gameState.currentScore += 10;// 增加连击数gameState.streak++;// 更新最大连击数if (gameState.streak > gameState.maxStreak) {gameState.maxStreak = gameState.streak;}// 检查是否打破最高分记录if (gameState.currentScore > gameState.highScore) {gameState.highScore = gameState.currentScore;}// 保存分数saveScores();// 更新UIupdateStats();// 添加答题正确动画效果document.querySelector('.game-card').classList.add('correct-animation');setTimeout(() => {document.querySelector('.game-card').classList.remove('correct-animation');}, 500);
}// 处理错误答案
function handleWrongAnswer() {// 重置连击数gameState.streak = 0;// 更新UIupdateStats();// 添加答题错误动画效果document.querySelector('.game-card').classList.add('wrong-animation');setTimeout(() => {document.querySelector('.game-card').classList.remove('wrong-animation');}, 500);
}// 更新游戏统计信息UI
function updateStats() {currentScoreEl.textContent = gameState.currentScore;highScoreEl.textContent = gameState.highScore;currentStreakEl.textContent = gameState.streak;maxStreakEl.textContent = gameState.maxStreak;
}// 重置游戏
function resetGame() {// 重置当前分数和连击gameState.currentScore = 0;gameState.streak = 0;// 更新UIupdateStats();// 生成新题目generateProblem();// 显示重置反馈feedbackEl.classList.remove('hidden', 'correct', 'incorrect');feedbackEl.innerHTML = '<i class="fas fa-gamepad"></i> 游戏已重置,开始新挑战吧!';
}// 绑定事件监听器
function bindEvents() {// 答案提交表单answerForm.addEventListener('submit', (e) => {e.preventDefault();const userAnswer = parseInt(answerInput.value, 10);if (!isNaN(userAnswer)) {checkAnswer(userAnswer);}});// 重新开始按钮restartBtn.addEventListener('click', resetGame);// 添加键盘事件支持answerInput.addEventListener('focus', () => {answerInput.select();});
}// 添加CSS动画样式
const style = document.createElement('style');
style.textContent = `.correct-animation {animation: correctPulse 0.5s ease-in-out;}.wrong-animation {animation: wrongShake 0.5s ease-in-out;}@keyframes correctPulse {0% { box-shadow: 0 6px 20px rgba(0,0,0,0.08); }50% { box-shadow: 0 6px 20px rgba(46, 204, 113, 0.3); }100% { box-shadow: 0 6px 20px rgba(0,0,0,0.08); }}@keyframes wrongShake {0%, 100% { transform: translateX(0); }25% { transform: translateX(-10px); }50% { transform: translateX(10px); }75% { transform: translateX(-10px); }}
`;
document.head.appendChild(style);// 初始化游戏
document.addEventListener('DOMContentLoaded', initGame);

效果展示:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/917639.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/917639.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

EXCEL删除数据透视表

wps版 点击红框内任意区域 在顶部工具栏选择删除Excel 版 1.点击红框内任意区域2. 点击Enable Selection,再按住键盘上的Delete键&#xff0c;记住不是Backspace键

Python 飞机大战:从零开发经典 2D 射击游戏

引言&#xff1a;重温经典游戏开发 飞机大战作为经典的 2D 射击游戏&#xff0c;承载了许多人的童年回忆。使用 Python 和 Pygame 开发这样一款游戏不仅能重温经典&#xff0c;更是学习游戏开发绝佳的实践项目。本文将带你从零开始&#xff0c;一步步实现一个完整的飞机大战游…

Vue项目中实现浏览器串口通信:Web Serial API完整指南

前言 在现代Web开发中&#xff0c;随着IoT设备和硬件交互需求的增长&#xff0c;浏览器与串口设备的通信变得越来越重要。本文将详细介绍如何在Vue项目中使用Web Serial API实现串口通信功能&#xff0c;为开发者提供一个完整的解决方案。 技术背景 传统方案的局限性 传统的串口…

Github怎么只下载某个目录文件?(Git稀疏检出、GitZip for Github插件、在线工具DownGit)Github下载目录

文章目录**方法一&#xff1a;使用 Git 的稀疏检出&#xff08;Sparse Checkout&#xff09;**&#xff08;略&#xff09;**步骤&#xff1a;****方法二&#xff1a;使用 SVN 下载特定目录**&#xff08;略&#xff09;**步骤&#xff1a;****方法三&#xff1a;使用浏览器插件…

把“多视图融合、深度传感”组合在一起,今天分享3篇3D传感技术干货

关注gongzhonghao【计算机sci论文精选】3D传感技术起源于工业领域高精度测量需求&#xff0c;早期以激光三角测量、结构光等技术为主&#xff0c;主要服务于制造业的零部件检测与形变分析。随着消费电子智能化升级&#xff0c;苹果iPhone X的Face ID将结构光技术推向大众市场&a…

dubbo源码之消费端启动的高性能优化方案

一、序言 dubbo作为一款最流行的服务治理框架之一,在底层做了很多的优化,比如消费端在启动的时候做了很多性能提升的设计,接下来从连接的层面、序列化功能的层面进行介绍下。 二、优化点 1、消费端在服务启动的时候会调用DubboProtocol类的protocolBindingRefer方法来创建…

zookeeper常见命令和常见应用

前言 ZooKeeper自带一个交互式命令行工具&#xff08;通过zkCli.sh或zkCli.cmd启动&#xff09;&#xff0c;提供了一系列操作ZooKeeper数据节点的命令 下面我们对zookeeper常用命令进行介绍 使用prettyZoo命令行窗口 使用prettyZoo客户端链接zookeeper 打开zookeeper命令…

前端异步任务处理总结

一、异步任务常见场景网络请求&#xff1a;fetch()、axios 等 API 调用定时操作&#xff1a;setTimeout、setInterval用户交互&#xff1a;事件监听回调资源加载&#xff1a;图片/脚本动态加载Web Workers&#xff1a;后台线程计算二、核心处理方案1. Promise&#xff08;ES6&a…

机器学习第三课之逻辑回归(二)LogisticRegression

目录 简介 一.分类评估⽅法 1.混淆矩阵 2.精确率(Precision)与召回率(Recall) 3.F1-score 4.分类评估报告api 2.正则化惩罚 3.⽋拟合和过拟合 4.K折交叉验证 5.代码分析 简介 接上一篇博客最后 机器学习第二课之逻辑回归&#xff08;一&#xff09;LogisticRegres…

基于ELK Stack的实时日志分析与智能告警实践指南

基于ELK Stack的实时日志分析与智能告警实践指南 一、业务场景描述 在生产环境中&#xff0c;服务实例数量众多&#xff0c;日志量激增&#xff0c;传统的文本 grep 或 SSH 登录方式已无法满足实时监控与故障定位需求。我们需要搭建一个可扩展、低延迟的日志收集与分析平台&…

需求变更过程中出现的团队资源冲突问题处理的一些小技巧

​​一、资源冲突的典型场景​​ ​​技术资源争夺​​:多个需求同时需要同一开发人员或技术专家支持 ​​人力资源过载​​:突发需求导致团队成员工作量超负荷(如同时处理3个紧急需求) ​​设备/环境冲突​​:测试服务器资源不足或特定开发工具许可证被占用 ​​跨团队协…

基于Matlab图像处理的液晶显示器表面缺陷检测与分类研究

本课题设计并实现了一种基于 MATLAB 的图像缺陷检测系统&#xff0c;系统集成中值滤波、对比度增强、梯度检测与区域分析等图像处理技术&#xff0c;能够对图像中的点状、线状和块状缺陷进行有效识别与分类。用户可通过图形用户界面&#xff08;GUI&#xff09;导入待测图像&am…

prometheus应用demo(一)接口监控

目录 完整代码&#xff08;纯Cursor生成&#xff09; 1、pom 2、配置和启动类 3、自定义指标bean 4、上报 5、业务代码 一、统计API请求&#xff08;次数、响应码等&#xff09; 1、统计总数 关键代码&#xff1a; &#xff08;1&#xff09;自定义指标DTO &#xff0…

逃离智能家居“孤岛”!用 Home Assistant 打造你的全屋互联自由王国

文章目录&#x1f914; 痛点暴击&#xff1a;智能家居的“巴别塔困境”&#x1f6e0;️ Home Assistant 是个啥&#xff1f;简单粗暴版定义&#x1f50d; 硬核拆解&#xff1a;Home Assistant 的魅力之源&#x1f680; 上车指南&#xff1a;如何开始你的 HA 之旅&#xff1f;第…

数据结构:如何判断一个链表中是否存在环(Check for LOOP in Linked List)

目录 初始思考&#xff1a;什么叫“链表有环”&#xff1f; ❌ 第一种直接想法&#xff08;失败&#xff09;&#xff1a;我们是不是能“记住走过的节点”&#xff1f; 那我们换一个思路&#xff1a;我们能否只用两个指针来检测环&#xff1f; 第一步&#xff1a;定义两个指…

深入理解Java的SPI机制,使用auto-service库优化SPI

文章目录一、简介二、使用1、服务提供者&#xff08;或者第三方公共&#xff09;&#xff1a;定义接口2、服务提供者&#xff1a;定义实现类3、服务提供者&#xff1a;注册服务4、构建服务提供者jar包5、客户端&#xff1a;使用 ServiceLoader 来加载服务三、源码分析1、源码2、…

PPT自动化 python-pptx - 10 : 表格(tables)

在日常工作中&#xff0c;我们经常需要制作包含表格的 PowerPoint 演示文稿&#xff0c;以此清晰展示数据或文本信息。手动制作不仅耗时&#xff0c;当数据更新时还需重复操作&#xff0c;效率低下。而 python-pptx 库为我们提供了自动化操作 PowerPoint 表格的可能。本文将详细…

在安卓中使用 FFmpegKit 剪切视频并添加文字水印

在安卓中用到的三方库&#xff1a;https://github.com/arthenica/ffmpeg-kit 这个库很强大&#xff0c;支持很多平台&#xff0c;每个平台都有各自的分支代码&#xff0c;用了一段时间&#xff0c;稳定性挺好的&#xff0c; 找到安卓下的分支&#xff1a;FFmpegKit for Andro…

Flask + HTML 项目开发思路

Flask HTML 项目开发思路&#xff1a;以公共资源交易信息展示为例 一、开篇明义——为什么选 Flask 框架 在众多 Python Web 框架&#xff08;如 Django、Tornado 等&#xff09;里&#xff0c;本次项目坚定选择 Flask&#xff0c;背后有清晰的技术考量&#xff1a; 1. 轻量…

Vue中:deep()和 ::v-deep选择器的区别

在 Vue.js 中&#xff0c;:deep()和 ::v-deep都是用于穿透组件作用域的深度选择器&#xff0c;但它们在语法、适用场景和版本支持上存在区别。以下是两者的核心差异&#xff1a;一、​​语法与用法​ &#xff1a;Vue2中用 ::v-deep&#xff0c;Vue2中不支持:deep()&#xff0c…