【问题标题】:Trying to make a randomly generated number guessing game尝试制作一个随机生成的数字猜谜游戏
【发布时间】:2015-07-10 02:50:11
【问题描述】:

我应该做一个随机数猜谜游戏。

所以我知道我需要随机生成一个介于 0 到 50 之间的数字,并且用户需要猜测。根据他们的猜测,我必须告诉他们它们是太低还是太高。

这是我目前所做的,但我不知道接下来我应该做什么。 (或者如果它是正确的。)

<!DOCTYPE html>
<html>
<head>
    <title>Number Game</title>
</head>
<body>
    <h2>I'm thinking of a number between 0 and 50...</h2>
    <div id="output"></div>
    <input id="txtInput" /><br>
    <button onClick="checkInput();genNum();">Is this your number?</button>
    <script src="js/main.js">
        var outputDiv = document.querySelector("#output");

        function checkInput() {
            var guess = parseInt(txtInput.value);
        }

        function genNum() {
            txtInput.value = Math.round(Math.random() * 50);
        }
    </script>
</body>
</html>

【问题讨论】:

  • 使用javascript的alertconsole.log进行调试。我们不是来写你的代码的。
  • 为什么每次用户猜测时你都在做genNum
  • 我不想让任何人写我的代码,我只想知道到目前为止是否有错误。我认为我需要 genNum 来生成他们应该猜测的随机数。就像我说的,不完全确定如何去做。

标签: javascript random


【解决方案1】:

首先,您在错误的位置生成数字。您应该在页面加载后以及每次单击按钮后立即执行此操作。将genNum 的输出存储在任何函数之外的变量中;在你的脚本标签中初始化一个像randomNum 这样的变量; var randomNum = 0;

您只需要获取checkInput中文本字段的值即可。

这样做:

var guessBox = document.getElementById('txtInput')
var theGuess = parseInt(guessBox.value)

然后,使用if 语句来确定theGuess 是高于还是低于randomNum。为此,请使用 &lt;&gt; 运算符。根据条件,将输出 div 的内容设置为:outputDiv.innerHTML = 'Your value was (something) than the real value'

