項目概述
使用原生JavaScript實現一個乘法答題游戲,隨機生成乘法題目,判斷答案正誤并記錄分數,通過localStorage實現分數持久化存儲。
核心功能需求
- 隨機題目生成:動態生成1-10之間的乘法題
- 答題交互:輸入答案并提交,支持回車提交
- 正誤判定:判斷答案正確性并給出視覺反饋
- 積分系統:答對加分,記錄當前分數和歷史最高分
- 分數持久化:使用localStorage保存分數數據
- 游戲控制:支持重新開始游戲
技術棧
- 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);
效果展示: