Guess a number game using HTML and javascript - javascript

Hello I have a simple script:
var play = true;
var correct = false;
var number = 0;
var guess = 0;
while (play) {
// random number between 1 and 10.
number = Math.floor(Math.random() * 10 - 1);
if (number == 0) number = 1;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
When I get the number right and prompted to "Do you want another game?" and enter "yes", the program redisplays and stuck at "Do you want another game?".

You need to reset the state of correct on every play loop:
let play = true;
while (play) {
let number = Math.floor(Math.random() * 10 + 1);
let guess = 0;
let correct = false;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}

Related

Odds/Evens Javascript Value not updating between turns

all the code was given by the teacher and you just had to place it in the right spot. even working with the teacher we couldn't get it to update the "value" attribute in between turns. it updates at the finish of the game but not during? what are we not seeing? any help appreciated.. if you need to see html i can add as comment
"use strict";
var $ = function(id) { return document.getElementById(id); };
var getRandomNumber = function(max) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
return random;
};
var playGame = function() {
var odd = 0;
var even = 0;
var player, computer, total;
resetFields(); // clear any previous entries
while (odd < 50 && even < 50) {
//get computers fingers
computer = getRandomNumber(5);
// get player's fingers
player = parseInt(prompt("Enter a number between 1 and 5, or 999 to quit", 999));
if (!isNaN(player) && player <= 5) {
// show current round
$("player").value = player;
$("computer").value = computer;
// update totals
total = player + computer;
if (total % 2 === 0) {
even = even + total;
$("even").value = even;
} else {
odd = odd + total;
$("odd").value = odd;
}
}
//if loop for player quitting
if (player === 999) {
resetFields();
break;
}
}
//after loop ends, determine winner
if (odd >= 50) { $("message").firstChild.nodeValue = "You WIN!"; }
else if (even >= 50) { $("message").firstChild.nodeValue = "You lose :("; }
else { $("message").firstChild.nodeValue = "You quit"; }
// set focus on button so you can play again
$("play").focus();
};
var resetFields = function() {
$("player").value = "0";
$("computer").value = "0";
$("odd").value = "0";
$("even").value = "0";
$("message").firstChild.nodeValue = "";
};
window.onload = function() {
$("play").onclick = playGame;
$("play").focus();
};

How to stop execution of a JavaScript program

So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();

JavaScript weird issue with else if statement

I'm making a game of Guess the Number, and I want to test if a variable guess is greater than a variable difficulty. difficulty has been taken from my HTML page, and it is not comparing correctly with guess.
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = document.getElementById("difficulty").value;
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = prompt("Enter your guess: ");
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
body {
font-family: sans-serif;
text-align: center;
animation: background 10s infinite;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
animation: heading 10s infinite;
}
button {
height: 48px;
width: 250px;
font-size: 24px;
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
Read this: key info
This code works, but I want something to happen: When the guess is greater than difficulty, I want to print "Please enter a number between 1-" + difficulty. However, when I change this code:
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
into this:
else if (guess < 1 || guess > difficulty) {...}
(EDIT: the above code is to find out if the guess is greater than difficulty)
then what happens is that EVERY guess except 1, difficulty and anything more than difficulty is alerted by Please enter a number.
How should I fix this?
You're comparing strings not numbers. Convert your strings into numbers.
else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
Better way: Convert it directly after input and...
guess = parseInt(prompt("Enter your guess: "));
...get the difficulty value as number
var difficulty = parseInt(document.getElementById("difficulty").value);
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = parseInt(document.getElementById("difficulty").value);
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = parseInt(prompt("Enter your guess: "));
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1 || guess > difficulty) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
change else if (guess < 1 || guess > parseInt(difficulty))
to else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
or change the type at the input
guess = parseInt(prompt("Enter your guess: "));
You can also use the built-in Number function. See how I fixed your code below:
difficulty = Number(difficulty);
guess = Number(guess);
Try applying this after your variables are declared and it should work!
Change to this should help:
else if (guess < 1 || guess > parseInt(difficulty)) {

How to put timer in guessing game in Javascript?

I'm having a problem with my Javascript code that involves putting a timer in a Random guessing game. I must give the user 5 seconds to guess the number. The user can guess multiple times within the span of 5 seconds. If the time runs out, I must prompt the user if he wants to play again or exit. If yes I have to loop back to the game. My timer is not working. I would every much appreciate it if any of you guys can help. Thank you.
<script type="text/javascript">
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0
function timer (upper) {
var timeID = setInterval (getRandomNumber, 5000);
}
function getRandomNumber (upper) {
var number = Math.floor(Math.random()*upper) +1;
return number;
}
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
}else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
}else if(parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
</script>
As prompt freezes the internal timer (in Chrome, Opera and Safari), we can't set a timeout for the user's response. One way is to use html <input> instead of prompt. In this case setTimeout works as desired.
const input = document.getElementById("input");
const getRandomNumber = (upper) => Math.floor(Math.random() * upper) + 1;
const upper = 10;
let guessCounter = 0;
let randomNumber = getRandomNumber(upper);
let timer;
const play = () => {
if (timer) clearTimeout(timer);
input.value = "";
guessCounter++;
timer = setTimeout(() => {
if (confirm("Time is out. Play again?")) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
}
}, 5000);
}
document.getElementById("question").innerHTML = `I am thinking of a number between 1 and ${upper}. What is it?`;
document.getElementById("guess").addEventListener("click", () => {
let userGuess = parseInt(input.value);
if (userGuess > randomNumber) {
alert('Try again! Your number is too high');
play();
} else if (userGuess < randomNumber) {
alert('Try again! Your number is too low ');
play();
} else if (userGuess === randomNumber) {
if (confirm(`You have guessed the number! It took you: ${guessCounter} tries. Play again?`)) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
} else {
clearTimeout(timer);
}
}
});
play();
<div id="question"></div>
<input id="input" type="input">
<button id="guess">Guess</button>
I recommend moving your game into a function and naming it, e.g. "startGame". Then, when the game finishes it, you can implement your timer to relaunch the game.
function getRandomNumber(upper) {
var number = Math.floor(Math.random()*upper) + 1;
return number;
}
function startGame() {
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0;
var playAgain;
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
} else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
} else if (parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
if (confirm('Do you want to play again?')) {
setInterval(startGame, 5000); // Start a new game in 5 seconds
}
}
startGame();

for loop getting skipped in javascript

I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");

Categories