之后,仍然在checkInput中,将randomNum变量重新赋值给genNum的输出:randNum = genNum()(需要注意的是,我们没有再次使用var关键字。

这应该让你知道该怎么做。

【讨论】:

    【解决方案2】:

    问题很少……

    1) script 元素不能同时包含 src 和 body 内容,如果要包含外部 js 脚本,请使用单独的 script 标签 2)单击按钮时,您需要生成随机数并根据输入中输入的值检查它

    var outputDiv = document.getElementById("output");
    var txtInput = document.getElementById("txtInput");
    
    function checkInput() {
      var guess = +txtInput.value, //convert the input value to number
        ran = genNum(); //generate a random number
      if (isNaN(guess)) { //if the entered value is not a numerical value
        outputDiv.innerHTML = 'Enter a number'
      } else if (guess == ran) { //if both values are same
        outputDiv.innerHTML = 'Correct'
      } else if (guess < ran) { //if we entered a lesser value
        outputDiv.innerHTML = 'Less:' + ran
      } else { //we entered a greater value
        outputDiv.innerHTML = 'More:' + ran
      }
    }
    
    function genNum() {
      return Math.round(Math.random() * 50);
    }
    <h2>I'm thinking of a number between 0 and 50...</h2>
    <div id="output"></div>
    <input id="txtInput" />
    <br>
    <button onClick="checkInput()">Is this your number?</button>

    脚本标签应该是

    <script src="js/main.js"></script>
    <script>
        var outputDiv = document.querySelector("#output");
    
        function checkInput() {
            var guess = parseInt(txtInput.value);
        }
    
        function genNum() {
            txtInput.value = Math.round(Math.random() * 50);
        }
    </script>
    

    【讨论】:

      【解决方案3】:

      所以,这听起来像是功课,所以让我们试着找出实现游戏所需的步骤。完成这些步骤后,在 Google 先生的帮助下,将其翻译成 html/js 或任何其他编程语言应该相对容易。

      1. Load: What do you need to be able to start a game?
          1.1 We need a secret random number
          1.2 We also need a way to let the user input his/her guess
          1.3 We need to let the user check if their guess is right
          1.4 We need a way to communicate the result to the user
      
      2. Start: Lets play!
          2.1 The user types a number
          2.2 The user confirms the number and sends it to be checked
          2.3 The game checks if the number is equal to the secret number, if not continue at 2.4
              2.3.1 The game communicates to the user that his/her guess was correct!
          2.4 The game checks if the number is less than the secret number, if not continue at 2.5
              2.4.1 The game communicates to the user that his/her guess was too low
              2.4.2 The user tries another guess, continue at 2.1
          2.5 The number must be greater than the secret number
              2.5.1 The game communicates to the user that his/her guess was too high
              2.5.2 The user tries another guess, continue at 2.1
      
      3. End: Want to play again?
          3.1 Restart
          3.2 Bye bye
      

      让我们开始把它变成代码

      // 1. Load: What do you need to be able to start a game?
      //     1.1 We need a secret random number in js
             var secretRandomNumber = Math.round(Math.random() * 50);
      //     1.2 We also need a way to let the user input his/her guess in html
             <input type="text" id="guess" />
      //     1.3 We need to let the user check if their guess is right in html
             <button onclick="checkGuess();">Guess!</button> 
      //     and in js
             function checkGuess(){
                  ???
             }
      //     1.4 We need a way to communicate the result to the user in html
             <div id="message"></div> 
      
      // 2. Start: Lets play!
      //     2.1 The user types a number
      //     2.2 The user confirms the number and sends it to be checked (presses the Guess button)
             var guess = document.getElementById('guess').value;
      //     2.3 The game checks if the number is equal to the secret number, if not continue at 2.4
                 if (guess == secretRandomNumber){ 
      //         2.3.1 The game communicates to the user that his/her guess was correct!
                     document.getElementById('message').innerHTML = 'Correct!';
                 }else
      //     2.4 The game checks if the number is less than the secret number, if not continue at 2.5
                 if (guess < secretRandomNumber){
      //         2.4.1 The game communicates to the user that his/her guess was too low
      //         2.4.2 The user tries another guess, continue at 2.1
                     document.getElementById('message').innerHTML = 'Too low, try again';
                 }else{
      //     2.5 The number must be greater than the secret number
      //         2.5.1 The game communicates to the user that his/her guess was too high
      //         2.5.2 The user tries another guess, continue at 2.1
                     document.getElementById('message').innerHTML = 'Too high, try again';
                 }
      
      // 3. End: Want to play again?
      //     3.1 Restart - generate a new secret random number
      //     3.2 Bye bye - close the page
      

      清理一下

          <input type="text" id="guess" />
          <button onclick="checkGuess();">Guess!</button>
          <div id="message"></div>
          <button onclick="generateSecretRandomNumber()">Restart</button>
      
          <script>
          var secretRandomNumber; // outside makes it available to other functions
          function generateSecretRandomNumber(){
             secretRandomNumber = Math.round(Math.random() * 50);
          }
      
          function checkGuess(){
              var guess = document.getElementById('guess').value;
              if (guess == secretRandomNumber){
                  document.getElementById('message').innerHTML = 'Correct!';
              }else if (guess < secretRandomNumber){
                  document.getElementById('message').innerHTML = 'Too low, try again';
              }else{
                  document.getElementById('message').innerHTML = 'Too high, try again';
              }
          }
      
          // make sure we have a brand new secret number once the page loads
          generateSecretRandomNumber();
          </script>
      

      现在您可以将其插入完整的 html 页面并调整其余部分,希望对您有所帮助:)

      【讨论】:

        【解决方案4】:

        首先,您不能在一次“onclick”中调用两个函数。您应该创建一个调用这两个函数的函数并将其用作“onclick”函数。下面是一些可以帮助您入门的内容:

          <!DOCTYPE html>
          <html>
        
          <head>
            <title>Number Game</title>
          </head>
          <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
          <body>
        
             <script>
        
                function theGuess() {
                    var guess = $('#txtInput').val();
        
                    return(Number(guess))
        
                };
        
        
                function highLow() {
                    // Generate a random number that is between 0 to 50
                    // Math.random() returns a random number between 0 and 1
                    var rand = Number(Math.random()*50);
                    var roundRand = Number(rand).toFixed(0);
                    // store user's guess as a variable
                    var userGuess = theGuess();
                    // validate the guess
                    if (userGuess > 50) {
                        return($('#output').html('Please enter a number that is between 0 and 50'));
                    } else if (isNaN(userGuess)){
                        return($('#output').html('Please enter a number, not any other data type'));
                    } 
                    // check equality of the guess
                    if (userGuess < roundRand){
                        $('#output').html("Too Low!");
                    } else if(userGuess > roundRand) {
                        $('#output').html("Too High!");
                    } else if(userGuess == roundRand)  {
                        $('#output').html("You guessed it!!");
                    }
                }
                // onclick function
                function answer() {
                    theGuess();
                    highLow();
                }
            </script>
            <h2>I'm thinking of a number between 0 and 50...</h2>
        
            <div id="output"></div>
            <input id="txtInput" />
              <br/>
            <button onclick="answer()">Is this your number?</button>
        
        
          </body>
        
        </html>
        

        您仍然乐于弄清楚如何验证输入;如何检查输入是否为空白? :)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-29
          • 1970-01-01
          • 2019-06-02
          • 1970-01-01
          • 1970-01-01
          • 2023-01-22
          相关资源
          最近更新 更多