How to run a program forever? - javascript

I've got got a stupid question, can you help me please?
I want this program to run and run and run. At this moment after each try I have to refresh page to play again and it sucks.
"8. Write a JavaScript program where the program takes a random integer between 1 to 10, the user is then prompted to input a guess number. If the user input matches with guess number, the program will display a message "Good Work" otherwise display a message "Not matched"."
Here's what I've got:
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Looser! The number was " + randomNumber);
};

Put it in an endless loop:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
but, I wouldn't do that. I'd offer a way to get out:
while (true) {
var randomNumber = Math.floor(Math.random() * 9 + 1);
var guessNumber = prompt("enter a number between 1 and 10");
if (!guessNumber) { // ***
break; // ***
} // ***
if (guessNumber == randomNumber) {
alert("Good work!");
} else {
alert("Loser! The number was " + randomNumber);
}
}
If the user presses Esc at the prompt, guessNumber will be "" or null (depending on the browser), both of which are falsy, so you'll break out of the loop.
Side note: "Loser" has only one "o" in it, and control-flow statements with attached blocks don't have ; after the block.

Put all of your code into the while (true) loop.

just make an infinite loop
var run = true
while (run)
{
console.log('foobar');
}
never set run as false and your loop will never stop

Related

Javascript : problem with while loop that does not work

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();

How do I make a continuous loop for "confirm" alert in javascript

So I'm kinda new to Javascript, so sorry if this question sounds pretty basic. So I'm trying to make a guessing game where the computer guesses the number the user is thinking. I want to make it so that no matter how many times the user clicks "cancel" a new random number will show up until it the computer "guesses" the number the user was thinking. but i cant figure out how to make a loop out of that.
here's my code:
const guesser = () => {
let min = 0;
let max = 100;
let guess;
alert("Think of a number between 0 and 100");
while (min <= max) {
guess = Math.round((min + max) / 2);
if(confirm("is your number " + guess) == false){
if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false){
if (confirm("is your number " + Math.floor(Math.random() * guess)) == true){
alert("haha got your number!")
}
}
else if (confirm("is your number " + Math.floor((Math.random() * 50) + guess)) == true){
alert("haha got your number!")
}
}
else {
alert("haha got your number!")
}
return;
}
alert("I could not guess your number. I think you are cheating!");
};
You ask the user to tell you if their number is higher or lower than your guess, but you need to do something with that information. Specifically, if their number is greater than the current guess, increase the guess by bringing the minimum up to the current guess. If their number is less than the current guess, decrease the guess by bringing the maximum down to the current guess.
function main() {
var min = 0;
var max = 100;
alert(`Think of a number between ${min} and ${max}`);
while (min<max) {
var guess = Math.round((min + max) / 2);
if(confirm("is your number " + guess)) {
alert("haha got your number!")
return;
} else {
if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'")) {
min = guess+1;
} else {
max = guess-1;
}
}
}
alert("I could not guess your number. I think you are cheating!");
}
main();
Here is another way to achieve what you're looking for:
document.addEventListener("DOMContentLoaded", function(event) {
const guesser = () => {
let min = 0;
let max = 100;
let guess;
alert("Think of a number between 0 and 100");
while (min <= max) {
// initial guess
guess = Math.round((min + max) / 2);
if (confirm("is your number " + guess) == false) {
if (confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false) {
// number is lower than guess
max = guess;
} else {
// number is higer than guess
min = guess
}
} else {
alert("guessed your number!")
return
}
}
}
guesser();
});
<html>
<head>
</head>
<body>
Hello World!
</body>
</html>

Alert displays the wrong message when running the code

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/

How to ask a user to guess a number between 1 - 1000

