Javascript won't display message - javascript

I'm trying to create a simple program where a user needs to pick a maximum number, then try to guess a number between 1 and that maximum number. When they enter their guess, I need to validate the input, and offer a choice of feedback: different messages if it's (1) not a number, (2) a number not within the range, (3) the correct guess, (4) too high, but within range, and (5) too low, but within range.
function do_guess(prompt) {
let valid_input = false;
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
while (!valid_input) {
input = window.prompt(prompt);
guess = Number(input);
if (isNaN(guess)) {
message.innerHTML = "That is not a number!";
} else if (guess < 1 || guess > val) {
// val = max_num - "I wasn't sure how to code this."
message.innerHTML = "That number is not in the range, try again.";
} else if (guess == num) {
valid_input = true;
message.innerHTML = "You got it!";
} else if (guess > num) {
message.innerHTML = "No, try a lower number.";
} else {
message.innerHTML = "No, try a higher number.";
}
}
}
do_guess("Number from 1 to 10")
Guess <input id="guess" value="" />
<div id="message"></div>

Based on your requirements, I'm loading the max_val from the input box and calling the do_guess function with a new button.
function do_guess(prompt) {
let valid_input = false;
let max_val = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
let output = '';
let num = Math.floor((Math.random() * max_val) + 1);
prompt = prompt + max_val;
while (!valid_input) {
input = window.prompt(prompt + output);
let guess = Number(input);
if (isNaN(guess)) {
output = " That is not a number!";
} else if (guess < 1|| guess > max_val) {
output = " That number is not in the range, try again.";
} else if (guess == num) {
valid_input = true;
message.innerHTML = "You got it!";
} else if (guess > num) {
output = " No, try a lower number.";
} else {
output = " No, try a higher number.";
}
}
}
Max Guess <input id="guess" value="" />
<div id="message"></div>
<button onClick="javascript:do_guess('Number from 1 to ')">
Guess
</button>

Related

How to check whether i submit blank input in javascript? i have written a program but it is not working

I have written a javascript code in an HTML file using a script tag,
where I want to know whether my input is greater than or less than 10
or equals to 10 or any blank input. I use the if-else method to solve
this problem, but my last else if condition which is "Your input is
blank" not outputting in any way.
//f1 function will run when some hit the submit button
function f1() {
//here we are taking the value of the input field using id "myinput" in the variable called myinputvar
var myinputvar = document.getElementById("myinput").value;
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
} else if (myinputvar = " ") {
document.getElementById("txt").innerHTML = "Your input is blank";
}
}
<!-- this is the input tag to take inputs from user -->
Enter a integer number between 0 to anynumber = <input type="text" id="myinput"><br><br>
<!-- this is the button to submit the value -->
<button onclick="f1()">submit</button>
<!-- this is the heading tag to print the output -->
<h1 id="txt"></h1>
Wrap in a form and make it required
Also cast to number
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
//here we are taking the value of the input field using id "myinput" in the variable called myinputvar
var myinputvar = +document.getElementById("myinput").value; // make it a number
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
} else if (myinputvar = " ") {
document.getElementById("txt").innerHTML = "Your input is blank";
}
})
<form id="myForm">
Enter a integer number between 0 to anynumber =
<input type="text" required id="myinput"><br><br>
<button>submit</button>
</form>
<h1 id="txt"></h1>
A general way to check for only whitespace input uses the regex pattern ^\s*$. Sample code:
if (/^\s*$/.test(inputvar)) {
document.getElementById("txt").innerHTML = "Your input is blank";
}
pay attention not to use the shortcut:
if (inputvar) {
// this won't catch "0"!
}
but the more proper
if (inputvar === "") {
// is empty
}
and of course you should check for this condition first, if you want to handle numbers as input.
You can use ASCII code to check for that
else if(myinputvar.carCodeAt(0) === 13) {
document.getElementById("txt").innerHTML = "Your input is blank";
}
13 is ASCII code of enter key
https://www.asciitable.com/
> This method is also working, the logic is i should have use a nested
> if like this
function f1() {
var myinputvar = document.getElementById("myinput").value;
if (myinputvar == "") {
document.getElementById("txt").innerHTML = "Your input is blank";
} else {
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
}
}
}
As Tim Biegeleisen mentioned, it worked in this way:
var myinputvar = document.getElementById("myinput").value;
if (/^\s*$/.test(myinputvar)) {
document.getElementById("txt").innerHTML = "Your input is blank";
} else {
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
}
}
Check if the given input value is a valid number or not
function isNumber(n){ return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }

How do I prevent duplicate guesses in number guessing game?

