彩票游戏-不允许输入相同的数字两次- JS



我是javaScript的新手,我目前正在尝试编写彩票游戏。用户可以输入1到49之间的6个数字,然后生成6个随机数字,然后它会告诉你有多少个数字是正确的。到目前为止,一切似乎都很好,但我不知道如何编写代码,

  1. 不能两次输入相同的数字(这会导致错误代码)
  2. 随机发生器不允许抽取相同的数字两次

我的代码到目前为止是这样的:

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来促进这种交互,收集用户数据,并处理用户数据和/或新数据。为了回答你的问题,我不得不向你展示一种达到你的目标的方法,并为你的特定问题提供一个万无一失的解决方案。

如果你需要与用户进行交互,使用<form>并将所有相关布局保留在其中。只呈现用户需要使用的东西,最好是一个表单控件,比如按钮。隐藏HTML的其余部分,并限制用户只能执行各个阶段。用简单的信息和视觉提示来指导用户。不要使用prompt()(它在美学上没有吸引力,弹出窗口感觉"粗鲁";国际海事组织):

图1 -布局

<form id='lottery'><!-- Wrap <form> around everything -->
<fieldset id='box'>
<!-- Always have simple clear directions -->
<legend>Click the button to begin</legend>
<!-- Offer the user only one or two choices at a time -->
<!-- ATM there are two empty <select> and a <button> that automatically 
has focus (see Figure II). There's a <legend> prompting user to click
the <button>. There's also a hidden <button> and <output> ready for
the next phase.
-->
<select id='choices' multiple></select>
<!-- This button has focus as soon as the page is loaded because it's 
assigned "tab-index='0'" and there's a line of JavaScript
(see Figure II)
-->
<button id='begin' tab-index='0'>Begin</button>
<button id='done' tab-index="0" type='button'>Done</button>
<select id='picked' multiple></select>
</fieldset>
<output id='note' class='hide'>
<small><sup>✳️</sup>To deselect a number, click the number in field on the right</small>
</output>
<!-- This hidden section is the final phase which displays the user's 
numbers, the winning lottery numbers, and the numbers that matched.
-->
<fieldset id='results' class='hide'>  
<label for='final'>Your Numbers: </label><output id='final' class='array'></output><br>
<label for='targets'>Winning Numbers: </label><output id='targets' class='array'></output><br>
<label for='hits'>Matching Numbers: </label><output id='hits' class='array'></output><br>
<button type='reset'>Replay</button>
</fieldset>
</form>

JavaScript

// This will hold the numbers the user picks
let numbers = [];
/*
This is an array of 49 empties "". It will be used as a counter and
then later repurposed to hold the winning numbers
*/
let A49 = [...Array(49)];
/* 
Throughout this example the terse syntax of the HTMLFormsElement 
interface will be used extensively. This references the <form>
*/
const lot = document.forms.lottery;

