-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
97 lines (63 loc) · 2.48 KB
/
main.js
File metadata and controls
97 lines (63 loc) · 2.48 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const prompt = require('prompt-sync')();
const chalk = require('chalk');
function getDifficulty() {
console.log("\nPlease select the difficulty level:")
console.log(chalk.green("1. Easy (10 chances)"))
console.log(chalk.yellow("2. Medium (5 chances)"))
console.log(chalk.red("3. Hard (3 chances)\n"))
const difficultyLevel = prompt("Enter your choice: ");
if (difficultyLevel == 1) {
console.log("Great! You have selected the Easy difficulty level.");
console.log("Let's start the game!");
return 10;
}
else if (difficultyLevel == 2) {
console.log("Great! You have selected the Medium difficulty level.");
console.log("Let's start the game!");
return 5;
}
else if (difficultyLevel == 3) {
console.log("Great! You have selected the Hard difficulty level.");
console.log("Let's start the game!");
return 3;
}
else {
console.log("Error selecting difficulty...")
return getDifficulty(); //recursion
}
}
console.log("Welcome to the Number Guessing Game!")
console.log("I'm thinking of a number between 1 and 100.")
console.log("You have 5 chances to guess the correct number.")
do {
//get difficulty level from user
let numTries = getDifficulty();
//get random number
randomNumber = Math.floor(Math.random() * 100);
//console.log(randomNumber)
//start timer
const startingTime = Date.now()
numAttempts = 0;
for (let i = 0; i < numTries; i++) {
let guess = prompt("Enter your guess: ");
numAttempts++;
if (guess == randomNumber) {
//end timer
const elapsedTime = Math.floor((Date.now() - startingTime) / 1000);
console.log(`Congratulations! You guessed the correct number in ${numAttempts} attempts and ${elapsedTime} seconds.`);
break;
}
else if (guess != randomNumber && numTries - numAttempts != 0) {
if (guess > randomNumber) {
console.log(`Incorrect! The number is less than ${guess}.`)
}
else if (guess < randomNumber) {
console.log(`Incorrect! The number is greater than ${guess}.`)
}
}
else if (guess != randomNumber && numTries - numAttempts == 0) {
console.log(`Game over! You've used all your chances. The correct number was ${randomNumber}.`)
}
}
choice = prompt("Play again? (y/n): ");
} while (choice == "y")