I created an array called tries to collect what numbers the user has guessed. When the user finally guesses the correct number, the number of tries and what numbers were guessed told to the user. How would I avoid the user guessing a number that they already guessed? I know I will have to check the array after every guess to see if that number has been guessed already and is in the array. (if guess is in array, show message saying "You guessed that already, try again") Also, should I add that guess to the number of guesses or do no include it since it is a repeat guess?
let num = Math.floor(Math.random() * 20) + 1;
console.log(num);
let num_guess = 0
let tries = []
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
}
else if (guess > 20) {
message.innerHTML = 'That number is not in range, try again.';
num_guess++
tries.push(guess)
}
else if (guess > num) {
message.innerHTML = "No, try a lower number.";
num_guess++
tries.push(guess)
}
else if (guess < num) {
message.innerHTML = "No, try a higher number.";
num_guess++
tries.push(guess)
}
else if (guess == num) {
num_guess++
tries.push(guess)
message.innerHTML = "You got it! It took you " + num_guess + " tries and your guesses were " + tries + ".";
}
}
Simple, use Array.includes:
[1, 2, 3].includes(1)
> true
[1, 2, 3].includes(4)
> false
On whether you want to include the duplicate guesses: it's up to you.
You can use includes to check if an element exists in an array or not.
The includes() method determines whether an array includes a certain
value among its entries, returning true or false as appropriate.
You need to add following code before all condition
if (tries.includes(guess)) {
message.innerHTML = "You guessed that already, try again";
}
let num = Math.floor(Math.random() * 20) + 1;
console.log(num);
let num_guess = 0;
let tries = [];
const guessContainer = document.getElementById("guess");
const check = document.getElementById("check");
let message = document.getElementById("message");
guessContainer.addEventListener("keyup", (e) => {
message.innerHTML = "";
});
function do_guess() {
let guess = Number(guessContainer.value);
let isCorrect = false;
if (tries.includes(guess)) {
message.innerHTML = "You guessed that already, try again";
} else if (isNaN(guess)) {
message.innerHTML = "That is not a number!";
} else if (guess > 20) {
message.innerHTML = "That number is not in range, try again.";
num_guess++;
tries.push(guess);
} else if (guess > num) {
message.innerHTML = "No, try a lower number.";
num_guess++;
tries.push(guess);
} else if (guess < num) {
message.innerHTML = "No, try a higher number.";
num_guess++;
tries.push(guess);
} else if (guess == num) {
isCorrect = true;
num_guess++;
tries.push(guess);
message.innerHTML =
"You got it! It took you " +
num_guess +
" tries and your guesses were " +
tries +
".";
}
if (isCorrect) {
message.classList.add("right");
message.classList.remove("wrong");
} else {
message.classList.add("wrong");
message.classList.remove("right");
}
}
check.addEventListener("click", do_guess);
body {
padding: 1rem;
}
button {
background-color: indianred;
color: white;
border: none;
padding: .25rem .5rem;
border-radius: 4px;
text-transform: uppercase;
}
.wrong {
color: tomato;
}
.right {
color: green;
}
h5 {
margin-top: 1rem;
}
<input type="text" id="guess" />
<button id="check">check</button>
<h5 id="message"></h5>
Try this:
var num = Math.floor(Math.random() * 20) + 1;
console.log(num);
var num_guess = 0;
var tries = [];
function go_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if(tries.includes(guess)){
message.innerText = "You guessed that already, try again";
} else {
if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
}
else if (guess > 20) {
message.innerHTML = 'That number is not in range, try again.';
num_guess++;
tries.push(guess);
}
else if (guess > num) {
message.innerHTML = "No, try a lower number.";
num_guess++;
tries.push(guess);
}
else if (guess < num) {
message.innerHTML = "No, try a higher number.";
num_guess++;
tries.push(guess);
}
else if (guess == num) {
let _tries = `${tries[0]}`;
for(let i = 1;i<tries.length;i++){
_tries += `, ${tries[i]}`;
}
num_guess++;
message.innerText = `You got it! It took you ${num_guess} tries and your guesses were ${_tries}.`;
}
};
});

Random Number Guessing Game - Limit the Number of guesses

