Spaces:
Running
Running
Commit
·
16974e5
1
Parent(s):
c8b1781
Update game.js
Browse files
game.js
CHANGED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Function to generate a random 4-digit number without repeating digits and without the first digit being 0
|
2 |
+
function generateRandomNumber() {
|
3 |
+
let num = [Math.floor(Math.random() * 9) + 1];
|
4 |
+
for (let i = 1; i < 4; i++) {
|
5 |
+
num.push(Math.floor(Math.random() * 10));
|
6 |
+
}
|
7 |
+
return num;
|
8 |
+
}
|
9 |
+
|
10 |
+
// Generate the random number
|
11 |
+
let a;
|
12 |
+
do {
|
13 |
+
a = generateRandomNumber();
|
14 |
+
} while (new Set(a).size !== 4);
|
15 |
+
|
16 |
+
alert("Generated number: " + a);
|
17 |
+
|
18 |
+
// Main game loop
|
19 |
+
while (true) {
|
20 |
+
// Get user input
|
21 |
+
let x = prompt("Enter your guess (type 'exit' to quit):");
|
22 |
+
|
23 |
+
// Check for exit command
|
24 |
+
if (x.toLowerCase() === 'exit') {
|
25 |
+
let confirmExit = confirm("Are you sure you want to exit the game?");
|
26 |
+
if (confirmExit) {
|
27 |
+
alert("Thanks for playing! Exiting the game.");
|
28 |
+
break;
|
29 |
+
} else {
|
30 |
+
continue;
|
31 |
+
}
|
32 |
+
}
|
33 |
+
|
34 |
+
// Check for repeated digits or first digit being 0
|
35 |
+
if (new Set(x).size !== 4 || x[0] === '0') {
|
36 |
+
alert("Invalid input. Please enter a 4-digit number with non-repeating digits and the first digit not being 0.");
|
37 |
+
continue;
|
38 |
+
}
|
39 |
+
|
40 |
+
let b = x.split('').map(Number);
|
41 |
+
let cow = 0;
|
42 |
+
let bull = 0;
|
43 |
+
|
44 |
+
// Check for bulls and cows
|
45 |
+
if (b.length > 4) {
|
46 |
+
alert("Invalid input. Please enter a 4-digit number with non-repeating digits and the first digit not being 0.");
|
47 |
+
continue;
|
48 |
+
}
|
49 |
+
|
50 |
+
for (let i = 0; i < 4; i++) {
|
51 |
+
if (b[i] === a[i]) {
|
52 |
+
cow += 1;
|
53 |
+
} else if (a.includes(b[i])) {
|
54 |
+
bull += 1;
|
55 |
+
}
|
56 |
+
}
|
57 |
+
|
58 |
+
// Provide feedback
|
59 |
+
alert("Bulls: " + bull + "\nCows: " + cow);
|
60 |
+
|
61 |
+
// Check if the player has won
|
62 |
+
if (cow === 4) {
|
63 |
+
alert("Congratulations! You won the game.");
|
64 |
+
break;
|
65 |
+
}
|
66 |
+
}
|