For an assignment, I need to make a JS number guessing game. It needs to include a loop to check the user's guess and a reset game button. My problem is getting the loop to work. I want the number of turns to start at 10. Each time the user makes an incorrect guess, their number of turns decreases by 1, and if they guess correctly, their number of turns is 0. If they push the "Start New Game" button, a new number should be generated and the number of turns should be reset to 10.
The loop doesn't specifically need to be a while loop, I just need one in the code for my assignment. Can anybody help me out?
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="guess" placeholder="Insert your guess" type="number">
<input name="requestInfo" onclick="getResults()" type="button" value="Confirm">
<p></p>
<textarea cols="50" name="results" readonly="true" rows="8"></textarea>
<p></p><input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
var guess = parseFloat(document.Input.guess.value);
while (turns > 0) {
if (guess == num) {
turns = 0;
document.Input.results.value = "Congratulations, you won! The mystery number was " + num + ".";
} else if (guess < num) {
turns--;
document.Input.results.value = "Your guess was too low. Turns remaining: " + turns;
} else if (guess > num) {
turns--;
document.Input.results.value = "Your guess was too high. Turns remaining: " + turns;
}
}
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
document.Input.guess.value = "";
document.Input.results.value = "";
}
function getResults() {
checkNumber();
}
</script>
</body>
Alright, I guess since it is a college/HS assignment your professor is trying to teach you using prompt under a loop.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="requestInfo" onclick="getResults()" type="button" value="Start Guessing!">
<input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
while (turns > 0) {
guess=prompt("Tell me your guess.", "Your guess: ");
if (guess == num) {
turns = 0;
alert("Congratulations, you won! The mystery number was " + num + ".");
} else if (guess < num) {
turns--;
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
turns--;
alert("Your guess was too high. Turns remaining: " + turns);
}
}
if (turns==0)
alert ("You failed to guess sadly.");
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
}
function getResults() {
checkNumber();
}
</script>
I agree that the taks seems a bit weird - obviously, with a non-modal dialog, you will not need a loop.
One thing you could do is use the prompt method (example: window.prompt("sometext","defaultText");), which would then open a modal dialog to ask the user until the number of remaining guesses is zero, or until the guess was correct. That would work within the loop.
Here have a go with this one. Makes sure that the user enters a number.
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it? Click button to start game.</p>
<button type="button" onclick="startNewGame()">Start New Game</button>
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns;
function checkNumber() {
while (turns > 0) {
var guess = prompt("Insert your guess");
if (!guess || isNaN(guess)) {
alert("Please enter a valid number");
continue;
}
if (guess == num) {
alert("Congratulations, you won! The mystery number was " + num + ".");
return;
} else {
turns--;
if (guess < num) {
alert("Your guess was too low. Turns remaining: " + turns);
} else if (guess > num) {
alert("Your guess was too high. Turns remaining: " + turns);
}
}
}
if (turns == 0) {
alert("You have lost");
}
}
function startNewGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
checkNumber();
}
</script>
</body>
Related
I am new to learning these languages, and everything looks syntactically correct. The issue I'm having is that the correct button will just keep click as correct rather or not the answer is correct or not. The tables are updating, but I'm not sure where the issue is. The if-else statement looks to be okay (I know I don't need the else if in there). If anyone could help me figure out what is wrong I would appreciate it.
window.onload = function() {
equations();
};
window.onload = equations;
var sum;
var correct = 0,
incorrect = 0;
function equations() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ['+', '-', '÷', 'x'];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length)
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return (sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight() {
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl = document.getElementById('incorrectCount');
sum = equations();
if (userInput = sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput = '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<body>
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function() {
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="button" id="submit" value="Enter" onclick="confirmIfRight()" onclick="document.getElementById('userInput').value = '' " />
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
</body>
The main reason your code wasn't working is because you aren't using the equality operator (==), you are using the assignment operator (=) in your if..else statements. Fixing that alone should resolve the main problem in your question.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
However, this presents another problem in your code immediately: you're comparing sum immediately after reassigning it in confirmIfRight(). A new equation will have been generated prior to the comparison. This means the value in sum will most likely not be correct considering the original equation presented and the answer given.
To resolve this, remove the sum = equations(); line just before the if..else statements:
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Additionally, I do agree that you can remove the else if section and this should capture all cases where the answer does not equal the expected result.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Testing a few times showed that this is all you need to have your code working. Run the code snippet below as an example:
window.onload = equations;
var sum;
var correct=0, incorrect=0;
function equations(){
var a,b,sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a+b , a-b ,a /b ,a *b ];
signs = ['+', '-','÷','x'];
//assign random opperation
let randoArr = Math.floor(Math.random()*solve.length)
sum=solve[randoArr];
showSign=signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return(sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight(){
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl= document.getElementById('incorrectCount');
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function(){
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput"/>
<input type="button" id ="submit" value="Enter"onclick="confirmIfRight()" onclick=
"document.getElementById('userInput').value = '' "/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
There were a few mistakes that you did. The main issue was that you were generating a new equation and sum value every time you call equations function.
So I've saved the value in a new hidden input that is visually hidden from the user. And then compare it to the user input value. There is a plus sign in front of some methods and it is to convert the value to a number. Also, I allowed myself to make a few code naming changes so the code can feel better. Also, you can remove the return statement in the equation method since it has no reason to be there anymore.
let correct = 0,
incorrect = 0;
function generateEquation() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ["+", "-", "÷", "x"];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length);
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById("showMath").innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
document.getElementById("hiddenInput").value = sum;
return sum;
}
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function isCorrect() {
let userInput = +document.getElementById("userInput").value;
const correctEl = document.getElementById("correctCount");
const incorrectEl = document.getElementById("incorrectCount");
if (userInput === +document.getElementById("hiddenInput").value) {
correct++;
correctEl.textContent = correct;
generateEquation();
} else if (userInput == "") {
incorrect++;
incorrect.textContent = incorrect;
generateEquation();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
generateEquation();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById("userInput").value = "";
}
generateEquation();
<!DOCTYPE html>
<html lang="eng">
<head>
<link rel="stylesheet" href="fastmath_style.css" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial scale = 1" ; />
<title>Fast Math</title>
</head>
<body>
<h1>Welcome to Fast Math!</h1>
<p>A website for solving simple math problems.</p>
<!-- Math Stuff-->
<div id="showMath"></div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="hidden" id="hiddenInput" />
<input
type="button"
id="submit"
value="Enter"
onclick="isCorrect()"
onclick="document.getElementById('userInput').value = '' "
/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount">0</td>
<td id="incorrectCount">0</td>
</tr>
</table>
<script src="./app.js"></script>
</body>
</html>
My goal is to keep track of the attempts made in the game. This is my code so far.
I have edited this post to understand difference between count = 0 and count = 1.
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.getElementById("attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let count = 1
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value;
if (guessValue < randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too low";
count++
} else if (guessValue > randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too high";
count++
} else {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "You guessed correctly in " + count++ + "
attempts";
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Guess the number</title>
</head>
<body>
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
<script src="script.js"></script>
</body>
I can't understand why attempt.innerHTML won't work. It doesn't show up on the page like "result" does.
You are declaring a global attempt variable outside the function which holds the html element and then you are declaring a local attempt variable in your function which will always be 1.
Declare a counter outside the function and then increment it everytime your function is called.
Also in your answer you are only incrementing the count and updating the attempt.innerHTML inside your if else block under specific conditions. You want to move this code outside of the if else block so it updates on every guess.
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let attempt = document.querySelector(".attempt")
let attemptCounter = 0
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value
// Increment Attempts by 1
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
}
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
This is a simplified function version of setting up multiple number guessing games on a single page. All game related data is kept in dataset attributes num and try of the associated input field.
function guess(id){
let el = document.getElementById(id);
el.dataset.try=0;
el.dataset.num = Math.floor(Math.random() * 30) + 1;
el.onchange=()=>el.nextElementSibling.innerHTML =
"Attempt "+(++el.dataset.try)+":<br>Your guess is "
+["too low.","correct!","too high."]
[Math.sign(el.value-el.dataset.num)+1]
}
guess('guess1');guess('guess2');
<h1>GUESS SOME NUMBERS:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess1">
<div></div>
<p>Enter another guess:</p>
<input type="number" id="guess2">
<div></div>
You're redefining the attempt variable in a local scope as an integer which is overriding the reference to the document element. When you use "innerHTML" your using it on the localized attempt (an integer not the document element)
Try this:
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.querySelector(".attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
button.addEventListener("click", checkGuess)
let attemptCount = 1 // Renamed this from attempt and moved to global scope
function checkGuess() {
let guessValue = document.getElementById("guess").value
attempt.innerHTML = "Attempt n: " + attemptCount
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
attemptCount++;
}
I am writing on a code that should guess a number the user entered and return a paragraph with a string and the number of tries the script needed to get the number. Nothing too fancy. The problem is that as soon as I start the page on firefox, it basically crashes down and I don't know why.
Thanks for the help.
This is my code:
<input id="guess" placeholder="Your Number">
<button id="guessButton">Guess it!</button>
<br>
<div id="scriptOutput"></div>
<script>
var myNumber = document.getElementById("guess").value
var guess = false
var scriptGuess = Math.random()
scriptGuess = scriptGuess*6
scriptGuess = Math.floor(scriptGuess)
var guessCount = 1
document.getElementById("guessButton").onclick = function() {
while (guess == false) {
if (myNumber == scriptGuess) {
document.getElementById("scriptOutput").innerHTML = "<p>" + "I got it after" + guessCount + "times!" + "</p>";
guess = true;
}else {
guessCount ++;
}
}
}
</script>
</body>
You are defining scriptGuess before the while loop, thus, each time the while loop runs, scriptGuess isn't changing. This is creating an infinite loop.
Try adding the guess logic inside of the while loop. This way, a new scriptGuess value is initialized every instance of the while loop:
<body>
<input id="guess" placeholder="Your Number">
<button id="guessButton">Guess it!</button>
<br>
<div id="scriptOutput"></div>
<script>
var myNumber = document.getElementById("guess").value
var guess = false
var guessCount = 1
document.getElementById("guessButton").onclick = function () {
while (guess == false) {
var scriptGuess = Math.random()
scriptGuess = scriptGuess * 6
scriptGuess = Math.floor(scriptGuess)
if (myNumber == scriptGuess) {
document.getElementById("scriptOutput").innerHTML = "<p>" + "I got it after" + guessCount + "times!" + "</p>";
guess = true;
} else {
guessCount++;
}
}
}
</script>
</body>
However, I still think you are going to run into problems with time complexity. This is going to take a lot of time to guess a user's inputted number, especially without a pre determined range.
Why is this not working. There are no errors in console and compiler does not show anything specific. Probably something wrong with the variable check?
document.getElementById("checknumber").onclick = function() {
var numberSelected = document.getElementById("input").value;
//alert(numberSelected)
var number = Math.floor((Math.random() * 6) + 1);
//alert(number)
if (input == number) {
alert("got it");
} else("noup not now");
}
<p>Guess the number: </p>
<p><input id="input"> </p>
<p><button id="checknumber">Check !</button></p>
The input variable is not defined anywhere, and I think you missed an alert in the else("noup not now") statement.
Side note: you are confronting a String with a Number, in this case it behave as expected because of Js Coercion and the equality operator.
document.getElementById("checknumber").onclick = function() {
var numberSelected = document.getElementById("input").value;
//alert(numberSelected)
var number = Math.floor((Math.random() * 6) + 1);
//alert(number)
if (numberSelected == number) {
alert("got it");
} else {
alert("noup not now");
}
}
<p>Guess the number: </p>
<p><input id="input"> </p>
<p><button id="checknumber">Check !</button></p>
I'm creating a simple program called guess a number. I'm having problem showing my output. So I don't know if i got the right formula.
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
<script>
function guess() {
var num = document.getElementById("number").value;
var answer = Math.floor(Math.Random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
</body>
You had a syntax error when generating a random number.
It should be
Math.random();
But you have
Math.Random();
Here is the complete code:
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
<script>
function guess() {
var num = document.getElementById("number").value;
var answer = Math.floor(Math.random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
</body>
When developing Javascript, always have your browser's console turned on. It would have showed you this error. All browsers have consoles.
Your code is correct but you need to test the function with a fixed number to see if it works, then use Math.random(); (lowercase random()), in this case, I'm using 11 as the correct number..
function guess() {
var num = document.getElementById("number").value;
//var answer = Math.floor(Math.random() * 100 + 1);
var answer = 11;
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
</body>
// --- use Math.random instead of Math.Random ------
`
<script>
function guess() {
var num = document.getElementById("number");
//alert(num);
var answer = Math.floor(Math.random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
</body>