game1 / game.js
JAYASWAROOP's picture
Update game.js
42d8520
// Function to generate a random 4-digit number without repeating digits and without the first digit being 0
function generateRandomNumber() {
let num = [Math.floor(Math.random() * 9) + 1];
for (let i = 1; i < 4; i++) {
num.push(Math.floor(Math.random() * 10));
}
return num;
}
// Generate the random number
let a;
do {
a = generateRandomNumber();
} while (new Set(a).size !== 4);
// Main game loop
while (true) {
// Get user input
let x = prompt("Enter your guess (type 'exit' to quit):");
// Check for exit command
if (x.toLowerCase() === 'exit') {
let confirmExit = confirm("Are you sure you want to exit the game?");
if (confirmExit) {
alert("Thanks for playing! Exiting the game.");
break;
} else {
continue;
}
}
// Check for repeated digits or first digit being 0
if (new Set(x).size !== 4 || x[0] === '0') {
alert("Invalid input. Please enter a 4-digit number with non-repeating digits and the first digit not being 0.");
continue;
}
let b = x.split('').map(Number);
let cow = 0;
let bull = 0;
// Check for bulls and cows
if (b.length > 4) {
alert("Invalid input. Please enter a 4-digit number with non-repeating digits and the first digit not being 0.");
continue;
}
for (let i = 0; i < 4; i++) {
if (b[i] === a[i]) {
cow += 1;
} else if (a.includes(b[i])) {
bull += 1;
}
}
// Provide feedback
alert("Bulls: " + bull + "\nCows: " + cow);
// Check if the player has won
if (cow === 4) {
alert("Congratulations! You won the game.");
break;
}
}