Adding Prompt() to High/Low Game - javascript

I created a high/low game that goes from 1-20. To take it a step further, I'm attempting to have the user pick the number to play against: pick between 1 - x (user input number). There are other parameters within the game that need to be tweaked as well with that change. I want to use specifically Prompt() for the user to select a number to play against, I'm just not sure how to add it as well as other changes that will need to be made. Any tips are appreciated!
var answer = Math.floor(Math.random()*20) + 1;
var no_of_guesses = 0;
var guesses_num = [];
function guessing(){
var user_guess = document.getElementById("guess").value;
if(user_guess < 1 || user_guess > 20 ){
alert("That number is not in range, try again!");
}
else{
guesses_num.push(user_guess);
no_of_guesses+= 1;
if(user_guess < answer){
outcome1.textContent = "Too low"
outcome2.textContent = "Number Of Guesses : " +
no_of_guesses;
outcome3.textContent = "Guessed Number Are: " +
guesses_num;
}
else if(user_guess > answer){
outcome1.textContent = "Too High"
outcome2.textContent = "No. Of Guesses : " +
no_of_guesses;
outcome3.textContent = "Guessed Number Are: " +
guesses_num;
}
else if(user_guess == answer){
outcome1.textContent = "You're Correct!!"
outcome2.textContent = "the Number was " + answer
outcome3.textContent = " You guessed it in " + no_of_guesses +"Guesses";
}
}
}
var outcome1 = document.getElementById("outcome1")
var outcome2 = document.getElementById("outcome2")
var outcome3 = document.getElementById("outcome3")
<div class="container">
<h3>Guess between 1-20!</h3>
<input type="text" placeholder="Choose a number" id="picknum"><br>
<button onclick="guessing()" id="my_btn">GUESS</button>
<input type="text" placeholder="Guess a number in range" id="guess"><br>
<p id="outcome1">Are you feeling lucky?</p>
<p id="outcome2"></p>
<p id="outcome3"></p>
</div>

I am not quite sure why you want to use prompt() for the user dialogue. My snippet uses the already provided <input> element instead and avoids unnecessary repetitions in the code:
const answer = Math.floor(Math.random()*20) + 1,
guesses=[];
const inp=document.getElementById("guess"),
out=document.querySelectorAll("[id^=outcome]");
function guessing(){
const n=inp.value;
guesses.push(n);
[`The number ${n} is ${n==answer? "correct!" : "too "+(n<answer?"low.":"high.")}`,
`You had ${guesses.length} guesses.`,
`The guessed numbers were: ${guesses.join(", ")}.`].forEach((o,i)=>out[i].textContent=o)
}
<div class="container">
<h3>Guess between 1-20!</h3>
<input type="text" placeholder="Guess a number in range" id="guess"><button onclick="guessing()" id="my_btn">GUESS</button><br>
<p id="outcome1">Are you feeling lucky?</p>
<p id="outcome2"></p>
<p id="outcome3"></p>
</div>

