JQuery random number guessing game: loop woes - javascript

I am trying to make a simple number guessing game: a random number between 1 and 9999999999 is generated and printed to the console. I want the user to input their guess in a form - and keep looping guesses until the guess matches the random number.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Number Guess</title>
</head>
<body>
<!--text display/button -->
<p>Try and "guess" the random number! Click "Generate new random number" to start"</p>
<div id="out1"></div>
<form id="promptUser">
Your guess:
<input type="text" id="inUserGuess">
<input type="submit" value="Submit">
</form>
<br>
<button id="btn1">Generate new random number</button>
<div id="in1"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>/*SEE SCRIPT BEOW */</script>
</body>
</html>
And here is the javascript/jquery inside:
$(document).ready(function() {
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var win = false;
while (win = false) {
$('#promptUser').on('submit', function(e){
e.preventDefault;
var userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
});
/*yes: "congrats! start again"*/
if (userGuess == randNum){
console.log("User guess is correct");
alert("You got it! Try another round.");
win = true;
}
/*no: "not quite. guess again."*/
else {
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
win = false;
}
}
In order to keep the user guessing until they get it right, I put the guess input inside a while loop and used and if/else statement to determine whether their guess matches the random number.
It seems as though the code gets messed up somewhere before the if/else statement- the console log never shows up. Instead, a new random number is generated when submit is pressed.
I know the syntax of gathering input works - before I attempted to give the user infinite guesses the if statement ran fine (though a new random number was automatically generated after each "play", regardless of correct/incorrect guess)
I feel stupid asking this - but I've been fiddling with it for hours.
[[EDIT]] I now have the submit button event handler doing two things: storing the user input to userGuess and checking to see whether or not it matches randNum, but still is stuck in an infinite loop:
<script>
/*initialize random number*/
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum);
var userGuess = "";
do {
$(document).ready(function() {
$('#promptUser').on('submit', function(e){
e.preventDefault;
userGuess = $('#inUserGuess').val();
console.log("User guess:" + userGuess);
if(userGuess == randNum){
console.log("user guess is correct");
alert("That's right! Play again.");
}
else{
console.log("user guess is incorrect");
alert("Not quite. Guess again.");
}
});
});
}
while (userGuess != randNum);
/*generate new random number each on button click */
$('#btn1').on('click', function(){
var randNum = Math.round(Math.exp(Math.random()*Math.log(10000000-0+1)));
console.log(randNum); /*(return random number to console for cheating)*/
});
</script>

Related

JavaScript code does not work as expected

So I made this little thing as I am quite new to programming, but when I open it in Chrome, I am able to type input but then nothing happens. Does anyone know how I can fix this code?
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input type="submit" value="GO!">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low +1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
for (var i=0;i=0) {
if (guess>number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
}
if (guess<number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
}
if (guess==number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
}
}
}
startGame();
</script>
</body>
</html>
You've got a lot of problems, starting with a syntax error.
You have a submit button, but no form to submit. You really just need a button. But, even then, you have to set up a click event handler for it.
Then, your loop isn't configured properly.
You also are not accessing the data the user has typed into the textbox correctly - you need to get the value of the element.
Your if statements should be else if.
The b element should not be used just for presentation. HTML is a "semantic" language, meaning that you use a tag to describe the meaning (not presentation) of an element. For styling use CSS.
See comments inline below for details.
/* CSS is for presentation, not HTML */
#bold { font-weight:bold; }
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<!-- Don't use HTML for styling, use it for semantics. -->
<span id="bold">Guess:</span> <input type="text" id="guess">
<!-- You need a <form> if you have a submit button. For this, you just want a button. -->
<input type="button" value="GO!" id="go">
<script>
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
var number = getRandomNumber(1,10);
var guess = document.getElementById("guess");
// Get a reference to the output area just once
var output = document.getElementById("bold");
// Give the user 3 tries. Your loop wasn't configured properly.
for (var i=0; i < 3; i++) {
// You want to access the data in the textbox. That's the value
// Also, if the first condition isn't true, try the next and so on.
// This is done with else if branches
if (guess.value > number) {
output.textContent = "You're too high, try lower!";
} else if (guess.value < number) {
output.textContent = "You're too low, try higher!";
} else if (guess.value == number) {
alert("You're correct, the number is "+number+"!!!");
alert("Thanks for playing my game and have a good day!");
break; // Get out of the loop because the game is over.
}
}
}
// Set it up so that clicks on the button run the function
document.getElementById("go").addEventListener("click", startGame);
</script>
</body>
</html>
you have some errors:
this doesnt work, it wont loop. actually, why do you want to loop?
for (var i=0;i=0) {
this will run the function once, this means when the user writes the value it wont be checked
startGame();
the button doesnt do anything, also it has a submit and you don't have any forms:
input type="submit" value="GO!">
on each if, the conditions are exclusive, use if/else
below is a working code:
<!DOCTYPE html>
<html>
<head>
<title>Number Guessing</title>
</head>
<body>
<b id="bold">Guess:</b> <input type="text" id="guess">
<input value="GO!" onclick="checkGuess()">
<script>
var number = 0;
function startGame() {
function getRandomNumber(low, high) {
var number = Math.floor(Math.random() * (high - low + 1)) + low;
return number;
}
number = getRandomNumber(1, 10);
}
function checkGuess() {
var guess = document.getElementById("guess").value;
if (guess > number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too high, try lower!";
} else if (guess < number) {
guess = document.getElementById("guess");
document.getElementById("bold").innerHTML = "You're too low, try higher!";
} else if (guess == number) {
alert("You're correct, the number is " + number + "!!!");
alert("Thanks for playing my game and have a good day!");
}
}
startGame();
</script>
</body>
</html>
Although i have no idea about what your program does. you have a syntax error at
for (var i=0;i=0) {
and also you should bind an event to that button rather than doing a submit.

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.

HTML Javascript converter program

I am trying to create a simple HTML program that will allow the user to input a number or word, then if the userInput matches what I have defined, it changes that input to something else, then outputs the new value on the screen.
Also looking for a button to reset the program (at any time to start over)
Any ideas?
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test() {
var userInput = document.getElementById("userInput").value;
//Need to add If, else if, else to change the value of userInput
// for example, If xxxx value, set to yyyy, then output yyyy
document.write(userInput);
}
// Need to add a "reset" to go back to restart the program
</script>
</body>
</html>
Working better now with... but where does the reset go? How do I format the output? all noob questions yes
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
userInput="yyyy";
}
else if(userInput == "yyyy") {
userInput="zzzz";
}
else {
userInput="Not Found";
}
document.write(userInput);
}
// Need to add a "reset" to go back to restart the program
</script>
</body>
</html>
Convert the function to the following.
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
// I forgot the updating part here.
document.getElementById("otherIdToWriteOutput").innerHTML = "yyyy";
}
}
You can also add the reset button. And remove the current text using
document.getElementById("id").innerHTML = ""; // remove the inner html.