// 1st phase init(e) populates a <select> with 49 <option>s
lot.addEventListener('submit', init);
/* 
2nd phase pick(e) allows the user to pick 6 numbers, no need to validate
user input there are 49 numbers and each number can only be picked once.
*/
lot.addEventListener('input', pick);
/*
Last phase draw(e) collects the users array of 6 numbers, then generates
a randomized array of 6 numbers, then displays both arrays with matches
highlighted.
*/
lot.elements.done.addEventListener('click', draw);
lot.onreset = function() {
window.location.reload();
};
lot.elements.begin.focus();
function init(e) {
e.preventDefault();
const IO = this.elements;
A49 = A49.map((_, index) => {
IO.choices.insertAdjacentHTML(
'beforeend',
`<option value="${index + 1}">${index + 1}</option>`
);
return index + 1;
});
//... 

这个答案太大了,抱歉,我稍后会回来解释这段代码的其余部分。这是万无一失的,如果没有超过OP的所有目标,我希望这有助于。

<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<style>
html {
font: 300 5vmin/1.25 'Segoe UI';
}
fieldset {
max-width: 15rem;
}
#box {
display: flex;
justify-content: center;
align-items: center;
}
input,
button,
output,
select,
label {
display: inline-block;
margin: 4px;
font: inherit;
}
button {
padding-bottom: 0.25rem;
border: 0;
border-radius: 2px;
outline: 0;
cursor: pointer;
}
label {
width: 4rem;
margin-right: 0;
}
mark {
padding: 1px;
background-color: #0047AB;
color: gold;
}
small {
font-size: 0.5rem;
}
legend b {
font-family: Consolas;
}
select {
width: 3rem;
height: 9rem;
border: 0.5 inset lightgrey;
border-radius: 2px;
outline: 0;
font-family: Consolas;
}
#choices {
overflow-y: scroll;
scrollbar-width: thin;
}
#choices::-webkit-scrollbar {
width: 0.25rem;
height: 9rem;
}
#picked {
overflow-y: hidden;
}
.array {
width: 7.5rem;
font-family: Consolas;
}
.hide {
visibility: hidden;
}
#done {
display: none;
}
#note {
margin-top: -4px;
}
[type='reset'] {
float: right;
}
select:focus,
button:focus {
color: #0047AB;
box-shadow: 0 0 0 2pt cornflowerblue;
}
</style>
</head>
<body>
<form id="lottery">
<fieldset id="box">
<legend>
Click the button to begin
</legend>
<select id="choices" multiple></select>
<button id="begin" tab-index="0">Begin</button>
<button id="done" tab-index="0" type="button">Done</button>
<select id="picked" multiple></select>
</fieldset>
<output id="note" class="hide">
<small>
<sup>✳️</sup>To deselect a number, click the number in field on the
right
</small>
</output>
<fieldset id="results" class="hide">
<label for="final">Your Numbers: </label>
<output id="final" class="array"></output><br />
<label for="targets">Winning Numbers: </label>
<output id="targets" class="array"></output><br />
<label for="hits">Matching Numbers: </label>
<output id="hits" class="array"></output><br />
<button id='replay' tab-index='0' type="reset">Replay</button>
</fieldset>
</form>
<script>
let numbers = [];
let A49 = [...Array(49)];
const lot = document.forms.lottery;
lot.addEventListener('submit', init);
lot.addEventListener('input', pick);
lot.elements.done.addEventListener('click', draw);
lot.onreset = function() {
window.location.reload();
};
lot.elements.begin.focus();
function init(e) {
e.preventDefault();
const IO = this.elements;
A49 = A49.map((_, index) => {
IO.choices.insertAdjacentHTML(
'beforeend',
`<option value="${index + 1}">${index + 1}</option>`
);
return index + 1;
});
IO.box.firstElementChild.innerHTML = `Pick <b>6</b> numbers -- 1 to 49<sup><small>✳️</small></sup>`;
IO.note.classList.remove('hide');
IO.begin.remove();
IO.done.style.display = 'inline-block';
IO.done.disabled = true;
IO.choices.focus();
}
function pick(e) {
const IO = this.elements;
const sel = e.target;
if (sel.id === 'choices') {
const copy = sel.options[sel.selectedIndex].cloneNode(true);
IO.picked.append(copy);
numbers.push(+sel.value);
sel.options[sel.selectedIndex].remove();
}
if (sel.id === 'picked') {
const copy = sel.options[sel.selectedIndex].cloneNode(true);
IO.choices.append(copy);
let nodeList = [...IO.choices.options];
let ordered = nodeList.sort((a, b) => +a.value - +b.value);
IO.choices.replaceChildren(...nodeList, ...ordered);
numbers = numbers.filter((number) => number !== +sel.value);
sel.options[sel.selectedIndex].remove();
}
if (numbers.length === 6) {
IO.choices.disabled = true;
IO.done.disabled = false;
IO.done.focus();
} else {
IO.choices.disabled = false;
IO.done.disabled = true;
}
IO.box.firstElementChild.innerHTML = `Pick <b>${
6 - numbers.length
}</b> numbers -- 1 to 49<sup><small>✳️</small></sup>`;
}
function draw(e) {
const IO = this.closest('form').elements;
IO.box.disabled = true;
IO.note.classList.add('hide');
IO.results.classList.remove('hide');
let drawn = shuffle(A49);
drawn.length = 6;
let match = drawn.filter((number) => numbers.includes(number));
IO.final.innerHTML = mark(numbers, match);
IO.targets.innerHTML = mark(drawn, match);
let outcome = match.length > 0 ? mark(match) : 'Goose Egg 🥚';
IO.hits.innerHTML = outcome;
IO.replay.focus();
}
function shuffle(array) {
let qty = array.length,
temp,
i;
while (qty) {
i = Math.floor(Math.random() * qty--);
temp = array[qty];
array[qty] = array[i];
array[i] = temp;
}
return array;
}
function mark(arrayA, arrayB = arrayA) {
arrayA.sort((a, b) => a - b);
return arrayA.map((n) =>
arrayB.includes(n) ? `<mark>${n}</mark>` : n
);
}
</script>
</body>
</html>

最新更新