cancel button on javascript dialog to stop a loop - javascript

Greeting. When I open the following in Internet Explorer 11, the game would not stop when I hit the cancel button. How I can press the cancel button and the game stops. The current behavior is it just keep looping even with cancel ??
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
function do_game() {
var random_number = Math.random() * 100;
var random_number_integer = Math.floor(random_number);
target = random_number_integer;
while (!finished) {
guess_input_text = prompt("I am thinking of a number "+
"in the range 1 to 100.\n\n"+
"What is the number?");
guess_input = parseInt(guess_input_text);
guesses += 1;
finished = check_guess();
}
}
function check_guess() {
if (isNaN(guess_input)) {
alert("You have not entered a number.\n\n" +
"Please enter a number in the range 1 to 100.");
return false;
}
if ((guess_input < 1) || (guess_input > 100)) {
alert("Please enter an integer number in the range 1 to 100.");
return false;
}
if (guess_input > target) {
alert("Your number is too large!");
return false;
}
if (guess_input < target) {
alert("Your number is too small!");
return false;
}
alert("You got it! The number was " + target +
".\n\nIt took you " + guesses +
" guesses to get the number!");
return true;
}

When you press the Cancel button on prompt's prompt, it returns null. So
if (guess_input_text === null) {
break;
}
...will exit the loop.
Note that on quite old browsers, it would return "" rather than null. But anything vaguely modern (IE9+) should be fine.

Related

random number doesn't change in loop

The random number doesn't change using while loop. When I want to play again, the randomnumber is still the same.
Here's the code:
randomnumber=Math.floor(Math.random()*10);
while(true){
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
You should repeat the generation of the random number when a next game is requested:
var randomnumber = Math.floor(Math.random()*10);
while (true) {
var yourguess = prompt("Please Enter A Number Between 1-10");
if (randomnumber == yourguess) {
alert("Good Job");
var answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
randomnumber = Math.floor(Math.random()*10); //<---
} else {
break;
}
} else {
alert("Not Matched "+ randomnumber);
}
}
Make sure to declare your variables (with var, let or const).
You need to generate that randomnumber inside the while loop:
while(true){
var randomnumber=Math.floor(Math.random()*10);
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
If you want a different random number each time the loop is executed, you need to generate the randomnumber inside the while loop.
while (true) {
let randomnumber = Math.floor(Math.random() * 10);
yourguess = prompt("Please Enter A Number
Between 1 - 10");
if (randomnumber == yourguess) {
alert("Good Job");
answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
} else {
break;
}
} else {
alert("Not Matched " + randomnumber);
}
}
You could make randomnumber a function and call it on loop start. In addition your code snippet was changed a bit in order not to get stuck in a loop of un-closing prompt windows, what was missing is a small part that checks what happens when user does not provide an answer or clicks the cancel button.
var randomnumber = function() { return Math.floor(Math.random()*10); }
while(true){
let number = randomnumber();
yourguess=prompt("Please Enter A Number Between 1-10");
if(!yourguess) {
break;
}
if(number===parseInt(yourguess)){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N");
if(!RegExp("y","gi").test(answer) || !answer){
break;
}
}else{
alert("Not Matched "+ number);
}
}

JS code guessing game color NOT WORKING

I am a neophyte JS, I'm making a game where the user has to guess a randomly generated color.
I noticed that the code I tried to write results in errors, that is, when I go to enter a color in the prompt, even if it is wrong always says the right thing. I have something wrong in check_guess function where I wrote the conditions.
Another mistake I detected when the game ends, should be out in the background the color that guessed it, nor should you.
Can you help me figure out where I'm wrong?
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" +
colors_message + "\n\n What is the color am I thinking of?");
guess_input = guess_input_text.toLowerCase();
guesses += 1;
finished = check_guess();
}
}
function check_guess() {
if (guess_input == -1) {
alert("Sorry, I don't recognize your color. \n\n Please try again.");
return false;
} else if (guess_input > target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
return false;
} else if (guess_input < target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
return false;
} else {
alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = target;
return true;
}
}
</script>
Referring to your code revisions I got the required data. There were few glitches that were found like:
You were checking guess_input with target, where guess_input holds a string value of the user input and target holds an integer value of the correct answer. None of the conditions will ever be satisfied in this case, and thus the last else part will be executed always. That is, alert("Congratulations! You ha..);
myBody.style.background = target; will set the background
property to an integer (index of answer in colors array). You need
to set it like myBody.style.background = colors[target];
Below is the working code:
var colors = ["antiquewhite", "blueviolet", "crimson", "deepskyblue", "forestgreen", "gold", "lawngreen", "magenta", "palegreen", "skyblue"];
var colors_message = colors.join(", ");
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var ask_again = false;
function do_game() {
var target_index = Math.random() * colors.length;
var target_index_integer = Math.floor(target_index);
target = target_index_integer;
var answer = String(colors[target]).toLowerCase();
//Alert correct answer for testing purposes
alert("The correct answer is: " + answer);
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + colors_message + "\n\n What is the color am I thinking of?");
while (!finished) {
if(ask_again){
guess_input_text = prompt("What is the color I was thinking of?");
}
guess_input = guess_input_text.toLowerCase();
guesses += 1;
finished = check_guess(colors.indexOf(guess_input));
}
}
function check_guess(guess_index) {
ask_again = true;
if (guess_index == -1) {
alert("Sorry, I don't recognize your color. \n\n Please try again.");
return false;
} else if (guess_index > target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
return false;
} else if (guess_index < target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
return false;
} else {
ask_again = true;
alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = colors[target];
return true;
}
}
<body onload="do_game()"></body>

