Skip to content

Instantly share code, notes, and snippets.

@Dangeranger
Created April 8, 2021 23:48
Show Gist options
  • Save Dangeranger/7d747f01803358daf8f182c03e3e4aee to your computer and use it in GitHub Desktop.
Save Dangeranger/7d747f01803358daf8f182c03e3e4aee to your computer and use it in GitHub Desktop.
Helper files for Guess the Number
const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);
function ask(questionText) {
return new Promise((resolve, reject) => {
rl.question(questionText, resolve);
});
}
start();
async function start() {
let min = 1;
let max = 100;
console.log("Let's play a game where you (human) make up a number and I (computer) try to guess it.")
while (true) {
let secretNumber = await ask(
"What is your secret number?\nI won't peek, I promise...\n"
);
if (checkNumber(secretNumber, min, max)) {
console.log("You entered: " + secretNumber);
break;
} else {
console.log("Please enter a number again.");
}
}
gameLoop(); // keeps running until the answer
process.exit();
}
function gameLoop() {
while (true) {
let answer = await ask("Is this your number");
if (answer === "yes") {
console.log('Yay, I got the numebr')
break
}
}
}
function checkNumber(someInput, minimum, maximum) {
// return true or false
let maybeNumber = +someInput;
if (isNaN(maybeNumber)) {
return false;
}
if (someInput >= minimum && someInput <= maximum) {
return true;
}
}
function cleanAnswer(dirtyAnswer) {
if (["higher", "Higher", "H", "h"].includes(answer)) {
return "h";
} else if (["lower", "Lower", "L", "l"].includes(answer)) {
return "l";
} else {
return "";
}
}
// updateRange(answer, low, high)
function updateRange(answer, guess, low, high) {
if (["higher", "Higher", "H", "h"].includes(answer)) {
low = guess + 1;
return true;
} else if (["lower", "Lower", "L", "l"].includes(answer)) {
high = guess - 1;
return true;
} else {
return false;
}
}
// random randomGuess(50,75)
function randomGuess(lowBound, highBound) {
let difference = highBound - lowBound;
return Math.floor(Math.random() * (difference + 1) + lowBound);
}
// midpoint guess
function midpointGuess(lowBound, highBound) {
return Math.floor((lowBound + highBound) / 2);
}

STEPS

  1. Ask the user for a secret number
  2. Store the SECRET number
  3. Make a computer GUESS, within a range of MIN and MAX
  • Create the guess randomly or using a mid-point between min/max
  1. Ask, if the GUESS is correct
  • IF yes, THEN send message and exit the game
  • IF no, THEN ask a follow up question, for HIGH or LOW
  1. Ask, Is SECRET number HIGHER or LOWER
  • IF HIGHER
    • Update the MIN to the GUESS + 1
  • IF LOWER
    • Update the MAX to the GUESS - 1
  1. Loop back to Step.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment