Last active
March 20, 2023 21:55
-
-
Save leopolicastro/dd775acd8d745837731428e530e51615 to your computer and use it in GitHub Desktop.
Number Guessing Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Declare our variables | |
const prompt = require('readline-sync'); | |
let maxGuesses = 3; | |
let currentGuess = 0; | |
const maxRange = 10; | |
// Generate random number | |
let randomNumber = Math.floor(Math.random() * maxRange + 1); | |
// console.log('Random number: ', randomNumber); | |
// Get user name | |
// Prompt user to make first guess | |
let userGuess = prompt.question( | |
`Hi, I have chosen a number between 1 and ${maxRange}, you have ${maxGuesses} tries to guess it.\n` | |
); | |
const handleGuess = userGuess => { | |
for (let guesses = 0; guesses < maxGuesses; guesses++) { | |
if (userGuess == randomNumber) { | |
console.log('You win! 🏆'); | |
guesses = maxGuesses; | |
playAgain(); | |
} else if (guesses === maxGuesses - 1) { | |
console.log(`You lose. 💀\nThe number was ${randomNumber}`); | |
playAgain(); | |
} else if (userGuess > randomNumber) { | |
thinkLower(); | |
userGuess = prompt.question('Guess again...\n'); | |
} else { | |
thinkHigher(); | |
userGuess = prompt.question('Guess again...\n'); | |
} | |
} | |
}; | |
// Play Again Function | |
const playAgain = () => { | |
let playAgain = prompt.question('Do you want to play again? y || n \n'); | |
playAgain = playAgain.toLowerCase(); | |
if (playAgain === 'y') { | |
randomNumber = Math.floor(Math.random() * maxRange + 1); | |
// console.log("New random number", randomNumber); | |
let newGuess = prompt.question( | |
`I have chosen a number between 1 and ${maxRange}, you have ${maxGuesses} tries to guess it.\n` | |
); | |
currentGuess = 0; | |
guesses = 0; | |
handleGuess(newGuess); | |
} else { | |
console.log('Thanks for playing.\nGoodbye.'); | |
} | |
}; | |
// Function declaration | |
function thinkLower() { | |
console.log('Think lower.'); | |
currentGuess++; | |
console.log('Guesses Left: ', maxGuesses - currentGuess); | |
} | |
// ES6 Arrow function | |
const thinkHigher = () => { | |
console.log('Think higher.'); | |
currentGuess++; | |
console.log('Guesses Left: ', maxGuesses - currentGuess); | |
}; | |
// Call our function | |
handleGuess(userGuess); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment