How do I get user input, and THEN run code. My code doesn't let me answer, and just continues.
Try running this in node:
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
let num1 = 0;
let num2 = 0;
let mode = "+";
let ans = 0;
let input = "";
while (true) {
num1 = Math.floor(Math.random() * 10);
num2 = Math.floor(Math.random() * 10);
ans = num1 + num2;
console.log(`What is ${num1} + ${num2}?`);
readline.question("Enter Answer >>", (ans) => {
readline.close();
});
sleep(3000);
if (ans == input) {
console.log("Correct!");
} else {
console.log("Wrong! Review this video for help: *insert youtube link*.");
console.log(`Answer: ${ans}`);
}
sleep(3000);
}
If this question is unclear, please tell me and I will try to explain what I mean.
What it should run like (written in python):
import random
n1 = 0
n2 = 0
ans = 0
userinput = ""
while True:
n1 = random.randrange(0, 10)
n2 = random.randrange(0, 10)
ans = n1 + n2
userinput = input(f'What is {str(n1)} + {str(n2)}? >> ')
if int(userinput) == ans:
print("Correct!")
else:
print("Wrong!")
One key difference between node.js and Python you have to understand up front is that node.js is completely non-blocking: you can't block the main (or in the case of Javascript only) thread waiting for user input. So you have to write the program differently, because node isn't made for writing that sort of program.
This should about do the trick:
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('close', () => {
process.exit(0);
});
function askQuestion(num1, num2) {
return new Promise(resolve => {
rl.question(`What is ${num1} + ${num2}? (press q to quit)`, input => {
resolve(input);
});
});
}
function sleep(n) {
return new Promise(resolve => setTimeout(resolve, n));
}
async function turn() {
const num1 = Math.floor(Math.random() * 10);
const num2 = Math.floor(Math.random() * 10);
const userInput = await askQuestion(num1, num2);
if (userInput === "q") return userInput;
if (+userInput === num1 + num2) {
console.log('correct');
} else {
console.log('wrong');
}
}
(async function() {
let result;
while (true) {
result = await turn();
if (result === "q") break;
await sleep(3000);
}
rl.close();
})();
This may seem long and complex compared to the Python version you posted, but if you actually wrote the equivalent Python program using asyncio, Futures, and an event loop it would look a lot more like this one.