在匹配游戏 java 脚本中添加分数

Adding up score in matching game java script

我对 java 脚本还很陌生,所以请耐心等待我:) 所以我正在用 java 脚本制作一个匹配游戏(将动物图案与它们的名字匹配),即使我点击正确答案,永远不会加分,所以你总是输。

我该如何解决这个问题?

这是我的代码

function randSort (a,b) {
  return Math.random() - 0.5;
}

var questions = [
  {
    text: " What animal is this?", 
    img: "AnimalPrints/1.jpg", 
    answers: ["Cheetah", "Tiger", "Ladybird"], 
    ans: "A"
  },
  {
    text: " What animal is this one?", 
    img: "AnimalPrints/2.jpg", 
    answers: ["Elephant", "Giraffe", "Snake"], 
    ans: "B"
  },
  {
    text: "What animal is this one please?", 
    img: "AnimalPrints/3.jpg", 
    answers: ["Bumblebee", "Tiger", "Lady bird"], 
    ans: "Bumblebee"
  }
];

var correctCount = 0;
var currentQ = 0;


function select(nr) {
  if (nr == questions[currentQ].ans)
  {
    correctCount++;
    document.getElementById('display').innerHTML= "You win"
  }
  else
  {
    document.getElementById('display').innerHTML= "You lose"
  }
  document.getElementById('display').innerHTML += "<p>Score: "+ correctCount;

  // if its the last one
  nextQ();

}   

function showQ() {
  document.getElementById('questionText').innerHTML = questions[currentQ].text;
  document.getElementById('animalPrint').src = questions[currentQ].img;
  newhtml = "";
  for (var i = 0; i< questions[currentQ].answers.length; i++)
  {
    newhtml+= "<button onclick = 'select(" + i + ")'>"+ questions[currentQ].answers[i] + "</button>";
  }
  document.getElementById('alloptions').innerHTML = newhtml;
}


function nextQ(){
  if (currentQ < questions.length-1)
  {   
    currentQ++;
    showQ();
  }
}


window.onload =init;


function init()
{
  correctCount = 0;
  questions.sort(randSort);
  currentQ = 0;
  showQ();
}
body {
    background-position: center;
    background-color:lime;
}

#questionText {width: 350px; background: white;}


#nextbutton {
    background-image: url(Buttons/nextbutton.jpg);
    background-size:contain;
    background-repeat:repeat-y;
    background-position: center;
    width:100px;
    height:44px;
    margin-left: 250px;
    border-radius:10px;
}


#main {
  margin-top:200px;
  margin-left:250px;
  border:1px solid red;
  width:600px;

}

#display {
    width:150px;
    height:50px;
    background-color:blue;
    color:white;
    border-radius:5px;
    font-family:aqua;
}
<div id = main>
  <div id = "questionText"> Testing</div>
  <div id ="animal">
    <img id = "animalPrint" src = "AnimalPrints/1.jpg">
  </div>

  <div id = "alloptions"> </div>

  <button id = "nextbutton" onclick = "nextQ();"></button>
</div>
<div id = "display">    Score:  </div>

您根据单击的按钮将答案的(数字,基于 0)索引传递给函数 select。您将其与 ans 属性 进行比较,后者的第一个问题的值为 'A''B'

0,显然不等于'A'.

所以把ans改成0到N的值,指定正确答案的索引,就可以了。