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
英文地址,請注明出處:http://en.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…