If you're willing to put up with its UI limitations, calls to prompt return the user's input; you could use your existing code, changing only the first line of guessing() to read
var user_guess = prompt("What is your guess?")
(Note that prompt returns a string; you'll want to use Number(user_guess) when doing mathematical comparisons.)

Related

JavaScript: Generating a random number with user input from a prompt box (number guess game)

The user has to guess a randomly generated number based on the highest value THEY input into a prompt box. Example (from 1 to ?)
I have to use a prompt and the value cannot be a decimal or string.
I'm not sure how to validate that or just not allow the user to input an invalid entry.
I am having issues reusing the number they input in the function for random number generation let num = Math.floor(Math.random() * inputMaxNumber + 1); in the game. I tried converting the value from a string to a number but that didn't work either.
This is what I have so far:
//prompt for max number the user inputs
function maxNumber() {
let inputMaxNumber = prompt ("Enter the maximum number the game can pick", " #");
if ( inputMaxNumber > 1) {
document.getElementById("maxNumber").innerHTML = "Guess a number between 1 and " + inputMaxNumber;
}
else {
alert("You must enter a positive whole number greater than 1");
}
console.log(inputMaxNumber);
}
inputMaxNumber = Number(document.getElementById("maxNumber").value); //converts this to a number from a string
// array that stores guesses
var numGuessArray = []
//validates user input for guesses (no decimals, strings, or negative numbers)
function onlyNumbers(num){
if ( /[^0-9]+/.test(num.value) ){
num.value = num.value.replace(/[^0-9]*/g,"")
}
}
//get user input to use in random number generation
// random value generated based on user input (a) new variable is num
let num = Math.floor(Math.random() * inputMaxNumber + 1);
console.log(num);
//counts the number of guesses for correct guess
var guess = 1;
//store counts and numbers guess in an array (don't count invalid guesses)
function do_guess() {
let guess = Number(document.getElementById("guess").value); //converts this to a number from a string
let message = document.getElementById("message");
//show on console
console.log(guess);
//hints about guess
if(guess == num) { //correct guess with count
message.innerHTML = "You got it and it took " + guess + " guess!";
}
else if (guess > num) { //number too high
message.innerHTML = "No, try a lower number";
}
else {//number too low
message.innerHTML = "No, try a higher number";
}
//you already guessed that number NO COUNT
}
//guess button used to guess
//use an array to keep track of the guess
<div class="container">
<h1>Higher - Lower</h1>
<p>Guess a number</p>
<div class = "row">
<div class ="col-lg-3 col-md-6">
<form>
<div class ="form-group">
<!-- This button triggers the prompt to allow the user to enter the max number-->
<input type ="button" value = "Click To Start" onclick = "maxNumber()";/>
</div>
<div class ="form-group">
<label> Your Guess:</label>
<!-- Prevents user from inputing decimals with onkeyup-->
<input type ="text" onkeyup="onlyNumbers(this)" id="guess" class ="form-control">
</div>
<p id = "maxNumber" ></p><!--Outputs maximum number range the user selected-->
<!--Button calls guess funciton when clicked-->
<button type="button" class ="btn btn-primary" onclick = "do_guess()">Guess</button>
</form>
</div>
</div>
<p id="message"></p> <!--Where message will go-->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
Inside function maxNumber() you define inputMaxNumber locally let inputMaxNumber = prompt(...); so its value is lost when the function execution ends.
Additionally, the code where you generate the random number is executed only once, upon page load let num = Math.floor(...);. It's not executed after user enters his choice for the maximum.
Solution:
define num globally
assign the random value to it inside maxNumber()

How to add an if statement to check multiple variables in a function (Javascript)

This block of code in my HTML doc serves as a function to perform a calculation. It prompts the user to enter the number of rooms and total sq. ft., then multiplies the sq ft by 5 to get the estimate. I am trying to figure out how to add an if-statement to serve as an error message if a user inputs a negative number. Below is the function copied from the code. Would I add it directly in the function, before or after it? What I basically want to say is,
if (var a && b <= 0) {
print "Invalid entry. Please reload the page and enter a positive number." }
How would I go about doing this in JavaScript? Also, is there a better way to ask the user than using < p> < /p>?
<div class="container-fluid">
<p>Please enter the number of rooms affected, and the total square foot. </p>
<input type="text" name="numRooms" id="numRooms"> <br>
<input type="text" name="roomSize" id="roomSize"><br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>
<script>
function submit1(){
var a = document.getElementById("numRooms").value;
var b = document.getElementById("roomSize").value;
var c = parseInt(b) * 5;
document.getElementById("result").innerHTML="Your estimate is : $" + c;
}
</script>
You could check the values in advance and exit early, if an error occurs.
function submit1() {
var a = +document.getElementById("numRooms").value; // get a number with +
var b = +document.getElementById("roomSize").value;
var c = parseInt(b) * 5;
if (isNaN(a) || a <= 0 || isNaN(b) || b <= 0) { // check if number or smaller/eq than zero
document.getElementById("result").innerHTML = '<span style="color: #b00;">Please insert only positive numbers.</span>';
return;
}
document.getElementById("result").innerHTML = 'Your estimate is : $ ' + c;
}
<div class="container-fluid">
<p>Please enter the number of rooms affected, and the total square foot. </p>
<input type="text" name="numRooms" id="numRooms"> Rooms<br>
<input type="text" name="roomSize" id="roomSize"> Size [sq ft]<br>
<button type="button" onclick="submit1()">submit</button><br>
<p id="result"></p>
</div>

How to store user input as a variable?

I am trying to design a simple companion interface for a board game I am creating. How do you request user input, and then update a variable with the new input and display the new result? ie. "What number did you roll?" -> "You are now on [this] space."
Sorry, I am very new to coding... Here is the closest I've got
<var space = 1>
<button onclick="mySpaceNumber()">Die Roll</button>
<p id="demo"></p>
<script>
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll != null) {
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
function mySpace(){
'space'= 'space'+ 'dieroll'
space
}
}
}
</script>
if (dieroll != null) { - This will always be NOT null if something isn't entered. Reason being is that it is UNDEFINED, rather than NULL. These are two different things. Null is an actual value. When a variable has been declared, but no value has been given to it then it becomes undefined.
With that said, I would make this line if (dieroll !== "undefined)"
Regarding 'space'= 'space'+ 'dieroll'
I would not put any apostraphe's in the variable's NAME, that is something you want to do when you declare a string.
Regarding this: You will want to put your code on one line.
From:
document.getElementById("demo").innerHTML =
"You are now on " + function mySpace ;
To:
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
The variable space is undefined, you have not initialized it or given it a value. To do that we need to add this in var space=0;
Lastly, I don't see your HTML so I'm not sure what element the variable space is supposed to reference. If it's some other box or something you can remove the var space=0; and get the value by selecting the element you need it from. Without knowing what that would be or what your html looks like I can't speculate further.
With all that said, here is where we are.
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
function mySpace(){
var space=0;
space = space + dieroll;
return space
}
}
}
Then onto the HTML
This is not valid.
Code Snippet
function mySpaceNumber() {
var dieroll = prompt("What did you roll?", "Enter Value");
if (dieroll !== "undefined") {
document.getElementById("roll").value = dieroll;
document.getElementById("demo").innerHTML = "You are now on " + mySpace();
}
function mySpace(){
result = getSpace();
return result;
}
function getSpace(){
gs1 = +document.getElementById('quantity').value + +document.getElementById('roll').value
return gs1;
}
document.getElementById('quantity').value = +document.getElementById('quantity').value + +document.getElementById('roll').value
}
function resetSpace(){
document.getElementById('quantity').value = '1';
}
<div>Roll:
<input type="number" id="roll" name="roll" style="width: 50px;" />
Current Space:
<input type="number" id="quantity" name="quantity" value="1" style="width: 50px;" />
</div>
<button onclick="mySpaceNumber()">Die Roll</button>
<button id="reset" onclick="resetSpace()">reset</button>
<div id="demo"></div>