How to make sure user input is a valid string in js

I am very new to JS,
how do I make sure that the user input is a valid string?
If the string is inside of the array, the game should continue.
if the string is outside of the array, the game should ask user to input their guess again.
var color = ["AliceBlue","Black","FireBrick","GreenYellow","LightBlue","Ivory","MediumBlue","Indigo","SpringGreen","Moccasin"];
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var rightAnswer;
var i = 0;
function do_game() {
var random_number = Math.random()* color.length;
var random_number_interger = Math.floor(random_number);
target = random_number_interger + 1;
rightAnswer = color[target];
while(!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + color.sort()+ "\n\n The right answer is\n" + rightAnswer);
guess_input = guess_input_text;
guesses +=1;
finished = check_guess();
}
}
function check_guess() {
if(guess_input < rightAnswer){
console.log("Hint: your color is alphabetically lower than mine")
return false;
}
else if( guess_input > rightAnswer) {
console.log("Hint: your color is alphabetically higher than mine ")
return false;
}
else (guess_input == rightAnswer)
{
console.log("Congrats!!!")
return true;
}
)
}
You can use indexOf to check the position of guess_input in the color array. It will return -1 if it is not present.
So:
function check_guess() {
if (color.indexOf(guess_input) < 0) {
console.log("Not a valid colour, try again.");
return false;
}
return true;
}
You can use Array.prototype.find function with ES6 arrow functions to make it even snappier.
if(color.findIndex(e => e === guess_input) === -1){
alert("Please guess again!);
}
The above code alerts the user to guess again if the guess_input isn't found in the array.

code stops looping

My code is not working properly. It is not continuing the loop. It is just showing that your value is low or high and stopping it there. Why doesn't it keep looping?
var target;
var count = 0;
var play;
var game;
function do_this() {
var choose = (Math.floor(Math.random() * 100));
target = choose + 1;
while (true) {
play = prompt("I am thinking of a no. between 1 and 100\n\n" + "enter the no.");
game = parseInt(play);
count = count + 1;
if (isNaN(game)) {
alert("Please enter integer value");
return false;
}
if ((game < 1) || (game > 100)) {
alert("Please enter the value between 1 and 100");
return false;
}
if (game < choose) {
alert("enter higher value");
return false;
}
if (game > choose) {
alert("enter lower value");
return false;
}
alert("You are correct\n\n" + "you took" + count + "to guess the game");
return true;
}
}
do_this()
You are using return false; when the value is higher or lower. Replace that with continue;

Simple Guessing Game Program in Javascript

Trying to create a very simple number guessing game as a first project. I want the player to have 5 guesses before they lose.
I'm having difficulty troubleshooting the bugs or coding mistakes.
var num = Math.floor((Math.random(1,10) * 10) +1);
console.log(num); //To check
var counter = 5;
while(counter > 0){
function guess(){
counter = counter-1
var guess = prompt("You've got " + counter + " tries to guess the number.");
if (num == guess){
alert("That's the number!");
}else if (guess != (int){
alert("That's not a number...");
}else{
alert("Nice try");
}
}
}
alert("You lost.");
Working fiddle: http://jsfiddle.net/0skh4t4r/
var num = Math.floor((Math.random(1, 10) * 10) + 1);
console.log(num); //To check
var counter = 5;
function guess() {
var x = prompt("You've got " + counter + " tries to guess the number.");
if (!x) return; // cancel the game
counter--;
if (num === parseInt(x)) {
alert("That's the number!");
return;
} else if (isNaN(x)) {
alert("That's not a number...");
} else {
alert("Nice try");
}
if(counter === 0) {
alert("You lost");
} else {
guess(); // next try
}
}
guess();

Categories

Resources