【问题标题】:JS addition game: how do I display 4 possible answers, 3 of them are random and 1 is the correct answer ? (Codepen included)JS加法游戏:如何显示4个可能的答案,其中3个是随机的,1个是正确答案? (包括 Codepen)
【发布时间】:2017-10-17 20:32:04
【问题描述】:

我正在用 JS 构建游戏。游戏规则很简单:你会被问到 (num1) + (num2) 等于多少(正如你在 codepen 中看到的那样)。

在游戏中,您有 4 种可能的选择来回答问题。

我现在被困在创建那些可能的选项:我想显示三个错误的随机数和一个正确的数字。

我的 JS:

var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;

document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;

var options = {
    option1: document.getElementById('option1'),
    option2: document.getElementById('option2'),
    option3: document.getElementById('option3'),
    option4: document.getElementById('option4'),
}

这是我的代码笔:

https://codepen.io/teenicarus/pen/Oxaaoe

我该怎么做?

感谢所有回答

【问题讨论】:

  • 您在运行时生成 num1 和 num2 一次,因此您的所有选项都将具有相同的随机生成值。您希望为每个不正确的选项执行一次此随机数生成。

标签: javascript jquery


【解决方案1】:

解决方案有点复杂,描述每一行会很长,如果有什么不清楚的地方,请随时询问。需要说的是,卡片上的数字顺序也是随机生成的。这里是:

function shuffle(o) {
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

function startGame() {
  var num1 = Math.floor((Math.random() * 30) + 10);
  var num2 = Math.floor((Math.random() * 30) + 10);
  var result = num1 + num2;
  var otherNumbers = [];
  var counter = 0;

  document.getElementById('field1').innerHTML = num1;
  document.getElementById('field2').innerHTML = num2;

  var options = {
	  option1: document.getElementById('option1'),
	  option2: document.getElementById('option2'),
	  option3: document.getElementById('option3'),
	  option4: document.getElementById('option4'),
  }

  function generateRandomNumber() {
    for (var i = 0; counter < 3; i++) {
      var num = Math.floor((Math.random() * 30) + 10);
      if (num !== result && counter < 3) {
         counter++;
         otherNumbers.push(num);
       } else {
        generateRandomNumber();
      }
    }
  }

  generateRandomNumber();
  
  otherNumbers.push(result);
  otherNumbers = shuffle(otherNumbers);
  
  var arrCount = otherNumbers.length - 1;
  for (var key in options) {
    if (arrCount >= 0) {
      options[key].innerHTML = otherNumbers[arrCount];
      arrCount--;
    }
  }
}

startGame();
.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 60px;
}

.App-header {
  background-color: #222;
  height: 180px;
  padding: 20px;
  color: white;
}

.App-intro {
  font-size: large;
}

@keyframes App-logo-spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.text-info {
  color: #fff;
  font-weight: bold;
  font-size: 2.1rem;
}

.question {
  font-size: 2rem;
}

.options {
  margin: 5%;
  display: flex;
  margin-right: -12px;
  margin-left: -12px;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: stretch;
  flex: 1 0 auto;
}

.fields {
  display: flex;
  padding: 12px;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  flex: 1;
}

.field-block {
  display: flex;
  min-height: 160px;
  padding: 10%;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  /*flex: 1 0 auto;*/
  border-radius: 4px;
  background-color: #f9bad0;
  font-size: 6rem;
  color: #fff;
  cursor: pointer;
}

.quiz {
  color: #ddd;
  margin: 2%;
  background-color: #ec1561;
  padding: 2%;
  width: 90%;
  position: relative;
}

.button {
  display: flex;
  height: 48px;
  padding-right: 16px;
  padding-left: 16px;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex: 0 0 auto;
  border-radius: 4px;
  background-color: #2fcaaa;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .05), 0 2px 12px 0 rgba(0, 0, 0, .1);
  transition: box-shadow 200ms ease-out;
  color: #fff;
  font-weight: 500;
  text-align: center;
  cursor: pointer;
}

.quiz .after {
  position: absolute;
  top: 5%;
  left: 5%;
  width: 90%;
  height: 80%;
  /*display: none;*/
  color: #FFF;
  text-align: center;
  align-items: center;
  justify-content: center;
  display: flex;
  opacity: 0.8;
  font-size: 3rem;
}

.correct {
  background-color: green;
}

.wrong {
  background-color: #D91E18;
}

.hide {
  display: none !important;
}
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Adding 2 Numbers | Happy Learning!</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
  </head>
<body>
	
<a href="https://happy-learning.herokuapp.com/ " target="_blank"><img alt="Join Slack" height="40" width="139" src="http://i.imgur.com/0Lne5Vr.png"/></a>
<div>
	<h1>Adding Game</h1>

	<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>

