javascript - 如何将分数推入数组,然后显示它
问题描述
我正在尝试制作一个骰子游戏,其中每个参与者的目标是尽可能快地收集积分以通过 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>
解决方案
基本上,您只需将另一个单击事件侦听器添加到其回调函数的“暂时完成”按钮
- 将当前点推送到数组
- 将点重置为 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>
推荐阅读
- c# - Gridview 行颜色基于 GridView 外部的文本框值
- kubernetes - CORS 规则 nginx-ingress 规则
- r - 根据另一个数据框中的日期范围划分数据框中的值
- ajax - 在 CakePHP 3.6 中使用 ajax 上传图像时 CSRF 令牌不匹配
- android - 来自 URL 的音频流无法从数据源初始化?
- google-bigquery - 当字段包含@sign BigQuery Standard SQL时,我如何使用函数从Google BigQuery中提取json
- android - 未知类:AndroidX 双向数据绑定中的 java.lang.String
- wordpress - wp简单会员插件同时登录
- c++ - 将任何类型的对象的函数传递给 C++ 中的另一个对象
- linux - 使用 Qt 使用 cc2564moda 在 beagleboneblack 上配置蓝牙