0

I am making a very basic game in Node.js. Because it's not working, I've made it even more basic - if a user enters 'red' they win, 'blue' they don't.

The do...while loop should get the user's input, evaluate it, and stop the loop when they enter 'red' i.e. win.

My problem is that it isn't getting the user input before repeating the loop - it just asks the user the question endlessly in an infinite loop without letting them input anything? How can I fix this? Code below:

I declared a variable 'won':

const won = false;

I have a function getInput() that prompts the user and returns the input

function getInput() {

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

  readline.question('Red or blue?'), color => {
  return color
  readline.close();
  }
}

Then the do...while loop which should evaluate the user input and set won to true or false, with true ending the loop:

do {
  let color = getInput()
  
  if (color === "red") {
    console.log("You win!");
    won = true
  }
  
  else {
    console.log("Try again!")
  }
}
while (won === false)
Sammy
  • 63
  • 1
  • 7
  • you can put a `console.log` after this line `let color = getInput()` and check what is the input – Vivek Bani Jun 05 '21 at 13:48
  • `getInput` can't return what's been input because the input only arrives **later**. You can fix that by making it an `async` function and also p;utting the code using it in an `async` function, using `await`, and a promisified version of [`question`](https://nodejs.org/api/readline.html#readline_rl_question_query_options_callback). See that last link for an example. – T.J. Crowder Jun 05 '21 at 13:51
  • Also note that if you make `won` a `const`, you can't change its value from `false` to `true` later, because `const` means "constant" (unchanging). Use `let` instead. – T.J. Crowder Jun 05 '21 at 13:51
  • I recommend avoiding using `===` and `!==` (or `==` and `!=`) with boolean values. Instead of `while (won === false)`, the standard way to write that is `while (!won)`. – T.J. Crowder Jun 05 '21 at 13:52

0 Answers0