JavaScript 6选49彩票游戏开发求助:实现输入数字不重复校验及无重复随机数生成
Hey there! Let's tackle those two duplicate-related problems you're having with your lottery game. I'll break down the fixes and explain each change so you understand how it works.
1. Preventing Duplicate User Inputs
First, your existing containsDuplicates function has a small bug—it references an undefined array variable instead of using the input parameter. Plus, you weren't actually calling this function to check for duplicates after collecting the user's numbers. Here's how to fix that:
Updated Duplicate Check Function
function containsDuplicates(arr) { // A Set automatically removes duplicates, so if the size is smaller than the array length, there are duplicates return new Set(arr).size !== arr.length; }
Add Duplicate Check in Jetzt_Spielen
After collecting all 6 user numbers into the values array, add this check before proceeding:
let values = [value1, value2, value3, value4, value5, value6]; // Check for duplicate numbers if (containsDuplicates(values)) { alert("Doppelte Zahlen sind nicht erlaubt! Bitte geben Sie eindeutige Zahlen zwischen 1-49 ein."); return; // Stop execution if duplicates are found }
2. Generating Unique Random Winning Numbers
Your current random number generation can produce duplicates because it creates a new number each loop without checking if it's already been used. Instead, we'll create a function that builds an array of 6 unique random numbers:
New Random Number Generator Function
function generateWinningNumbers() { const winningNumbers = []; while (winningNumbers.length < 6) { // Use Math.floor for equal probability across 1-49 (Math.round can skew odds for 1 and 49) const randomNum = Math.floor(Math.random() * 49) + 1; // Only add the number if it's not already in the array if (!winningNumbers.includes(randomNum)) { winningNumbers.push(randomNum); } } return winningNumbers; }
Replace the Random Number Loop in Jetzt_Spielen
Remove your existing 6-loop random number code and replace it with this:
let matched = 0; const winningNumbers = generateWinningNumbers(); // Output each winning number and check for matches winningNumbers.forEach(num => { output("Gezogene Zahl: " + num); if (values.includes(num)) { matched++; } });
Full Updated JavaScript Code
Here's the complete fixed JavaScript code combining all the changes:
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(arr) { return new Set(arr).size !== arr.length; } 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 generateWinningNumbers() { const winningNumbers = []; while (winningNumbers.length < 6) { const randomNum = Math.floor(Math.random() * 49) + 1; if (!winningNumbers.includes(randomNum)) { winningNumbers.push(randomNum); } } return winningNumbers; } 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]; // Check for duplicate user inputs if (containsDuplicates(values)) { alert("Doppelte Zahlen sind nicht erlaubt! Bitte geben Sie eindeutige Zahlen zwischen 1-49 ein."); return; } let outputDiv = document.getElementById("output"); outputDiv.innerHTML = ""; let matched = 0; // Generate unique winning numbers and check matches const winningNumbers = generateWinningNumbers(); winningNumbers.forEach(num => { output("Gezogene Zahl: " + num); if (values.includes(num)) { matched++; } }); output("Du hast " + matched + " richtige Zahl(en)") }
Notes on Improvements
- Math.floor vs Math.round: Using
Math.floor(Math.random() * 49) + 1ensures every number from 1 to 49 has an equal chance of being selected.Math.round()would make 1 and 49 slightly less likely (since they only map from 0.5-1.0 and 48.0-48.5 respectively). - Set for Duplicate Checks: Using a
Setis a clean, efficient way to detect duplicates because it automatically ignores duplicate values.
Your HTML code doesn't need any changes—it works perfectly with the updated JavaScript!
内容的提问来源于stack exchange,提问作者soph

