首页 > 解决方案 > 如何将分数推入数组,然后显示它

问题描述

我正在尝试制作一个骰子游戏,其中每个参与者的目标是尽可能快地收集积分以通过 100。每个参与者可以根据需要多次投掷骰子并添加积分,但在一个如果滚动某个游戏,则某些游戏会消失。例如,如果您在一场比赛中获得 15 分并且及时停止,则这些积分可以进一步用于第二轮。这些积分不能在以后的一轮中丢失,因此会包含在摘要中。

我设法:

我需要帮助的是如何编写代码来激活“暂时完成”按钮并获取该值并将其推送到数组中(????)然后清除下一轮的分数->然后显示分数在网站上,而其他轮次继续进行。它还应该总结每轮的得分和投掷(从第一到 100)。

这是我的代码:

var points = 0;

var start, dice, print;

window.onload = run;

function $(id) {
  return document.getElementById(id);
}

function run() {
  start = $("throwDice");
  dice = $("dice");
  print = $("print");
  start.onclick = throwDice;
}

function throwDice() {
  var throwD = Math.floor(Math.random() * 6) + 1;
  throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';

  add(throwD);
}

function add(value) {

  points += value;

  if (value == 1) {
    points = 0;
    $("print2").innerHTML = "GAME OVER"
  } else {
    $("print2").innerHTML = "";
    $("print").innerHTML = points;
  }
}
<div class="round">
  <h1>The endless road</h1>
  <button id="throwDice">Throw Dice</button> <button>Done for now</button>
  <div id="dice" class="dice"></div>
  <h2 id="print"></h2>
  <p id="print2"></p>
</div>

标签: javascripthtmldice

解决方案


基本上,您只需将另一个单击事件侦听器添加到其回调函数的“暂时完成”按钮

  • 将当前点推送到数组
  • 将点重置为 0
  • 更新屏幕上的文本元素

就像是:

var points = 0;
var pointsArray = new Array();
var start, dice, print;


function $(id) {
  return document.getElementById(id);
}

function run() {
  start = $("throwDice");
  dice = $("dice");
  print = $("print");
  start.onclick = throwDice;
  done = $("done");
  done.onclick = stopRound;
}

function stopRound() {
  pointsArray.push(points);
  points = 0;
  $("print").innerHTML = points;
  $("print3").innerHTML = pointsArray;
}

function throwDice() {
  var throwD = Math.floor(Math.random() * 6) + 1;
  throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';

  add(throwD);
}

function add(value) {

  points += value;

  if (value == 1) {
    points = 0;
    $("print2").innerHTML = "GAME OVER"
  } else {
    $("print2").innerHTML = "";
    $("print").innerHTML = points;
  }
}
run();
<div class="round">
  <h1>The endless road</h1>
  <button id="throwDice">Throw Dice</button> <button id="done">Done for now</button>
  <div id="dice" class="dice"></div>
  <p id="print3" style="float:right;"></p>
  <h2 id="print"></h2>
  <p id="print2"></p>

</div>


推荐阅读