Conteúdo do Curso
Node.js Express: API & CLI Apps
2. Aplicações de Console
4. Desenvolver API REST
Node.js Express: API & CLI Apps
Aplicativo de Console: Jogo de Adivinhação
Neste capítulo, prepare-se para aperfeiçoar suas habilidades em aplicativos de console enquanto mergulhamos na criação de um empolgante jogo 🎮 Adivinhe o Número 🔢. Este jogo interativo desafiará os jogadores a exercitar sua intuição ao adivinhar um número gerado aleatoriamente dentro de um intervalo predefinido. Ao longo do caminho, vamos desvendar os mistérios de conceitos fundamentais como:
- 🎲 geração de números aleatórios
- ✅ validação de entrada
- 🤝 interação com o usuário
- 💾 até mesmo salvando os resultados do jogo em um arquivo
🏆 Desafio à Espera
Imagine-se mergulhando em um aplicativo que promete emoção e intriga. Os jogadores são convidados a adivinhar um número misteriosamente escolhido dentro de uma faixa predefinida. O aplicativo oferece um feedback instantâneo a cada palpite e um registro meticuloso das tentativas realizadas.
Este exemplo prático é a sua chance de aprimorar suas habilidades na construção de Apps de Linha de Comando e demonstra a arte de criar programas interativos.
🚀 App Resultante
Veja a mágica acontecer! Abaixo está um GIF ilustrando o emocionante aplicativo Jogo de Adivinhar o Número que você estará criando:
Construindo um Jogo de Adivinhação de Console
Você se depara com dois caminhos. A primeira opção convida você a embarcar na jornada sem assistência, enquanto a segunda oferece um guia útil para garantir seu sucesso. Quer você mergulhe corajosamente ou siga o guia estruturado, você terá uma experiência fascinante que resultará em um aplicativo de console funcional e cativante.
Plano Mestre
👉 Passo 1: Configuração e Inicializações 👉 Passo 2: Definir Parâmetros do Jogo 👉 Passo 3: Definir Funções Úteis 👉 Passo 4: Lógica do Jogo 👉 Passo 5: Salvar Resultado do Jogo 👉 Passo 6: Iniciar o Jogo 🎉 Conclusão 🏁 Código Completo do Aplicativo
Etapa 1: Configuração e Inicializações
Prepare o ambiente criando um novo diretório e um arquivo chamado app.js
. Dentro deste arquivo, vamos invocar os módulos necessários:
Crie uma interface Readline:
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.
Explicação: Importamos os módulos necessários: readline
para interação com o usuário e fs.promises
para operações com arquivos. Em seguida, criamos uma interface Readline
chamada rl
para lidar com entrada e saída.
Etapa 2: Definir Parâmetros do Jogo
Defina os números mínimo e máximo:
Gere o número secreto:
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
.
Inicialize o contador de tentativas:
Explicação: Definimos o intervalo de números (minNumber
e maxNumber
) dentro do qual o número secreto será gerado. O número secreto é gerado aleatoriamente utilizando Math.random()
e atribuído a secretNumber
. A variável attempts
é iniciada para acompanhar as tentativas do usuário.
Passo 3: Definir Funções de Utilitário
Equipe-se com uma função de utilitário para validação impecável:
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.
Explicação: A função isValidGuess
verifica se o palpite do usuário é um número válido dentro do intervalo especificado (minNumber
a maxNumber
).
Passo 4: Lógica do Jogo
As mecânicas centrais do jogo através da função playGame
:
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.
Explicação: A função playGame
forma o loop principal do jogo. Ela utiliza rl.question
para solicitar ao usuário um palpite. Se o palpite for válido, a função verifica se ele corresponde ao número secreto. Caso contrário, fornece um feedback ao usuário e continua o loop do jogo de forma recursiva.
Passo 5: Salvar Resultado do Jogo
Implemente a lógica de salvar as conquistas do usuário no jogo no arquivo game_results.txt
.
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.
Explicação: A função saveGameResult
usa fs.promises
para adicionar o resultado do jogo a um arquivo chamado game_results.txt
. Ela fornece um retorno sobre o sucesso ou falha ao salvar o resultado.
Passo 6: Iniciar o Jogo
Crie a mensagem de boas-vindas e inicie o jogo:
Explicação: Exibimos uma mensagem de boas-vindas e iniciamos o loop do jogo chamando a função playGame
.
🎉 Conclusão: Volta da Vitória
Ao desenvolver o Aplicativo Jogo de Adivinhar o Número, você adquiriu experiência valiosa no desenho de aplicações de console interativas e atrativas. Este exemplo destaca a fusão da entrada de usuário, geração de números aleatórios, validação e manipulação de arquivos, resultando em uma experiência de jogo envolvente.
👨💻 Código Completo do App
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.
Tudo estava claro?
Conteúdo do Curso
Node.js Express: API & CLI Apps
2. Aplicações de Console
4. Desenvolver API REST
Node.js Express: API & CLI Apps
Aplicativo de Console: Jogo de Adivinhação
Neste capítulo, prepare-se para aperfeiçoar suas habilidades em aplicativos de console enquanto mergulhamos na criação de um empolgante jogo 🎮 Adivinhe o Número 🔢. Este jogo interativo desafiará os jogadores a exercitar sua intuição ao adivinhar um número gerado aleatoriamente dentro de um intervalo predefinido. Ao longo do caminho, vamos desvendar os mistérios de conceitos fundamentais como:
- 🎲 geração de números aleatórios
- ✅ validação de entrada
- 🤝 interação com o usuário
- 💾 até mesmo salvando os resultados do jogo em um arquivo
🏆 Desafio à Espera
Imagine-se mergulhando em um aplicativo que promete emoção e intriga. Os jogadores são convidados a adivinhar um número misteriosamente escolhido dentro de uma faixa predefinida. O aplicativo oferece um feedback instantâneo a cada palpite e um registro meticuloso das tentativas realizadas.
Este exemplo prático é a sua chance de aprimorar suas habilidades na construção de Apps de Linha de Comando e demonstra a arte de criar programas interativos.
🚀 App Resultante
Veja a mágica acontecer! Abaixo está um GIF ilustrando o emocionante aplicativo Jogo de Adivinhar o Número que você estará criando:
Construindo um Jogo de Adivinhação de Console
Você se depara com dois caminhos. A primeira opção convida você a embarcar na jornada sem assistência, enquanto a segunda oferece um guia útil para garantir seu sucesso. Quer você mergulhe corajosamente ou siga o guia estruturado, você terá uma experiência fascinante que resultará em um aplicativo de console funcional e cativante.
Plano Mestre
👉 Passo 1: Configuração e Inicializações 👉 Passo 2: Definir Parâmetros do Jogo 👉 Passo 3: Definir Funções Úteis 👉 Passo 4: Lógica do Jogo 👉 Passo 5: Salvar Resultado do Jogo 👉 Passo 6: Iniciar o Jogo 🎉 Conclusão 🏁 Código Completo do Aplicativo
Etapa 1: Configuração e Inicializações
Prepare o ambiente criando um novo diretório e um arquivo chamado app.js
. Dentro deste arquivo, vamos invocar os módulos necessários:
Crie uma interface Readline:
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.
Explicação: Importamos os módulos necessários: readline
para interação com o usuário e fs.promises
para operações com arquivos. Em seguida, criamos uma interface Readline
chamada rl
para lidar com entrada e saída.
Etapa 2: Definir Parâmetros do Jogo
Defina os números mínimo e máximo:
Gere o número secreto:
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
.
Inicialize o contador de tentativas:
Explicação: Definimos o intervalo de números (minNumber
e maxNumber
) dentro do qual o número secreto será gerado. O número secreto é gerado aleatoriamente utilizando Math.random()
e atribuído a secretNumber
. A variável attempts
é iniciada para acompanhar as tentativas do usuário.
Passo 3: Definir Funções de Utilitário
Equipe-se com uma função de utilitário para validação impecável:
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.
Explicação: A função isValidGuess
verifica se o palpite do usuário é um número válido dentro do intervalo especificado (minNumber
a maxNumber
).
Passo 4: Lógica do Jogo
As mecânicas centrais do jogo através da função playGame
:
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.
Explicação: A função playGame
forma o loop principal do jogo. Ela utiliza rl.question
para solicitar ao usuário um palpite. Se o palpite for válido, a função verifica se ele corresponde ao número secreto. Caso contrário, fornece um feedback ao usuário e continua o loop do jogo de forma recursiva.
Passo 5: Salvar Resultado do Jogo
Implemente a lógica de salvar as conquistas do usuário no jogo no arquivo game_results.txt
.
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.
Explicação: A função saveGameResult
usa fs.promises
para adicionar o resultado do jogo a um arquivo chamado game_results.txt
. Ela fornece um retorno sobre o sucesso ou falha ao salvar o resultado.
Passo 6: Iniciar o Jogo
Crie a mensagem de boas-vindas e inicie o jogo:
Explicação: Exibimos uma mensagem de boas-vindas e iniciamos o loop do jogo chamando a função playGame
.
🎉 Conclusão: Volta da Vitória
Ao desenvolver o Aplicativo Jogo de Adivinhar o Número, você adquiriu experiência valiosa no desenho de aplicações de console interativas e atrativas. Este exemplo destaca a fusão da entrada de usuário, geração de números aleatórios, validação e manipulação de arquivos, resultando em uma experiência de jogo envolvente.
👨💻 Código Completo do App
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.
Tudo estava claro?