首页 > 解决方案 > 如何使响应以不同的顺序显示?

问题描述

我希望答案与问题一起出现混乱,因此答案看起来并不总是相同,但答案似乎与问题混乱。

问题 1 中的示例 谁是真正的厨师?响应,'Monica','Chandler','Rachel','Ross' 我希望这些响应随机显示为'Chandler','Ross''Rachel','Monica'或'Monica','Rachel','罗斯,“钱德勒”

$(document).ready(function() {
  $("#remaining-time").hide();
  $("#start").on("click", trivia.startGame);
  $(document).on("click", ".option", trivia.guessChecker);
});

var trivia = {
    correct: 0,
    incorrect: 0,
    unanswered: 0,
    currentSet: 0,
    // "seen" property will keep track of the seen questions so we don't re-display them again
    seen: [],
    // Update: limit the number of question per game. Usong a property so you can change its value whenever you want to change the limit
    limit: 4,
    timer: 20,
    timerOn: false,
    timerId: "",
    // questions options and answers data
    questions: {
      q1: "Who is actually a chef?",
      q2: "What does Joey love to eat?",
      q3: "How many times has Ross been divorced?",
      q4: "How many types of towels does Monica have?",
      q5: "Who stole Monica's thunder after she got engaged?",
      q6: "Who hates Thanksgiving?",
      q7: "Who thinks they're always the last to find out everything?"
    },
    options: {
      q1: ["Monica", "Chandler", "Rachel", "Ross"],
      q2: ["Fish", "Apples", "Oranges", "Sandwhiches"],
      q3: ["5", "2", "1", "3"],
      q4: ["3", "8", "11", "6"],
      q5: ["Rachel", "Phoebe", "Emily", "Carol"],
      q6: ["Joey", "Chandler", "Rachel", "Ross"],
      q7: ["Ross", "Phoebe", "Monica", "Chandler"]
    },
    answers: {
      q1: "Monica",
      q2: "Sandwhiches",
      q3: "3",
      q4: "11",
      q5: "Rachel",
      q6: "Chandler",
      q7: "Phoebe"
    },
    // random number generator
    random: (min, max) => Math.floor(Math.random() * (max - min + 1)) + min,
    startGame: function() {
      trivia.currentSet = 0;
      // set "seen" to an empty array for a new game
      trivia.seen = [];
      trivia.correct = 0;
      trivia.incorrect = 0;
      trivia.unanswered = 0;
      clearInterval(trivia.timerId);
      $("#game").show();
      $("#results").html("");
      $("#timer").text(trivia.timer);
      $("#start").hide();
      $("#remaining-time").show();
      trivia.nextQuestion();
    },
    nextQuestion: function() {
      trivia.timer = 10;
      $("#timer").removeClass("last-seconds");
      $("#timer").text(trivia.timer);
      if (!trivia.timerOn) {
        trivia.timerId = setInterval(trivia.timerRunning, 1000);
      }
      // get all the questions
      const qts = Object.values(trivia.questions);
      // init the random number
      let rq = null;
      // firstly, if no more questions to show set rq to -1 to let us know later that the game has finished 
      // Update: checking if we reached the "limit"
      if (trivia.seen.length >= trivia.limit) rq = -1
      else {
        // otherwise generate a random number from 0 inclusive to the length of the questions - 1 (as array indexing starts from 0 in JS) also inclusive
        do {
          // generate a random number using the newly added "random" method
          rq = trivia.random(0, qts.length - 1);
        } while (trivia.seen.indexOf(rq) != -1); // if the question is already seen then genrate another number, do that till we get a non-seen question index
        // add that randomly generated index to the seen array so we know that we have already seen it
        trivia.seen.push(rq);
        // increment the counter
        trivia.counter++;
      }
      // current question index is the generated random number "rq"
      trivia.currentSet = rq;
      var questionContent = Object.values(trivia.questions)[rq];
      $("#question").text(questionContent);
      var questionOptions = Object.values(trivia.options)[trivia.currentSet];
      $.each(questionOptions, function(index, key) {
        $("#options").append(
          $('<button class="option btn btn-info btn-lg">' + key + "</button>")
        );
      });
    },
    timerRunning: function() {
      if (
        trivia.timer > -1 &&
        // all the questions have already been seen
        // Update: now we check against the limit property
        trivia.seen.length < trivia.limit
    ) {
      $("#timer").text(trivia.timer);
      trivia.timer--;
      if (trivia.timer === 4) {
        $("#timer").addClass("last-seconds");
      }
    } else if (trivia.timer === -1) {
      trivia.unanswered++;
      trivia.result = false;
      clearInterval(trivia.timerId);
      resultId = setTimeout(trivia.guessResult, 1000);
      $("#results").html(
        "<h3>Out of time! The answer was " +
        Object.values(trivia.answers)[trivia.currentSet] +
        "</h3>"
      );
    }
    // if the game ended as we know that -1 means no more questions to display
    else if (trivia.currentSet === -1) {
      $("#results").html(
        "<h3>Thank you for playing!</h3>" +
        "<p>Correct: " +
        trivia.correct +
        "</p>" +
        "<p>Incorrect: " +
        trivia.incorrect +
        "</p>" +
        "<p>Unaswered: " +
        trivia.unanswered +
        "</p>" +
        "<p>Please play again!</p>"
      );
      $("#game").hide();
      $("#start").show();
    }
  },
  guessChecker: function() {
    var resultId;
    var currentAnswer = Object.values(trivia.answers)[trivia.currentSet];
    if ($(this).text() === currentAnswer) {
      //turn button green for correct
      $(this).addClass("btn-success").removeClass("btn-info");
      trivia.correct++;
      clearInterval(trivia.timerId);
      resultId = setTimeout(trivia.guessResult, 1000);
      $("#results").html("<h3>Correct Answer!</h3>");
    } else {
      $(this).addClass("btn-danger").removeClass("btn-info");

      trivia.incorrect++;
      clearInterval(trivia.timerId);
      resultId = setTimeout(trivia.guessResult, 1000);
      $("#results").html(
        "<h3>Better luck next time! " + currentAnswer + "</h3>"
      );
    }
  },

  guessResult: function() {
    // no need to increment trivia.currentSet anymore
    $(".option").remove();
    $("#results h3").remove();
    trivia.nextQuestion();
  }
};
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="header text-center clearfix">
    <h1 class="text-muted">Friends trivia game</h1>
  </div>
  <div class="jumbotron jumbotron-fluid">
    <div class="container">
      <div id="game">
        <h2>FRIENDS Trivia Game</h2>
        <p id="remaining-time" class="lead">Remaining Time: <span id="timer"></span></p>
        <p id="question" class="lead"></p>
      </div>
      <div id="results">
      </div>
    </div>

    <div class="row">
      <div id="choices" class="text-center">
        <button id="start" class="btn btn-info btn-lg">Start Game</button>
        <div id="options">

        </div>

      </div>
    </div>

  </div>
  <!-- /container -->

