I'm working on what should be an extremely simple "guess my number" game in Javascript, however, I can't get it to work correctly.
The program is supposed to choose a random integer between 1 and 10 and allow the user to try and guess that number as many times as it takes to get it right. If the user guesses a number that's lower than the correct one, the program is supposed to display a "your guess is too low" message, this is the same for when the guess is too high, or correct. The program must display the message on the webpage, not in an alert or any type of pop-up. Also, the program is supposed to keep a running list of the numbers that have been guessed by the user and display them on the page each time the user makes a guess (I want this list to display below my heading "Here are the numbers you've guessed so far:"). And finally, the program is supposed to display a "you already tried using that number" message if the user tries to input a number that they've already used.
Here is my code, along with a JSfiddle I've created and am still playing with.
<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 = [];
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, 10);
}
catch (e) {
document.getElementById("guess").value = "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.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
else if(tries.indexOf(guess) != -1 {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else {
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value;
display();
document.getElementById("guess").value = " ";
return false;
}
}
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
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>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<div id = "result">
<input type = "text" id = "result" size = "20" />
</div>
<h3>Here are the numbers you've guessed so far:</h3>
</body>
</html>
http://jsfiddle.net/v09ttL74/
As you should be able to see from the fiddle, nothing is happening when I click either one of the buttons, so I'm not really sure where the problem is. I am getting a few errors when I select the JShints option on the fiddle, but most are things like "Missing semicolon" in places where there's not supposed to be a semicolon, like an one line where all I have written is
else {
Any suggestions would be greatly appreciated. I feel like this is just a really simple project that I am over-thinking since I'm stressed about it not working.
There's a lot of issues in your code. Just to mention a few...
1- Unclosed parenthesis here
tries.push(document.getElementById("guess").value;
it should be...
tries.push(document.getElementById("guess").value);
2- Expression not terminated with a close parenthesis here
else if(tries.indexOf(guess) != -1 {
it should be...
else if(tries.indexOf(guess) != -1) {
3- Wrong declaration of functions inside a function
function display() {
var number = ";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
I could be going forever but, really, the errors are a bit obvious
Alright as some of the answers must have already given you an idea of how many mistakes your Script as well as HTML code had.. from missing parenthesis to same ids to missing elements. Well i have corrected them and it's working now:
<h1>Would You Like To Play A Game?</h1>
<h3>Directions:</h3>
<p>
The game is very simple. I am thinking of a non-decimal number between 1 and 10, it is your job to guess what that number is. If you guess incorrectly on your first attempt, don't worry. You can keep guessing until you guess my number.
</p>
<h3>Thanks for playing and good luck!</h3>
<h3>Created by Beth Tanner</h3>
<p>Your Guess:
<input type = "text" id = "guess" size = "10" />
<br />
<input type = "button" value = "Submit Guess" onclick = "guessNumber()" onclick = "display()" />
<input type = "reset" value = "Reset Game" onclick = "resetGame()" />
</p>
<h3>How'd you do?</h3>
<input type = "text" id = "result" size = "20" />
<h3>Here are the numbers you've guessed so far:</h3>
<p id='tries'></p>
Script:
var tries = [];
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, 10);
}
catch (e) {
document.getElementById("guess").value = "Enter a guess.";
this.turns++;
return false;
}
alert(guess+ ' '+this.num);
if (guess == this.num) {
document.getElementById("result").value = "Correct! It took you " + this.turns + " tries to guess my number.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return true;
}
else if(tries.indexOf(guess) != -1) {
document.getElementById("result").value = "You have already guessed that number. Try again.";
document.getElementById("guess").value = " ";
return false;
}
else if(guess > this.num) {
document.getElementById("result").value = "Your guess is too high. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
else if(guess < this.num){
document.getElementById("result").value = "Your guess is too low. Try again.";
tries.push(document.getElementById("guess").value);
display();
document.getElementById("guess").value = " ";
return false;
}
}
}
function display() {
var number = "";
for(i=0; i<tries.length; i++) {
number += tries[i] + "<br >";
}
document.getElementById("tries").innerHTML = number;
}
function guessNumber() {
var guess = document.getElementById("guess").value;
game.guessNumber(guess);
document.getElementById("guess").value = " ";
}
function resetGame() {
game.reset();
document.getElementById("guess").value = " ";
}
resetGame();
See the DEMO here
Related
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
while (attempts < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
while learning how to use a random number generator, I wantd to add a while loop and give 3 attempts to choose from a random number.
When I create a variable to set the number of attempts, if I make the variable equal to 0, my page doesn't load, but if I leave the variable empty without a value, the script doesn't run.
Any ideas of why this may be happening?
var randomNumber = Math.floor(Math.random() * 6);
var x = 0
var maximum = 3
while (x < maximum){
document.getElementById("submit").onclick = function() {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
Your while loop runs synchronously, during pageload. The script never finishes, because the while loop's condition is never negated, so control is never yielded back to the browser to repaint the page, so the user never has a chance to input a number or click on the button.
While you could keep using while by promisifying the onclick and awaiting a Promise, it'd be better to create the handler outside, once, and have it check if the attempts are maxed out.
You also need to use consistent variable names: either use x or attempts, not both:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0
var maximum = 3
document.getElementById("submit").onclick = function() {
if (attempts >= maximum) return;
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
}
<input type="text" id="input">
<button id="submit">Submit</button>
You could disable the button after the maximum number of attempts has been reached, like:
var randomNumber = Math.floor(Math.random() * 6);
var attempts = 0;
var maximum = 3;
document.getElementById("submit").onclick = function(e) {
attempts += 1;
if (document.getElementById("input").value == randomNumber) {
alert("You chose the right number");
} else {
alert("WRONG Number! You have " + attempts + " attempts.");
}
if (attempts === maximum) e.target.disabled = true;
};
<input type="text" id="input" />
<button id="submit">Submit</button>
I want user to guess how many fingers are there (Math.random()), but it does not work the way I expect it to and I can't find the mistake.
This is all in a <body> tag:
<p>How many fingers am I holding?</p>
<input type="number" id="userInput">
<button onclick="check()">Guess</button>
<p id="numberOfTries"></p>
<script>
var fingers = parseInt(Math.random()*6);
var userInput = document.getElementById("userInput").value;
var i = 0;
var num = document.getElementById("numberOfTries");
function check(){
if (userInput == fingers)
{
alert("You got it!");
}
else{
alert("Try again!");
i++;
}
num.innerHTML = "Number of tries: " + i;
}
</script>
So, the way I see this: when the page loads it creates a random number (fingers), and then I just compare that number to the number in input.
Why doesn't it work?
You had just a small error. You only checked their input once. See I moved to the function scope and now it works.
var fingers = parseInt(Math.random() * 6);
console.log(fingers);
var i = 0;
var num = document.getElementById("numberOfTries");
function check() {
// This was in the wrong place. We need to check user input each time.
var userInput = document.getElementById("userInput").value;
if (userInput == fingers) {
alert("You got it!");
} else {
alert("Try again!");
i++;
}
num.innerHTML = "Number of tries: " + i;
}
<p>How many fingers am I holding?</p>
<input type="number" id="userInput">
<button onclick="check()">Guess</button>
<p id="numberOfTries"></p>
I'm probably going to ask a stupid question, but I really need a definitive verdict on this.
I've got 2 while loops.
Code 1:
document.getElementById("guess").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var gotIt = false;
var numberOfGuesses = 1;
while (gotIt == false) {
var guess = Math.random();
guess = guess * 6;
guess = Math.floor(guess);
if (guess == myNumber) {
gotIt = true;
alert("Got it! It was a " + guess + ". It took me " + numberOfGuesses + " guesses.");
} else {
numberOfGuesses++;
}
}
}
<input type="text" name="" id="myNumber">
<button id="guess">Guess!</button>
Code 2:
document.getElementById("guess").onclick = function() {
var myNumber = document.getElementById("myNumber").value;
var gotIt = false;
var numberOfGuesses = 1;
while (gotIt == false) {
var guess = Math.random();
guess = guess * 6;
guess = Math.floor(guess);
if (guess == myNumber) {
gotIt = true;
alert("Got it! It was a " + guess + ". It took me " + numberOfGuesses + " guesses.");
} else {
numberOfGuesses++;
}
}
}
<select id="myNumber">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<button id="guess">Guess!</button>
The 2nd piece works fine; the 1st crashes the browser. My idea is the 1st one is taking too many loops to guess, but I can't quite work out why this is happening.
Thanks to anyone willing to explain.
Basically both approaches work just fine. You just have a little logical error in your first implementation.
The reason you have number one hanging is because you don't limit the user to input numbers in the range of 0-5. Therefore any number out of that range will loop forever as it will never result in a number of the 0-5 range, which you have restricted to when multiplying the random by 6.
Bottom line:
Either go with option 2, or validate that the user actually typed a number in the range of 0-5.
I am writing a number guessing game. Every time I run the document it automatically goes to my outer else statement and I know why, but I can't figure out how to make it wait for an input value of the textbox. I want to set "guess" = to the value of the text box by pressing submit which will then enter the if statements. At the moment it is automatically setting to null and causing the error. Here is the code.
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1><br>
<button onclick = "search(1,100)">Press to play!</button>
</body>
<script type="text/javascript">
var counter = 0;
var randomNumber = Math.floor(Math.random()*100+1);
function search(first, last){
document.open();
document.write("<h1>Number Guessing Game</h1><br>");
document.write("<input id = 'guessBox' type = 'text'> ");
document.write("<input type = 'submit' id = 'submit' value = 'Submit'><br>");
document.write("<h2>Numbers Left</h2>");
for(var i = first; i <= last; i++){
document.write(i + " ");
}
document.write("<br><br><h3>Number of tries: " + counter + "</h3>");
document.close();
var guess = document.getElementById('guessBox').value;
//var guess = prompt("Guess!");
myguess = parseInt(guess);
if(myguess <= last && myguess >= first && cont == true){
if(myguess == randomNumber){
counter++;
if(counter <=3){
alert("WOW, that was amazingly quick! You found it in " + counter + " tries.");
}
else if(counter < 6 && counter >= 4){
alert("Not bad! You found it in " + counter + " tries.");
}
else if(counter < 10 && counter >= 6){
alert("Ouch! You found it in " + counter + " tries.");
}
else{
alert("Having a bad day aren't you? You found it in "+ counter + " tries");
}
}
else if(myguess < randomNumber){
first = myguess+1;
alert("Try again! The number is higher.");
counter++;
search(first, last);
}
else{
last = myguess-1;
alert("Try again! The number is lower.");
counter++;
search(first, last);
}
}
else{
alert("Invalid Number, try again.");
search(first, last);
}
}
</script>
Have you tried to disable the button, then add an onChange event to your text box so that you can enable the button once you have the desired input? You will need to add an ID or Name value to your button so it can be accessed? And to add what #LGSon added:
if(myguess <= last && myguess >= first && cont == true){, you check the variable cont, which I can't find in your code, so if it is not declared and set somewhere, you code will always take the outer route.
Second, you need to split your search function into 2 functions, one that generates the input, one that runs when someone entered a value (which can be fired on keypress or with a button)
I'm brand new to javascript and html so I was hoping someone could peek at my code and tell me why certain syntax isn't working. In the code below I use document.getElementById to retreive the element I'd like to work with each time. I do declare them as local variables within gameTime() and use it throughout the function.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
function gameTime()
{
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
document.getElementById("guess").value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
document.getElementById("guess").value = "";
document.getElementById("status").value = "";
}
function quit()
{
document.getElementById("status").value += ("The correct number was " + randNum + "!\r")
}
Then I tried it by globally declaring the two elements and use it in every function which does not seem to work at all and I just don't understand why.
var randNum = Math.floor( 100*Math.random() ) +1;
var numGuesses = 0;
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
function gameTime()
{
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
guess.value = "";
}
function reset()
{
randNum = Math.floor( 100*Math.random() ) +1;
numGuesses = 0;
guess.value = "";
status.value = "";
}
function quit()
{
status.value += ("The correct number was " + randNum + "!\r")
}
And here's the html file that accompanies these js files guess.js is the first code block, guessAgain.js is the second code block.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" src="guessAgain.js"></script>
</head>
<body>
<label for = "guess"> Your Guess: </label>
<input type = "text" id = "guess" value = "" />
<input type = "button" onclick = "gameTime()" value = "Submit" />
<input type = "button" onclick = "reset()" value = "New Game" />
<input type = "button" onclick = "quit()" value = "Quit" />
<br>
<textarea id = "status" rows = "10" cols = "52"></textarea>
</body>
</html>
Thanks for any insight you can give me.
Issue 1:
You are calling the following before the body loads and hence, they return undefined.
var guess = document.getElementById("guess");
var status = document.getElementById("status");
You should do these only after the body loads on the onload() event.
Issue 2:
Also, when you assign the value itself to a variable, it isn't updated as the textbox is. var guess = document.getElementById("guess").value, then guess's value does not get updated if you change the textbox.
If you refer to var guess = document.getElementById("guess"), then, repeatedly calling
guess.value will return the latest value of the input field.
(Working Example)
The following is not wrong by unnecessarily complicated.
numGuesses++;
if(guess.value == "")
{
alert("You did not guess a number!")
numGuesses--;
}
...
Instead, you could increment numGuesses once it is deemed a valid guess, i.e. at the end.
You're setting guess to element.value
It should be
var guess = document.getElementById("guess");
Problem is that you're using guess as an element here:
guess.value = "";
You'll also need to modify places where you use guess as a string into guess.value.