<div class="quiz">
  <div class="quiz-content">
    <div class="question">
    What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
    </div>
    <div class="options">
      <div class="fields animated zoomIn">
        <div class="field-block" id="option1">
          10
        </div>
      </div>
      <div class="fields animated zoomIn">
        <div class="field-block" id="option2">
          10
        </div>
      </div>
      <div class="fields animated zoomIn">
        <div class="field-block" id="option3">
          10
        </div>
      </div>
      <div class="fields animated zoomIn">
        <div class="field-block" id="option4">
          10
        </div>
      </div>
    </div>
    <div class="after hide" id="after">

    </div>
    <div class="play-again">
      <a class="button" onclick="startGame()">Play Again</a>
    </div>
  </div>
</div>

<script src='index.js'></script>

</body>
</html>

【讨论】:

    【解决方案2】:

    这是您可以参考的解决方案。

    document.addEventListener("DOMContentLoaded", function(event) { 
      var num1 = Math.floor((Math.random() * 30) + 10);
        var num2 = Math.floor((Math.random() * 30) + 10);
        var result = num1 + num2;
    
        document.getElementById('field1').innerHTML = num1;
        document.getElementById('field2').innerHTML = num2;
        var opts = [];
        for(var i=0;i<3;i++){
          opts.push(findRandom(result,opts));
        }  
        opts.push(result);
        opts.sort();  
        for(var i=1;i<5;i++){ 
         document.getElementById('option'+i).innerHTML = opts[i-1];
        }  
    });
    
    function findRandom(n,opts){
      var result = 0;
      while(result !=n && result == 0){
        result = Math.floor(Math.random() * (n + 1)); 
        if(opts.indexOf(result) >0){
          result = 0;
        }
      }
      return result;
       
    }
    .App {
      text-align: center;
    }
    
    .App-logo {
      animation: App-logo-spin infinite 20s linear;
      height: 60px;
    }
    
    .App-header {
      background-color: #222;
      height: 180px;
      padding: 20px;
      color: white;
    }
    
    .App-intro {
      font-size: large;
    }
    
    @keyframes App-logo-spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    
    .text-info {
      color: #fff;
      font-weight: bold;
      font-size: 2.1rem;
    }
    
    .question {
      font-size: 2rem;
    }
    
    .options {
      margin: 5%;
      display: flex;
      margin-right: -12px;
      margin-left: -12px;
      flex-direction: row;
      flex-wrap: wrap;
      align-items: stretch;
      flex: 1 0 auto;
    }
    
    .fields {
      display: flex;
      padding: 12px;
      flex-direction: column;
      justify-content: flex-start;
      align-items: stretch;
      flex: 1;
    }
    
    .field-block {
      display: flex;
      min-height: 160px;
      padding: 10%;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      /*flex: 1 0 auto;*/
      border-radius: 4px;
      background-color: #f9bad0;
      font-size: 6rem;
      color: #fff;
      cursor: pointer;
    }
    
    .quiz {
      color: #ddd;
      margin: 2%;
      background-color: #ec1561;
      padding: 2%;
      width: 90%;
      position: relative;
    }
    
    .button {
      display: flex;
      height: 48px;
      padding-right: 16px;
      padding-left: 16px;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      flex: 0 0 auto;
      border-radius: 4px;
      background-color: #2fcaaa;
      box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .05), 0 2px 12px 0 rgba(0, 0, 0, .1);
      transition: box-shadow 200ms ease-out;
      color: #fff;
      font-weight: 500;
      text-align: center;
      cursor: pointer;
    }
    
    .quiz .after {
      position: absolute;
      top: 5%;
      left: 5%;
      width: 90%;
      height: 80%;
      /*display: none;*/
      color: #FFF;
      text-align: center;
      align-items: center;
      justify-content: center;
      display: flex;
      opacity: 0.8;
      font-size: 3rem;
    }
    
    .correct {
      background-color: green;
    }
    
    .wrong {
      background-color: #D91E18;
    }
    
    .hide {
      display: none !important;
    }
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Adding 2 Numbers | Happy Learning!</title>
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
      </head>
    <body>
    	
    <a href="https://happy-learning.herokuapp.com/ " target="_blank"><img alt="Join Slack" height="40" width="139" src="http://i.imgur.com/0Lne5Vr.png"/></a>
    <div>
    	<h1>Adding Game</h1>
    
    	<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
    </div>
    <hr>
    
    <div class="quiz">
      <div class="quiz-content">
        <div class="question">
        What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
        </div>
        <div class="options">
          <div class="fields animated zoomIn">
            <div class="field-block" id="option1">
              10
            </div>
          </div>
          <div class="fields animated zoomIn">
            <div class="field-block" id="option2">
              10
            </div>
          </div>
          <div class="fields animated zoomIn">
            <div class="field-block" id="option3">
              10
            </div>
          </div>
          <div class="fields animated zoomIn">
            <div class="field-block" id="option4">
              10
            </div>
          </div>
        </div>
        <div class="after hide" id="after">
    
        </div>
        <div class="play-again">
          <a class="button">Play Again</a>
        </div>
      </div>
    </div>
    
    <script src='index.js'></script>
    
    </body>
    </html>

    【讨论】:

      【解决方案3】:

      根据我的评论,您将需要重新运行该数字生成器,以便为剩余的 3 个选项生成新的和不正确的答案。您需要注意以下几点:

      1. 您必须避免冲突,即不要生成与答案相同的数字,或与任何预先生成的错误选项相同的数字。我们可以使用while 循环来进行这个简单的检查
      2. 您可以使用泛型函数生成num1 + num2,以便再次使用它来生成错误答案。
      3. 不要给您的选项提供唯一 ID,而只需给它们一个通用类,例如&lt;div class="field-block option"&gt;&lt;/div&gt; 。我们希望能够知道我们有多少选项,以便我们生成正确数量的答案 + 错误答案。
      4. 在将它们附加到 DOM 之前,您可能需要 shuffle your answers array,否则它们都将具有包含正确答案的第一个元素。

      旁注:虽然您的原始答案中没有提到它,但我希望您在用户单击该选项时想知道哪个是正确答案。当从选项触发单击事件时,您可以简单地获取选项的索引,并根据answers 数组检查它。如果选项的索引与数组中正确答案的索引匹配,那么您就可以开始了。


      在下面的代码 sn-p 中,我已经剥离了样式表和一些不必要的标记:

      // FY shuffle
      function shuffle(a) {
          var j, x, i;
          for (i = a.length - 1; i > 0; i--) {
              j = Math.floor(Math.random() * (i + 1));
              x = a[i];
              a[i] = a[j];
              a[j] = x;
          }
      }
      
      // Function that generates all options
      var generateAllOptions = function() {
        // Number generator
        var getRandomNumber = function() {
          return Math.floor((Math.random() * 30) + 10);
        };
        
        // Get the question + correct answer
        var num1 = getRandomNumber();
        var num2 = getRandomNumber();
        var correctAnswer = num1 + num2;
        var answers = [correctAnswer];
        
        // Update question
        document.getElementById('field1').innerHTML = num1;
        document.getElementById('field2').innerHTML = num2;
        
        // Generate incorrect answers/options, but make sure there are no collisions
        var options = document.querySelectorAll('.options .option');
        while(answers.length < options.length) {
          var incorrectAnswer = getRandomNumber() + getRandomNumber();
          if (answers.indexOf(incorrectAnswer) === -1)
            answers.push(incorrectAnswer);
        }
        
        // Shuffle answers
        shuffle(answers);
        
        // Store index of correct answer
        var correctIndex = answers.indexOf(correctAnswer);
        
        // Append shuffled answers to options
        for (var i = 0; i < options.length; i++) {
        
          var option = options[i];
          
          // Write answer values into innerHTML
          option.innerHTML = answers[i];
          
          // Bind click event to all options, use IIFE!
          (function(idx) {
            option.addEventListener('click', function() {
              if (idx === correctIndex) {
                alert('You have selected the right answer!');
              } else {
                alert('That is an incorrect answer.');
              }
            });
          })(i);
        }
        
        
        
        
      };
      
      generateAllOptions();
      .option {
        font-weight: bold;
        background-color: steelblue;
        color: #fff;
        border-radius: 4px;
        padding: 10px;
        margin: 5px;
      }
      <div>
        <h1>Adding Game</h1>
      
        <p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
      </div>
      <hr>
      
      <div class="quiz">
        <div class="quiz-content">
          <div class="question">
            What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
          </div>
          <div class="options">
            <div class="fields animated zoomIn">
              <div class="field-block option"></div>
            </div>
            <div class="fields animated zoomIn">
              <div class="field-block option"></div>
            </div>
            <div class="fields animated zoomIn">
              <div class="field-block option"></div>
            </div>
            <div class="fields animated zoomIn">
              <div class="field-block option"></div>
            </div>
          </div>
          <div class="after hide" id="after">
      
          </div>
          <div class="play-again">
            <a class="button">Play Again</a>
          </div>
        </div>
      </div>

      【讨论】:

        【解决方案4】:

        试试这个简单的解决方案。这会生成 4 个唯一的随机选项,其中一个选项是正确的。正确答案的选项编号也是随机的。

        你只需要修改你的js。

        var num1 = Math.floor((Math.random() * 30) + 10);
        var num2 = Math.floor((Math.random() * 30) + 10);
        var result = num1 + num2;
        
        var ansIndex=(Math.floor((Math.random()*10))%4)+1; //this index will be the position of the correct answer
        
        var option=[];
        
        //the below loop fills the options array with random but unique options
        for(var i=0;i<4;i++){
           var temp=Math.floor((Math.random() * 30) + 10);
           if(final.indexOf(temp)==(-1)){
                option.push(temp);
                continue;
           }
           else{
                i--;
           }
        }
        
        //finally the correct option is overwritten
        option[ansIndex-1]=result;
        
        
        var answer=document.getElementsByClassName("field-block");
        answer[0].innerHTML=option[0];
        answer[1].innerHTML=option[1];
        answer[2].innerHTML=option[2];
        answer[3].innerHTML=option[3];
        
        
        
        document.getElementById('field1').innerHTML = num1;
        document.getElementById('field2').innerHTML = num2;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多