When the user correctly guesses the random number, the message should display how many total guesses were made and what each guess was. I have created an array, but the array shows 2 for the number of tries and the random number for the values every time. I understand that in the arrray, the index equals the total number of guesses and the value at each index should be the guess made. I added the .push function in each if statement loop, but it's still not working. I cannot figure out why. Please help.
I made 4 guesses (14, 61, 63, 62) on this run, and the array is still wrong.
function do_guess() {
let guess = document.getElementById("guess").value;
let message = document.getElementById("message");
const guesses = [];
guesses.push(guess);
if (guess == num) {
guesses.push(guess);
message.innerHTML = "You got it! It took you " + guesses.length + " tries and your guesses were " + guesses;
} else if (guess > Math.ceil(input)) {
message.innerHTML = "That number is not in range!";
} else if (guess <= 0) {
message.innerHTML = "That number is not in range!";
} else if (guess < 1) {
message.innerHTML = "That number is not in range!";
} else if (guess < num) {
guesses.push(guess);
message.innerHTML = "Try a higher number.";
} else if (guess > num) {
guesses.push(guess);
message.innerHTML = "Try a lower number.";
} else if (guess !== Number) {
message.innerHTML = "That is not a number!"
}
}
You're close, but there are a couple of minor problems with your implementation:
Declaring guesses within your doGuess function means it's a new array each time doGuess is invoked; you lose the guess history.
You're calling guesses.push twice: once at the start of the function and again within the conditions.
You can solve the first (bigger) problem by moving const guesses = [] outside of the function body.
const guesses = []; // <= move this outside the function
function do_guess() {
let guess = document.getElementById("guess").value;
let message = document.getElementById("message");
// ...
}
And the second by either removing the initial push call or removing the additional push calls within the conditions, so you're not adding the guess twice:
function do_guess() {
let guess = document.getElementById("guess").value;
let message = document.getElementById("message");
const guesses = [];
guesses.push(guess); // <== either remove this
if (guess == num) {
guesses.push(guess); // <= or remove this
message.innerHTML = "You got it! It took you " + guesses.length + " tries and your guesses were " + guesses;
}
// ...
} else if (guess > num) {
guesses.push(guess); <= and this
message.innerHTML = "Try a lower number.";
}
Related
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
I'm working on a random number guessing game in JavaScript. I want the user to input a lowLimit and a highLimit and have the random number generated between those two numbers. I tried hardcoding the lowLimit and highLimit as below:
let lowLimit = 5;
let highLimit = 20;
let random = Math.floor(Math.random() * highLimit);
if (random < lowLimit) {
random += lowLimit;
}
console.log(random);
and everything works well.
However, when I allow the user to input values, the random number always becomes the sum of lowLimit and upperLimit. I cannot figure this out!
My final code is this:
let lowLimit = prompt('Input the lower limit:');
let highLimit = prompt('Input the upper limit:');
let random = Math.floor(Math.random() * highLimit);
let tries = 0;
if (random < lowLimit) {
random += lowLimit;
}
console.log(random);
let guess = prompt('Secret number generated. Enter guess:');
while (guess !== random) {
if (guess === 'q') break;
tries += 1;
if (guess > random) {
prompt('You guessed too high. Guess again...');
} else if (guess < random) {
prompt('You guessed too low. Guess again...');
} else {
alert('You guessed correctly! You made ' + tries + " guesses.");
}
}
This solution works. Any refactoring suggestions are welcome.
let lowLimit = Number(prompt('Input the lower limit:'));
let highLimit = Number(prompt('Input the upper limit:'));
while (!lowLimit || !highLimit) {
lowLimit = Number(prompt('Input a valid lower limit:'));
highLimit = Number(prompt('Input a valid upper limit:'));
}
lowLimit = Number(lowLimit);
highLimit = Number(highLimit);
let random = Math.floor(Math.random() * (highLimit - lowLimit) + lowLimit);
let guesses = 0;
console.log(random);
guess = prompt('Enter guess:');
while (guess !== random) {
if (guess === 'q') {
alert('Ok. Quitting... You made ' + guesses + ' guesses')
break;
}
guesses += 1;
guess = Number(guess);
if (guess > random) {
guess = prompt('You guessed too high. Guess again...');
} else if (guess < random) {
guess = prompt('You guessed too low. Guess again...');
} else alert('You guessed correctly! You made ' + guesses + " guesses.");
}
A few tweaks to improve the code, and one bug fix (the case where user guesses correctly on the first try, they will receive no feedback)...
// + is concise way to coerce an int
const lowLimit = +prompt('Input the lower limit:');
const highLimit = +prompt('Input the upper limit:');
// note - we could add checks here for invalid or disordered values
// this presumes we want random to be exclusive of highLimit. if not, we'll need to tweak
const random = Math.floor(Math.random() * (highLimit - lowLimit) + lowLimit);
// we'll vary the prompt during the game
let promptMsg = 'Enter guess:', guesses = 0, guess;
// bug fix and cleanup: do while, so we always play at least once
// prompt in just one place, alter the prompt message to represent game state
do {
guess = prompt(promptMsg);
guesses++;
if (guess !== 'q') {
guess = +guess;
if (guess > random) {
promptMsg = 'You guessed too high. Guess again...';
} else if (guess < random) {
promptMsg = 'You guessed too low. Guess again...';
}
}
} while (guess !== 'q' && guess !== random);
const endMsg = guess === 'q' ? 'Ok. Quitting' : 'You guessed correctly.'
const guessesMsg = `You made ${guesses} ${guesses === 1 ? 'guess' : 'guesses'}`;
alert(`${endMsg} ${guessesMsg}`)
We can generate a random number by using the Date.now()
let res = Date.now() % (highLimit - lowLimit + 1) + lowLimit.
This is because nobody can estimate the time in milisecond the code runs.
I have a prompt asking a user for a number(guess), until they guess a randomly selected number(num). I'm trying to keep track of these guesses by putting them in an array.
let guessesArray = [];
if (guess == num && guess != NaN) {
guessesArray.push(guess);
message.innerHTML = "You got it! It took you " + guessesArray.length +
" tries and your guesses were " + guessesArray + ".";
}
else if (guess > num && guess != NaN) {
if (guess <= max) {
guessesArray.push(guess);
message.innerHTML = "No, try a lower number.";
} etc...
as i watch the console while guessing numbers, every time the push function is used, it just replaces the value at index 0. so when the user finds the correct answer, the message they receive is always that they got the answer in 1 guess and what should be a list of numbers that they guessed, is instead just the last number they guessed. How can I properly append to an array in JS?
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let guessesArray = [];
if (guess == num && guess != NaN) {
guessesArray.push(guess);
message.innerHTML = "You got it! It took you " + guessesArray.length +
" tries and your guesses were " + guessesArray + ".";
}
else if (guess > num && guess != NaN) {
if (guess <= max) {
guessesArray.push(guess);
message.innerHTML = "No, try a lower number.";
}
else {
message.innerHTML = "That number is not in range, try again.";
}
}
else if (guess < num && guess != NaN) {
if (0 < guess) {
guessesArray.push(guess);
message.innerHTML = "No, try a higher number.";
}
else {
message.innerHTML = "That number is not in range, try again.";
}
}
else {
message.innerHTML = "That is not a number!";
}
console.log(guessesArray);
}
Every time you call the do_guess method you're resetting guessesArray to an empty array (line 3). You need to define guessesArray outside of your method if you want it to retain the values you've pushed into it.
I am trying to let the game only let the user have 3 guesses to guess correctly. The problem is that it lets the user guess a 4th time, but even if user guesses correctly on 4th attempt I get a wrong answer message. I tried changing the number of guesses, changing that i = 0 start position, subtracting one from maxGuesses in the for loop. No matter what I try the relationship is off by one. Here is my code so far.
let readlineSync = require("readline-sync");
let hint = "";
let maxGuesses = 3;
const maxRange = 10;
const minRange = 1;
let userGuess = readlineSync.question(
"I have chosen a number between " +
minRange +
" and " +
maxRange +
". You have " +
maxGuesses +
" tries to guess it!\n"
);
const randomNumber = Math.floor(Math.random() * maxRange + 1);
function handleGuess(userGuess) {
if (userGuess != null && userGuess != undefined && (userGuess <= maxRange && userGuess >= minRange)) {
for (i = 0; i <= maxGuesses - 1; i++) {
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
return;
} else {
if (userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
}
console.log("Dude...YOU SUCK!");
return;
} else {
userGuess = readlineSync.question("Fix your answer fool! \n");
handleGuess(userGuess);
}
}
I assume your first call is handleGuess() with no parameter.
Then, your program asks the user for its first guess (withe the message "Fix your answer fool!"). If you call handleGuess() with a parameter, the following still applies.
After that, the loop will begin.
if the first answer is wrong, the console will display the message "Think [higher/lower] you fool.", and then request the second guess. Still in the first loop iteration.
Do you see where the problem is ?
If the second guess is still wrong, the console will display the second wrong message and request the third guess while still being in the second loop iteration.
Finally, If the third guess is still incorrect, the third "wrong" message will appear and your code will request a fourth guess before ending the loop and display the message "Dude...YOU SUCK!" without verifying your input.
To prevent that, you can do something like this :
function handleGuess(userGuess) {
i = 0;
do {
if(i > 0) {
if(userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
while(isNaN(userGuess)) {
userGuess = readlineSync.question("Correct you guess. \n");
}
} while(userGuess != randomNumber && i < maxGuesses);
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
} else {
console.log("Dude...YOU SUCK!");
}
}
Just set the condition for your loop to be i < maxGuesses not i <= maxGuesses -1:
var maxGuesses = 3;
for (i = 0; i < maxGuesses; i++) {
console.log("Guess " + (i + 1)); // Only adding 1 here so output is 1-based
}
I am following a Javascript track on Teamtreehouse and I trying to make a game. It asks the user to guess a number between 1 and 6 and. The user can either guess the number, type smaller one and get another chance, type a bigger one and get another chance or not guess it at all.
var correctGuess = false;
var randomNumber = Math.floor(Math.random() * 6) +1;
var guess = prompt("I am thinking of a number between 1 and 6. What is it?");
if (parseInt(guess) === randomNumber) {
correctGuess = true;}
else if (parseInt(guess) < randomNumber) {
var guessMore = prompt("Try again! The value I am thinking of is lower than " + guess);
if (parseInt(guessMore) === randomNumber ) {
correctGuess =true;}
} else if (parseInt(guess) > randomNumber) {
var guessLess = prompt("Try again! The number I am thinking of is smaller than " + guess);
if (parseInt(guessLess) === randomNumber) {
correctGuess = true; }
}
if ( correctGuess) {
alert("Yey!");
} else {
alert("Better luck next time! The number was " + randomNumber);
};
Although the code seems fine to me, every 1 our of 5 times (let's say) it displays an anomaly (although the user the guessed the number, it runs the else statement; or it asks you for a smaller number only to find out that the result was in fact a bigger number etc). You have to run to run the code a few times to see what I mean. What am I doing wrong?
So your problem with:
or it asks you for a smaller number only to find out that the result
was in fact a bigger number etc)
This is due to the fact that you have both "lower than" and "smaller than" in your conditional statement. I changed "lower than" to "greater than".
else if (parseInt(guess) < randomNumber) {
var guessMore = prompt(
"Try again! The value I am thinking of is greater than " + guess);
if (parseInt(guessMore) === randomNumber ) {
correctGuess =true;}
}
else if (parseInt(guess) > randomNumber) {
var guessLess = prompt(
"Try again! The number I am thinking of is smaller than " + guess);
if (parseInt(guessLess) === randomNumber) {
correctGuess = true; }
}
https://jsfiddle.net/7yhhfv6g/4/