Contenido del Curso
Node.js Express: API & CLI Apps
4. Developing REST API
Node.js Express: API & CLI Apps
Console App: Guessing Game
In this chapter, get ready to level up your console application skills as we dive into the creation of an exciting 🎮 Guess the Number 🔢 game app. This interactive game will challenge players to exercise their intuition by guessing a randomly generated number within a predefined range. Along the way, we'll unravel the mysteries of fundamental concepts such as
- 🎲 Random number generation;
- ✅ Input validation;
- 🤝 User interaction;
- 💾 Even saving game results to a file.
🏆 Challenge Awaits
Imagine delving into an app that promises excitement and intrigue. Players are invited to guess a mysteriously chosen number within a predefined range. The app offers instant feedback on each guess and a meticulous tally of the attempts made.
This hands-on example is your chance to refine your skills in building CLI Apps and showcases the art of crafting interactive programs.
🚀 Resulting App
See the magic in action! Below is a GIF illustrating the exciting Guess the Number Game app that you'll be crafting:
Building a Guessing Game Console App
You're presented with two paths. The first option beckons you to embark on the journey without assistance, while the second offers a helpful guide to ensure your success. Whether you dive in boldly or follow the structured guide, you're in for a fascinating experience that will leave you with a functional and captivating console app.
Masterplan
👉 Step 1: Setup and Initializations; 👉 Step 2: Define Game Parameters; 👉 Step 3: Define Utility Functions; 👉 Step 4: Game Logic; 👉 Step 5: Save Game Result; 👉 Step 6: Start the Game; 🎉 Conclusion; 🏁 Full App Code.
Step 1: Setup and Initializations
Prepare the canvas by creating a new directory and a file named app.js
. Within this file, we conjure the necessary modules:
Create a Readline interface:
Code Description
readline
: This is the Node.js built-in module that provides
an interface for reading input and writing output to and from the console.
-
readline.createInterface({ ... })
: This method creates an
instance of the readline.Interface
class. It takes an object
with two properties: input
and output
. -
input: process.stdin
: This sets the input stream for the
interface to the standard input process.stdin
. This means the
interface will read user input from the keyboard. -
output: process.stdout
: This sets the output stream for the
interface to the standard output process.stdout
. This means the
interface will write text to the console.
Explanation: We import the necessary modules: readline
for user interaction and fs.promises
for file operations. Then, we create a Readline
interface named rl
to handle input and output.
Step 2: Define Game Parameters
Set the minimum and maximum numbers:
Generate the secret number:
Code Description
Math.random()
: This function generates a random
floating-point number between 0 (inclusive) and 1 (exclusive). -
maxNumber - minNumber + 1
: This calculates the range of
possible numbers. Adding 1 to the difference between
maxNumber
and minNumber
is necessary because we
want to include both the minimum and maximum numbers in the possible range.
-
Math.random() * (maxNumber - minNumber + 1)
: This expression
produces a random number between 0 and the range of possible numbers. -
Math.floor(...)
: This function rounds down the floating-point
result of the previous expression to the nearest integer. This ensures that
the generated random number will be within the range of possible integers.
-
... + minNumber
: After rounding down, the result is then
added to minNumber
to shift the range of possible numbers from starting at 0 to starting at
minNumber
.
Initialize the attempts counter:
Explanation: We define the range of numbers (minNumber
and maxNumber
) within which the secret number will be generated. The secret number is randomly generated using Math.random()
and assigned to secretNumber
. The attempts
variable is initialized to keep track of the user's attempts.
Step 3: Define Utility Functions
Equip with a utility function for impeccable validation:
Code Description
!isNaN(guess)
: The isNaN()
function checks if
the provided value is "Not-a-Number" (NaN). In this case, it's used to
validate whether the guess
is a valid numeric input. If
guess
is a valid number, the isNaN()
function
returns false
, and the !
(logical NOT) operator
negates it, resulting in true
. -
guess >= minNumber
: This condition checks whether the
guess
is greater than or equal to the minNumber
.
It ensures that the guess is within the lower bound of the valid range.
-
guess <= maxNumber
: This condition checks whether the
guess
is less than or equal to the maxNumber
. It
ensures that the guess is within the upper bound of the valid range. -
&&
: The logical AND operator is used to combine all three
conditions. All conditions must be true for the entire expression to be
true.
Explanation: The isValidGuess
function checks whether the user's guess is a valid number within the specified range (minNumber
to maxNumber
).
Step 4: Game Logic
The game's core mechanics through the playGame
function:
Code Description
rl.question(Guess a number between ${minNumber} and ${maxNumber}: , guess
=> { ... })
: This line prompts the user to guess a number within the specified range
using the rl.question()
method. The user's response is passed
as the guess
argument to the provided callback function. -
if (isValidGuess(guess)) { ... }
: This condition checks if
the user's guess is valid using the isValidGuess
function you
defined earlier. -
attempts++;
: This increments the
attempts
counter, tracking the number of guesses the player has
made. -
const guessNumber = parseInt(guess);
: This line converts the
user's guess (which is a string) into an integer using
parseInt()
. -
if (guessNumber === secretNumber) { ... } else if (guessNumber <
secretNumber) { ... } else { ... }
: These conditional statements provide feedback to the player based on
their guess compared to the secretNumber
.
- If the player's guess matches the
secretNumber
, they've won. The game congratulates them, saves
the result, closes the readline
interface, and ends the game.
- If the player's guess is less than the
secretNumber
, they're prompted to try a higher number, and the
playGame()
function is called recursively to allow the player
to guess again. - If the player's guess is greater than the
secretNumber
, they're prompted to try a lower number, and the
playGame()
function is called recursively to allow the player
to guess again. -
else { ... }
: If the player's guess is not a valid number,
they're informed to enter a valid number within the specified range, and the
playGame()
function is called recursively to prompt the player
for another guess.
Explanation: The playGame
function forms the core game loop. It uses rl.question
to prompt the user for a guess. If the guess is valid, the function checks if the guess matches the secret number. If not, it provides feedback to the user and continues the game loop recursively.
Step 5: Save Game Result
Implement the logic of saving the user's game achievements into the game_results.txt
file.
Code Description
async function saveGameResult(result) { ... }
: This defines
an asynchronous function named saveGameResult
that takes a
result
parameter. This function will use the await keyword to
handle asynchronous operations within its body. -
try { ... } catch (err) { ... }
: This is a
try...catch
block used to handle potential errors that might
occur during the asynchronous operation.
-
await fs.appendFile('game_results.txt', ${result}\n);
: This
line uses the await
keyword to pause the execution of the
function until the asynchronous operation is complete. It appends the
provided result
along with a newline character to the
"game_results.txt" file using the fs.appendFile()
method. The
await
keyword is used because
fs.appendFile()
returns a promise. -
console.log('Game result saved.');
: If the appending of the
result to the file is successful, this line logs a message indicating that
the game result has been successfully saved. -
console.log('Failed to save game result.');
: If an error
occurs during the asynchronous operation (inside the
try
block), this line logs a message indicating that the
attempt to save the game result has failed.
Explanation: The saveGameResult
function uses fs.promises
to append the game result to a file named game_results.txt
. It provides feedback on the success or failure of saving the result.
Step 6: Start the Game
Create the welcome message and launch the game:
Explanation: We display a welcome message and start the game loop by calling the playGame
function.
🎉 Conclusion: Victory Lap
By developing the Guess the Number Game App, you've gained valuable experience in designing interactive and engaging console applications. This example showcases the fusion of user input, random number generation, validation, and file manipulation, resulting in a compelling gaming experience.
👨💻 Full App Code
Code Description
readline
module and the
fs
module's promises
API, which provides
asynchronous file system operations. Lines 4-7: Create a readline interface named
rl
for
reading from the console and writing to it.Lines 9-10: Define the minimum and maximum numbers for the guessing range.
Lines 12-13: Generate a secret number within the specified range using
Math.random()
and adjust it according to the minimum and
maximum values.Line 14: Initialize the
attempts
counter to keep track
of the number of guesses made.Lines 16-18: Define a function named
isValidGuess(guess)
that checks if the provided
guess
is a valid number within the specified range.Lines 20-47: Define a recursive function named
playGame()
that:- Prompts the user to guess a number within the specified range.
- Validates the guess and takes appropriate actions based on the guess.
- If the guess is correct, it congratulates the player, saves the game result, closes the readline interface, and ends the game.
- If the guess is too low, it prompts the user to try a higher number and calls
playGame()
again.- If the guess is too high, it prompts the user to try a lower number and calls
playGame()
again.- If the guess is invalid, it informs the user and calls
playGame()
again.Lines 49-56: Define an asynchronous function named
saveGameResult(result)
that appends the provided
result
to a text file named "game_results.txt". It handles both
successful and failed attempts to save the result.Line 58: Display a welcome message to the player.
Line 59: Start the game by calling the
playGame()
function.In summary, this code implements a simple guessing game where the player has to guess a secret number within a specified range. The player is prompted to make guesses, and the game provides feedback based on the correctness of the guesses. The game also saves the result of each play in a text file named "game_results.txt". The interaction with the player is managed using the
readline
module, and the file saving is
performed asynchronously using the fs
module's promises API.
¿Todo estuvo claro?
Contenido del Curso
Node.js Express: API & CLI Apps
4. Developing REST API
Node.js Express: API & CLI Apps
Console App: Guessing Game
In this chapter, get ready to level up your console application skills as we dive into the creation of an exciting 🎮 Guess the Number 🔢 game app. This interactive game will challenge players to exercise their intuition by guessing a randomly generated number within a predefined range. Along the way, we'll unravel the mysteries of fundamental concepts such as
- 🎲 Random number generation;
- ✅ Input validation;
- 🤝 User interaction;
- 💾 Even saving game results to a file.
🏆 Challenge Awaits
Imagine delving into an app that promises excitement and intrigue. Players are invited to guess a mysteriously chosen number within a predefined range. The app offers instant feedback on each guess and a meticulous tally of the attempts made.
This hands-on example is your chance to refine your skills in building CLI Apps and showcases the art of crafting interactive programs.
🚀 Resulting App
See the magic in action! Below is a GIF illustrating the exciting Guess the Number Game app that you'll be crafting:
Building a Guessing Game Console App
You're presented with two paths. The first option beckons you to embark on the journey without assistance, while the second offers a helpful guide to ensure your success. Whether you dive in boldly or follow the structured guide, you're in for a fascinating experience that will leave you with a functional and captivating console app.
Masterplan
👉 Step 1: Setup and Initializations; 👉 Step 2: Define Game Parameters; 👉 Step 3: Define Utility Functions; 👉 Step 4: Game Logic; 👉 Step 5: Save Game Result; 👉 Step 6: Start the Game; 🎉 Conclusion; 🏁 Full App Code.
Step 1: Setup and Initializations
Prepare the canvas by creating a new directory and a file named app.js
. Within this file, we conjure the necessary modules:
Create a Readline interface:
Code Description
readline
: This is the Node.js built-in module that provides
an interface for reading input and writing output to and from the console.
-
readline.createInterface({ ... })
: This method creates an
instance of the readline.Interface
class. It takes an object
with two properties: input
and output
. -
input: process.stdin
: This sets the input stream for the
interface to the standard input process.stdin
. This means the
interface will read user input from the keyboard. -
output: process.stdout
: This sets the output stream for the
interface to the standard output process.stdout
. This means the
interface will write text to the console.
Explanation: We import the necessary modules: readline
for user interaction and fs.promises
for file operations. Then, we create a Readline
interface named rl
to handle input and output.
Step 2: Define Game Parameters
Set the minimum and maximum numbers:
Generate the secret number:
Code Description
Math.random()
: This function generates a random
floating-point number between 0 (inclusive) and 1 (exclusive). -
maxNumber - minNumber + 1
: This calculates the range of
possible numbers. Adding 1 to the difference between
maxNumber
and minNumber
is necessary because we
want to include both the minimum and maximum numbers in the possible range.
-
Math.random() * (maxNumber - minNumber + 1)
: This expression
produces a random number between 0 and the range of possible numbers. -
Math.floor(...)
: This function rounds down the floating-point
result of the previous expression to the nearest integer. This ensures that
the generated random number will be within the range of possible integers.
-
... + minNumber
: After rounding down, the result is then
added to minNumber
to shift the range of possible numbers from starting at 0 to starting at
minNumber
.
Initialize the attempts counter:
Explanation: We define the range of numbers (minNumber
and maxNumber
) within which the secret number will be generated. The secret number is randomly generated using Math.random()
and assigned to secretNumber
. The attempts
variable is initialized to keep track of the user's attempts.
Step 3: Define Utility Functions
Equip with a utility function for impeccable validation:
Code Description
!isNaN(guess)
: The isNaN()
function checks if
the provided value is "Not-a-Number" (NaN). In this case, it's used to
validate whether the guess
is a valid numeric input. If
guess
is a valid number, the isNaN()
function
returns false
, and the !
(logical NOT) operator
negates it, resulting in true
. -
guess >= minNumber
: This condition checks whether the
guess
is greater than or equal to the minNumber
.
It ensures that the guess is within the lower bound of the valid range.
-
guess <= maxNumber
: This condition checks whether the
guess
is less than or equal to the maxNumber
. It
ensures that the guess is within the upper bound of the valid range. -
&&
: The logical AND operator is used to combine all three
conditions. All conditions must be true for the entire expression to be
true.
Explanation: The isValidGuess
function checks whether the user's guess is a valid number within the specified range (minNumber
to maxNumber
).
Step 4: Game Logic
The game's core mechanics through the playGame
function:
Code Description
rl.question(Guess a number between ${minNumber} and ${maxNumber}: , guess
=> { ... })
: This line prompts the user to guess a number within the specified range
using the rl.question()
method. The user's response is passed
as the guess
argument to the provided callback function. -
if (isValidGuess(guess)) { ... }
: This condition checks if
the user's guess is valid using the isValidGuess
function you
defined earlier. -
attempts++;
: This increments the
attempts
counter, tracking the number of guesses the player has
made. -
const guessNumber = parseInt(guess);
: This line converts the
user's guess (which is a string) into an integer using
parseInt()
. -
if (guessNumber === secretNumber) { ... } else if (guessNumber <
secretNumber) { ... } else { ... }
: These conditional statements provide feedback to the player based on
their guess compared to the secretNumber
.
- If the player's guess matches the
secretNumber
, they've won. The game congratulates them, saves
the result, closes the readline
interface, and ends the game.
- If the player's guess is less than the
secretNumber
, they're prompted to try a higher number, and the
playGame()
function is called recursively to allow the player
to guess again. - If the player's guess is greater than the
secretNumber
, they're prompted to try a lower number, and the
playGame()
function is called recursively to allow the player
to guess again. -
else { ... }
: If the player's guess is not a valid number,
they're informed to enter a valid number within the specified range, and the
playGame()
function is called recursively to prompt the player
for another guess.
Explanation: The playGame
function forms the core game loop. It uses rl.question
to prompt the user for a guess. If the guess is valid, the function checks if the guess matches the secret number. If not, it provides feedback to the user and continues the game loop recursively.
Step 5: Save Game Result
Implement the logic of saving the user's game achievements into the game_results.txt
file.
Code Description
async function saveGameResult(result) { ... }
: This defines
an asynchronous function named saveGameResult
that takes a
result
parameter. This function will use the await keyword to
handle asynchronous operations within its body. -
try { ... } catch (err) { ... }
: This is a
try...catch
block used to handle potential errors that might
occur during the asynchronous operation.
-
await fs.appendFile('game_results.txt', ${result}\n);
: This
line uses the await
keyword to pause the execution of the
function until the asynchronous operation is complete. It appends the
provided result
along with a newline character to the
"game_results.txt" file using the fs.appendFile()
method. The
await
keyword is used because
fs.appendFile()
returns a promise. -
console.log('Game result saved.');
: If the appending of the
result to the file is successful, this line logs a message indicating that
the game result has been successfully saved. -
console.log('Failed to save game result.');
: If an error
occurs during the asynchronous operation (inside the
try
block), this line logs a message indicating that the
attempt to save the game result has failed.
Explanation: The saveGameResult
function uses fs.promises
to append the game result to a file named game_results.txt
. It provides feedback on the success or failure of saving the result.
Step 6: Start the Game
Create the welcome message and launch the game:
Explanation: We display a welcome message and start the game loop by calling the playGame
function.
🎉 Conclusion: Victory Lap
By developing the Guess the Number Game App, you've gained valuable experience in designing interactive and engaging console applications. This example showcases the fusion of user input, random number generation, validation, and file manipulation, resulting in a compelling gaming experience.
👨💻 Full App Code
Code Description
readline
module and the
fs
module's promises
API, which provides
asynchronous file system operations. Lines 4-7: Create a readline interface named
rl
for
reading from the console and writing to it.Lines 9-10: Define the minimum and maximum numbers for the guessing range.
Lines 12-13: Generate a secret number within the specified range using
Math.random()
and adjust it according to the minimum and
maximum values.Line 14: Initialize the
attempts
counter to keep track
of the number of guesses made.Lines 16-18: Define a function named
isValidGuess(guess)
that checks if the provided
guess
is a valid number within the specified range.Lines 20-47: Define a recursive function named
playGame()
that:- Prompts the user to guess a number within the specified range.
- Validates the guess and takes appropriate actions based on the guess.
- If the guess is correct, it congratulates the player, saves the game result, closes the readline interface, and ends the game.
- If the guess is too low, it prompts the user to try a higher number and calls
playGame()
again.- If the guess is too high, it prompts the user to try a lower number and calls
playGame()
again.- If the guess is invalid, it informs the user and calls
playGame()
again.Lines 49-56: Define an asynchronous function named
saveGameResult(result)
that appends the provided
result
to a text file named "game_results.txt". It handles both
successful and failed attempts to save the result.Line 58: Display a welcome message to the player.
Line 59: Start the game by calling the
playGame()
function.In summary, this code implements a simple guessing game where the player has to guess a secret number within a specified range. The player is prompted to make guesses, and the game provides feedback based on the correctness of the guesses. The game also saves the result of each play in a text file named "game_results.txt". The interaction with the player is managed using the
readline
module, and the file saving is
performed asynchronously using the fs
module's promises API.
¿Todo estuvo claro?