1+ /**
2+ * Simple Command-Line "Guess the Number" Game in JavaScript (Node.js)
3+ *
4+ * The computer picks a random number between 1 and 100. The player
5+ * tries to guess it, and the computer provides hints ("Too high!" or
6+ * "Too low!") until the player guesses correctly.
7+ */
8+
9+ // To read user input
10+ const readline = require ( 'readline' ) . createInterface ( {
11+ input : process . stdin ,
12+ output : process . stdout
13+ } ) ;
14+
15+ // 1. Generate the random number (between 1 and 100)
16+ const targetNumber = Math . floor ( Math . random ( ) * 100 ) + 1 ;
17+
18+ // 2. Initialize the attempts counter
19+ let attempts = 0 ;
20+
21+ /**
22+ * The main game loop function.
23+ * It recursively asks the user for a guess until they get it right.
24+ */
25+ function askGuess ( ) {
26+ readline . question ( 'Guess a number between 1 and 100: ' , ( input ) => {
27+ const guess = parseInt ( input ) ;
28+
29+ // 3. Input Validation
30+ if ( isNaN ( guess ) || guess < 1 || guess > 100 ) {
31+ console . log ( 'Invalid input. Please enter a number between 1 and 100.' ) ;
32+ askGuess ( ) ; // Ask again without counting it as an attempt
33+ return ;
34+ }
35+
36+ // Valid guess, increment attempt counter
37+ attempts ++ ;
38+
39+ // 4. Feedback Logic
40+ if ( guess < targetNumber ) {
41+ console . log ( 'Too low! Try again.' ) ;
42+ askGuess ( ) ; // Recursive call for the next guess
43+ } else if ( guess > targetNumber ) {
44+ console . log ( 'Too high! Try again.' ) ;
45+ askGuess ( ) ; // Recursive call for the next guess
46+ } else {
47+ // 5. Win Condition
48+ console . log ( `\n🎉 Correct! The number was ${ targetNumber } .` ) ;
49+ console . log ( `You guessed it in ${ attempts } attempts!` ) ;
50+ readline . close ( ) ;
51+ }
52+ } ) ;
53+ }
54+
55+ // Start the game
56+ console . log ( '--- Welcome to Guess the Number! ---' ) ;
57+ console . log ( "I'm thinking of a number between 1 and 100..." ) ;
58+ askGuess ( ) ;
0 commit comments