While loop in JS slows down browser - javascript

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.

Related

How to keep track of attempts in a JavaScript guess-the-number game

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++;
}

issue with random number guess game. Does not show if answer is correct

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>

Inserting a loop into a Javascript number guessing game

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>

How can i get a variable to change number depending on what the user has eneterd

So i am creating a simple dice game which you enter the guess of the dice roll and amount you wish to bet. I cant seem to figure out how i can get my balance to change when a user enters a number.
My code:
//declaring global variables
var diceroll = 0;
var balance = 1000;
var stake = 0;
var guess = 0;
while (balance <= 0) {
var guess = document.getElementById("guess").nodeValue;
var stake = document.getElementById("stake").nodeValue;
var diceroll = roll();
if (guess === diceroll) {
balance = balance + (stake * 5);
} else {
balance = balance - stake;
}
}
//Rolling the dice
function roll() {
"use strict";
diceroll = Math.floor(Math.random() * 6 + 1);
alert(diceroll);
}
//Display balance
document.getElementById("balance").innerHTML = balance;
<!DOCTYPE html>
<html>
<head>
<title>Dice-Game: GL HF</title>
</head>
<body>
<p id="balance"></p>
<form action="#">
Enter guess:
<input type="text" id="guess">
<br>Enter stake:
<input type="number" id="stake" name="stake">
<br>
<input type="button" name="play" onclick="roll()" value="PLAY!">
<br>
</form>
<script src="Dice.js" type="text/javascript"></script>
</body>
</html>
A few things:
The way I looked at it, your while loop wasn't doing anything. The whole balance calculation wasn't even part of your roll function. I removed it altogether.
You were using .nodeValue to get your guess and stake input values, which is deprecated. It should just be .value. Those two variables were returning null.
Your balance update wasn't being called with your function either, so it wouldn't have updated on the page even if the balance was actually updating.
Your declaration of global variables was a bit redundant and unnecessary.
//declaring global variables
var balance = 1000;
//Rolling the dice
function roll() {
var guess = document.getElementById("guess").value;
var stake = document.getElementById("stake").value;
"use strict";
var diceroll = Math.floor(Math.random() * 6 + 1);
alert(diceroll);
if(guess == diceroll) {
balance = balance + (stake * 5);
} else {
balance = balance - stake;
}
//Update display balance
document.getElementById("balance").innerHTML = balance;
}
//Initial display balance
document.getElementById("balance").innerHTML = balance;
Put
//Display balance
document.getElementById("balance").innerHTML = balance;
inside of the loop.
I also don't think your while condition is correct..
Try this,
balance = parseInt(balance) - parseInt(stake);

Javascript function checks user input but always posts "wrong"

I got a task in class today- im asking the user a simple math qustion, and if the he answers correctly alert with "Correct" will pop up, if not a "wrong" alert.
<body>
<h1 style="text-decoration:underline">Math test!</h1>
<p id="question"></p>
<script>
var firstnum = Math.floor((Math.random() * 10) + 1);
var secondnum = Math.floor((Math.random() * 10) + 1);
var trueanswer = firstnum * secondnum;
function setquestion() {
document.getElementById("question").innerHTML = firstnum + " * " + secondnum;
}
setquestion();
function checkuseranswer() {
var useranswer = document.getElementById("useranswer");
if (trueanswer == useranswer) {
alert("Correct!");
}
else {
alert("Wrong!");
}
}
</script>
<h2>Press submit to test yourself</h2>
<input type="text" id="useranswer" />
<input type="submit" id="submit" value="submit" onclick="checkuseranswer()" />
I think the problem is that var useranswer isn't being recieved correctly, but debugging didn't help at all. I also tried putting function checkuseranswer in the botton, but same result.
All help appreciated.
var useranswer = document.getElementById("useranswer");
You're comparing against the DOM element itself, not the value of the input.
var useranswer = document.getElementById("useranswer").value;
An element will never equal a number, no matter how much you wish it.

Categories