File size: 1,735 Bytes
16974e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 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;
    }
}