I'm trying to write some javascript code that asks the user to guess a number from 1 to 1000 and enter it into the prompt box. If the user guesses right, an alert box will pop up saying they got it right. If they guess wrong, another alert box will popup and say that they are wrong and to try once more.
The issue here is that I don't know what I have to do to make the code loop infinitely until they get the right answer. Here's what i have so far:
var a = 489; // the number that needs to be guessed to win the game.
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
Number matching
Basically, when you make prompt, it returns a String or text, not a number. To fix this, do:
if (parseInt(b,10) === a) {
//Code
}
Other ways
They're a lot of ways to parse numbers. Here's a few more:
parseFloat(b); // Also parses decimals: '5.3' -> 5.3
parseInt(b, 10); // Gives an integer (base 10): '5.3' -> 5
+b; // A very 'short' way; '5.4' -> 5.4
Number('5.4e2'); // Number case: '5.4e2' -> 540
Looping
Now to repeat? Make it a loop!
var a = 432;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a){
alert("You're right!");
break; // Stops loop
} else if (!b) { break; }
else {
alert("Incorrect! Try again!");
}
}
Not sure why, but some people hate while true loops. They shouldn't cause any problems as long as you coded it properly
Random Numbers
You can get a random number using Math.random.
var min = 1,
max = 1000;
Math.floor(Math.random() * (max - min + 1)) + min;
If you're like me and want short code, you can shorten it by:
Math.floor(Math.random() * (999)) + 1;
All Together Now!
var a = Math.floor(Math.random() * (999)) + 1;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
break; // Stops loop
} else if (!b) {
alert("The Correct Answer was: " + a); //Shows correct answer
break;
} else {
alert("Incorrect! Try again!");
}
}
Just stick your prompt in some kind of loop. The code will inside the loop will run over and over until the comparison is false.
Basic example:
http://jsfiddle.net/s2he1twj/
var a = 500,
b;
while (parseInt(b) !== a) {
b = prompt('Enter a number!');
if (b === null) break;
}
while loop
Do this recursively by calling the same function like
var a = 489;
function promptGuess(){
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a){
alert("You're right!");
} else {
alert("Incorrect! Try again!");
promptGuess();
}
}
promptGuess();
Use a while until the match:
var a = 489;
var b;
while(b != a) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
}
One more thing: although the b != a evaluation is correct, it's error-prone. The != operator do conversion type, whilst the !== operator compares types and value.
In your case: 5 != '5' will return false, but 5 !== '5' returns true. It's recommended that your comparisons be conversion-free. It's more strict.
In your case, this means:
while(parseInt(b) !== a)
Greetings!

Very basic dice game in Javascript - trying to log 'wins' variable

I'm trying to make a very basic dice game (new to Javascript). On the page load, the 'dice' is 'rolled' three times and the results are displayed, with a message to say whether you managed to roll a 6 or not. I'm trying to put in a permanant message about how many games have been won - problem is, if you look at my code below, the variable I'm using for this 'wins' is incremented each time there is a win, but it only actually displays two values: 0 if the user just lost, and 1 if it was a win. It never gets to a higher number no matter how many times the dice is rolled. Wondering if anyone has a solution/explanation?
Code:
console.log("Dice game. You have 3 tries to roll a 6 - go");
var rolls = 0;
var wins = 0;
function rollDice() {
var dice = Math.random();
if (dice <= .17) {
dice = 1;
}
else if (dice <= .33) {
dice = 2;
}
else if (dice <= .50) {
dice = 3;
}
else if (dice <= .67) {
dice = 4;
}
else if (dice <= .84) {
dice = 5;
}
else if (dice <= 1) {
dice = 6;
}
return dice;
}
function diceGame() {
do {
var dice = rollDice();
console.log(dice);
rolls++;
if (dice === 6) {
console.log("You won!");
wins++;
if (rolls === 1) {
console.log("It took " + rolls + " try");
}
else {
console.log("It took " + rolls + " tries");
}
break;
}
}
while (rolls <= 2);
if (dice !== 6) {
console.log("You lost");
}
}
diceGame();
console.log("Times won: " + wins);
The value 1 will never be hit, because:
The Math.random() function returns a floating-point, pseudo-random
number in the range [0, 1) that is, from 0 (inclusive) up to but not
including 1 (exclusive), which you can then scale to your desired
range. The implementation selects the initial seed to the random
number generation algorithm; it cannot be chosen or reset by the user.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
How are you running the code? Each time it runs, it resets the wins variable to 0. You need to call the function with a button, or something so it doesn't have to refresh the code block to run a second time.
Some improvements ;)
Call continue instead of break MDN continue
Change rollDice function Random number from range
anonymous function for create namespace
// namespace for our variables
(function(){
console.log("Dice game. You have 3 tries to roll a 6 - go");
var rolls = 0;
var wins = 0;
function rollDice() {
// simple random from range ( https://stackoverflow.com/a/1527820/2746472 )
return Math.floor(Math.random()*6)+1;
}
function diceGame() {
do {
var dice = rollDice();
console.log(dice);
rolls++;
if (dice === 6) {
console.log("You won!");
wins++;
if (rolls === 1) {
console.log("It took " + rolls + " try");
} else {
console.log("It took " + rolls + " tries");
}
continue; //instead of break!
}
} while (rolls <= 2);
if (dice !== 6) {
console.log("You lost");
}
}
diceGame();
console.log("Times won: " + wins);
})();
Your rollDice function can be simplified to 1 line.
var dice = Math.floor(Math.random() * 6) + 1;
It's because you have a break if you win so it exits the loop after the first win.

Categories