<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>猜數字遊戲</title>
<style>
body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; padding: 1rem; }
#result { font-size: 1.2rem; margin-top: 1rem; white-space: pre-wrap; }
button { padding: 0.5rem 1rem; font-size: 1rem; cursor: pointer; }
</style>
</head>
<body>
<h1>猜數字遊戲 (1~100)</h1>
<button id="startBtn">開始新遊戲</button>
<div id="result"></div>
<script>
const startBtn = document.getElementById('startBtn');
const resultDiv = document.getElementById('result');
startBtn.addEventListener('click', playGame);
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function playGame() {
const answer = getRandomNum(1, 100);
let attempts = 0;
const maxAttempts = 10;
resultDiv.textContent = '遊戲開始!請輸入 1~100 之間的數字。';
function askGuess() {
if (attempts >= maxAttempts) {
resultDiv.textContent += `\n機會用盡!正確答案是 ${answer}。`;
return;
}
const input = prompt(`第 ${attempts + 1} 次猜測 (還有 ${maxAttempts - attempts} 次機會):`);
if (input === null) { // 使用者按取消
resultDiv.textContent += '\n遊戲已取消。';
return;
}
const guess = parseInt(input, 10);
if (isNaN(guess) || guess < 1 || guess > 100) {
alert('請輸入 1 到 100 之間的有效數字!');
askGuess(); // 重新詢問,不消耗次數
return;
}
attempts++;
if (guess === answer) {
resultDiv.textContent += `\n🎉 恭喜!你在第 ${attempts} 次猜中了!答案就是 ${answer}。`;
} else if (guess < answer) {
resultDiv.textContent += `\n第 ${attempts} 次:${guess} — 太小了!`;
askGuess();
} else {
resultDiv.textContent += `\n第 ${attempts} 次:${guess} — 太大了!`;
askGuess();
}
}
askGuess();
}
</script>
</body>
</html>
Math.floor(Math.random() * (max - min + 1)) + min 確保包含邊界值。askGuess() 函式自我呼叫,直到猜中或次數用盡,邏輯清晰。isNaN 與範圍,避免非數字或超出範圍輸入消耗機會。prompt 互動,結果累積顯示於頁面,並支援「取消」離開。localStorage。prompt,避免瀏覽器封鎖彈窗。這個小遊戲雖然簡單,但涵蓋了隨機數、迴圈/遞迴、條件判斷、DOM 操作與事件處理等 JavaScript 核心概念,非常適合初學者練手。