Guessing Game in Javascript - javascript

What I'm trying to do is make a simple guessing game where the user can any the number without limit but will be graded at the end when the guessed the number correctly based on the number of their guesses. However, with my code when I enter a number and press the button to multiple times the hint changes from "Higher" to "Lower" even if the number is not changed also the message that should be displayed when the number is guessed correctly is not showing. Here's my code, I'm a beginner so there's bound to be errors in the code and any help is appreciated.
<fieldset>
<input type="number" id="guess" />
<button onClick="checknum();">Check Number</button>
</fieldset>
<fieldset>
<p>Your current status:</p>
<output id="status_output">You have yet to guess anything.</output>
</fieldset>
<script type="text/javascript">
function checknum(){
var randomNumber = Math.floor((Math.random() * 100) + 1);
var guessNumber = document.getElementById("guess").value;
//var guessNumber = parseInt(guess.value);
var statusOutput = document.getElementById('status_output');
var counter = 0;
var isguessed = false;
do {
counter = (counter + 1)
if (guessNumber < randomNumber) {
statusOutput.value = ("Higher");
}
else if (guessNumber > randomNumber) {
statusOutput.value = ("Lower");
}
else if (guessNumber = randomNumber) {
set (isguessed = true());
statusOutput.value = ("Correct" + mark());
}
}
while (isguessed = false);
}
function mark(){
if (counter < 10){
statusOutput.value("Excellent");
}
else if (counter > 10 && counter <20){
statusOutput.value("Okay");
}
else
statusOutput.value("Needs Practice");
}
</script>

In your while you are assigning false to the variable named isguessed.
You want to do while (isguessed === false) instead. This will check if isguessed is set to false
isguessed = false : assigns the varibles isguessed to false
isguessed === false : a boolean expression return true or false

Related

Evaluate if statements in javascript

So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Your if statement is absolutely fine, the reason you never see the message "Please enter a Number between ${min} and ${max}" is because you let the code continue, and almost immediately that message is overwritten by a different one. Simply adding a return statement within your if block will solve this problem.
Note I also fixed this line guessInput = ''; which should be guessInput.value = '';
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
return; // here
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput.value = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Try changing the const to let. You're editing all these later in your code:
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');

While Loop Input Issue

I am trying to make a program that takes numbers from the user until they input a 0, the output how many positive and negative numbers were input, while also telling the user whether the number they input was positive, negative, or zero, however, when I use it, it crashes the webpage immediately if anything but a 0 is input. So I was wondering where this issue would be coming from and how I could resolve it.
JS:
var pos = 0;
var neg = 0;
var inp = 1;
function interpreter() {
while (inp != 0) {
inp = (document.getElementById("number"));
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML = pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML = neg + " negative numbers were inputted";
}
}
}
Where "number" is a text field for input, and the function is called upon the press of a button. Thanks in advance!
You're misunderstanding the event-processing nature of JavaScript.
If you have a while loop like that, you'll never yield control back to the browser itself, to handle user input, etc. You may be looking for something like this -- in addition to the removal of the explicit loop, note how the handling of inp has changed; previously you were comparing strings to numbers.
var pos = 0;
var neg = 0;
function interpret() {
var inp = parseInt(document.getElementById("number").value);
if (inp < 0) {
document.getElementById("output1").innerHTML = "Input is: negative";
neg += 1;
} else if (inp > 0) {
document.getElementById("output1").innerHTML = "Input is: positive";
pos += 1;
} else {
document.getElementById("output1").innerHTML = "Input is: zero";
document.getElementById("output2").innerHTML =
pos + " positive numbers were inputted";
document.getElementById("output3").innerHTML =
neg + " negative numbers were inputted";
}
}
<form onsubmit="interpret();event.preventDefault()">
<input id="number">
<input type="submit" value="Interpret value">
</form>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
If you really want my suggest:
var pos = 0
, neg = 0
;
document.forms['my-form'].addEventListener('submit',function(evt)
{
evt.preventDefault()
let inp = this.number.valueAsNumber
{
if (inp < 0)
{
this.out_1.textContent = 'Input is: negative'
neg++
}
else if (inp > 0)
{
this.out_1.textContent = 'Input is: positive'
pos++
}
else
{
this.out_1.textContent = 'Input is: zero';
this.out_2.textContent = pos + ' positive numbers were inputted'
this.out_3.textContent = neg + ' negative numbers were inputted'
}
}
})
label, button, output { display: block; margin:.4em; }
<form name="my-form">
<label>
Input:
<input name="number" type="number" min="-32768" max="32768" value="1">
</label>
<button type="submit"> enter </button>
<output name="out_1"></output>
<output name="out_2"></output>
<output name="out_3"></output>
</form>

Page doesn't load when I set variable to 0 in Javascript

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>

Unable to make thss script to run on click. Need it to re run after input has been changed

I've tried many times but can not figure out how to get this full script to run on click it will not work. Need answer to change after the value of the input has been changed.
<input id="a" value="500" type="number">
<p id="b"></p>
<script>
var bills = [100, 250, 450, 950, 1150];
var money = mod(document.getElementById("a").value);
function mod(num){
if (num % 5 === 0){
return num;
} else {
return num + 5 - num % 5
}
}
function foo(num){
var index = bills.length - 1;
var splits = [];
while (money >= bills[0]){
if (money >= bills[index]){
money -= bills[index];
splits.push(bills[index]);
} else {
index--;
}
}
return splits;
}
document.getElementById("b").innerHTML = foo(money) </script>

How do I make a document wait for an assigned input value?

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)

Categories

Resources