我是javaScript的新手,我目前正在尝试编写彩票游戏。用户可以输入1到49之间的6个数字,然后生成6个随机数字,然后它会告诉你有多少个数字是正确的。到目前为止,一切似乎都很好,但我不知道如何编写代码,
- 不能两次输入相同的数字(这会导致错误代码)
- 随机发生器不允许抽取相同的数字两次
我的代码到目前为止是这样的:
function validateBall(num) {
let ballValue = document.getElementById("ball" + num).value;
if (ballValue == "") {
alert("Ball " + num + " braucht eine Zahl");
return false;
}
if (isNaN(ballValue)) {
alert("Ball " + num + " ist keine Zahl");
return false;
}
let numberValue = parseInt(ballValue);
if (numberValue <= 0 || numberValue > 49) {
alert("Die Zahl des Balls muss zwischen 1-49 liegen");
return false;
}
return numberValue;
}
function containsDuplicates(ballValue) {
return array.length !== new Set(ballValue).size;
}
function output(str) {
let output = document.getElementById("output");
var tag = document.createElement("p");
var text = document.createTextNode(str);
tag.appendChild(text);
output.appendChild(tag);
}
function Jetzt_Spielen() {
let value1 = validateBall("1");
if (value1 == false)
return;
let value2 = validateBall("2");
if (value2 == false)
return;
let value3 = validateBall("3");
if (value3 == false)
return;
let value4 = validateBall("4");
if (value4 == false)
return;
let value5 = validateBall("5");
if (value5 == false)
return;
let value6 = validateBall("6");
if (value6 == false)
return;
let values = [value1, value2, value3, value4, value5, value6];
let outputDiv = document.getElementById("output");
outputDiv.innerHTML = "";
let matched = 0;
for (let i = 0; i < 6; i++) {
let randomNumber = Math.round(1 + Math.random() * 48);
output("Gezogene Zahl: " + randomNumber);
for (let j = 0; j < 6; j++) {
let myBallValue = values[j];
if (randomNumber == myBallValue) {
matched++;
break;
}
}
}
output("Du hast " + matched + " richtige Zahl(en)")
}
<div class="gelbe_box">
<h1>Lotto 6aus49</h1>
</div> <br>
<div class="position_middle">
<input id="ball1" class="LottoZahlen" />
<input id="ball2" class="LottoZahlen" />
<input id="ball3" class="LottoZahlen" />
<input id="ball4" class="LottoZahlen" />
<input id="ball5" class="LottoZahlen" />
<input id="ball6" class="LottoZahlen" />
<button id="submitBtn" value="button" onclick=" Jetzt_Spielen();">Jetzt Spielen</button>
<div id="output">
</div>
我真的不知道如何继续下去。要么我已经做错了什么,我不能用这段代码做,要么我只是不能弄清楚代码…
我真的很感激你的帮助!
提前谢谢你:)
良好的用户体验和限制
首先规划布局(HTML和基本CSS)。为了控制与用户的交互如何在很大程度上依赖于HTML和CSS,使用JavaScript来促进这种交互,收集用户数据,并处理用户数据和/或新数据。为了回答你的问题,我不得不向你展示一种达到你的目标的方法,并为你的特定问题提供一个万无一失的解决方案。