I'm trying to make a program that generates a random number which the user guesses. It also limits the number of guesses the user can make (or is supposed to.)
var highLimit = 5;
var randNum = Math.floor((Math.random() * highLimit) + 1);
var allowedGuesses = 2;
var numGuesses = 0;
function guessingGame() {
if (numGuesses <= allowedGuesses) {
do {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
} while(numGuesses < allowedGuesses && inputNum != randNum);
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
numGuesses = 0;
function newGame() {
randNum = Math.floor((Math.random() * highLimit) + 1);
guessingGame();
return false;
}
And the HTML:
<form name = "numForm">
<fieldset>
<label for = "randNum">Enter a number between 1 and 5: </label>
<input type = "text" name = "number" value = "" id = "randNum" size = "1" maxlength = "1" />
</fieldset>
<input class = "button" type = "button" name = "submit" onclick = "guessingGame()" value = "Submit Number" />
<input class = "button" type = "reset" name = "newGame" onclick = "newGame()" value = "New Game" />
<fieldset>
<textarea name = "gameResults" onclick = "" readonly = "true" value = "" rows = "5" cols = "40" ></textarea>
</fieldset>
</form>
Right now, the program is stuck in a infinite loop since highLimit is set at 5. But if I set it at ten, the program works. How can I fix it so it works at any value? I would also appreciate other suggestions for improvement.
Thanks in advance!
I think you don't need a loop in this one. You can simple say:
function guessingGame() {
if (numGuesses < 0){numGuesses=0;}
if ((numGuesses < allowedGuesses) && (inputNum != randNum)) {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
the if (numGuesses < 0){numGuesses=0;} will help also. for negative cases.
This is an update for:
Ran the Snippet and answeared in "0 tries"
This is how I did it: But you're going to have to replace the 'prompts' and 'alerts' with your specified inputs and outputs, if you still need it after 4 years:
let maximum = parseInt(prompt('Enter the maximum number!') );
while(!maximum) {
maximum = parseInt (prompt('Please enter a valid number') )
}
const targetNum = Math.floor(Math.random()*maximum)+1;
let attempts =0;
let maxAttempts = Math.ceil(maximum/2);
// ==== Uncomment the line below to cheat --> ======
// console.log(targetNum)
let guess = parseInt(prompt(`Enter your first guess!, you have ${maxAttempts} attempts (press 'q' anytime to escape from this hellish nightmare)`));
while(parseInt(guess) !==targetNum && attempts < maxAttempts-1) {
if (typeof(guess) === 'string' && guess.toLowerCase() ==='q') {break;}
attempts++;
if(guess>targetNum) {
guess = (prompt(`Too High! Enter new guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}else {
guess= (prompt(`Too low! Entere a new Guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}
}
if(typeof(guess) === 'string' && guess.toLowerCase() ==='q') {
alert(`You gave up after ${attempts} attempts`);
}
else if(attempts >= maxAttempts-1) {alert(`Oops, your ${maxAttempts} attempts ran out, the number was ${targetNum}: Verification : ${targetNum==guess}`);}
else {
alert(`Good job, you got it ${attempts+1} attempts!, the number was ${targetNum}: Verification : ${targetNum==guess}`) ;
}

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

do while javascript - loop for guessing game

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<title>Game</title>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<h1>GameSite</h1>
<p> This program will generate a random number. Please input your guess in the box!</p>
<button onclick="guessGame()">Press me to play a quick game!</button>
<script>
function guessGame(){
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
do {
guess = prompt("Keep guessing!");
if (number < guess) {
prompt("You've guessed too high!");
} else if (number > guess) {
prompt("You've guessed too low!");
} else document.write("Good Job!");
} while (guess != number);
}
</script>
</body>
</html>
I am having trouble with the loop. It loops fine but if I move the guess statement too after the if statement it goes back to that each time. If I put it outside the if statement then it seems to not actually allow me to guess a valid number. It's hard to explain :\
I would suggest just to use only one prompt and assign it to the variable.
function guessGame() {
var number = Math.random() * 11 | 0,
guess,
text = 'Guess a number:';
do {
guess = prompt(text);
if (number < guess) {
text = "You've guessed too high!";
} else if (number > guess) {
text = "You've guessed too low!";
}
} while (guess != number);
document.write("Good Job!");
}
guessGame();
Try this:
function guessGame(){
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
while (guess != number) {
if (number < guess) {
guess = prompt("You've guessed too high! Keep guessing!");
} else {
guess = prompt("You've guessed too low! Keep guessing!");
}
}
document.write("Good Job!");
}
The while loop will keep running until the correct number is guessed, and then it will terminate.
edit: sorry, mistakes from typing too fast
I'd recommend use alert when you don't need user's response
function guessGame(){
number = Math.floor(Math.random()*11);
var guess;
do {
guess = prompt("Guess a number: "); // you should handle string input here
if (number < guess) {
alert("You've guessed too high!");
alert("Keep guessing!");
} else if (number > guess) {
alert("You've guessed too low!");
alert("Keep guessing!");
}
} while (guess != number);
alert("Good Job!");
}
Trust me, I'm a programmer.
function guessGame() {
guess:
var number = Math.floor(Math.random() * 11);
document.write(number);
var guess;// = prompt("Guess a number: ");
var text = 'Guess a number:';
guess = prompt(text);
if (number == guess) {
document.write("Good Job!");
return true;
} else {
if (number < guess) {
text = "You've guessed too low!";
} else {
text = "You've guessed too high!";
}
goto guess;
}
}
guessGame();

Categories

Resources