I'm creating a guess the number with limited guesses. I have add an incrementor to check the number of times a user submits an answer. Everything seems to work except the loop starts at the final iteration and the games ends on the first try.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<div>Guess The Number</div>
<input type="text" id="input">
<button id="btn">Check Answer</button>
<p id="guesses" style="display: inline-block;"></p>
<p id="hint"></p>
</body>
</html>
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
btn.addEventListener('click', () => {
if(isNaN(input.value)){
input.value = "Please type a number"
} else{
const hint = document.getElementById("hint");
let i = 0;
while (i < 10){
if(input.value === rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
break;
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else{
hint.innerHTML = "Too low";
} i++; guesses.innerHTML = "You have guessed " + i + " times";
}
if(i === 10){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
}
})
I've tried changing the number in the while loop condition. I've tried moving the incrementor in and out of the loops function. I've also tried chatgpt to see if it would work. But no luck. I would really appreciate your help.
I think you're misunderstanding the while loop. The loop will run once for every instance of i from 1 to 10 then stop running when the condition in the while loop is false. Based on what you mentioned you don't want a loop at all but to store the number of guesses into its own variable and increase that variable until you reach your limit.
const rndmNum = Math.floor(Math.random() * 100) + 1;
let numberOfGuesses = 0;
btn.addEventListener('click', () => {
if (isNaN(input.value)) {
return input.value = "Please type a number";
}
const hint = document.getElementById("hint");
if (input.value === rndmNum) {
hint.innerHTML = "Congratulations, You guessed correctly!";
return;
} else if (input.value > rndmNum) {
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
numberOfGuesses++;
guesses.innerHTML = "You have guessed " + numberOfGuesses + " times";
if (numberOfGuesses === 10) {
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
})
I believe this is what you were trying to accomplish. The reason why it's not working with the loop because it will run ten times with the click of the button once.
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
//keep track of guess count
let count = 0;
//event listner to check the users answer
btn.addEventListener("click", checkAnswer)
//this function will check for answers or display game over
function checkAnswer(){
if(count > 9){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
} else if(input.value == rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
count++
guesses.innerHTML = "You have guessed " + count + " times";
}
Related
I'm very new to coding and thus VS Code. I am on a mac. Whenever I try to link an external file in VS Code to another file it never works. I understand it has to be a bad file path but I cannot figure it out at all. I've tried removing files from folders so they're in their own section and this does not work.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script src="/js/number-guessing-game.js"></script>
</body>
</html>
js file:
function runGame() {
let guessString = '';
let guessNumber = 0;
let correct = false;
let numtries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
// const target = Math.floor(Math.random() * 100) + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target);
} while (!correct);
alert('You got it! The number was' + target + '.\n\nIt took you' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target){
let correct = false;
if (isNaN(guessNumber)) {
alert('You have not entered a number.\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!');
} else if (guessNumber < target) {
alert('Your number is too small!');
} else {
correct = true;
}
} return correct;
}
Here's what file setup looks like:
You should pass the relative path instead of absolute:
<script src="js/number-guessing-game.js"></script>
Also you have syntax error in js, here is an working example:
function runGame() {
let guessString = '';
let guessNumber = 0;
let correct = false;
let numtries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
// const target = Math.floor(Math.random() * 100) + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target);
} while (!correct);
alert('You got it! The number was' + target + '.\n\nIt took you' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target) {
let correct = false;
if (isNaN(guessNumber)) {
alert('You have not entered a number.\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!');
} else if (guessNumber < target) {
alert('Your number is too small!');
} else {
correct = true;
}
return correct;
}
I'm trying to keep track of how many guesses are made and then print that number when the correct number is guessed. The number of guesses isn't being updated when the wrong number is guessed, so it keeps showing up that it took only 1 guess, when it really took more.
let num = Math.floor(Math.random() * 20) + 1;
console.log(num);
let num_guess = 0
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let num_guess = 1
let message = document.getElementById("message");
if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
}
else if (guess > 20) {
message.innerHTML = 'That number is not in range, try again.'
num_guess+=;
}
else if (guess > num) {
message.innerHTML = "No, try a lower number."
num_guess+=;
}
else if (guess < num) {
message.innerHTML = "No, try a higher number."
num_guess+=;
}
else if (guess == num) {
message.innerHTML = "You got it! It took you " + num_guess + " tries.";
}
}
<!doctype html>
<head>
<title>Higher - Lower</title>
</head>
<body>
<div class="container">
<h1>Higher Lower</h1>
<p>Guess a number between 1 and a maximum number of your choosing!</p>
<div class="row">
<div class="col-lg-3 col-md-6">
<form>
<div class="form-group">
<label>Your guess:</label>
<input type="text" id="guess" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="do_guess()">Guess</button>
</form>
</div>
</div>
<p id="message"></p>
</div>
<script src="higherlower.js"></script>
</body>
```
let num_guess = 1
You are declaring the variable twice and each time the function is called, it will be set to 1.
num_guess+=; this won't increment the variable. See below.
let num = Math.floor(Math.random() * 20) + 1;
console.log(num);
let num_guess = 0;
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
}
else if (guess > 20) {
message.innerHTML = 'That number is not in range, try again.'
num_guess += 1;
}
else if (guess > num) {
message.innerHTML = "No, try a lower number."
num_guess += 1;
}
else if (guess < num) {
message.innerHTML = "No, try a higher number."
num_guess += 1;
}
else if (guess == num) {
message.innerHTML = "You got it! It took you " + num_guess + " tries.";
num_guess += 1;
}
}
I'm having a problem with my Javascript code that involves putting a timer in a Random guessing game. I must give the user 5 seconds to guess the number. The user can guess multiple times within the span of 5 seconds. If the time runs out, I must prompt the user if he wants to play again or exit. If yes I have to loop back to the game. My timer is not working. I would every much appreciate it if any of you guys can help. Thank you.
<script type="text/javascript">
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0
function timer (upper) {
var timeID = setInterval (getRandomNumber, 5000);
}
function getRandomNumber (upper) {
var number = Math.floor(Math.random()*upper) +1;
return number;
}
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
}else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
}else if(parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
</script>
As prompt freezes the internal timer (in Chrome, Opera and Safari), we can't set a timeout for the user's response. One way is to use html <input> instead of prompt. In this case setTimeout works as desired.
const input = document.getElementById("input");
const getRandomNumber = (upper) => Math.floor(Math.random() * upper) + 1;
const upper = 10;
let guessCounter = 0;
let randomNumber = getRandomNumber(upper);
let timer;
const play = () => {
if (timer) clearTimeout(timer);
input.value = "";
guessCounter++;
timer = setTimeout(() => {
if (confirm("Time is out. Play again?")) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
}
}, 5000);
}
document.getElementById("question").innerHTML = `I am thinking of a number between 1 and ${upper}. What is it?`;
document.getElementById("guess").addEventListener("click", () => {
let userGuess = parseInt(input.value);
if (userGuess > randomNumber) {
alert('Try again! Your number is too high');
play();
} else if (userGuess < randomNumber) {
alert('Try again! Your number is too low ');
play();
} else if (userGuess === randomNumber) {
if (confirm(`You have guessed the number! It took you: ${guessCounter} tries. Play again?`)) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
} else {
clearTimeout(timer);
}
}
});
play();
<div id="question"></div>
<input id="input" type="input">
<button id="guess">Guess</button>
I recommend moving your game into a function and naming it, e.g. "startGame". Then, when the game finishes it, you can implement your timer to relaunch the game.
function getRandomNumber(upper) {
var number = Math.floor(Math.random()*upper) + 1;
return number;
}
function startGame() {
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0;
var playAgain;
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
} else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
} else if (parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
if (confirm('Do you want to play again?')) {
setInterval(startGame, 5000); // Start a new game in 5 seconds
}
}
startGame();
I'm a new programmer learning HTML/CSS/Javascript, and was fiddling around with it until I came across a bug. I was making the computer guess my number (0-5), but then realized if I put in a number higher than 5, the website just crashes. Is there any way I can make it so that if the user puts in a number higher than 5 it will just delete it automatically? Or is that not Javascript. Thanks in advance :)
document.getElementById("guess").onclick=function() {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Try this :
document.getElementById("guess").onclick=function() {
if(document.getElementById("myNumber").value > 5) {
document.getElementById("myNumber").value = "";
alert("Please provide a number that is with in 0 to 5");
} else {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Than define a onchange function to check length:
document.getElementById("myNumber").onchange = function (ev){
try{
var target = document.getElementById("myNumber");
if(parseInt(target.value) > x) { // can throw exception, when given a non number
target.value="";
}
} catch(ex) {
alert('Not a number');
}
};
IMPORTANT:
You have a greater problem here: You are generating a random number, and then comparing it to input( that does not change). This is an infinite loop. Because this is a random operation, and you can hit same number more than once.
You need to generate your number first (before click event on 'guess' button), before clicking on quess button. Like so:
var luckyNumber = x;
var guesses=1;
document.getElementById("start").onclick=function(){ //init counters once
guesses=0;
x=Math.floor(Math.random()*6);
gotit = false;
}
document.getElementById("guess").onclick=function() { // guess as many times as you want
if(document.getElementById("myNumber").value==x) {
gotit=true;
}
guesses++;
if(gotit){
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
}
But if you want to computer to quess your number, than you need to limit number of guesses (add a counter), or it will hang eventualy.
I took this as a little challenge and just went ahead and re-did your little game. Hope this helps.
Demo here
(function (guess, tryy, message) {
var comp = function () {
return Math.floor(Math.random() * 6)
};
var number = comp();
var count = 0;
var test = function () {
var val = guess.value;
if (!Number.isNaN(val) && val >= 0 && val <= 5) {
switch (true) {
case val > number:
message.innerHTML = 'Your guess was too high!';
count++;
break;
case val < number:
message.innerHTML = 'Your guess was too low!';
count++;
break;
case val == number:
count++;
message.innerHTML = 'Congratulations you found the number! It took you ' + count + ' guesses';
//Reseting game here
setTimeout(function(){
count = 0;
number = comp();
guess.value = '';
message.innerHTML = 'Your game has been reset';
}, 2000);
break;
};
}
};
tryy.onclick = test;
guess.onkeyup = function (e) {
if (e.keyCode == 13) {
test();
}
}
})(document.getElementById('guess'), document.getElementById('tryy'), document.getElementById('message'));
I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");