Javascript number guessing game - setting up the counter & while loop

I'm trying to create a random number guessing game in Javascript that compares user input to a number generated with the math.random method. I'm confused by how to set up the counter the right way. I have to validate the number, display each guess with "too high," "too low" or "you win" then show the 'secret' number at the end. Not sure what I'm doing wrong! Right now it is overwriting each answer and the counter is staying at #5.
function myFunction() {
var userInput = document.getElementById("text").value;
// test for valid input number from 1 to 999
if (userInput < 0 || userInput > 999) {
alert("Your number must be from 1 to 999");
} else {
alert("Input OK");
} // end function myFunction
var randomNum = Math.floor(Math.random()* 999)+1;
var userInput = document.getElementById("text").value;
var counter = 0;
var totalGuesses = 0;
while (totalGuesses <= 5) {
counter++;
document.getElementById('loopResults').innerHTML = "<p>You have made" + counter + "guesses</p>";
if (userInput < randomNum) {
document.getElementById('loopResults').innerHTML += "<p>Your guess is too low!</p>";
} else {
document.getElementById('loopResults').innerHTML += "<p>Your guess is too high!</p>";
}
}
}
</script>
</head>
<body>
<h1>Guessing Game</h1>
<p id="loopResults"></p>
<form action="" method="post" enctype="multipart/form-data" name="userData">
<input name="userInput" id="text" type="text" size="10" /> - Enter a number from 1-999!</form>
<p><span style="background-color:#066aff; color: #ffffff; padding: 5px;" onclick="myFunction();" >enter number</span>
</p>
</body>
You don't need a while loop here. What happen is simply once it enters the while loop, it increments your counter to 5.
Take the while loop out and it will do what you want it to do.
And I don't think you need the totalGuesses
Edit:
So I further look into your code. In order to do what you want it to do, instead of putting everything in your myFunction, here are the steps:
create a random_number
create a counter
a function that is bind to onclick, this is where the main logic is. And here's what you need to do.
get the input result from the input field, and parse it to Integer
compare with the stored random_number
if correct, alert ok
if not, increment the counter
if the counter reaches limit, alert and show result
Not going to write down the code, and I think you can figure it out.

