2 回答
TA贡献1856条经验 获得超11个赞
考虑下面的小游戏,它使用你的情况,它从源数组中计算你的 randomNumber 的总和。
它检查总和是否 >= 12。然后让游戏休息!
这有帮助吗?
const Numbers = [8, 4, 6, 2];
var randomNumber = 0;
var sum = 0;
function calcSum() {
randomNumber = Numbers[Math.floor(Math.random() * Numbers.length)];
sum = sum + randomNumber;
if (sum >= 12) {
document.getElementById('calculatedTotal').innerHTML = "Your score exceeded 12, click 'start game' to play again!";
sum = 0;
randomNumber = 0;
}
else {
document.getElementById('calculatedTotal').innerHTML = sum;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn" onclick="calcSum()">Start game!!</button>
<h2>Your Score: </h2>
<h3 id="calculatedTotal"></h3>
<script src="test.js"></script>
</body>
</html>
TA贡献1784条经验 获得超8个赞
每次选择随机数时
您必须过滤掉不构成 12 的数字。
从总和中减去选择的数字,然后重复步骤 1 直到总和达到 0
编辑:根据问题更新,假设您使用的是 Bootstrap
document.getElementById("start").addEventListener("click", _ => {
let sum = +document.getElementById("sum").value;
let numbers = document.getElementById("numbers").value.split(',').map(x=>+x);
let picked = [];
while(sum > 0) {
// filter available `numbers` based on the `sum`
numbers = numbers.filter(x => x <= sum);
let n = numbers[Math.floor(Math.random() * numbers.length)];
picked.push(n);
// subtract `n` from `sum`
sum -= n;
}
document.getElementById("row").innerHTML = picked.map(n => `<div class="border border-dark p-3 col-${n}">col-${n}</div>`).join("");
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
Sum: <input type="text" id="sum" value="12" />
Numbers: <input type="text" id="numbers" value="8,6,2,4" /> <br/>
<button type="button" id="start">Start</button>
<div class="container-fluid">
<div class="row" id="row">
</div>
</div>
添加回答
举报