JS加法游戏:我如何显示4个可能的答案,其中3个是随机的,1个是正确的答案? (包括Codepen)

时间:2017-10-17 11:08:39

标签: javascript jquery

我正在用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

我该怎么做?

我感谢所有答案

4 个答案:

答案 0 :(得分:2)

解决方案有点复杂,描述每一行都会很长,所以请随意询问是否有任何不清楚的地方。需要说明的是,卡片上的数字顺序也是随机生成的。这是:

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>

答案 1 :(得分:0)

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

&#13;
&#13;
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;
   
}
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

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

  1. 您必须避免冲突,即不要生成与答案相同的数字,或者与任何预先生成的错误选项相同。我们可以使用while循环
  2. 进行简单检查
  3. 您可以使用通用函数生成num1 + num2,以便可以再次使用它来生成错误的答案。
  4. 不要给您的选项提供唯一ID,只需给它们一个通用类,例如<div class="field-block option"></div>。我们希望能够知道我们有多少选项,以便生成正确数量的答案+错误的答案。
  5. 在将它们附加到DOM之前,您可能需要shuffle your answers array,否则它们都将包含包含正确答案的第一个元素。
  6. 旁注:虽然原始答案中未提及,但我希望您在用户点击该选项时知道哪个是正确的答案。当从该选项触发click事件时,您只需获取该选项的索引,并根据answers数组进行检查。如果选项的索引与数组中正确答案的索引匹配,那么你就可以了。

    在下面的代码片段中,我删除了样式表和一些不必要的标记:

    &#13;
    &#13;
    // 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();
    &#13;
    .option {
      font-weight: bold;
      background-color: steelblue;
      color: #fff;
      border-radius: 4px;
      padding: 10px;
      margin: 5px;
    }
    &#13;
    <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>
    &#13;
    &#13;
    &#13;

答案 3 :(得分:0)

试试这个简单的解决方案。这将生成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;