Displaying Messages Without Using Alerts

I am working on a "guess my number" game and have ran into a problem. My game is supposed to select a random integer between 1 and 10 and allow the user to guess until they guess the correct number. After each guess, I'm supposed to display a message telling whether their guess was too high, too low, correct, or if they'd guessed that number before. I had the game working (except for displaying the array of previously guessed numbers) by using alerts to display the whether the user was too high, low, correct, etc like this.
if (guess == this.num) {
alert("Correct! It took you " + turns " tries to guess my number.");
...
}
However, going back over the directions I see that we are not supposed to user alerts or any other kinds of pop-ups. So I need to figure out how to display these messages on the screen rather than in an alert box.
Here is how I've attempted to do this without the use of alerts, but now the game is not working at all (nothing happens when I click either of the buttons):
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Guess My Number</title>
<script type="text/javascript">
var tries = [];
var game = {
num : 0,
turns : 1,
reset : function() {
this.turns = 1;
this.newNum();
},
newNum : function() {
this.num = parseInt(Math.random() * 10) +1;
},
guessNumber : function(guess) {
try {
guess = parseInt(guess);
}
catch(e) {
alert("Enter a guess!");
this.turns++;
return false;
}
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
alert("Correct! It took you " + this.turns + " turns to guess my number.");
tries.push(guess);
document.querySelector("#tries").textContent = tries.join(', ');
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
alert("Your guess is too high. Try again.");
document.querySelector("#tries").textContent = tries.join(', ');
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed this number. Try again.";
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
document.querySelector("#tries").textContent = tries.join(', ');
tries.push(guess);
this.turns++;
document.getElementById("guess").value = " ";
return false;
}
}
};
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
</script>
</head>
<body>
<h1>Would You Like To Play A Game?</h1>
<h2>Thank you for checking out my game. Good luck!</h2>
<h3>Created by Beth Tanner</h3>
<h2>Directions:</h2>
<p>
The game is very simple. I am thinking of a number between 1
and 10. It is your job to guess that number. If you do not guess
correctly on your first attempt, don't worry, you can keep guessing
until you guess the correct number.
</p>
<p>
Your Guess: <input type="text" id="guess" size="10" />
<br />
<input type="button" value="Sumbit Guess" onclick="guessNumber()" />
<input type="reset" value="Reset Game" onclick="resetGame()"/>
</p>
<h3>How Did You Do?:</h3>
<p>
<input type="hidden" id="result" size="20" />
</p>
<h3>Here Are Your Guesses So Far:</h3
</body>
</html>
Is there any simple way to do this. I want the messages to display in a hidden text filed below the heading "How did you do?:" if that makes it a little clearer.
Here is a jsfiddle I made with my most recent code, http://jsfiddle.net/3p3f86fj/6/
You should add a div to your body with a unique ID, like <div id='result'></div> and then in your JS, reference it by getting the document by ID and your functions should change the text of the div to whatever you need it to be. Make a function to change the name if you want to abstract some of the logic away.
It's broken because of this line I believe:
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.");
You have a stray ) at the end.
I'm looking into other issues I see now.

Categories

Resources