Why does this think it's correct?

I'm new to js and I have this very simple code. It's supposed to be a login, and it's not working. I don't need any tips on making it better, I'm planning to do that when this starts to work.
<!DOCTYPE html>
<head> Sign-in </head>
<body>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em = "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa = "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</body>
</html>
What it's doing now is no matter what, it thinks that the correct e-mail and password were used. Could somebody help?
I've fixed your code up a bit. Some things to note.
You can't just put raw content in the <head>.
Your password is in the raw source of the page, so anyone can view the page source and see what the correct password is. That's an absolutely horrible design. Passwords should be passed to server side where they're checked for validity.
In C like programming language such as Javascript, == tests for equality and will return a boolean. The = sign assigns a value to a variable.
<!DOCTYPE html>
<head>
<title>Sign-in
</title>
<script type="text/javascript">
var em = prompt("Enter E-mail Here:")
if(em == "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa == "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
</script>
</head>
<body>
</body>
</html>
Just one addition:
== checks value
=== checks value and type
Someone who deactivates js or doesn't support it like curl/wget and others, will not be stopped by this, except you load the whole website with js, what might be stupid cause of search engines might not index the content though.
Hope this helps.
fixed
var em = prompt("Enter E-mail Here:")
if(em === "I hid this to prevent spam"){
var pa = prompt("Enter Password Here:")
if(pa === "jct28if5"){
alert("Welcome!")
}
else{
alert("Incorrect password!")
}
}
else {
alert("Invalid e-mail!")
}
You use a single = when you're assigning a variable a value. like var x = 1.
But if you want to check equality, use ===. like if(x ===1)

Categories

Resources