标签: javascripthtmlcss

解决方案


在您开始向页面添加答案的地方,请尝试以下代码:

$.each(Object.values(trivia.options)[trivia.currentSet].sort( () => { 
    return .5 - Math.random(); 
}), key => {
    $("#options").append(
        $('<button class="option btn btn-info btn-lg">' + key + "</button>")
    );
});

这不是随机化数组的安全或有效方式,但它可以解决这样的问题。它只是选择一个介于 0 和 1 之间的随机数并从 0.5 中减去它,因此返回的数字介于 -0.5 和 0.5 之间。该sort函数完成其余的工作。

这整个事情属于你的trivia.nextQuestion功能结束。

这整个事情可以在没有 jQuery 的情况下完成。如果您没有出于任何特定原因使用它,那么在 vanilla JavaScript 中尝试一下可能是值得的。为了让您开始,这里是相同的代码块:

const options = document.getElementById("options");
Object.values(trivia.options)[trivia.currentSet].sort( () => { 
    return .5 - Math.random(); 
}).forEach(key => {
    options.innerHTML += `<button class="option btn btn-info btn-lg">${key}</button>';
});

当您使用它时,请查看 、 或 是否trivia.questions需要trivia.options成为trivia.answers对象,或者数组是否可以正常工作。但这属于代码审查中的 mroe ......


推荐阅读