-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
78 lines (64 loc) · 2.64 KB
/
Copy pathscript.js
File metadata and controls
78 lines (64 loc) · 2.64 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
// Function to get a valid guess from the player
// It keeps prompting the user until a valid number (1-100) is entered or the user cancels.
function getPlayerGuess() {
while (true) {
const userInput = prompt("Enter a whole number between 1 and 100:");
if (userInput === null) {
return null; // User cancelled the game
}
// Check if the input is a valid number between 1 and 100
if (/^\d+$/.test(userInput)) {
const userGuess = Number(userInput);
if (userGuess >= 1 && userGuess <= 100) {
return userGuess; // Return the valid guess
}
}
// If the input is invalid, alert the user and continue the loop
alert("🚫 Invalid input. Please enter a whole number between 1 and 100.");
}
}
// Function to check the player's guess against the correct number
function checkGuess(playerGuess, correctNumber) {
if (playerGuess < correctNumber) {
return "Too low! 🔽 Try a higher number.";
} else if (playerGuess > correctNumber) {
return "Too high! 🔼 Try a lower number.";
} else {
return "🎉 Correct! You guessed the number!";
}
}
// Main function to play the number guessing game
function playGame() {
const correctNumber = Math.floor(Math.random() * 100) + 1;
const maxTries = 10;
let attempts = 0;
alert("🎯 Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.\nCan you guess it?");
while (attempts < maxTries) {
// Get a valid guess from the player (no need for a label here anymore)
const userGuess = getPlayerGuess();
if (userGuess === null) {
alert("Game cancelled. Goodbye!");
return; // Exit the game
}
attempts++; // A valid guess was made, so increment attempts
const result = checkGuess(userGuess, correctNumber);
alert(`Attempt ${attempts} of ${maxTries}: ${result}`);
if (userGuess === correctNumber) {
alert(`👏 You got it in ${attempts} attempt${attempts > 1 ? 's' : ''}!`);
break; // Exit the loop because the player won
}
}
// Check if the loop ended because the player ran out of attempts
if (attempts === maxTries && userGuess !== correctNumber) {
alert(`😞 You've used all ${maxTries} attempts.\nThe correct number was: ${correctNumber}`);
}
// Ask to play again
const playAgain = confirm("🔁 Do you want to play again?");
if (playAgain) {
playGame(); // Start a new game
} else {
alert("👋 Thanks for playing! Goodbye.");
}
}
// Start the game
playGame();