我怎么能正确地总分?

时间:2016-03-13 14:14:43

标签: javascript

我是javascript学习者,正在努力为我的孩子(5到10岁)设计一个小的javascript游戏,其中点数基于时间流逝。但是,我无法找到一种总分的方法。我已经管理了下面的代码,但结果并不准确。可能该程序在每次点击时总计阵列中的所有项目。有人可以帮忙吗?我是新手,在这里会有很多错误或荒谬,我要求你在纠正我的时候礼貌地帮助你。任何帮助表示赞赏..

document.getElementById("box1").onclick = function() {
  clickT = Date.now();
  reactT = (clickT - createdT) / 1000; //gets the time difference for reaction.

  points = reactT * 1000;
  points = 2000 - points;

  pRecord.push(points); //add points to array.

  for (i = 0; i < pRecord.length; i++) {
    totalpoints += pRecord[i];
  }

  document.getElementById("time").innerHTML = reactT;
  this.style.display = "none";

  document.getElementById("score").innerHTML = totalpoints;
}

2 个答案:

答案 0 :(得分:2)

在对点数求和之前,只需将totalpoints设置为零:

document.getElementById("box1").onclick = function() {
    var clickT = Date.now();
    var reactT = (clickT - createdT) / 1000; //gets the time difference for reaction.

    var points = reactT * 1000;

    points = 2000 - points;

    pRecord.push(points); //add points to array.

    var totalpoints = 0;
    for (var i = 0; i < pRecord.length; i++){
       totalpoints += pRecord[i];
    }


    document.getElementById("time").innerHTML = reactT;
    this.style.display = "none";

    document.getElementById("score").innerHTML = totalpoints;
}

而且我不知道你是否在外部范围内定义了变量,但我猜你没有,所以我在每个变量创建之前都添加了var

答案 1 :(得分:0)

以下是代码的改进版本,它还可以正确记录反应时间,将最大允许反应时间限制为配置值。

在原始实施中,如果反应时间超过2秒,您可能会得到不良读数。

此外,在您的原始代码中,您不需要除以1000然后再乘以,因为您最终还是以毫秒结束。

就是这样:

document.getElementById("box1").addEventListener("click", function() {
  clickT = Date.now();

  // Gets the time difference in milliseconds for reaction.
  reactT = clickT - createdT; 

  // Maximum allowed reaction time after which we give no more points.
  var maxPoints = 2000;

  // We cap the registered reaction time to the maximum allowed.
  points = Math.max(reactT, maxPoints);
  // We score the reaction time based
  points = maxPoints - points;

  // Add points to array.
  pRecord.push(points); 

  // Compute the total points.
  var totalpoints = 0;
  for (i = 0; i < pRecord.length; i++){
    totalpoints += pRecord[i];
  }

  document.getElementById("time").innerHTML = reactT;
  this.style.display = "none";

  document.getElementById("score").innerHTML = totalpoints;
}

您可以注意到我已经定义了totalpoints变量(并将其初始化为0),否则,在每次点击时,您的所有分数都会重新添加,而不仅仅是最后一个。

我已经假设在您粘贴的代码之前尚未定义totalpoints。如果这个假设是错误的并且您之前已经在代码中初始化了totalpoints,那么您需要从我的代码中替换以下部分:

// Compute the total points.
var totalpoints = 0;
for (i = 0; i < pRecord.length; i++){
  totalpoints += pRecord[i];
}

...与:

// Add the new points to the total.
totalpoints += points;
相关问题