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();
Related
My game has two players that get random numbers, and the person who has the bigger number gets 1 "win". My while loop is for the "auto-roll" button, and instead of clicking "roll dice" each time, auto-roll will do it for you until one player has wins == game limit # (bestof.value). No matter where I put my setInterval it increases by a bunch at a time. If bestof.value = 10 then each interval displays at least 10 wins for one player at a time.
checkBox.checked = input checkmark that enables auto-roll feature. So this setInterval will only be active while the auto-roll loop is active.
Anyways, what am I doing wrong?
button.addEventListener("click", myFunction);
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
screenID.innerHTML = random;
screenIDD.innerHTML = random2;
if (random > random2){
winNumber.innerHTML = ++a;
} else if(random2 > random){
winNumba1.innerHTML = ++b;
} else {
console.log("Draw");
}
if (a > b){
winNumber.style.color = 'white';
winNumba1.style.color = 'black';
} else if(b > a){
winNumba1.style.color = 'white';
winNumber.style.color = 'black';
} else {
winNumber.style.color = 'black';
winNumba1.style.color = 'black';
}
if (checkBox.checked){
setInterval(myFunction, 2000)
while(a < bestof.value && b < bestof.value){
myFunction();
}};
if (winNumba1.innerHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumba1 wins!');
} else if (winNumber.innterHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumber wins!');
} else {}
};
I wrote a simplified js only version of your game here since I don't have html at hand, but I am sure you can adjust it to your environment.
Main difference: I check if someone won and use return to stop the function
If no one won and autoplay is activated I autoplay after 500ms again.
let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
console.log("New Round " + random + " vs " + random2)
if (random > random2) {
playerA++
} else if (random2 > random) {
playerB++
} else {
console.log("Draw");
}
if (playerA > playerB) {
console.log("a is winning")
} else if (playerB > playerA) {
console.log("b is winning")
} else {
console.log("There has been a draw")
}
if (playerA == bestOf) {
console.log('A won');
return
} else if (playerB == bestOf) {
console.log('B won');
return
}
if (autoPlay) {
setTimeout(myFunction, 500)
};
};
myFunction()
So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();
Hello I have a simple script:
var play = true;
var correct = false;
var number = 0;
var guess = 0;
while (play) {
// random number between 1 and 10.
number = Math.floor(Math.random() * 10 - 1);
if (number == 0) number = 1;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
When I get the number right and prompted to "Do you want another game?" and enter "yes", the program redisplays and stuck at "Do you want another game?".
You need to reset the state of correct on every play loop:
let play = true;
while (play) {
let number = Math.floor(Math.random() * 10 + 1);
let guess = 0;
let correct = false;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
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.");