萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 猜數字遊戲:經典入門小專案完整實作

遊戲規則

  • 系統隨機產生 1~100 之間的整數。
  • 玩家擁有 10 次猜測機會。
  • 每次猜測後提示「太大」、「太小」或「正確」。
  • 猜中或用盡機會即結束遊戲。

完整程式碼

<!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>

關鍵點解析

  1. 隨機數產生: 使用 Math.floor(Math.random() * (max - min + 1)) + min 確保包含邊界值。
  2. 遞迴詢問: askGuess() 函式自我呼叫,直到猜中或次數用盡,邏輯清晰。
  3. 輸入驗證: 檢查 isNaN 與範圍,避免非數字或超出範圍輸入消耗機會。
  4. 使用者體驗: 以 prompt 互動,結果累積顯示於頁面,並支援「取消」離開。

進階擴充建議

  • 加入難度選擇(調整範圍與次數)。
  • 記錄最佳成績至 localStorage。
  • 改用表單輸入取代 prompt,避免瀏覽器封鎖彈窗。
  • 加入鍵盤事件監聽 (Enter 鍵送出)。

這個小遊戲雖然簡單,但涵蓋了隨機數、迴圈/遞迴、條件判斷、DOM 操作與事件處理等 JavaScript 核心概念,非常適合初學者練手。

copyright © 萬盛學電腦網 all rights reserved