【问题标题】:How to push score into an array, then display it如何将分数推入数组,然后显示
【发布时间】:2019-11-02 09:30:08
【问题描述】:

我正在尝试制作一个骰子游戏,其中每个参与者的目标是尽可能快地收集点数以超过 100。每个参与者可以随意投掷骰子并添加点数,但实现了如果掷出一个,则某场比赛中的分数会下降。例如,如果您在一场比赛中获得 15 分并且及时停止,则这些积分可以进一步进入第二轮。这些积分不会在以后的一轮中丢失,因此会包含在摘要中。

我已经做到了:

  • 编写代码,显示骰子图像并总结当前分数(图像 = 1.png、2.png 等)。
  • 当玩家掷出 1 时,将当前分数重置为 0。

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

【问题讨论】:

  • 欢迎来到 SO。请修改您的帖子以准确解释您的脚本在做什么或不做什么。它是相当模糊的。
  • 仅供参考,一个骰子,两个骰子
  • 我正在寻找一种解决方案,当单击“暂时完成”按钮时,程序会获取所获得的分数 - 可变点 - 并将其保存到一个空数组中。我需要这个数组在网站的左侧或右侧列出,同时进行另一轮。单击此按钮时,单击“掷骰子”时出现的骰子分数应重置,但您获得的分数将存储在数组中。
  • 我明白当你在我的电脑上看不到作为艺术品图像的骰子时很难。
  • revise解释....

标签: javascript html dice


【解决方案1】:

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

  • 将当前点推送到数组中
  • 将点重置为 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>

【讨论】:

    猜你喜欢
    • 2013-12-08
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2018-08-28
    相关资源
    最近更新 更多